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