0

我正在尝试使用 wifi python 模块通过 kivy 接口连接 wifi 网络。Kivy GUI 在成功执行“scheme.activate()”(用于连接到 wifi 网络)后 5 到 10 秒内挂起(冻结)。我也尝试过线程,但它仍然挂起。完整的代码可以在这里找到。

主文件

import commands
import string
import threading
from kivy.app import App
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.checkbox import CheckBox
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from kivy.uix.relativelayout import RelativeLayout
from kivy.clock import Clock, mainthread
import time
from kivy.uix.spinner import Spinner
from kivy.uix.tabbedpanel import TabbedPanel, TabbedPanelItem
from kivy.uix.textinput import TextInput
from kivy.uix.widget import Widget

from kivy.properties import ObjectProperty
from wifi import Scheme, Cell

class WifiLayout(RelativeLayout):
    global alive
    # awai = ObjectProperty()
    switchwifi = ObjectProperty()
    wifilayout = ObjectProperty()
    wifiscreen = ObjectProperty()


    def offRefresh(self):
        alive = False

class myApp(App):
    def build(self):
        return WifiLayout()


    def checkIfExist(ssid):
        schemes = list(Scheme.all())
        for scheme in schemes:
            checkSsid = scheme.options.get('wpa-ssid', scheme.options.get('wireless-essid'))

            if checkSsid == ssid:
                return True
            else:
                return False

    def refresh(self):
        global alive

        try:
            cell = Cell.all('wlan0')
        except:
            print "CELL ERROR"
            return
        if not alive:
            return
        self.wifilayout.clear_widgets()

        for c in cell:
            if c.ssid:
                    self.networkButton = ssidButton(text=c.ssid, cellname= c , height=50,size_hint_y=None,background_color=(0.9411,0.9725,1,1))#,on_release=self.ssidclicked))
                    self.wifilayout.add_widget(self.networkButton)


    def wifi_on(self):
        global alive
        switch = self.root.switchwifi
        self.wifilayout = self.root.wifilayout
        # wifi_label = self.root.ids.wifi_label
        if switch.active:
            ##            self.refresh()
            alive = True

            def A():
                while alive:
                    self.refresh()
                    time.sleep(5)

            if alive:
                thread = threading.Thread(target=A)
                # thread.daemon = True
                thread.start()

        else:
            alive = False
            self.wifilayout.clear_widgets()


class ssidButton(Button):

    def __init__(self, cellname, **kwargs):
        super(ssidButton, self).__init__(**kwargs)
        self.cell = cellname

    def enterPasswordEntryPopup(self, modify=False):
        global popup, ip

        def cancel(event):
            global popup
            popup.dismiss()
            return

        def connect(event):
            global activateThread
            global popup, alive

            def connecting():
                global stop
                inalive = True
                while inalive:#True:
##                    if stop.is_set():
##                        return
                    connectnet()
                    time.sleep(1)
                    inalive = False
            def connectnet():
                global stopper, alive
                print "ACTIVATING"
            self.scheme.activate()
                popup.dismiss()
        print "ACTIVATED"

            self.password = self.network_password.text
            if modify:
                self.scheme.delete()
                self.iptext = ip.text
                self.gwtext = gateway.text
                self.nmtext = netmask.text
                print self.password, self.iptext, self.gwtext, self.nmtext
            self.scheme = Scheme.for_cell('wlan0', self.schemeName, self.cell, self.password)
            self.scheme.save()

            activateThread = threading.Thread(target=connectnet)
            activateThread.start()


        connectncancel = BoxLayout()

        connectncancel.add_widget(Button(text="Cancel", on_release=cancel))
        connectncancel.add_widget(Button(text="Connect", on_release=connect))
        passwordEntryContent = BoxLayout(orientation='vertical')
        passwordEntryContent.add_widget(Label(text='Password'))
        self.network_password = TextInput(multiline=False, password=False)
        passwordEntryContent.add_widget(self.network_password)
        windowSize = (300, 200)

        if modify:
            b = BoxLayout()
            a = AnchorLayout()
            t = TextInput(text=self.network_password.text, size_hint_x=1, password=False, size_hint_y=.8)
            a.add_widget(t)
            b1 = BoxLayout(spacing='20dp')
            b1.add_widget(Label(text="Password", size_hint_x=.5))
            b1.add_widget(a)
            # b1.add_widget(Button(height = 10,text = "OK"))

            b3 = BoxLayout(padding="5dp", spacing="20dp")
            cancel = Button(text="Cancel")
            save = Button(text="Save")
            b3.add_widget(cancel)
            b3.add_widget(save)

            b2 = BoxLayout()
            b2.add_widget(Widget(size_hint_x=1))
            b2.add_widget(CheckBox(size_hint_x=.5))
            b2.add_widget(Label(text="Show Password", size_hint_x=.5))
            b2.add_widget((Widget(size_hint_x=1)))
            bm = BoxLayout(orientation='vertical')
            bm.add_widget(b1)
            bm.add_widget(b2)
            bm.add_widget(b3)
            tabbed_panel = TabbedPanel()
            # tabbed_panel.do_default_tab = False
            content = BoxLayout(orientation='vertical')
            # content.add_widget(Label(markup = True,text = "[b] Device MAC address : [/b]" + self.wifimacaddress))
            content.add_widget(bm)
            tabbed_panel.default_tab_content = content

            tabbed_panel.default_tab_text = "Wifi"
            b.add_widget(tabbed_panel)

            ######------ipv4tab-------#########

            ipv4tab = TabbedPanelItem(text="IPV4 Settings")
            ipv4tabcontent = BoxLayout(orientation='vertical')
            b1 = BoxLayout(padding="10dp", size_hint_y=1)
            l = Label(text="Method")
            s = Spinner(text="Automatic(DHCP)", values=["Manual", "Automatic(DHCP)"])  # on_text
            b1.add_widget(l)
            b1.add_widget(s)

            b2 = BoxLayout(padding='2dp', spacing='5dp', size_hint_y=1)
            b21 = BoxLayout(orientation='vertical')
            iplabel = Label(text="Address")
            ipaddress = TextInput(multiline=False)
            b21.add_widget(iplabel)
            b21.add_widget(ipaddress)

            # b22 = BoxLayout(orientation = "vertical")
            b22 = BoxLayout(orientation='vertical')
            nmlabel = Label(text="Netmask")
            netmask = TextInput(multiline=False)
            b22.add_widget(nmlabel)
            b22.add_widget(netmask)

            # b23 = BoxLayout(orientation="vertical")
            b23 = BoxLayout(orientation='vertical')
            gwlabel = Label(text="Gateway")
            gateway = TextInput(multiline=False)
            b23.add_widget(gwlabel)
            b23.add_widget(gateway)

            b2.add_widget(b21)
            b2.add_widget(b22)
            b2.add_widget(b23)

            ipv4tabcontent.add_widget(b1)
            ipv4tabcontent.add_widget(b2)
            ipv4tabcontent.add_widget(Button(text="Save", size_hint_y=.5))

            ipv4tab.content = ipv4tabcontent
            tabbed_panel.add_widget(ipv4tab)

            windowSize = (500, 250)
            popup = Popup(title=self.text,
                          size_hint=(None, None), size=windowSize,
                          # pos=(50, 50),
                          # pos_hint={'x':0,'top':1},
                          pos_hint={'middle': 1, 'top': 1},
                          content=b, disabled=False, auto_dismiss=True)

            return popup
            ###################################

        passwordEntryContent.add_widget(connectncancel)
        # print(self.root,self.root.h,self.parent.width)
        popup = Popup(title=self.text,
                      size_hint=(None, None), size=windowSize,
                      # pos=(50, 50),
                      # pos_hint={'x':0,'top':1},
                      # pos_hint={'right': 1, 'top': 1},
                      content=passwordEntryContent, disabled=False, auto_dismiss=False)

        return popup

    def on_release(self):
        global popup
        specialList = string.printable.split("Z")[-1]
        self.schemeName = self.text

        for char in specialList:
            if char in self.schemeName:
                self.schemeName = self.schemeName.split(char)[0]
                break

        self.scheme = Scheme.find('wlan0', self.schemeName)
        if not self.scheme:  # Scheme.find('wlan0', schemeName):

            popup = self.enterPasswordEntryPopup()
            popup.open()
            #######################################
            # scheme = Scheme.for_cell('wlan0', schemeName, cell, 'pikkme@123')

        # elif self.scheme.options.get('wpa-ssid') != self.cell.ssid:

        else:

            def forgetnetwork(event):
                global popup
                self.scheme = Scheme.find('wlan0', self.schemeName)
                self.scheme.delete()
                commands.getoutput("sudo ifdown wifi")#killall dhclient")
                popup.dismiss()

            def modifynetwork(event):
                global popup
                popup.dismiss()
                self.passwordPopup = self.enterPasswordEntryPopup(modify=True)
                self.passwordPopup.open()
                # Open(None)

            # self.scheme = Scheme.find('wlan0', self.schemeName)

            # self.activate()
            ##############################################3
            content = BoxLayout(orientation='vertical', padding=10, spacing=10)
            # content_cancel = Button(text='OK', size_hint_y=None, height=40)
            content.add_widget(Button(text='Forget Network', on_release=forgetnetwork))
            content.add_widget(Button(text='Modify Network', on_release=modifynetwork))
            popup = Popup(title=self.text,
                          size_hint=(None, None), size=(300, 200),
                          content=content, disabled=False, auto_dismiss=True)
            popup.open()


myApp().run()

我的.kv

<ScreenLabel@Label>:
    pos_hint: {'x': 0, 'top': 1}
    size_hint_y: .1
    font_size: self.height/2
    markup:True
    bold: True
    valign: 'middle'
    halign: 'left'
    text_size: self.size
    padding: 40,100
    canvas:
        Color:
            rgba: 47 / 255., 167 / 255., 212 / 255., .4
        Rectangle:
            pos: self.pos
            size: self.size


<MyImageButton@ButtonBehavior+Image>:

<WifiLayout>:
    name: "wifiscreen"
    id: wifiscreen
    switchwifi: switchwifi
    wifilayout: wifilayout
    on_touch_down: app.sstimer = 0
    ScreenLabel:
        text: 'Wi-Fi'


    Switch:
        id: switchwifi
        pos_hint: {'right': .8, 'top': 1}
        size_hint: .1,.1
        on_active: app.wifi_on()
    Button:
        pos_hint: {'right':.92, 'top':1}
        size_hint: .1,.1
        on_release: app.exit()
        text: "exit"


    ScrollView:
        pos_hint: {'x': 0,'y': 0.1}
        size_hint: 1,.8
        GridLayout:
            cols: 1
            rows:20
            id: wifilayout
            size_hint_y: None
            height: self.minimum_height
4

0 回答 0