e31075f751d4d9f839f9f45c2e3ccde536dde5af
[vuplus_dvbapp] / lib / python / Plugins / SystemPlugins / WirelessLanSetup / plugin.py
1 from Screens.Screen import Screen
2 from Screens.MessageBox import MessageBox
3 from Screens.InputBox import InputBox
4 from Screens.Standby import *
5 from Screens.VirtualKeyBoard import VirtualKeyBoard
6 from Screens.HelpMenu import HelpableScreen
7 from Components.Network import iNetwork
8 from Screens.NetworkSetup import NameserverSetup
9 from Components.Sources.StaticText import StaticText
10 from Components.Sources.Boolean import Boolean
11 from Components.Sources.List import List
12 from Components.Label import Label,MultiColorLabel
13 from Components.Pixmap import Pixmap,MultiPixmap
14 from Components.MenuList import MenuList
15 from Components.config import config, ConfigYesNo, ConfigIP, NoSave, ConfigText, ConfigPassword, ConfigSelection, getConfigListEntry, ConfigNothing
16 from Components.config import ConfigInteger, ConfigSubsection
17 from Components.ConfigList import ConfigListScreen
18 from Components.PluginComponent import plugins
19 from Components.MultiContent import MultiContentEntryText, MultiContentEntryPixmapAlphaTest
20 from Components.ActionMap import ActionMap, NumberActionMap, HelpableActionMap
21 from Components.Console import Console
22 from Tools.Directories import resolveFilename, SCOPE_PLUGINS, SCOPE_CURRENT_SKIN
23 from Tools.LoadPixmap import LoadPixmap
24 from Plugins.Plugin import PluginDescriptor
25 from enigma import eTimer, ePoint, eSize, RT_HALIGN_LEFT, eListboxPythonMultiContent, gFont
26 from os import path as os_path, system as os_system, unlink,listdir
27 from re import compile as re_compile, search as re_search
28 from Tools.Directories import fileExists
29 import time
30 from pythonwifi.iwlibs import Wireless
31 import pythonwifi.flags
32
33 class WlanSelection(Screen,HelpableScreen):
34         skin =  """
35                 <screen position="center,center" size="510,400" title="Wireless Network Adapter Selection..." >
36                         <ePixmap pixmap="skin_default/div-h.png" position="0,350" zPosition="1" size="560,2" />
37                         <ePixmap pixmap="skin_default/border_menu.png" position="10,10" zPosition="1" size="250,300" transparent="1" alphatest="on" />
38
39                         <ePixmap pixmap="skin_default/buttons/red.png" position="10,360" size="140,40" alphatest="on" />
40                         <ePixmap pixmap="skin_default/buttons/green.png" position="360,360" size="140,40" alphatest="on" />
41
42                         <widget source="key_red" render="Label" position="10,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" foregroundColor="#ffffff" transparent="1" />
43                         <widget source="key_green" render="Label" position="360,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" foregroundColor="#ffffff" transparent="1" />
44
45                         <widget name="menulist" position="20,20" size="230,260" transparent="1" backgroundColor="#371e1c1a" zPosition="10" scrollbarMode="showOnDemand" />
46                         <widget source="description" render="Label" position="305,10" size="195,300" font="Regular;19" halign="center" valign="center" />
47                 </screen>
48                 """
49         def __init__(self, session):
50                 Screen.__init__(self,session)
51                 HelpableScreen.__init__(self)
52                 self.mainmenu = self.getWlandevice()
53                 self["menulist"] = MenuList(self.mainmenu)
54                 self["key_red"] = StaticText(_("Close"))
55                 self["key_green"] = StaticText(_("Select"))
56                 self["description"] = StaticText()
57                 self["description"].setText(_("Select Wireless Lan module. \n" ))
58                 self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
59                 {
60                         "ok": (self.ok, _("select interface")),
61                         "cancel": (self.close, _("exit network interface list")),
62                 })
63
64                 self["ColorActions"] = HelpableActionMap(self, "ColorActions",
65                 {
66                         "green": (self.ok, _("select interface")),
67                         "red": (self.close, _("exit network interface list")),
68                 })
69                 self.updateInterfaces()
70                 self.onClose.append(self.cleanup)
71
72         def updateInterfaces(self):
73                 iNetwork.config_ready = False
74                 iNetwork.msgPlugins()
75                 iNetwork.getInterfaces()
76
77         def checkIfaceMode(self, iface = None):
78                 try:
79                         obj = Wireless(iface)
80                         if obj.getMode() == 'Master':
81                                 return -1
82                         else:
83                                 return 0
84                 except:
85                         return -2
86
87         def ok(self):
88 #               print len(self["menulist"].list)
89                 if len(self["menulist"].list) == 0:
90                         self.session.open(MessageBox, (_("Can not find any WirelessLan Module\n")),MessageBox.TYPE_ERROR,5 )
91                         return
92                 iface=self["menulist"].getCurrent()[1]
93                 if iface == None:
94                         return
95                 elif iNetwork.getAdapterAttribute(iface, "up") == True:
96                         ret = self.checkIfaceMode(iface)
97                         if ret == -2:
98                                 self.session.open(MessageBox, (_("Invalid WirelessLan Module.\n")),MessageBox.TYPE_ERROR,5 )
99                                 return
100                         elif ret == -1:
101                                 self.session.open(MessageBox, (_("Can not setup WirelessLan Module in 'AP Mode'\n")),MessageBox.TYPE_ERROR,5 )
102                                 return
103                 self.session.open(WlanSetup, iface)
104
105         def getWlandevice(self):
106                 list = []
107                 for x in iNetwork.getInstalledAdapters():
108                         if x.startswith('eth') or x.startswith('br') or x.startswith('mon'):
109                                 continue
110                         description=self.getAdapterDescription(x)
111                         if description == "Unknown network adapter":
112                                 list.append((description,x))
113                         else:
114                                 list.append((description + " (%s)"%x,x))
115                 return list
116
117         def getAdapterDescription(self, iface):
118                 classdir = "/sys/class/net/" + iface + "/device/"
119                 driverdir = "/sys/class/net/" + iface + "/device/driver/"
120                 if os_path.exists(classdir):
121                         files = listdir(classdir)
122                         if 'driver' in files:
123                                 if os_path.realpath(driverdir).endswith('rtw_usb_drv'):
124                                         return _("Realtek")+ " " + _("WLAN adapter.")
125                                 elif os_path.realpath(driverdir).endswith('ath_pci'):
126                                         return _("Atheros")+ " " + _("WLAN adapter.")
127                                 elif os_path.realpath(driverdir).endswith('zd1211b'):
128                                         return _("Zydas")+ " " + _("WLAN adapter.")
129                                 elif os_path.realpath(driverdir).endswith('rt73'):
130                                         return _("Ralink")+ " " + _("WLAN adapter.")
131                                 elif os_path.realpath(driverdir).endswith('rt73usb'):
132                                         return _("Ralink")+ " " + _("WLAN adapter.")
133                                 else:
134                                         return str(os_path.basename(os_path.realpath(driverdir))) + " " + _("WLAN adapter")
135                         else:
136                                 return _("Unknown network adapter")
137                 else:
138                         return _("Unknown network adapter")
139
140         def cleanup(self):
141                 iNetwork.stopGetInterfacesConsole()
142
143 class WlanSetup(Screen,HelpableScreen):
144         skin =  """
145                 <screen position="center,center" size="510,400" title="Wireless Network Setup Menu..." >
146                         <ePixmap pixmap="skin_default/div-h.png" position="0,350" zPosition="1" size="560,2" />
147                         <ePixmap pixmap="skin_default/border_menu.png" position="10,10" zPosition="1" size="250,300" transparent="1" alphatest="on" />
148
149                         <ePixmap pixmap="skin_default/buttons/red.png" position="10,360" size="140,40" alphatest="on" />
150                         <ePixmap pixmap="skin_default/buttons/green.png" position="360,360" size="140,40" alphatest="on" />
151
152                         <widget source="key_red" render="Label" position="10,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" foregroundColor="#ffffff" transparent="1" />
153                         <widget source="key_green" render="Label" position="360,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" foregroundColor="#ffffff" transparent="1" />
154
155                         <widget name="menulist" position="20,20" size="230,260" transparent="1" backgroundColor="#371e1c1a" zPosition="10" scrollbarMode="showOnDemand" />
156                         <widget source="description" render="Label" position="305,10" size="195,300" font="Regular;19" halign="center" valign="center" />
157                 </screen>
158                 """
159         def __init__(self, session, ifaces):
160                 Screen.__init__(self, session)
161                 HelpableScreen.__init__(self)
162                 self.session = session
163                 self.iface = ifaces
164                 self.restartLanRef = None
165                 self.LinkState = None
166                 self.mainmenu = self.MakeMenu()
167                 self["menulist"] = MenuList(self.mainmenu)
168                 self["key_red"] = StaticText(_("Close"))
169                 self["key_green"] = StaticText(_("Select"))
170                 self["description"] = StaticText()
171                 self["IFtext"] = StaticText()
172                 self["IF"] = StaticText()
173                 self["Statustext"] = StaticText()
174                 self["statuspic"] = MultiPixmap()
175                 self["statuspic"].hide()
176                 self.onLayoutFinish.append(self.loadDescription)
177                 
178                 self.oktext = _("Press OK on your remote control to continue.")
179                 
180                 self["WizardActions"] = HelpableActionMap(self, "WizardActions",
181                         {
182                         "up": (self.up, _("move up to previous entry")),
183                         "down": (self.down, _("move down to next entry")),
184                         "left": (self.left, _("move up to first entry")),
185                         "right": (self.right, _("move down to last entry")),
186                         })
187                 
188                 self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
189                         {
190                         "cancel": (self.close, _("exit networkadapter setup menu")),
191                         "ok": (self.ok, _("select menu entry")),
192                         })
193
194                 self["ColorActions"] = HelpableActionMap(self, "ColorActions",
195                         {
196                         "red": (self.close, _("exit networkadapter setup menu")),
197                         "green": (self.ok, _("select menu entry")),
198                         })
199
200                 self["actions"] = NumberActionMap(["WizardActions","ShortcutActions"],
201                 {
202                         "ok": self.ok,
203                         "back": self.close,
204                         "up": self.up,
205                         "down": self.down,
206                         "red": self.close,
207                         "left": self.left,
208                         "right": self.right,
209                 }, -2)
210                 self.onClose.append(self.cleanup)
211
212         def loadDescription(self):
213                 if self["menulist"].getCurrent()[1] == 'setting':
214                         self["description"].setText(_("Edit the network configuration of your STB.\n" ) + self.oktext )
215                 if self["menulist"].getCurrent()[1] == 'scanap':
216                         self["description"].setText(_("Scan your network for wireless access points and connect to them using your selected wireless device.\n" ) + self.oktext )
217                 if self["menulist"].getCurrent()[1] == 'dns':
218                         self["description"].setText(_("Edit the Nameserver configuration of your STB.\n" ) + self.oktext )
219                 if self["menulist"].getCurrent()[1] == 'status':
220                         self["description"].setText(_("Shows the state of your wireless LAN connection.\n" ) + self.oktext )
221                 if self["menulist"].getCurrent()[1] == 'test':
222                         self["description"].setText(_("Test the network configuration of your STB.\n" ) + self.oktext )
223                 if self["menulist"].getCurrent()[1] == 'restart':
224                         self["description"].setText(_("Restart your network connection and interfaces.\n" ) + self.oktext )
225
226         def up(self):
227                 self["menulist"].up()
228                 self.loadDescription()
229
230         def down(self):
231                 self["menulist"].down()
232                 self.loadDescription()
233
234         def left(self):
235                 self["menulist"].pageUp()
236                 self.loadDescription()
237
238         def right(self):
239                 self["menulist"].pageDown()
240                 self.loadDescription()
241
242         def ok(self):
243                 self.cleanup()
244                 if self["menulist"].getCurrent()[1] == 'setting':
245                         self.session.openWithCallback(self.checklist, WlanConfig, self.iface)
246                 elif self["menulist"].getCurrent()[1] == 'scanap':
247                         self.session.openWithCallback(self.WlanScanApCallback, WlanScanAp, self.iface)
248                 elif self["menulist"].getCurrent()[1] == 'dns':
249                         self.session.open(NameserverSetup)
250                 elif self["menulist"].getCurrent()[1] == 'status':
251                         self.session.open(Wlanstatus, self.iface)
252                 elif self["menulist"].getCurrent()[1] == 'test':
253                         self.session.openWithCallback(self.checklist,NetworkAdapterTest,self.iface)
254                 elif self["menulist"].getCurrent()[1] == 'restart':
255                         self.session.openWithCallback(self.restartLan, MessageBox, (_("Are you sure you want to restart your network interfaces?\n\n") + self.oktext ) )
256
257         def checklist(self):
258                 self["menulist"].setList(self.MakeMenu())
259
260         def MakeMenu(self):
261                 menu = []
262                 menu.append((_("Adapter settings"), "setting"))
263                 menu.append((_("Scan Wireless AP"), "scanap"))
264                 menu.append((_("Nameserver settings"), "dns"))
265                 if iNetwork.getAdapterAttribute(self.iface, "up"):
266                         menu.append((_("Show WLAN Status"), "status"))
267                 menu.append((_("Network test"), "test"))
268                 menu.append((_("Restart network"), "restart"))
269
270                 return menu
271
272         def WlanScanApCallback(self, essid = None):
273                 if essid is not None:
274                         self.session.openWithCallback(self.checklist, WlanConfig, self.iface, essid)
275
276         def restartLan(self, ret = False):
277                 if (ret == True):
278                         iNetwork.restartNetwork(self.restartLanDataAvail)
279                         self.restartLanRef = self.session.openWithCallback(self.restartfinishedCB, MessageBox, _("Please wait while your network is restarting..."), type = MessageBox.TYPE_INFO, enable_input = False)
280
281         def restartLanDataAvail(self, data):
282                 if data is True:
283                         iNetwork.getInterfaces(self.getInterfacesDataAvail)
284
285         def getInterfacesDataAvail(self, data):
286                 if data is True:
287                         self.restartLanRef.close(True)
288
289         def restartfinishedCB(self,data):
290                 if data is True:
291                         self.session.open(MessageBox, _("Finished restarting your network"), type = MessageBox.TYPE_INFO, timeout = 5, default = False)
292
293         def cleanup(self):
294                 iNetwork.stopRestartConsole()
295                 iNetwork.stopGetInterfacesConsole()
296
297 wlanconfig = ConfigSubsection()
298 wlanconfig.usedevice = ConfigSelection(default = "off", choices = [
299         ("off", _("off")), ("on", _("on"))])
300 wlanconfig.usedhcp = ConfigSelection(default = "off", choices = [
301         ("off", _("no")), ("on", _("yes"))])
302 wlanconfig.essid = ConfigSelection(default = "none", choices = ["none"])
303 wlanconfig.encrypt = ConfigSelection(default = "off", choices = [
304         ("off", _("no")), ("on", _("yes"))])
305 wlanconfig.method = ConfigSelection(default = "wep", choices = [
306         ("wep", _("WEP")), ("wpa", _("WPA")), ("wpa2", _("WPA2")),("wpa/wpa2", _("WPA/WPA2"))])
307 wlanconfig.keytype = ConfigSelection(default = "ascii", choices = [
308         ("ascii", _("ASCII")), ("hex", _("HEX"))])
309 wlanconfig.key = ConfigPassword(default = "XXXXXXXX", visible_width = 50, fixed_size = False)
310 wlanconfig.usegateway = ConfigSelection(default = "off", choices = [
311         ("off", _("no")), ("on", _("yes"))])
312 wlanconfig.ip    = ConfigIP([0,0,0,0])
313 wlanconfig.netmask = ConfigIP([0,0,0,0])
314 wlanconfig.gateway = ConfigIP([0,0,0,0])
315
316 selectap = None 
317 class WlanConfig(Screen, ConfigListScreen, HelpableScreen):
318         skin =  """
319                 <screen position="center,center" size="510,400" title="Wireless Network Configuration..." >
320                         <ePixmap pixmap="skin_default/buttons/red.png" position="10,360" size="140,40" alphatest="on" />
321                         <ePixmap pixmap="skin_default/buttons/green.png" position="360,360" size="140,40" alphatest="on" />
322
323                         <widget source="key_red" render="Label" position="10,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" foregroundColor="#ffffff" transparent="1" />
324                         <widget source="key_green" render="Label" position="360,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" foregroundColor="#ffffff" transparent="1" />
325
326                         <widget name="config" position="10,10" backgroundColor="#371e1c1a" transparent="1" size="480,210" scrollbarMode="showOnDemand" />
327                         <ePixmap pixmap="skin_default/div-h.png" position="0,225" zPosition="1" size="550,2" />
328                         <eLabel text="IP Address : " position="100,250" size="190,21" font="Regular;19" />
329                         <widget source="ipaddress" render="Label" position="300,250" zPosition="1" size="150,26" font="Regular;20" halign="center" valign="center" />
330                         <eLabel text="NetMask : " position="100,275" size="190,21" font="Regular;19" />
331                         <widget source="netmask" render="Label" position="300,275" zPosition="1" size="150,26" font="Regular;20" halign="center" valign="center" />     
332                         <eLabel text="Gateway : " position="100,300" size="190,21" font="Regular;19" />
333                         <widget source="gateway" render="Label" position="300,300" zPosition="1" size="150,26" font="Regular;20" halign="center" valign="center" />
334                         <widget name="VKeyIcon" pixmap="skin_default/buttons/key_text.png" position="460,230" zPosition="10" size="35,25" transparent="1" alphatest="on" />
335                         <widget name="HelpWindow" pixmap="skin_default/buttons/key_text.png" position="383,420" zPosition="1" size="1,1" transparent="1" alphatest="on" />
336                 </screen>
337                 """
338         def __init__(self, session, iface, essidSelected = None):
339                 Screen.__init__(self,session)
340                 self.session = session
341                 self["key_red"] = StaticText(_("Close"))
342                 self["key_green"] = StaticText(_("Ok"))
343                 self["ipaddress"] = StaticText(_("[ N/A ]"))
344                 self["netmask"] = StaticText(_("[ N/A ]"))              
345                 self["gateway"] = StaticText(_("[ N/A ]"))
346                 self["OkCancelActions"] = ActionMap(["ShortcutActions", "SetupActions" ],
347                 {
348                         "ok": self.saveWlanConfig,
349                         "green": self.saveWlanConfig,
350                         "cancel": self.keyCancel,
351                         "red": self.keyCancel,
352                 }, -2)
353                 self["HelpWindow"] = Pixmap()
354                 self["HelpWindow"].hide()
355                 self["VKeyIcon"] = Pixmap()
356                 self["VKeyIcon"].hide()
357                 self.iface = iface
358                 self.essidSelected = essidSelected
359                 self.ssid = None
360                 self.ap_scan = None
361                 self.scan_ssid = None
362                 self.key_mgmt = None
363                 self.proto = None
364                 self.key_type = None
365                 self.encryption_key = None
366                 self.wlanscanap = None
367                 self.wpaphraseconsole = None
368                 self.list = []
369                 ConfigListScreen.__init__(self, self.list,session = self.session)
370                 self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
371                 self.readWpaSupplicantConf()
372                 self.scanAplistTimer = eTimer()
373                 self.scanAplistTimer.callback.append(self.scanApList)
374                 self.emptyListMsgTimer = eTimer()
375                 self.emptyListMsgTimer.callback.append(self.emptyListMsg)
376                 self.Console = Console()
377                 self.updateInterfaces(self.readWlanSettings)
378                 self.onClose.append(self.cleanup)
379
380         def updateInterfaces(self,callback = None):
381                 iNetwork.config_ready = False
382                 iNetwork.msgPlugins()
383                 iNetwork.getInterfaces(callback)
384
385         def readWlanSettings(self,ret=None):
386                 if ret is not True:
387                         print "getInterfaces Fail... "
388                 if iNetwork.getAdapterAttribute(self.iface, "up") == True:
389                         default_tmp = "on"
390                 else:
391                         default_tmp = "off"
392                 wlanconfig.usedevice = ConfigSelection(default=default_tmp, choices = [("off", _("off")), ("on", _("on"))])
393
394                 if iNetwork.getAdapterAttribute(self.iface, "dhcp"):
395                         default_tmp = "on"
396                 else:
397                         default_tmp = "off"
398                 wlanconfig.usedhcp = ConfigSelection(default=default_tmp, choices = [("off", _("no")), ("on", _("yes"))])
399
400                 wlanconfig.ip = ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "ip")) or [0,0,0,0]
401
402                 wlanconfig.netmask = ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "netmask") or [255,0,0,0])
403                 if iNetwork.getAdapterAttribute(self.iface, "gateway"):
404                         default_tmp = "on"
405                 else:
406                         default_tmp = "off"
407                 wlanconfig.usegateway = ConfigSelection(default = default_tmp, choices = [("off", _("no")), ("on", _("yes"))])
408
409                 wlanconfig.gateway = ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "gateway") or [0,0,0,0])
410
411                 self["ipaddress"].setText(_(self.formatip(iNetwork.getAdapterAttribute(self.iface, "ip"))))
412                 self["netmask"].setText(_(self.formatip(iNetwork.getAdapterAttribute(self.iface, "netmask"))))
413                 self["gateway"].setText(_(self.formatip(iNetwork.getAdapterAttribute(self.iface, "gateway"))))
414
415                 if self.encryption_key is not None:
416                         default_tmp = "on"
417                 else:
418                         default_tmp = "off"
419                 wlanconfig.encrypt = ConfigSelection(default = default_tmp, choices = [("off", _("no")), ("on", _("yes"))])
420
421                 if self.key_mgmt=="NONE":
422                         default_tmp = "wep"
423                 elif self.key_mgmt == "WPA-PSK":
424                         if self.proto == "WPA":
425                                 default_tmp = "wpa"
426                         elif self.proto == "RSN":
427                                 default_tmp = "wpa2"
428                         elif self.proto in ( "WPA RSN", "WPA WPA2"):
429                                 default_tmp = "wpa/wpa2"
430                         else:
431                                 default_tmp = "wpa"
432                 else:
433                         default_tmp = "wep"
434
435                 wlanconfig.method = ConfigSelection(default = default_tmp, choices = [
436                         ("wep", _("WEP")), ("wpa", _("WPA")), ("wpa2", _("WPA2")),("wpa/wpa2", _("WPA/WPA2"))])
437
438                 if self.key_type == 0:
439                         default_tmp = "hex"
440                 else:
441                         default_tmp = "ascii"
442                 wlanconfig.keytype = ConfigSelection(default = default_tmp, choices = [
443                         ("ascii", _("ASCII")), ("hex", _("HEX"))])
444                 default_tmp = self.encryption_key or "XXXXXXXX"
445                 wlanconfig.key = ConfigPassword(default = default_tmp, visible_width = 50, fixed_size = False)
446                 self.getApList()
447
448         def readWpaSupplicantConf(self):
449                 try:
450                         if fileExists("/etc/wpa_supplicant.conf"):
451                                 wpafd = open("/etc/wpa_supplicant.conf","r")
452                                 if wpafd >0:
453                                         data = wpafd.readline()
454                                         while len(data) > 0:
455 #                                               print "####readWpaSupplicantConf, data : ",data
456                                                 data = data.lstrip()
457                                                 if len(data) == 0:
458                                                         data = wpafd.readline()
459                                                         continue
460                                                 if data.startswith('ssid=') and len(data) > 6:
461                                                         self.ssid = data[6:-2]
462                                                 elif data.startswith('ap_scan=') :
463                                                         self.ap_scan = data[8:]
464 #                                                       print "####readWpaSupplicantConf, ap_scan : ",self.ap_scan
465                                                 elif data.startswith('scan_ssid=') and len(data) > 10:
466                                                         self.scan_ssid = data[10:-1]
467                                                 elif data.startswith('key_mgmt=') and len(data) > 9:
468                                                         self.key_mgmt = data[9:-1]
469                                                 elif data.startswith('proto=') and len(data) > 6:
470                                                         self.proto = data[6:-1]
471                                                 elif data.startswith('wep_key0="') and len(data) > 11:
472                                                         self.key_type = 1 # ascii
473                                                         self.encryption_key = data[10:-2]
474                                                 elif data.startswith('wep_key0=') and len(data) > 9:
475                                                         self.key_type = 0 # hex
476                                                         self.encryption_key = data[9:-1]
477                                                 elif data.startswith('psk="') and len(data) > 6:
478                                                         self.key_type = 1 # ascii
479                                                         self.encryption_key = data[5:-2]
480                                                 elif data.startswith('#psk="') and len(data) > 6:
481                                                         self.key_type = 0 # hex
482                                                         self.encryption_key = data[6:-2]
483                                                 elif not self.encryption_key and data.startswith('psk=') and len(data) > 4:
484                                                         self.key_type = 0 # hex
485                                                         self.encryption_key = data[4:-1]
486                                                 data = wpafd.readline()
487 #                                       print self.ssid,self.scan_ssid,self.key_mgmt,self.proto,self.key_type,self.encryption_key
488                                         wpafd.close()
489                                 else:
490                                         print 'read error'
491                         else:
492                                 pass
493                 except:
494                         print 'failed loading wpasupplicant.conf'
495
496         def createConfig(self):
497                 self.configList=[]
498                 self.usedeviceEntry = getConfigListEntry(_("Use Device"), wlanconfig.usedevice)
499                 self.usedhcpEntry = getConfigListEntry(_("Use DHCP"), wlanconfig.usedhcp)
500                 self.essidEntry = getConfigListEntry(_("ESSID"), wlanconfig.essid)
501                 self.hiddenessidEntry = getConfigListEntry(_("Input Hidden ESSID"), wlanconfig.hiddenessid)
502                 self.encryptEntry = getConfigListEntry(_("Encrypt"), wlanconfig.encrypt)
503                 self.methodEntry = getConfigListEntry(_("Method"), wlanconfig.method)
504                 self.keytypeEntry = getConfigListEntry(_("Key Type"), wlanconfig.keytype)
505                 self.keyEntry = getConfigListEntry(_("KEY"), wlanconfig.key)
506
507                 self.ipEntry = getConfigListEntry(_("IP"), wlanconfig.ip)
508                 self.netmaskEntry = getConfigListEntry(_("NetMask"), wlanconfig.netmask)
509
510                 self.usegatewayEntry = getConfigListEntry(_("Use Gateway"), wlanconfig.usegateway)
511                 self.gatewayEntry = getConfigListEntry(_("Gateway"), wlanconfig.gateway)
512
513                 self.configList.append( self.usedeviceEntry )
514                 if wlanconfig.usedevice.value is "on":
515                         self.configList.append( self.usedhcpEntry )
516                         if wlanconfig.usedhcp.value is "off":
517                                 self.configList.append(self.ipEntry)
518                                 self.configList.append(self.netmaskEntry)
519                                 self.configList.append(self.usegatewayEntry)
520                                 if wlanconfig.usegateway.value is "on":
521                                         self.configList.append(self.gatewayEntry)
522                         self.configList.append( self.essidEntry )
523                         if wlanconfig.essid.value == 'Input hidden ESSID':
524                                 self.configList.append( self.hiddenessidEntry )
525                         self.configList.append( self.encryptEntry )
526                         if wlanconfig.encrypt.value is "on" :
527                                 self.configList.append( self.methodEntry )
528                                 if wlanconfig.method.value =="wep":
529                                         self.configList.append( self.keytypeEntry )
530                                 self.configList.append( self.keyEntry )
531
532                 self["config"].list = self.configList
533                 self["config"].l.setList(self.configList)
534                 if not self.showTextIcon in self["config"].onSelectionChanged:
535                         self["config"].onSelectionChanged.append(self.showTextIcon)
536
537         def showTextIcon(self):
538                 if isinstance(self["config"].getCurrent()[1], ConfigText) or isinstance(self["config"].getCurrent()[1], ConfigPassword):
539                         self["VKeyIcon"].show()
540                 else:
541                         self["VKeyIcon"].hide()
542
543         def getApList(self):
544                 if self.essidSelected is None:
545                         self.apList = []
546                         self.configurationmsg = self.session.open(MessageBox, _("Please wait for scanning AP..."), type = MessageBox.TYPE_INFO, enable_input = False)
547                         self.scanAplistTimer.start(100,True)
548                 else:
549                         self.apList = [self.essidSelected]
550                         wlanconfig.essid = ConfigSelection(choices = self.apList)
551                         if self.ssid is not None:
552                                 wlanconfig.hiddenessid = ConfigText(default = self.ssid, visible_width = 50, fixed_size = False)
553                         else:
554                                 wlanconfig.hiddenessid = ConfigText(default = "<Input ESSID>", visible_width = 50, fixed_size = False)
555                         self.createConfig()
556
557         def getScanResult(self, wirelessObj):
558                 Iwscanresult  = None
559                 try:
560                         Iwscanresult  = wirelessObj.scan()
561                 except IOError:
562                         print "%s Interface doesn't support scanning.."%self.iface
563                 return Iwscanresult
564
565         def scanApList(self):
566                 if self.oldInterfaceState is not True:
567                         os_system("ifconfig "+self.iface+" up")
568                         iNetwork.setAdapterAttribute(self.iface, "up", True)
569                 wirelessObj = Wireless(self.iface)
570                 Iwscanresult=self.getScanResult(wirelessObj)
571                 if Iwscanresult is None or len(Iwscanresult.aplist) == 0 :
572                         import time
573                         time.sleep(1.5)
574                         Iwscanresult=self.getScanResult(wirelessObj)
575                 self.configurationmsg.close(True)
576                 if Iwscanresult is None or len( Iwscanresult.aplist) == 0:
577                         self.emptyListMsgTimer.start(100,True)
578                 else:
579                         for ap in Iwscanresult:
580                                 if ap.essid is not None and ap.essid not in self.apList and len(ap.essid) > 0:
581                                         self.apList.append(ap.essid)
582                 self.apList.append('Input hidden ESSID')
583                 if selectap is not None and selectap in self.apList:
584                         wlanconfig.essid = ConfigSelection(default=selectap,choices = self.apList)
585                 elif self.scan_ssid is not None and self.scan_ssid.strip() == '1':
586                         wlanconfig.essid = ConfigSelection(default='Input hidden ESSID',choices = self.apList)
587                 elif self.ssid is not None and self.ssid in self.apList:
588                         wlanconfig.essid = ConfigSelection(default=self.ssid, choices = self.apList)
589                 else:
590                         try:
591                                 wlanconfig.essid = ConfigSelection(defalut = self.apList[0], choices = self.apList)
592                         except:
593                                 wlanconfig.essid = ConfigSelection(choices = self.apList)
594                 if self.ssid is not None:
595                         wlanconfig.hiddenessid = ConfigText(default = self.ssid, visible_width = 50, fixed_size = False)
596                 else:
597                         wlanconfig.hiddenessid = ConfigText(default = "<Input ESSID>", visible_width = 50, fixed_size = False)
598                 self.createConfig()
599
600         def emptyListMsg(self):
601                 self.session.open(MessageBox, _("No AP detected."), type = MessageBox.TYPE_INFO, timeout = 10)
602
603         def keyLeft(self):
604                 ConfigListScreen.keyLeft(self)
605                 self.newConfig()
606
607         def keyRight(self):
608                 ConfigListScreen.keyRight(self)
609                 self.newConfig()
610
611         def newConfig(self):
612                 if self["config"].getCurrent() == self.usedeviceEntry or self["config"].getCurrent() == self.encryptEntry \
613                         or self["config"].getCurrent() == self.usedhcpEntry or self["config"].getCurrent() == self.usegatewayEntry \
614                         or self["config"].getCurrent() == self.essidEntry or self["config"].getCurrent() == self.methodEntry:
615                         self.createConfig()
616
617         def saveWlanConfig(self):
618                 try:
619                         if self["config"].getCurrent() == self.keyEntry or self["config"].getCurrent() == self.hiddenessidEntry :
620                                 self["config"].getCurrent()[1].onDeselect(self.session)
621                         if self["config"].isChanged():
622                                 self.session.openWithCallback(self.checkNetworkConfig, MessageBox, (_("Are you sure you want to restart your network interfaces?\n") ) )
623                         else:
624                                 self.session.openWithCallback(self.checkNetworkConfig, MessageBox, (_("Network configuration is not changed....\n\nAre you sure you want to restart your network interfaces?\n") ) )
625                 except:
626                         pass
627
628         def checkNetworkConfig(self, ret = False):
629                 if ret == False:
630                         if self["config"].getCurrent() == self.keyEntry or self["config"].getCurrent() == self.hiddenessidEntry :
631                                 self["config"].getCurrent()[1].onSelect(self.session)
632                         return
633                 if wlanconfig.essid.value == 'Input hidden ESSID':
634                         if len(wlanconfig.hiddenessid.value) == 0:
635                                 self.session.open(MessageBox, ("PLEASE INPUT HIDDEN ESSID"), type = MessageBox.TYPE_ERROR, timeout = 10)
636                                 return
637                 if len(wlanconfig.key.value) == 0:
638                         self.session.open(MessageBox, ("PLEASE INPUT NETWORK KEY"), type = MessageBox.TYPE_ERROR, timeout = 10)
639                         return
640                 self.checkNetworkShares()
641
642         def checkNetworkShares(self):
643                 if not self.Console:
644                         self.Console = Console()
645                 cmd = "cat /proc/mounts"
646                 self.Console.ePopen(cmd, self.checkSharesFinished, self.confirmAnotherIfaces)
647
648         def checkSharesFinished(self, result, retval, extra_args):
649                 callback = extra_args
650 #               print "checkMountsFinished : result : \n",result
651                 networks = ['nfs','smbfs','ncp','coda']
652                 for line in result.splitlines():
653                         split = line.strip().split(' ',3)
654                         if split[2] in networks:
655                                 self.session.open(MessageBox, ("NOT deconfiguring network interfaces :\n network shares still mounted\n"), type = MessageBox.TYPE_ERROR, timeout = 10)
656                                 callback(False)
657                                 if self["config"].getCurrent() == self.keyEntry or self["config"].getCurrent() == self.hiddenessidEntry :
658                                         self["config"].getCurrent()[1].onSelect(self.session)
659                                 return
660                 callback(True)
661
662         def confirmAnotherIfaces(self, ret = False):
663                 if ret == False:
664                         return
665                 else:
666                         num_configured_if = len(iNetwork.getConfiguredAdapters())
667                         if num_configured_if >= 1:
668                                 if num_configured_if == 1 and self.iface in iNetwork.getConfiguredAdapters():
669                                         self.getWpaPhrase(False)
670                                 else:
671                                         self.session.openWithCallback(self.getWpaPhrase, MessageBox, _("A second configured interface has been found.\n\nDo you want to disable the second network interface?"), default = True)
672                         else:
673                                 self.getWpaPhrase(False)
674
675         def getWpaPhrase(self,ret):
676                 if ret == True:
677                         configuredInterfaces = iNetwork.getConfiguredAdapters()
678                         for interface in configuredInterfaces:
679                                 if interface == self.iface:
680                                         continue
681                                 iNetwork.setAdapterAttribute(interface, "up", False)
682                                 iNetwork.deactivateInterface(interface)
683                 if wlanconfig.method.value =="wep":
684                         self.writeWpasupplicantConf("wep") # passphrasekey is not None
685                 else:
686                         if wlanconfig.essid.value == 'Input hidden ESSID':
687                                 cmd = "wpa_passphrase '%s' %s" % (wlanconfig.hiddenessid.value,wlanconfig.key.value)
688                         else :
689                                 cmd = "wpa_passphrase '%s' %s" % (wlanconfig.essid.value,wlanconfig.key.value)
690                         print cmd
691                         self.wpaphraseconsole = Console()
692                         self.wpaphraseconsole.ePopen(cmd, self.parseWpaPhrase, self.writeWpasupplicantConf)
693
694         def parseWpaPhrase(self, result, retval, extra_args):
695                 (writewlanconfig) = extra_args
696                 if self.wpaphraseconsole is not None:
697                         if retval == 0:
698                                 self.wpaphraseconsole.killAll()
699                                 self.wpaphraseconsole = None
700 #                               print "parseWpaPhrase result : "
701 #                               print result
702                                 psk = None
703                                 for line in result.splitlines():
704                                         if line.find('ssid') == -1 and line.find('#psk=') != -1:
705                                                 plainpwd        = line
706                                         elif line.find('psk=') != -1:
707                                                 psk = line
708                                 if psk:
709                                         writewlanconfig(psk,plainpwd)
710                                 else:
711                                         writewlanconfig(None)
712                         else:
713                                 writewlanconfig(None)
714
715         def writeWpasupplicantConf(self, passphrasekey=None,plainpwd=None):
716                 if passphrasekey:
717                         wpafd = open("/etc/wpa_supplicant.conf","w")
718                         if wpafd > 0:
719                                 contents = "#WPA Supplicant Configuration by STB\n"
720                                 contents += "ctrl_interface=/var/run/wpa_supplicant\n"
721                                 contents += "eapol_version=1\n"
722                                 contents += "fast_reauth=1\n"
723                                 contents += "ap_scan=1\n"
724                                 contents += "network={\n"
725                                 if wlanconfig.essid.value == 'Input hidden ESSID':
726                                         contents += "\tssid=\""+wlanconfig.hiddenessid.value+"\"\n"
727                                         contents += "\tscan_ssid=1\n"
728                                 else :
729                                         contents += "\tssid=\""+wlanconfig.essid.value+"\"\n"
730                                         contents += "\tscan_ssid=0\n"
731                                 if wlanconfig.encrypt.value == "on":
732                                         if wlanconfig.method.value =="wep":
733                                                 contents += "\tkey_mgmt=NONE\n"
734                                                 contents += "\twep_key0="
735                                                 if wlanconfig.keytype.value == "ascii":
736                                                         contents += "\""+wlanconfig.key.value+"\"\n"
737                                                 else:
738                                                         contents += wlanconfig.key.value+"\n"
739                                         else:
740 #                                               print "plainpwd : ",plainpwd
741 #                                               print "passphrasekey : ",passphrasekey
742                                                 if wlanconfig.method.value == "wpa":
743                                                         contents += "\tkey_mgmt=WPA-PSK\n"
744                                                         contents += "\tproto=WPA\n"
745                                                         contents += "\tpairwise=CCMP TKIP\n"
746                                                         contents += "\tgroup=CCMP TKIP\n"       
747                                                 elif wlanconfig.method.value == "wpa2":
748                                                         contents += "\tkey_mgmt=WPA-PSK\n"
749                                                         contents += "\tproto=RSN\n"
750                                                         contents += "\tpairwise=CCMP TKIP\n"
751                                                         contents += "\tgroup=CCMP TKIP\n"
752                                                 else:
753                                                         contents += "\tkey_mgmt=WPA-PSK\n"
754                                                         contents += "\tproto=WPA RSN\n"
755                                                         contents += "\tpairwise=CCMP TKIP\n"
756                                                         contents += "\tgroup=CCMP TKIP\n"
757                                                 contents += plainpwd+"\n"
758                                                 contents += passphrasekey+"\n"
759                                 else:
760                                         contents += "\tkey_mgmt=NONE\n"
761                                 contents += "}\n"
762                                 print "content = \n"+contents
763                                 wpafd.write(contents)
764                                 wpafd.close()
765                                 self.writeNetConfig(0)
766                         else :
767                                 self.session.open(MessageBox, _("wpa_supplicant.conf open error."), type = MessageBox.TYPE_ERROR, timeout = 10)
768                                 self.writeNetConfig(-1)
769                 else:
770                         self.writeNetConfig(-2)
771
772         def writeNetConfig(self,ret = -1):
773                 if ret == -1:
774                         self.session.open(MessageBox, _("wpa_supplicant.conf open error."), type = MessageBox.TYPE_ERROR, timeout = 10)
775                         return
776                 elif ret == -2:
777                         self.session.open(MessageBox, _("Can NOT generate passphrase"), type = MessageBox.TYPE_ERROR, timeout = 10)
778                         return
779
780                 if wlanconfig.usedevice.value=="on":
781                         iNetwork.setAdapterAttribute(self.iface, "up", True)
782                         if wlanconfig.usedhcp.value =="on":
783                                 iNetwork.setAdapterAttribute(self.iface, "dhcp", True)
784                         else:
785                                 iNetwork.setAdapterAttribute(self.iface, "dhcp", False)
786                                 iNetwork.setAdapterAttribute(self.iface, "ip", wlanconfig.ip.value)
787                                 iNetwork.setAdapterAttribute(self.iface, "netmask", wlanconfig.netmask.value)
788                                 if wlanconfig.usegateway.value == "on":
789                                         iNetwork.setAdapterAttribute(self.iface, "gateway", wlanconfig.gateway.value)
790                 else:
791                         iNetwork.setAdapterAttribute(self.iface, "up", False)
792                         iNetwork.deactivateInterface(self.iface)
793                 contents = "\tpre-up wpa_supplicant -i"+self.iface+" -c/etc/wpa_supplicant.conf -B -D"+iNetwork.detectWlanModule(self.iface)+"\n"
794                 contents += "\tpost-down wpa_cli terminate\n\n"
795                 iNetwork.setAdapterAttribute(self.iface, "configStrings", contents)
796                 iNetwork.writeNetworkConfig()
797                 iNetwork.restartNetwork(self.updateCurrentInterfaces)
798                 self.configurationmsg = None
799                 self.configurationmsg = self.session.openWithCallback(self.configFinished, MessageBox, _("Please wait for activation of your network configuration..."), type = MessageBox.TYPE_INFO, enable_input = False)
800
801
802         def updateCurrentInterfaces(self,ret):
803                 if ret is True:
804                         iNetwork.getInterfaces(self.configurationMsgClose)
805
806         def configurationMsgClose(self,ret):
807                 if ret is True and self.configurationmsg is not None:
808                         self.configurationmsg.close(True)
809
810         def configFinished(self,data):
811                 global selectap
812                 if data is True:
813                         self.session.openWithCallback(self.configFinishedCB, MessageBox, _("Your network configuration has been activated."), type = MessageBox.TYPE_INFO, timeout = 10)
814                         selectap = wlanconfig.essid.value
815
816         def configFinishedCB(self,data):
817                 if data is not None:
818                         if data is True:
819                                 self.close()
820         
821         def formatip(self, iplist):
822                 list = []
823                 list = iplist
824 #               print "iplist : ",iplist
825                 try:
826                         if len(iplist) == 4:
827                                 result = str(iplist[0])+"."+str(iplist[1])+"."+str(iplist[2])+"."+str(iplist[3])
828                         else:
829                                 result ="0.0.0.0"
830 #                       print "result : ",result
831                         return result
832                 except:
833                         return "[N/A]"
834                         
835         def keyCancelConfirm(self, result):
836                 if not result:
837                         return
838                 if self.oldInterfaceState is False:
839                         iNetwork.setAdapterAttribute(self.iface, "up", False)
840                         iNetwork.deactivateInterface(self.iface,self.keyCancelCB)
841                 else:
842                         self.close()
843
844         def keyCancel(self,yesno = True):
845                 if self["config"].isChanged():
846                         self.session.openWithCallback(self.keyCancelConfirm, MessageBox, _("Really close without saving settings?"))
847                 else:
848                         self.keyCancelConfirm(True)
849
850         def keyCancelCB(self,data):
851                 if data is not None:
852                         if data is True:
853                                 self.close()
854
855         def cleanup(self):
856                 iNetwork.stopRestartConsole()
857                 iNetwork.stopGetInterfacesConsole()
858                 iNetwork.stopDeactivateInterfaceConsole()
859                 self.stopwlanscanapConsole()
860                 self.stopCheckNetworkSharesConsole()
861                 self.stopWpaPhraseConsole()
862
863         def stopwlanscanapConsole(self):
864                 if self.wlanscanap is not None:
865                         if len(self.wlanscanap.appContainers):
866                                 for name in self.wlanscanap.appContainers.keys():
867                                         self.wlanscanap.kill(name)
868
869         def stopCheckNetworkSharesConsole(self):
870                 if self.Console is not None:
871                         if len(self.Console.appContainers):
872                                 for name in self.Console.appContainers.keys():
873                                         self.Console.kill(name)
874
875         def stopWpaPhraseConsole(self):
876                 if self.wpaphraseconsole is not None:
877                         if len(self.wpaphraseconsole.appContainers):
878                                         for name in self.wpaphraseconsole.appContainers.keys():
879                                                 self.wpaphraseconsole.kill(name)
880
881 class WlanScanAp(Screen,HelpableScreen):
882         skin =  """
883                 <screen position="center,center" size="510,400" title="Wireless Network AP Scan..." >
884                         <ePixmap pixmap="skin_default/div-h.png" position="0,350" zPosition="1" size="560,2" />
885                         <ePixmap pixmap="skin_default/border_menu.png" position="10,10" zPosition="1" size="250,300" transparent="1" alphatest="on" />
886
887                         <ePixmap pixmap="skin_default/buttons/red.png" position="10,360" size="140,40" alphatest="on" />
888                         <ePixmap pixmap="skin_default/buttons/green.png" position="185,360" size="140,40" alphatest="on" />
889                         <ePixmap pixmap="skin_default/buttons/blue.png" position="360,360" size="140,40" alphatest="on" />
890
891                         <widget source="key_red" render="Label" position="10,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" foregroundColor="#ffffff" transparent="1" />
892                         <widget source="key_green" render="Label" position="185,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" foregroundColor="#ffffff" transparent="1" />
893                         <widget source="key_blue" render="Label" position="360,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" foregroundColor="#ffffff" transparent="1" />
894
895                         <widget name="menulist" position="20,20" size="230,260" backgroundColor="#371e1c1a" transparent="1" zPosition="10" scrollbarMode="showOnDemand" />
896
897                         <widget source="Address" render="Label" position="265,70" zPosition="1" size="240,30" font="Regular;18" halign="center" valign="center" />
898                         <widget source="ESSID" render="Label" position="265,100" zPosition="1" size="240,30" font="Regular;18" halign="center" valign="center" />
899                         <widget source="Protocol" render="Label" position="265,130" zPosition="1" size="240,30" font="Regular;18" halign="center" valign="center" />
900                         <widget source="Frequency" render="Label" position="265,160" zPosition="1" size="240,40" font="Regular;18" halign="center" valign="center" />
901                         <widget source="Encryption key" render="Label" position="265,200" zPosition="1" size="240,30" font="Regular;18" halign="center" valign="center" />
902                         <widget source="BitRate" render="Label" position="265,220" zPosition="1" size="240,60" font="Regular;18" halign="center" valign="center" />
903                 </screen>
904                 """
905         def __init__(self, session, iface):
906                 Screen.__init__(self,session)
907                 HelpableScreen.__init__(self)
908                 self.session = session
909                 self.iface = iface
910                 self.wlanscanap = None
911                 self.apList = {}
912                 self.setApList = []
913
914                 self["WizardActions"] = HelpableActionMap(self, "WizardActions",
915                 {
916                         "up": (self.up, _("move up to previous entry")),
917                         "down": (self.down, _("move down to next entry")),
918                         "left": (self.left, _("move up to first entry")),
919                         "right": (self.right, _("move down to last entry")),
920                 }, -2)
921
922                 self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
923                 {
924                         "cancel": (self.close, _("exit")),
925                         "ok": (self.ok, "select AP"),
926                 })
927
928                 self["ColorActions"] = HelpableActionMap(self, "ColorActions",
929                 {
930                         "red": (self.close, _("exit")),
931                         "green": (self.ok, "select AP"),
932                         "yellow": (self.restartScanAP, "restart scan AP"),
933                         "blue": (self.startWlanConfig, "Edit Wireless settings"),
934                 })
935
936                 self["menulist"] = MenuList(self.setApList)
937                 self["key_red"] = StaticText(_("Close"))
938                 self["key_green"] = StaticText(_("Select"))
939                 self["key_blue"] = StaticText(_("EditSetting"))
940                 self["Address"] = StaticText(_("Scanning AP List.."))
941                 self["ESSID"] = StaticText(_("Wait a moment"))
942                 self["Protocol"] = StaticText(" ")
943                 self["Frequency"] = StaticText(" ")
944                 self["Encryption key"] = StaticText(" ")
945                 self["BitRate"] = StaticText(" ")
946                 self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
947                 self.getAplistTimer = eTimer()
948                 self.getAplistTimer.callback.append(self.getApList)
949                 self.scanAplistTimer = eTimer()
950                 self.scanAplistTimer.callback.append(self.scanApList)
951                 self.emptyListMsgTimer = eTimer()
952                 self.emptyListMsgTimer.callback.append(self.emptyListMsg)
953                 self.apList = {}
954                 self.onClose.append(self.__onClose)
955                 self.getAplistTimer.start(100,True)
956                 
957         def left(self):
958                 self["menulist"].pageUp()
959                 self.displayApInfo()
960         
961         def right(self):
962                 self["menulist"].pageDown()
963                 self.displayApInfo()
964
965         def up(self):
966                 self["menulist"].up()
967                 self.displayApInfo()
968                 
969         def down(self):
970                 self["menulist"].down()
971                 self.displayApInfo()
972
973         def ok(self):
974                 global selectap
975                 if self["menulist"].getCurrent() is not None:
976                         selectAp=self["menulist"].getCurrent()[0]
977                         selectap = selectAp
978                 self.close()
979
980         def startWlanConfig(self):
981                 if self["menulist"].getCurrent() is not None:
982                         selectAp=self["menulist"].getCurrent()[0]
983                         self.close(selectAp)
984
985         def getApList(self):
986                 self.apList = {}
987                 self.setApList = []
988                 self.configurationmsg = self.session.open(MessageBox, _("Please wait for scanning AP..."), type = MessageBox.TYPE_INFO, enable_input = False)
989                 self.scanAplistTimer.start(100,True)
990
991         def getScanResult(self, wirelessObj):
992                 Iwscanresult  = None
993                 try:
994                         Iwscanresult  = wirelessObj.scan()
995                 except IOError:
996                         print "%s Interface doesn't support scanning.."%self.iface
997                 return Iwscanresult
998
999         def scanApList(self):
1000                 if self.oldInterfaceState is not True:
1001                         os_system("ifconfig "+self.iface+" up")
1002                         iNetwork.setAdapterAttribute(self.iface, "up", True)
1003                 wirelessObj = Wireless(self.iface)
1004                 Iwscanresult=self.getScanResult(wirelessObj)
1005                 if Iwscanresult is None or len(Iwscanresult.aplist) == 0 :
1006                         import time
1007                         time.sleep(1.5)
1008                         Iwscanresult=self.getScanResult(wirelessObj)
1009                 self.configurationmsg.close(True)
1010                 if Iwscanresult is not None and len(Iwscanresult.aplist) != 0:
1011                         (num_channels, frequencies) = wirelessObj.getChannelInfo()
1012                         index = 1
1013                         for ap in Iwscanresult:
1014                                 self.apList[index] = {}
1015                                 self.apList[index]["Address"] = ap.bssid
1016                                 if len(ap.essid) == 0:
1017                                         self.apList[index]["ESSID"] = "<hidden ESSID>"
1018                                 else:
1019                                         self.apList[index]["ESSID"] = ap.essid
1020                                         self.setApList.append( (self.apList[index]["ESSID"], index) )
1021                                 self.apList[index]["Protocol"] = ap.protocol
1022                                 self.apList[index]["Frequency"] = wirelessObj._formatFrequency(ap.frequency.getFrequency())
1023                                 try:
1024                                         self.apList[index]["Channel"] = frequencies.index(self.apList[index]["Frequency"] + 1)
1025                                 except:
1026                                         self.apList[index]["Channel"] = "Unknown"
1027
1028                                 self.apList[index]["Quality"] = "%s/%s" % \
1029                                         ( ap.quality.quality, wirelessObj.getQualityMax().quality )
1030                                 self.apList[index]["Signal Level"] = "%s/%s" % \
1031                                         ( ap.quality.getSignallevel(), "100" )
1032                                 self.apList[index]["Noise Level"] = "%s/%s" % \
1033                                         ( ap.quality.getNoiselevel(), "100" )
1034
1035 # get encryption key on/off
1036                                 key_status = "Unknown"
1037                                 if (ap.encode.flags & pythonwifi.flags.IW_ENCODE_DISABLED):
1038                                         key_status = "off"
1039                                 elif (ap.encode.flags & pythonwifi.flags.IW_ENCODE_NOKEY):
1040                                         if (ap.encode.length <= 0):
1041                                                 key_status = "on"
1042                                 self.apList[index]["Encryption key"] = key_status
1043                                 self.apList[index]["BitRate"] = wirelessObj._formatBitrate(ap.rate[-1][-1])
1044                                 index += 1
1045 #               print self.apList
1046 #               print self.setApList
1047                 self.displayApInfo()
1048                 if len(self.apList) == 0:
1049                         self.emptyListMsgTimer.start(100,True)
1050
1051         def displayApInfo(self):
1052                 if len(self.apList) >0:
1053                         self["menulist"].setList(self.setApList)
1054                         if self["menulist"].getCurrent() is not None:
1055                                 index = self["menulist"].getCurrent()[1]
1056                                 for key in ["Address", "ESSID", "Protocol", "Frequency", "Encryption key", "BitRate"]:
1057                                         if self.apList[index].has_key(key) and self.apList[index][key] is not None:
1058                                                 self[key].setText((key+":  "+self.apList[index][key]))
1059                                         else:
1060                                                 self[key].setText((key+": None"))
1061
1062         def emptyListMsg(self):
1063                 self.session.open(MessageBox, _("No AP detected."), type = MessageBox.TYPE_INFO, timeout = 10)
1064                 self["Address"].setText(_("No AP detected."))
1065                 self["ESSID"].setText(_(""))
1066
1067         def restartScanAP(self):
1068                 self.getAplistTimer.start(100,True)
1069
1070         def __onClose(self):
1071                 if self.oldInterfaceState is False:
1072                         iNetwork.setAdapterAttribute(self.iface, "up", False)
1073                         iNetwork.deactivateInterface(self.iface)
1074
1075 class NetworkAdapterTest(Screen):
1076         def __init__(self, session,iface):
1077                 Screen.__init__(self, session)
1078                 self.iface = iface
1079                 self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
1080                 self.setLabels()
1081                 self.onClose.append(self.cleanup)
1082                 self.onHide.append(self.cleanup)
1083                 
1084                 self["updown_actions"] = NumberActionMap(["WizardActions","ShortcutActions"],
1085                 {
1086                         "ok": self.KeyOK,
1087                         "blue": self.KeyOK,
1088                         "up": lambda: self.updownhandler('up'),
1089                         "down": lambda: self.updownhandler('down'),
1090                 
1091                 }, -2)
1092                 
1093                 self["shortcuts"] = ActionMap(["ShortcutActions","WizardActions"],
1094                 {
1095                         "red": self.cancel,
1096                         "back": self.cancel,
1097                 }, -2)
1098                 self["infoshortcuts"] = ActionMap(["ShortcutActions","WizardActions"],
1099                 {
1100                         "red": self.closeInfo,
1101                         "back": self.closeInfo,
1102                 }, -2)
1103                 self["shortcutsgreen"] = ActionMap(["ShortcutActions"],
1104                 {
1105                         "green": self.KeyGreen,
1106                 }, -2)
1107                 self["shortcutsgreen_restart"] = ActionMap(["ShortcutActions"],
1108                 {
1109                         "green": self.KeyGreenRestart,
1110                 }, -2)
1111                 self["shortcutsyellow"] = ActionMap(["ShortcutActions"],
1112                 {
1113                         "yellow": self.KeyYellow,
1114                 }, -2)
1115                 
1116                 self["shortcutsgreen_restart"].setEnabled(False)
1117                 self["updown_actions"].setEnabled(False)
1118                 self["infoshortcuts"].setEnabled(False)
1119                 self.onClose.append(self.delTimer)      
1120                 self.onLayoutFinish.append(self.layoutFinished)
1121                 self.steptimer = False
1122                 self.nextstep = 0
1123                 self.activebutton = 0
1124                 self.nextStepTimer = eTimer()
1125                 self.nextStepTimer.callback.append(self.nextStepTimerFire)
1126
1127         def cancel(self):
1128                 if self.oldInterfaceState is False:
1129                         iNetwork.setAdapterAttribute(self.iface, "up", self.oldInterfaceState)
1130                         iNetwork.deactivateInterface(self.iface)
1131                 self.close()
1132
1133         def closeInfo(self):
1134                 self["shortcuts"].setEnabled(True)              
1135                 self["infoshortcuts"].setEnabled(False)
1136                 self["InfoText"].hide()
1137                 self["InfoTextBorder"].hide()
1138                 self["key_red"].setText(_("Close"))
1139
1140         def delTimer(self):
1141                 del self.steptimer
1142                 del self.nextStepTimer
1143
1144         def nextStepTimerFire(self):
1145                 self.nextStepTimer.stop()
1146                 self.steptimer = False
1147                 self.runTest()
1148
1149         def updownhandler(self,direction):
1150                 if direction == 'up':
1151                         if self.activebutton >=2:
1152                                 self.activebutton -= 1
1153                         else:
1154                                 self.activebutton = 6
1155                         self.setActiveButton(self.activebutton)
1156                 if direction == 'down':
1157                         if self.activebutton <=5:
1158                                 self.activebutton += 1
1159                         else:
1160                                 self.activebutton = 1
1161                         self.setActiveButton(self.activebutton)
1162
1163         def setActiveButton(self,button):
1164                 if button == 1:
1165                         self["EditSettingsButton"].setPixmapNum(0)
1166                         self["EditSettings_Text"].setForegroundColorNum(0)
1167                         self["NetworkInfo"].setPixmapNum(0)
1168                         self["NetworkInfo_Text"].setForegroundColorNum(1)
1169                         self["AdapterInfo"].setPixmapNum(1)               # active
1170                         self["AdapterInfo_Text"].setForegroundColorNum(2) # active
1171                 if button == 2:
1172                         self["AdapterInfo_Text"].setForegroundColorNum(1)
1173                         self["AdapterInfo"].setPixmapNum(0)
1174                         self["DhcpInfo"].setPixmapNum(0)
1175                         self["DhcpInfo_Text"].setForegroundColorNum(1)
1176                         self["NetworkInfo"].setPixmapNum(1)               # active
1177                         self["NetworkInfo_Text"].setForegroundColorNum(2) # active
1178                 if button == 3:
1179                         self["NetworkInfo"].setPixmapNum(0)
1180                         self["NetworkInfo_Text"].setForegroundColorNum(1)
1181                         self["IPInfo"].setPixmapNum(0)
1182                         self["IPInfo_Text"].setForegroundColorNum(1)
1183                         self["DhcpInfo"].setPixmapNum(1)                  # active
1184                         self["DhcpInfo_Text"].setForegroundColorNum(2)    # active
1185                 if button == 4:
1186                         self["DhcpInfo"].setPixmapNum(0)
1187                         self["DhcpInfo_Text"].setForegroundColorNum(1)
1188                         self["DNSInfo"].setPixmapNum(0)
1189                         self["DNSInfo_Text"].setForegroundColorNum(1)
1190                         self["IPInfo"].setPixmapNum(1)                  # active
1191                         self["IPInfo_Text"].setForegroundColorNum(2)    # active                
1192                 if button == 5:
1193                         self["IPInfo"].setPixmapNum(0)
1194                         self["IPInfo_Text"].setForegroundColorNum(1)
1195                         self["EditSettingsButton"].setPixmapNum(0)
1196                         self["EditSettings_Text"].setForegroundColorNum(0)
1197                         self["DNSInfo"].setPixmapNum(1)                 # active
1198                         self["DNSInfo_Text"].setForegroundColorNum(2)   # active
1199                 if button == 6:
1200                         self["DNSInfo"].setPixmapNum(0)
1201                         self["DNSInfo_Text"].setForegroundColorNum(1)
1202                         self["EditSettingsButton"].setPixmapNum(1)         # active
1203                         self["EditSettings_Text"].setForegroundColorNum(2) # active
1204                         self["AdapterInfo"].setPixmapNum(0)
1205                         self["AdapterInfo_Text"].setForegroundColorNum(1)
1206                         
1207         def runTest(self):
1208                 next = self.nextstep
1209                 if next == 0:
1210                         self.doStep1()
1211                 elif next == 1:
1212                         self.doStep2()
1213                 elif next == 2:
1214                         self.doStep3()
1215                 elif next == 3:
1216                         self.doStep4()
1217                 elif next == 4:
1218                         self.doStep5()
1219                 elif next == 5:
1220                         self.doStep6()
1221                 self.nextstep += 1
1222
1223         def doStep1(self):
1224                 self.steptimer = True
1225                 self.nextStepTimer.start(3000)
1226                 self["key_yellow"].setText(_("Stop test"))
1227
1228         def doStep2(self):
1229                 self["Adapter"].setText(iNetwork.getFriendlyAdapterName(self.iface))
1230                 self["Adapter"].setForegroundColorNum(2)
1231                 self["Adaptertext"].setForegroundColorNum(1)
1232                 self["AdapterInfo_Text"].setForegroundColorNum(1)
1233                 self["AdapterInfo_OK"].show()
1234                 self.steptimer = True
1235                 self.nextStepTimer.start(3000)
1236
1237         def doStep3(self):
1238                 self["Networktext"].setForegroundColorNum(1)
1239                 self["Network"].setText(_("Please wait..."))
1240                 self.AccessPointInfo(self.iface)
1241                 self["NetworkInfo_Text"].setForegroundColorNum(1)
1242                 self.steptimer = True
1243                 self.nextStepTimer.start(3000)
1244
1245         def doStep4(self):
1246                 self["Dhcptext"].setForegroundColorNum(1)
1247                 if iNetwork.getAdapterAttribute(self.iface, 'dhcp') is True:
1248                         self["Dhcp"].setForegroundColorNum(2)
1249                         self["Dhcp"].setText(_("enabled"))
1250                         self["DhcpInfo_Check"].setPixmapNum(0)
1251                 else:
1252                         self["Dhcp"].setForegroundColorNum(1)
1253                         self["Dhcp"].setText(_("disabled"))
1254                         self["DhcpInfo_Check"].setPixmapNum(1)
1255                 self["DhcpInfo_Check"].show()
1256                 self["DhcpInfo_Text"].setForegroundColorNum(1)
1257                 self.steptimer = True
1258                 self.nextStepTimer.start(3000)
1259
1260         def doStep5(self):
1261                 self["IPtext"].setForegroundColorNum(1)
1262                 self["IP"].setText(_("Please wait..."))
1263                 iNetwork.checkNetworkState(self.NetworkStatedataAvail)
1264
1265         def doStep6(self):
1266                 self.steptimer = False
1267                 self.nextStepTimer.stop()
1268                 self["DNStext"].setForegroundColorNum(1)
1269                 self["DNS"].setText(_("Please wait..."))
1270                 iNetwork.checkDNSLookup(self.DNSLookupdataAvail)
1271
1272         def KeyGreen(self):
1273                 self["shortcutsgreen"].setEnabled(False)
1274                 self["shortcutsyellow"].setEnabled(True)
1275                 self["updown_actions"].setEnabled(False)
1276                 self["key_yellow"].setText("")
1277                 self["key_green"].setText("")
1278                 self.steptimer = True
1279                 self.nextStepTimer.start(1000)
1280
1281         def KeyGreenRestart(self):
1282                 self.nextstep = 0
1283                 self.layoutFinished()
1284                 self["Adapter"].setText((""))
1285                 self["Network"].setText((""))
1286                 self["Dhcp"].setText((""))
1287                 self["IP"].setText((""))
1288                 self["DNS"].setText((""))
1289                 self["AdapterInfo_Text"].setForegroundColorNum(0)
1290                 self["NetworkInfo_Text"].setForegroundColorNum(0)
1291                 self["DhcpInfo_Text"].setForegroundColorNum(0)
1292                 self["IPInfo_Text"].setForegroundColorNum(0)
1293                 self["DNSInfo_Text"].setForegroundColorNum(0)
1294                 self["shortcutsgreen_restart"].setEnabled(False)
1295                 self["shortcutsgreen"].setEnabled(False)
1296                 self["shortcutsyellow"].setEnabled(True)
1297                 self["updown_actions"].setEnabled(False)
1298                 self["key_yellow"].setText("")
1299                 self["key_green"].setText("")
1300                 self.steptimer = True
1301                 self.nextStepTimer.start(1000)
1302
1303         def KeyOK(self):
1304                 self["infoshortcuts"].setEnabled(True)
1305                 self["shortcuts"].setEnabled(False)
1306                 if self.activebutton == 1: # Adapter Check
1307                         self["InfoText"].setText(_("This test detects your configured Wireless LAN-Adapter."))
1308                         self["InfoTextBorder"].show()
1309                         self["InfoText"].show()
1310                         self["key_red"].setText(_("Back"))
1311                 if self.activebutton == 2: #LAN Check
1312                         self["InfoText"].setText(_("This test checks whether a network cable is connected to your Wireless LAN-Adapter."))
1313                         self["InfoTextBorder"].show()
1314                         self["InfoText"].show()
1315                         self["key_red"].setText(_("Back"))
1316                 if self.activebutton == 3: #DHCP Check
1317                         self["InfoText"].setText(_("This test checks whether your Wireless LAN Adapter is set up for automatic IP Address configuration with DHCP.\nIf you get a \"disabled\" message:\n - then your Wireless LAN Adapter is configured for manual IP Setup\n- verify thay you have entered correct IP informations in the AdapterSetup dialog.\nIf you get an \"enabeld\" message:\n-verify that you have a configured and working DHCP Server in your network."))
1318                         self["InfoTextBorder"].show()
1319                         self["InfoText"].show()
1320                         self["key_red"].setText(_("Back"))
1321                 if self.activebutton == 4: # IP Check
1322                         self["InfoText"].setText(_("This test checks whether a valid IP Address is found for your LAN Adapter.\nIf you get a \"unconfirmed\" message:\n- no valid IP Address was found\n- please check your DHCP, cabling and adapter setup"))
1323                         self["InfoTextBorder"].show()
1324                         self["InfoText"].show()
1325                         self["key_red"].setText(_("Back"))
1326                 if self.activebutton == 5: # DNS Check
1327                         self["InfoText"].setText(_("This test checks for configured Nameservers.\nIf you get a \"unconfirmed\" message:\n- please check your DHCP, cabling and Adapter setup\n- if you configured your Nameservers manually please verify your entries in the \"Nameserver\" Configuration"))
1328                         self["InfoTextBorder"].show()
1329                         self["InfoText"].show()
1330                         self["key_red"].setText(_("Back"))
1331                 if self.activebutton == 6: # Edit Settings
1332                         self.cleanup()
1333                         self.session.open(WlanConfig,self.iface)
1334                         self["shortcuts"].setEnabled(True)              
1335                         self["infoshortcuts"].setEnabled(False)
1336
1337         def KeyYellow(self):
1338                 self.nextstep = 0
1339                 self["shortcutsgreen_restart"].setEnabled(True)
1340                 self["shortcutsgreen"].setEnabled(False)
1341                 self["shortcutsyellow"].setEnabled(False)
1342                 self["key_green"].setText(_("Restart test"))
1343                 self["key_yellow"].setText("")
1344                 self.steptimer = False
1345                 self.nextStepTimer.stop()
1346
1347         def layoutFinished(self):
1348                 self.setTitle(_("Network test: ") + iNetwork.getFriendlyAdapterName(self.iface) )
1349                 self["shortcutsyellow"].setEnabled(False)
1350                 self["AdapterInfo_OK"].hide()
1351                 self["NetworkInfo_Check"].hide()
1352                 self["DhcpInfo_Check"].hide()
1353                 self["IPInfo_Check"].hide()
1354                 self["DNSInfo_Check"].hide()
1355                 self["EditSettings_Text"].hide()
1356                 self["EditSettingsButton"].hide()
1357                 self["InfoText"].hide()
1358                 self["InfoTextBorder"].hide()
1359                 self["key_yellow"].setText("")
1360
1361         def setLabels(self):
1362                 self["Adaptertext"] = MultiColorLabel(_("LAN Adapter"))
1363                 self["Adapter"] = MultiColorLabel()
1364                 self["AdapterInfo"] = MultiPixmap()
1365                 self["AdapterInfo_Text"] = MultiColorLabel(_("Show Info"))
1366                 self["AdapterInfo_OK"] = Pixmap()
1367                 
1368                 if self.iface in iNetwork.wlan_interfaces:
1369                         self["Networktext"] = MultiColorLabel(_("Wireless Network"))
1370                 else:
1371                         self["Networktext"] = MultiColorLabel(_("Local Network"))
1372                 
1373                 self["Network"] = MultiColorLabel()
1374                 self["NetworkInfo"] = MultiPixmap()
1375                 self["NetworkInfo_Text"] = MultiColorLabel(_("Show Info"))
1376                 self["NetworkInfo_Check"] = MultiPixmap()
1377                 
1378                 self["Dhcptext"] = MultiColorLabel(_("DHCP"))
1379                 self["Dhcp"] = MultiColorLabel()
1380                 self["DhcpInfo"] = MultiPixmap()
1381                 self["DhcpInfo_Text"] = MultiColorLabel(_("Show Info"))
1382                 self["DhcpInfo_Check"] = MultiPixmap()
1383                 
1384                 self["IPtext"] = MultiColorLabel(_("IP Address"))
1385                 self["IP"] = MultiColorLabel()
1386                 self["IPInfo"] = MultiPixmap()
1387                 self["IPInfo_Text"] = MultiColorLabel(_("Show Info"))
1388                 self["IPInfo_Check"] = MultiPixmap()
1389                 
1390                 self["DNStext"] = MultiColorLabel(_("Nameserver"))
1391                 self["DNS"] = MultiColorLabel()
1392                 self["DNSInfo"] = MultiPixmap()
1393                 self["DNSInfo_Text"] = MultiColorLabel(_("Show Info"))
1394                 self["DNSInfo_Check"] = MultiPixmap()
1395                 
1396                 self["EditSettings_Text"] = MultiColorLabel(_("Edit settings"))
1397                 self["EditSettingsButton"] = MultiPixmap()
1398                 
1399                 self["key_red"] = StaticText(_("Close"))
1400                 self["key_green"] = StaticText(_("Start test"))
1401                 self["key_yellow"] = StaticText(_("Stop test"))
1402                 
1403                 self["InfoTextBorder"] = Pixmap()
1404                 self["InfoText"] = Label()
1405
1406         def NetworkStatedataAvail(self,data):
1407                 if data <= 2:
1408                         self["IP"].setForegroundColorNum(2)
1409                         self["IP"].setText(_("confirmed"))
1410                         self["IPInfo_Check"].setPixmapNum(0)
1411                 else:
1412                         self["IP"].setForegroundColorNum(1)
1413                         self["IP"].setText(_("unconfirmed"))
1414                         self["IPInfo_Check"].setPixmapNum(1)
1415                 self["IPInfo_Check"].show()
1416                 self["IPInfo_Text"].setForegroundColorNum(1)            
1417                 self.steptimer = True
1418                 self.nextStepTimer.start(3000)          
1419                 
1420         def DNSLookupdataAvail(self,data):
1421                 if data <= 2:
1422                         self["DNS"].setForegroundColorNum(2)
1423                         self["DNS"].setText(_("confirmed"))
1424                         self["DNSInfo_Check"].setPixmapNum(0)
1425                 else:
1426                         self["DNS"].setForegroundColorNum(1)
1427                         self["DNS"].setText(_("unconfirmed"))
1428                         self["DNSInfo_Check"].setPixmapNum(1)
1429                 self["DNSInfo_Check"].show()
1430                 self["DNSInfo_Text"].setForegroundColorNum(1)
1431                 self["EditSettings_Text"].show()
1432                 self["EditSettingsButton"].setPixmapNum(1)
1433                 self["EditSettings_Text"].setForegroundColorNum(2) # active
1434                 self["EditSettingsButton"].show()
1435                 self["key_yellow"].setText("")
1436                 self["key_green"].setText(_("Restart test"))
1437                 self["shortcutsgreen"].setEnabled(False)
1438                 self["shortcutsgreen_restart"].setEnabled(True)
1439                 self["shortcutsyellow"].setEnabled(False)
1440                 self["updown_actions"].setEnabled(True)
1441                 self.activebutton = 6
1442
1443         def getInfoCB(self,status):
1444                 if status is not None:
1445                         if status.startswith("No Connection") or status.startswith("Not-Associated") or status == False:
1446                                 self["Network"].setForegroundColorNum(1)
1447                                 self["Network"].setText(_("disconnected"))
1448                                 self["NetworkInfo_Check"].setPixmapNum(1)
1449                                 self["NetworkInfo_Check"].show()
1450                         else:
1451                                 self["Network"].setForegroundColorNum(2)
1452                                 self["Network"].setText(_("connected"))
1453                                 self["NetworkInfo_Check"].setPixmapNum(0)
1454                                 self["NetworkInfo_Check"].show()
1455                                                 
1456         def cleanup(self):
1457                 iNetwork.stopLinkStateConsole()
1458                 iNetwork.stopPingConsole()
1459                 iNetwork.stopDNSConsole()
1460
1461         def AccessPointInfo(self,iface):
1462                 cmd = "iwconfig %s"%iface
1463                 self.iwconfigConsole = Console()
1464                 self.iwconfigConsole.ePopen(cmd,self.readAP,self.getInfoCB)
1465
1466         def readAP(self,result,retval,extra_args):
1467                 (callback) = extra_args
1468                 self.apState = None
1469                 if self.iwconfigConsole is not None:
1470                         if retval == 0:
1471                                 self.iwconfigConsole = None
1472                                 for content in result.splitlines():
1473                                         if 'Access Point' in content:
1474                                                 self.apState = content.strip().split('Access Point: ')[1]
1475                                                 callback(self.apState)
1476                                                 return
1477                 callback(self.apState)
1478                 
1479 class Wlanstatus(Screen):
1480         skin =  """
1481                 <screen position="center,center" size="510,400" title="Wireless Network Status..." >
1482                         <widget source="status" render="Label" position="5,15" size="500,350" font="Regular;18" zPosition="1" />
1483
1484                         <ePixmap pixmap="skin_default/buttons/red.png" position="185,360" size="140,40" alphatest="on" />
1485                         <widget source="key_red" render="Label" position="185,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" foregroundColor="#ffffff" transparent="1" />
1486                 </screen>
1487                 """
1488         def __init__(self, session,iface):
1489                 Screen.__init__(self,session)
1490                 self.session = session
1491                 self.iface = iface
1492                 self["status"] = StaticText(_("Wait a moment..."))
1493                 self["key_red"] = StaticText(_("Close"))
1494                 self["OkCancelActions"] = ActionMap(["ShortcutActions", "SetupActions" ],
1495                 {
1496                         "ok": self.ok,
1497                         "cancel": self.close,
1498                         "red": self.close,
1499                 }, -2)
1500                 self.readstatus()
1501                 self.onClose.append(self.cleanup)
1502
1503         def readstatus(self):
1504                 self.wlanstatus = Console()
1505                 cmd1 = "iwconfig "+self.iface
1506                 self.wlanstatus.ePopen(cmd1, self.iwconfigfinnished,self.statusdisplay)
1507
1508         def iwconfigfinnished(self, result, retval,extra_args):
1509                 try:
1510                         (statecallback) = extra_args
1511                         if self.wlanstatus is not None:
1512                                 if retval == 0:
1513                                         statecallback(result)
1514                                 else:
1515                                         statecallback(0)
1516                 except:
1517                         self.close()
1518
1519
1520         def statusdisplay(self,data):
1521                 if data == 0:
1522                         self["status"].setText(_("No information..."))
1523                 else:
1524                         self["status"].setText(data)
1525
1526         def ok(self):
1527                 pass
1528
1529         def cleanup(self):
1530                 self.stopWlanStatusConsole()
1531
1532         def stopWlanStatusConsole(self):
1533                 if self.wlanstatus is not None:
1534                         if len(self.wlanstatus.appContainers):
1535                                 for name in self.wlanstatus.appContainers.keys():
1536                                         self.wlanstatus.kill(name)
1537
1538 def openconfig(session, **kwargs):
1539         session.open(WlanSelection)
1540
1541 def selSetup(menuid, **kwargs):
1542         list=[]
1543         if menuid != "system":
1544                 return [ ]
1545         else:
1546                 for x in iNetwork.getInstalledAdapters():
1547                         if x.startswith('eth'):
1548                                 continue
1549                         list.append(x)
1550                 if len(list):
1551                         return [(_("Wireless LAN Setup"), openconfig, "wlansetup_config", 80)]
1552                 else:
1553                         return [ ]
1554         return [ ]
1555
1556 def Plugins(**kwargs):
1557         return  PluginDescriptor(name=_("Wireless LAN Setup"), description="Wireless LAN Setup", where = PluginDescriptor.WHERE_MENU, fnc=selSetup)