简体   繁体   English

在尝试使用python连接到wifi网络时出现ConnectionError

[英]Getting ConnectionError, while trying to connect to wifi network using python

To connect to network from my Raspberry Pi, I'm using this python library . 要从我的Raspberry Pi连接到网络,我正在使用此python库 My problem is that I'm constantly getting ConnectionError, even through I'm handling it in try/except block, or at least I think I'm handling. 我的问题是,即使我在try / except块中处理它,或者至少我认为我正在处理,我仍不断收到ConnectionError。 This program scans air interface for wifi networks, then excludes ones without matching prefix, and then sorts matching ones by signal quality. 该程序扫描空中接口以查找wifi网络,然后排除没有匹配前缀的接口,然后按信号质量对匹配的接口进行排序。 After that, connectToGateway() is trying to connect to the best one and if it fails, it looks for second one in the list and so on. 之后,connectToGateway()尝试连接到最佳连接,如果连接失败,它将在列表中寻找第二个连接,依此类推。 If scheme for some network was saved before, it reuses it (that's what AssertionError exception is handling). 如果某个网络的方案之前已保存过,它将重新使用它(这就是AssertionError异常正在处理的内容)。 My code: 我的代码:

from wifi import Cell, Scheme
from collections import namedtuple
from operator import attrgetter
from wifi.exceptions import ConnectionError
from optparse import OptionParser


class NetworkConnection:
    def __init__(self, prefix, interface, password):
        self.prefix = prefix
        self.interface = interface
        self.password = password

    def discover_avalible_networks(self, interface=None):
        all_networks = []
        interface = self.interface
        avalible_networks = Cell.all(interface)
        for network in avalible_networks:
            all_networks.append(network)
        return all_networks

    def select_appropriate_networks(self, prefix=None):
        appropriate_network = namedtuple('network', 'ssid quality encrypted encryption_type')
        appropriate_networks = []
        prefix = self.prefix
        for network in self.discover_avalible_networks():
            if network.ssid.startswith(prefix):
                appropriate_networks.append(
                appropriate_network(network.ssid, network.quality, network.encrypted, network.encryption_type))
        return appropriate_networks

    def sort_appropriate_networks(self):
        unsorted_appropriate_networks = self.select_appropriate_networks()
        sorted_appropriate_networks = sorted(unsorted_appropriate_networks, key=attrgetter('quality'), reverse=True)
        return sorted_appropriate_networks

    def connect_to_gateway(self, interface=None, password=None):
        interface = self.interface
        password = self.password
        networks = self.sort_appropriate_networks()
        for network in networks:
            try:
                print("Trying to connect to {}").format(network.ssid)
                scheme = Scheme.for_cell(interface, network.ssid, network, password)
                scheme.save()
                scheme.activate()
                print("Connected to {}").format(network.ssid)
                break
            except AssertionError:
                scheme = Scheme.find(interface, network.ssid)
                scheme.activate()
                print("Connected to {}").format(network.ssid)
                break
            except ConnectionError:
                print("Couldn't connect to {}").format(network.ssid)
                scheme = Scheme.find(interface, network.ssid)
                scheme.delete()
                continue

if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option('-p', '--prefix', dest='prefix', help="Specify gateway ssid prefix")
    parser.add_option('-i', '--interface', dest='interface', help="Specify name of wireless interface of choice")
    parser.add_option('-q', '--password', dest='password',
                      help="Specify password for the wireless network of choice")
    options, args = parser.parse_args()
    wireless_connection = NetworkConnection(prefix=options.prefix, interface=options.interface,
                                            password=options.password)
    wireless_connection.connect_to_gateway()

And results: 结果: 在此处输入图片说明

So it looks like it's not catching this error. 因此,看起来它没有捕获此错误。

That ConnectionError isn't being caught because it's not being raised by the scheme.activate() call inside the try section, it's being raised by the scheme.activate() call on line 52, inside the except AssertionError section. ConnectionError没有被抓住,因为它没有被升起scheme.activate()的调用内try部分,它正在募集的scheme.activate()调用上线52,里面except AssertionError部分。

I assume that the wifi module docs tell you to catch AssertionError like that, but it's a bit weird. 我假设wifi模块文档告诉您那样捕获AssertionError ,但这有点奇怪。 AssertionError is intended to be used to catch logic bugs in programs, IOW, things that should never happen if the program logic is correct, it's not supposed to be used to catch bad data or bad environment conditions. AssertionError旨在用于捕获程序,IOW中的逻辑错误,如果程序逻辑正确,则应该永远不会发生这种事情,不应将其用于捕获不良数据或不良环境条件。 So normally, if a program raises AssertionError it's a sign that the program itself needs fixing. 因此,通常,如果程序引发AssertionError则表明该程序本身需要修复。

I'm not familiar with that wifi module, so I don't know how to properly fix your problem. 我不熟悉该wifi模块,因此我不知道如何正确解决您的问题。 But the code seems to be having problems activating the Scheme returned by the Scheme.find call inside that except AssertionError section. 但是代码似乎在激活except AssertionError部分except AssertionErrorScheme.find调用返回的Scheme时遇到问题。 I guess you could put that whole try.. except block inside a while loop with a small time delay at the end, and just keep looping until you get a working connection. 我想你可以try.. except blockwhile循环内try.. except block ,最后只需要一点时间延迟,然后一直循环直到获得有效的连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM