cf3b83136edf1276fea53ba5902e85cf5158b78a
[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 _("Realtek")+ " " + _("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 = ConfigPassword(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.wpaphraseconsole = None
348 #               self.scanAPcount =5
349                 self.scanAPcount =1
350                 self.list = []
351                 ConfigListScreen.__init__(self, self.list,session = self.session)
352                 self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
353                 self.readWpaSupplicantConf()
354                 self.scanAPFailedTimer = eTimer()
355                 self.scanAPFailedTimer.callback.append(self.scanAPFailed)
356                 self.scanAplistTimer = eTimer()
357                 self.scanAplistTimer.callback.append(self.scanApList)
358                 self.Console = Console()
359 #               self.scanAplistTimer.start(100,True)
360                 self.updateInterfaces(self.readWlanSettings)
361                 self.onClose.append(self.cleanup)
362
363         def updateInterfaces(self,callback = None):
364                 iNetwork.config_ready = False
365                 iNetwork.msgPlugins()
366                 iNetwork.getInterfaces(callback)
367
368         def readWlanSettings(self,ret=None):
369                 if ret is not True:
370                         print "getInterfaces Fail... "
371                 if iNetwork.getAdapterAttribute(self.iface, "up") == True:
372                         default_tmp = "on"
373                 else:
374                         default_tmp = "off"
375                 wlanconfig.usedevice = ConfigSelection(default=default_tmp, choices = [("off", _("off")), ("on", _("on"))])
376
377                 if iNetwork.getAdapterAttribute(self.iface, "dhcp"):
378                         default_tmp = "on"
379                 else:
380                         default_tmp = "off"
381                 wlanconfig.usedhcp = ConfigSelection(default=default_tmp, choices = [("off", _("no")), ("on", _("yes"))])
382
383                 wlanconfig.ip = ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "ip")) or [0,0,0,0]
384
385                 wlanconfig.netmask = ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "netmask") or [255,0,0,0])
386                 if iNetwork.getAdapterAttribute(self.iface, "gateway"):
387                         default_tmp = "on"
388                 else:
389                         default_tmp = "off"
390                 wlanconfig.usegateway = ConfigSelection(default = default_tmp, choices = [("off", _("no")), ("on", _("yes"))])
391
392                 wlanconfig.gateway = ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "gateway") or [0,0,0,0])
393
394                 self["ipaddress"].setText(_(self.formatip(iNetwork.getAdapterAttribute(self.iface, "ip"))))
395                 self["netmask"].setText(_(self.formatip(iNetwork.getAdapterAttribute(self.iface, "netmask"))))
396                 self["gateway"].setText(_(self.formatip(iNetwork.getAdapterAttribute(self.iface, "gateway"))))
397
398                 if self.encryption_key is not None:
399                         default_tmp = "on"
400                 else:
401                         default_tmp = "off"
402                 wlanconfig.encrypt = ConfigSelection(default = default_tmp, choices = [("off", _("no")), ("on", _("yes"))])
403
404                 if self.key_mgmt=="NONE":
405                         default_tmp = "wep"
406                 elif self.key_mgmt == "WPA-PSK":
407                         if self.proto == "WPA":
408                                 default_tmp = "wpa"
409                         elif self.proto == "RSN":
410                                 default_tmp = "wpa2"
411                         elif self.proto in ( "WPA RSN", "WPA WPA2"):
412                                 default_tmp = "wpa/wpa2"
413                         else:
414                                 default_tmp = "wpa"
415                 else:
416                         default_tmp = "wep"
417
418                 wlanconfig.method = ConfigSelection(default = default_tmp, choices = [
419                         ("wep", _("WEP")), ("wpa", _("WPA")), ("wpa2", _("WPA2")),("wpa/wpa2", _("WPA/WPA2"))])
420
421                 if self.key_type == 0:
422                         default_tmp = "hex"
423                 else:
424                         default_tmp = "ascii"
425                 wlanconfig.keytype = ConfigSelection(default = default_tmp, choices = [
426                         ("ascii", _("ASCII")), ("hex", _("HEX"))])
427                 default_tmp = self.encryption_key or "XXXXXXXX"
428 #               default_tmp = "XXXXXXXX"
429                 wlanconfig.key = ConfigPassword(default = default_tmp, visible_width = 50, fixed_size = False)
430                 self.scanAplistTimer.start(100,True)
431
432         def readWpaSupplicantConf(self):
433                 try:
434                         if fileExists("/etc/wpa_supplicant.conf"):
435                                 wpafd = open("/etc/wpa_supplicant.conf","r")
436                                 if wpafd >0:
437                                         data = wpafd.readline()
438                                         while len(data) > 0:
439 #                                               print "####readWpaSupplicantConf, data : ",data
440                                                 data = data.lstrip()
441                                                 if len(data) == 0:
442                                                         data = wpafd.readline()
443                                                         continue
444                                                 if data.startswith('ssid=') and len(data) > 6:
445                                                         self.ssid = data[6:-2]
446                                                 elif data.startswith('ap_scan=') :
447                                                         self.ap_scan = data[8:]
448 #                                                       print "####readWpaSupplicantConf, ap_scan : ",self.ap_scan
449                                                 elif data.startswith('scan_ssid=') and len(data) > 10:
450                                                         self.scan_ssid = data[10:-1]
451                                                 elif data.startswith('key_mgmt=') and len(data) > 9:
452                                                         self.key_mgmt = data[9:-1]
453                                                 elif data.startswith('proto=') and len(data) > 6:
454                                                         self.proto = data[6:-1]
455                                                 elif data.startswith('wep_key0="') and len(data) > 11:
456                                                         self.key_type = 1 # ascii
457                                                         self.encryption_key = data[10:-2]
458                                                 elif data.startswith('wep_key0=') and len(data) > 9:
459                                                         self.key_type = 0 # hex
460                                                         self.encryption_key = data[9:-1]
461                                                 elif data.startswith('psk="') and len(data) > 6:
462                                                         self.key_type = 1 # ascii
463                                                         self.encryption_key = data[5:-2]
464                                                 elif data.startswith('#psk="') and len(data) > 6:
465                                                         self.key_type = 0 # hex
466                                                         self.encryption_key = data[6:-2]
467                                                 elif not self.encryption_key and data.startswith('psk=') and len(data) > 4:
468                                                         self.key_type = 0 # hex
469                                                         self.encryption_key = data[4:-1]
470                                                 data = wpafd.readline()
471                                         print self.ssid,self.scan_ssid,self.key_mgmt,self.proto,self.key_type,self.encryption_key
472                                         wpafd.close()
473                                 else:
474                                         print 'read error'
475                         else:
476                                 pass
477                 except:
478                         print 'failed loading wpasupplicant.conf'
479
480         def createConfig(self):
481                 self.configList=[]
482                 self.usedeviceEntry = getConfigListEntry(_("Use Device"), wlanconfig.usedevice)
483                 self.usedhcpEntry = getConfigListEntry(_("Use DHCP"), wlanconfig.usedhcp)
484                 self.essidEntry = getConfigListEntry(_("ESSID"), wlanconfig.essid)
485                 self.hiddenessidEntry = getConfigListEntry(_("Input Hidden ESSID"), wlanconfig.hiddenessid)
486                 self.encryptEntry = getConfigListEntry(_("Encrypt"), wlanconfig.encrypt)
487                 self.methodEntry = getConfigListEntry(_("Method"), wlanconfig.method)
488                 self.keytypeEntry = getConfigListEntry(_("Key Type"), wlanconfig.keytype)
489                 self.keyEntry = getConfigListEntry(_("KEY"), wlanconfig.key)
490
491                 self.ipEntry = getConfigListEntry(_("IP"), wlanconfig.ip)
492                 self.netmaskEntry = getConfigListEntry(_("NetMask"), wlanconfig.netmask)
493
494                 self.usegatewayEntry = getConfigListEntry(_("Use Gateway"), wlanconfig.usegateway)
495                 self.gatewayEntry = getConfigListEntry(_("Gateway"), wlanconfig.gateway)
496
497                 self.configList.append( self.usedeviceEntry )
498                 if wlanconfig.usedevice.value is "on":
499                         self.configList.append( self.usedhcpEntry )
500                         if wlanconfig.usedhcp.value is "off":
501                                 self.configList.append(self.ipEntry)
502                                 self.configList.append(self.netmaskEntry)
503                                 self.configList.append(self.usegatewayEntry)
504                                 if wlanconfig.usegateway.value is "on":
505                                         self.configList.append(self.gatewayEntry)
506                         self.configList.append( self.essidEntry )
507 #                       print "#### wlanconfig.essid.value : ",wlanconfig.essid.value
508                         if wlanconfig.essid.value == 'Input hidden ESSID':
509                                 self.configList.append( self.hiddenessidEntry )
510                         self.configList.append( self.encryptEntry )
511                         if wlanconfig.encrypt.value is "on" :
512                                 self.configList.append( self.methodEntry )
513                                 if wlanconfig.method.value =="wep":
514                                         self.configList.append( self.keytypeEntry )
515                                 self.configList.append( self.keyEntry )
516
517                 self["config"].list = self.configList
518                 self["config"].l.setList(self.configList)
519 #               if not self.selectionChanged in self["config"].onSelectionChanged:
520 #                       self["config"].onSelectionChanged.append(self.selectionChanged)
521
522         def scanApList(self):
523                 self.apList = []
524                 self.configurationmsg = self.session.open(MessageBox, _("Please wait for scanning AP..."), type = MessageBox.TYPE_INFO, enable_input = False)
525                 cmd = "ifconfig "+self.iface+" up"
526                 print 'cmd ',cmd
527                 os_system(cmd)
528                 self.wlanscanap = Console()
529                 cmd = "iwlist "+self.iface+" scan"
530                 print 'cmd ',cmd
531                 self.wlanscanap.ePopen(cmd, self.apListFinnished,self.apListParse)
532
533         def apListFinnished(self, result, retval,extra_args):
534                 (callback) = extra_args
535                 if self.wlanscanap is not None:
536                         if retval == 0:
537                                 self.wlanscanap = None
538                                 content = result.splitlines()
539                                 first = content[0].split()
540                                 completed = False
541                                 for x in first:
542                                         if x == 'completed':
543                                                 completed = True
544                                 if completed == True:
545                                         callback(result)
546                                 else:
547                                         callback(0)
548                         else:
549                                 callback(0)
550
551         def apListParse(self,data):
552                 global selectap
553                 if data == 0:
554                         if self.scanAPcount >0:
555                                 self.scanAPcount -=1
556                                 self.configurationmsg.close(True)
557                                 time.sleep(3)
558                                 self.scanAplistTimer.start(500,True)
559                                 return
560                         else:
561                                 self.configurationmsg.close(True)
562                                 self.scanAPFailedTimer.start(500,True)
563                                 return
564                 else:
565                         self.apList = []
566 #                       self.scanAPcount =5
567                         self.scanAPcount =0
568                         list = data.splitlines()
569                         for x in list:
570                                 xx = x.lstrip()
571                                 if xx.startswith('ESSID:') and len(xx)>8 and xx[7:-1]not in self.apList:
572                                         self.apList.append(xx[7:-1])
573                         self.apList.append('Input hidden ESSID')
574 #                       print "###### selectap : ",selectap
575                         if selectap is not None and selectap in self.apList:
576                                 wlanconfig.essid = ConfigSelection(default=selectap,choices = self.apList)
577                         elif self.ap_scan is not None and self.ap_scan.strip() == '2':
578                                 wlanconfig.essid = ConfigSelection(default='Input hidden ESSID',choices = self.apList)
579                         elif self.ssid is not None and self.ssid in self.apList:
580                                 wlanconfig.essid = ConfigSelection(default=self.ssid,choices = self.apList)
581                         else:
582                                 wlanconfig.essid = ConfigSelection(choices = self.apList)
583                         if self.ssid is not None:
584                                 wlanconfig.hiddenessid = ConfigText(default = self.ssid, visible_width = 50, fixed_size = False)
585                         else:
586                                 wlanconfig.hiddenessid = ConfigText(default = "<Input ESSID>", visible_width = 50, fixed_size = False)
587                 self.configurationmsg.close(True)
588                 self.createConfig()
589
590         def scanAPFailed(self):
591                 self.session.openWithCallback(self.keyCancel ,MessageBox, _("Scan AP Failed"), MessageBox.TYPE_ERROR,10)
592
593         def keyLeft(self):
594                 ConfigListScreen.keyLeft(self)
595                 self.newConfig()
596
597         def keyRight(self):
598                 ConfigListScreen.keyRight(self)
599                 self.newConfig()
600
601         def newConfig(self):
602                 if self["config"].getCurrent() == self.usedeviceEntry or self["config"].getCurrent() == self.encryptEntry \
603                         or self["config"].getCurrent() == self.usedhcpEntry or self["config"].getCurrent() == self.usegatewayEntry \
604                         or self["config"].getCurrent() == self.essidEntry or self["config"].getCurrent() == self.methodEntry:
605                         self.createConfig()
606
607         def saveWlanConfig(self):
608                 try:
609                         if self["config"].getCurrent() == self.keyEntry or self["config"].getCurrent() == self.hiddenessidEntry :
610                                 self["config"].getCurrent()[1].onDeselect(self.session)
611                         if self["config"].isChanged():
612                                 self.session.openWithCallback(self.checkNetworkConfig, MessageBox, (_("Are you sure you want to restart your network interfaces?\n") ) )
613                         else:
614                                 self.session.openWithCallback(self.checkNetworkConfig, MessageBox, (_("Network configuration is not changed....\n\nAre you sure you want to restart your network interfaces?\n") ) )
615                 except:
616                         pass
617
618         def checkNetworkConfig(self, ret = False):
619                 if ret == False:
620                         if self["config"].getCurrent() == self.keyEntry or self["config"].getCurrent() == self.hiddenessidEntry :
621                                 self["config"].getCurrent()[1].onSelect(self.session)
622                         return
623                 if wlanconfig.essid.value == 'Input hidden ESSID':
624                         if len(wlanconfig.hiddenessid.value) == 0:
625                                 self.session.open(MessageBox, ("PLEASE INPUT HIDDEN ESSID"), type = MessageBox.TYPE_ERROR, timeout = 10)
626                                 return
627                 if len(wlanconfig.key.value) == 0:
628                         self.session.open(MessageBox, ("PLEASE INPUT NETWORK KEY"), type = MessageBox.TYPE_ERROR, timeout = 10)
629                         return
630                 self.checkNetworkShares()
631
632 #       def checkNetworkShares(self,ret = False):
633 #               if ret == False:
634 #                       if self["config"].getCurrent() == self.keyEntry or self["config"].getCurrent() == self.hiddenessidEntry :
635 #                               self["config"].getCurrent()[1].onSelect(self.session)
636 #                       return
637         def checkNetworkShares(self):
638                 if not self.Console:
639                         self.Console = Console()
640                 cmd = "cat /proc/mounts"
641                 self.Console.ePopen(cmd, self.checkSharesFinished, self.confirmAnotherIfaces)
642
643         def checkSharesFinished(self, result, retval, extra_args):
644                 callback = extra_args
645                 print "checkMountsFinished : result : \n",result
646                 networks = ['nfs','smbfs','ncp','coda']
647                 for line in result.splitlines():
648                         split = line.strip().split(' ',3)
649                         if split[2] in networks:
650                                 self.session.open(MessageBox, ("NOT deconfiguring network interfaces :\n network shares still mounted\n"), type = MessageBox.TYPE_ERROR, timeout = 10)
651                                 callback(False)
652                                 if self["config"].getCurrent() == self.keyEntry or self["config"].getCurrent() == self.hiddenessidEntry :
653                                         self["config"].getCurrent()[1].onSelect(self.session)
654                                 return
655                 callback(True)
656
657         def confirmAnotherIfaces(self, ret = False):
658                 if ret == False:
659                         return
660                 else:
661                         num_configured_if = len(iNetwork.getConfiguredAdapters())
662                         if num_configured_if >= 1:
663                                 if num_configured_if == 1 and self.iface in iNetwork.getConfiguredAdapters():
664                                         self.getWpaPhrase(False)
665                                 else:
666                                         self.session.openWithCallback(self.getWpaPhrase, MessageBox, _("A second configured interface has been found.\n\nDo you want to disable the second network interface?"), default = True)
667                         else:
668                                 self.getWpaPhrase(False)
669
670         def getWpaPhrase(self,ret):
671                 if ret == True:
672                         configuredInterfaces = iNetwork.getConfiguredAdapters()
673                         for interface in configuredInterfaces:
674                                 if interface == self.iface:
675                                         continue
676                                 iNetwork.setAdapterAttribute(interface, "up", False)
677                                 iNetwork.deactivateInterface(interface)
678                 if wlanconfig.method.value =="wep":
679                         self.writeWpasupplicantConf("wep") # passphrasekey is not None
680                 else:
681                         if wlanconfig.essid.value == 'Input hidden ESSID':
682                                 cmd = 'wpa_passphrase %s %s' % (wlanconfig.hiddenessid.value,wlanconfig.key.value)
683                         else :
684                                 cmd = 'wpa_passphrase %s %s' % (wlanconfig.essid.value,wlanconfig.key.value)
685                         print cmd
686                         self.wpaphraseconsole = Console()
687                         self.wpaphraseconsole.ePopen(cmd, self.parseWpaPhrase, self.writeWpasupplicantConf)
688
689         def parseWpaPhrase(self, result, retval, extra_args):
690                 print "parseWpaPhrase"
691                 (writewlanconfig) = extra_args
692                 if self.wpaphraseconsole is not None:
693                         print "retval = ",retval
694                         if retval == 0:
695                                 self.wpaphraseconsole.killAll()
696                                 self.wpaphraseconsole = None
697                                 print "parseWpaPhrase result : "
698                                 print result
699                                 psk = None
700                                 for line in result.splitlines():
701                                         if line.find('ssid') == -1 and line.find('#psk=') != -1:
702                                                 plainpwd        = line
703                                         elif line.find('psk=') != -1:
704                                                 psk = line
705                                 if psk:
706                                         writewlanconfig(psk,plainpwd)
707 #                                       writewlanconfig(None)
708                                 else:
709                                         writewlanconfig(None)
710                         else:
711                                 writewlanconfig(None)
712
713         def writeWpasupplicantConf(self, passphrasekey=None,plainpwd=None):
714                 if passphrasekey:
715                         wpafd = open("/etc/wpa_supplicant.conf","w")
716                         if wpafd > 0:
717                                 contents = "#WPA Supplicant Configuration by STB\n"
718                                 contents += "ctrl_interface=/var/run/wpa_supplicant\n"
719                                 contents += "eapol_version=1\n"
720                                 contents += "fast_reauth=1\n"
721
722                                 if wlanconfig.essid.value == 'Input hidden ESSID':
723                                         contents += "ap_scan=2\n"
724                                 else :
725                                         contents += "ap_scan=1\n"
726                                 contents += "network={\n"
727                                 if wlanconfig.essid.value == 'Input hidden ESSID':
728                                         contents += "\tssid=\""+wlanconfig.hiddenessid.value+"\"\n"
729                                 else :
730                                         contents += "\tssid=\""+wlanconfig.essid.value+"\"\n"
731                                 contents += "\tscan_ssid=0\n"
732                                 if wlanconfig.encrypt.value == "on":
733                                         if wlanconfig.method.value =="wep":
734                                                 contents += "\tkey_mgmt=NONE\n"
735                                                 contents += "\twep_key0="
736                                                 if wlanconfig.keytype.value == "ascii":
737                                                         contents += "\""+wlanconfig.key.value+"\"\n"
738                                                 else:
739                                                         contents += wlanconfig.key.value+"\n"
740                                         else:
741                                                 print "plainpwd : ",plainpwd
742                                                 print "passphrasekey : ",passphrasekey
743                                                 if wlanconfig.method.value == "wpa":
744                                                         contents += "\tkey_mgmt=WPA-PSK\n"
745                                                         contents += "\tproto=WPA\n"
746                                                         contents += "\tpairwise=CCMP TKIP\n"
747                                                         contents += "\tgroup=CCMP TKIP\n"       
748                                                 elif wlanconfig.method.value == "wpa2":
749                                                         contents += "\tkey_mgmt=WPA-PSK\n"
750                                                         contents += "\tproto=RSN\n"
751                                                         contents += "\tpairwise=CCMP TKIP\n"
752                                                         contents += "\tgroup=CCMP TKIP\n"
753                                                 else:
754                                                         contents += "\tkey_mgmt=WPA-PSK\n"
755                                                         contents += "\tproto=WPA RSN\n"
756                                                         contents += "\tpairwise=CCMP TKIP\n"
757                                                         contents += "\tgroup=CCMP TKIP\n"
758                                                 contents += plainpwd+"\n"
759                                                 contents += passphrasekey+"\n"
760                                 else:
761                                         contents += "\tkey_mgmt=NONE\n"
762                                 contents += "}\n"
763                                 print "content = \n"+contents
764                                 wpafd.write(contents)
765                                 wpafd.close()
766                                 self.writeNetConfig(0)
767                         else :
768                                 self.session.open(MessageBox, _("wpa_supplicant.conf open error."), type = MessageBox.TYPE_ERROR, timeout = 10)
769                                 self.writeNetConfig(-1)
770                 else:
771                         self.writeNetConfig(-2)
772
773         def writeNetConfig(self,ret = -1):
774                 if ret == -1:
775                         self.session.open(MessageBox, _("wpa_supplicant.conf open error."), type = MessageBox.TYPE_ERROR, timeout = 10)
776                         return
777                 elif ret == -2:
778                         self.session.open(MessageBox, _("Can NOT generate passphrase"), type = MessageBox.TYPE_ERROR, timeout = 10)
779                         return
780
781                 if wlanconfig.usedevice.value=="on":
782                         iNetwork.setAdapterAttribute(self.iface, "up", True)
783                         if wlanconfig.usedhcp.value =="on":
784                                 iNetwork.setAdapterAttribute(self.iface, "dhcp", True)
785                         else:
786                                 iNetwork.setAdapterAttribute(self.iface, "dhcp", False)
787                                 iNetwork.setAdapterAttribute(self.iface, "ip", wlanconfig.ip.value)
788                                 iNetwork.setAdapterAttribute(self.iface, "netmask", wlanconfig.netmask.value)
789                                 if wlanconfig.usegateway.value == "on":
790                                         iNetwork.setAdapterAttribute(self.iface, "gateway", wlanconfig.gateway.value)
791                 else:
792                         iNetwork.setAdapterAttribute(self.iface, "up", False)
793                         iNetwork.deactivateInterface(self.iface)
794                 contents = "\tpre-up wpa_supplicant -i"+self.iface+" -c/etc/wpa_supplicant.conf -B -D"+iNetwork.detectWlanModule(self.iface)+"\n"
795                 contents += "\tpost-down wpa_cli terminate\n\n"
796                 iNetwork.setAdapterAttribute(self.iface, "configStrings", contents)
797                 iNetwork.writeNetworkConfig()
798                 iNetwork.restartNetwork(self.updateCurrentInterfaces)
799                 self.configurationmsg = None
800                 self.configurationmsg = self.session.openWithCallback(self.configFinished, MessageBox, _("Please wait for activation of your network configuration..."), type = MessageBox.TYPE_INFO, enable_input = False)
801
802
803         def updateCurrentInterfaces(self,ret):
804                 if ret is True:
805                         iNetwork.getInterfaces(self.configurationMsgClose)
806
807         def configurationMsgClose(self,ret):
808                 if ret is True and self.configurationmsg is not None:
809                         self.configurationmsg.close(True)
810
811         def configFinished(self,data):
812                 global selectap
813                 if data is True:
814                         self.session.openWithCallback(self.configFinishedCB, MessageBox, _("Your network configuration has been activated."), type = MessageBox.TYPE_INFO, timeout = 10)
815                         selectap = wlanconfig.essid.value
816
817         def configFinishedCB(self,data):
818                 if data is not None:
819                         if data is True:
820                                 self.close()
821         
822         def formatip(self, iplist):
823                 list = []
824                 list = iplist
825 #               print "iplist : ",iplist
826                 try:
827                         if len(iplist) == 4:
828                                 result = str(iplist[0])+"."+str(iplist[1])+"."+str(iplist[2])+"."+str(iplist[3])
829                         else:
830                                 result ="0.0.0.0"
831 #                       print "result : ",result
832                         return result
833                 except:
834                         return "[N/A]"
835                         
836         def keyCancelConfirm(self, result):
837                 if not result:
838                         return
839                 if self.oldInterfaceState is False:
840                         iNetwork.setAdapterAttribute(self.iface, "up", False)
841                         iNetwork.deactivateInterface(self.iface,self.keyCancelCB)
842                 else:
843                         self.close()
844
845         def keyCancel(self,yesno = True):
846                 if self["config"].isChanged():
847                         self.session.openWithCallback(self.keyCancelConfirm, MessageBox, _("Really close without saving settings?"))
848                 else:
849                         self.keyCancelConfirm(True)
850
851         def keyCancelCB(self,data):
852                 if data is not None:
853                         if data is True:
854                                 self.close()
855
856         def cleanup(self):
857                 iNetwork.stopRestartConsole()
858                 iNetwork.stopGetInterfacesConsole()
859                 iNetwork.stopDeactivateInterfaceConsole()
860                 self.stopwlanscanapConsole()
861                 self.stopCheckNetworkSharesConsole()
862                 self.stopWpaPhraseConsole()
863
864         def stopwlanscanapConsole(self):
865                 if self.wlanscanap is not None:
866                         if len(self.wlanscanap.appContainers):
867                                 for name in self.wlanscanap.appContainers.keys():
868                                         self.wlanscanap.kill(name)
869
870         def stopCheckNetworkSharesConsole(self):
871                 if self.Console is not None:
872                         if len(self.Console.appContainers):
873                                 for name in self.Console.appContainers.keys():
874                                         self.Console.kill(name)
875
876         def stopWpaPhraseConsole(self):
877                 if self.wpaphraseconsole is not None:
878                         if len(self.wpaphraseconsole.appContainers):
879                                         for name in self.wpaphraseconsole.appContainers.keys():
880                                                 self.wpaphraseconsole.kill(name)
881
882 class WlanScanAp(Screen,HelpableScreen):
883         skin = """
884         <screen name="WlanScanAp" position="209,48" size="865,623" title="Wireless Network Configuration..." flags="wfNoBorder" backgroundColor="transparent">
885                 <ePixmap pixmap="Vu_HD/Bg_EPG_view.png" zPosition="-1" position="0,0" size="865,623" alphatest="on" />
886                 <ePixmap pixmap="Vu_HD/menu/ico_title_Setup.png" position="32,41" size="40,40" alphatest="blend"  transparent="1" />
887                 <eLabel text="Wireless Network AP Scan..." position="90,50" size="600,32" font="Semiboldit;32" foregroundColor="#5d5d5d" backgroundColor="#27b5b9bd" transparent="1" />
888                 <ePixmap pixmap="Vu_HD/icons/clock.png" position="750,55" zPosition="1" size="20,20" alphatest="blend" />
889                 <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">
890                         <convert type="ClockToText">Format:%H:%M</convert>
891                 </widget>
892                 <ePixmap pixmap="Vu_HD/buttons/red.png" position="45,98" size="25,25" alphatest="blend" />
893                 <ePixmap pixmap="Vu_HD/buttons/green.png" position="240,98" size="25,25" alphatest="blend" />
894                 <ePixmap pixmap="Vu_HD/buttons/blue.png" position="630,98" size="25,25" alphatest="blend" />
895                 <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" />
896                 <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" />
897                 <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" />
898                 <ePixmap pixmap="Vu_HD/border_menu.png" position="120,140" zPosition="-1" size="342,358" transparent="1" alphatest="blend" />
899                 <widget name="menulist" position="130,150" size="322,338" transparent="1" backgroundColor="#27d9dee2" zPosition="10" scrollbarMode="showOnDemand" />
900                 <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" />               
901                 <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" />
902                 <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" />      
903                 <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" />     
904                 <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" />        
905                 <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" />
906         </screen>"""
907
908         def __init__(self, session, iface):
909                 Screen.__init__(self,session)
910                 HelpableScreen.__init__(self)
911                 self.session = session
912                 self.iface = iface
913                 self.wlanscanap = None
914 #               self.scanAPcount = 5
915                 self.scanAPcount = 1
916                 self.apList = {}
917                 self.SetApList = []
918
919                 self["WizardActions"] = HelpableActionMap(self, "WizardActions",
920                 {
921                         "up": (self.up, _("move up to previous entry")),
922                         "down": (self.down, _("move down to next entry")),
923                         "left": (self.left, _("move up to first entry")),
924                         "right": (self.right, _("move down to last entry")),
925                 })
926
927                 self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
928                 {
929                         "cancel": (self.close, _("exit")),
930                         "ok": (self.ok, "select AP"),
931                 })
932
933                 self["ColorActions"] = HelpableActionMap(self, "ColorActions",
934                 {
935                         "red": (self.close, _("exit")),
936                         "green": (self.ok, "select AP"),
937                         "blue": (self.startWlanConfig, "Edit Wireless settings"),
938                 })
939
940                 self["actions"] = NumberActionMap(["WizardActions","ShortcutActions"],
941                 {
942                         "ok": self.ok,
943                         "back": self.close,
944                         "up": self.up,
945                         "down": self.down,
946                         "red": self.close,
947                         "left": self.left,
948                         "right": self.right,
949                 }, -2)
950
951                 self["menulist"] = MenuList(self.SetApList)
952                 self["key_red"] = StaticText(_("Close"))
953                 self["key_green"] = StaticText(_("Select"))
954                 self["key_blue"] = StaticText(_("EditSetting"))
955                 self["Address"] = StaticText(_("Scanning AP List.."))
956                 self["ESSID"] = StaticText(_("Wait a moment"))
957                 self["Protocol"] = StaticText(" ")
958                 self["Frequency"] = StaticText(" ")
959                 self["Encryption key"] = StaticText(" ")
960                 self["BitRate"] = StaticText(" ")
961                 self.scanAPFailedTimer = eTimer()
962                 self.scanAPFailedTimer.callback.append(self.scanAPFailed)
963                 self.scanAplistTimer = eTimer()
964                 self.scanAplistTimer.callback.append(self.scanApList)
965                 self.scanAplistTimer.start(100,True)
966                 self.onClose.append(self.cleanup)
967                 
968         def left(self):
969                 self["menulist"].pageUp()
970                 self.displayApInfo()
971         
972         def right(self):
973                 self["menulist"].pageDown()
974                 self.displayApInfo()
975
976         def up(self):
977                 self["menulist"].up()
978                 self.displayApInfo()
979                 
980         def down(self):
981                 self["menulist"].down()
982                 self.displayApInfo()
983
984         def ok(self):
985                 global selectap
986                 selectAp=self["menulist"].getCurrent()[0]
987                 selectap = selectAp
988                 self.close()
989
990         def startWlanConfig(self):
991                 global selectap
992                 selectAp=self["menulist"].getCurrent()[0]
993                 selectap = selectAp
994                 self.cleanup()
995                 self.session.open(WlanConfig,self.iface)
996 #               self.close()
997
998         def scanApList(self):
999         #       print "self.scanAPcount : ",self.scanAPcount
1000                 self.apList = {}
1001                 self.SetApList = []
1002                 self.configurationmsg = self.session.open(MessageBox, _("Please wait for scanning AP..."), type = MessageBox.TYPE_INFO, enable_input = False)
1003                 os_system('ifconfig '+self.iface+" up")
1004                 self.wlanscanap = Console()
1005                 cmd = "iwlist "+self.iface+" scan"
1006                 print cmd
1007                 self.wlanscanap.ePopen(cmd, self.iwlistfinnished,self.APListParse)
1008
1009         def iwlistfinnished(self, result, retval,extra_args):
1010 #               print "iwlistfinnished"
1011                 (statecallback) = extra_args
1012                 if self.wlanscanap is not None:
1013 #                       print "retval = ",retval
1014                         if retval == 0:
1015                                 self.wlanscanap = None
1016                                 content = result.splitlines()
1017                                 first = content[0].split()
1018                                 completed = False
1019                                 for x in first:
1020                                         if x == 'completed':
1021                                                 completed = True
1022                                 if completed == True:
1023                                         statecallback(result)
1024                                 else:
1025                                         statecallback(0)
1026                         else:
1027                                 statecallback(0)
1028
1029         def APListParse(self,data):
1030                 if data == 0:
1031                         if self.scanAPcount >0:
1032                                 self.scanAPcount -=1
1033                                 self.configurationmsg.close(True)
1034                                 time.sleep(3)
1035                                 self.scanAplistTimer.start(500,True)
1036                                 return
1037                         else:
1038                                 self.configurationmsg.close(True)
1039                                 self.scanAPFailedTimer.start(500,True)
1040                                 return
1041                 else:
1042 #                       print data
1043                         self.apList = {}
1044 #                       self.scanAPcount =5
1045                         self.scanAPcount =0
1046                         list = data.splitlines()
1047                         for line in list:
1048 #                               print "line : ",line
1049                                 if line.strip().startswith("Cell"): #  Cell 01 - Address: 00:26:66:5C:EF:24
1050                                         parts = line.strip().split(" ")
1051                                         current_ap_id = int(parts[1])
1052                                         self.apList[current_ap_id]={}
1053                                         self.apList[current_ap_id]["Address"]=parts[4]
1054                                 elif line.strip().startswith("ESSID"):
1055                                         self.apList[current_ap_id]["ESSID"]=line.strip()[6:].strip('"')
1056                                         self.SetApList.append( (self.apList[current_ap_id]["ESSID"],current_ap_id) )
1057                                 elif line.strip().startswith("Protocol"):
1058                                         self.apList[current_ap_id]["Protocol"]=line.strip()[9:]
1059                                 elif line.strip().startswith("Frequency"):
1060                                         self.apList[current_ap_id]["Frequency"]=line.strip()[10:]
1061                                 elif line.strip().startswith("Encryption key"):
1062                                         self.apList[current_ap_id]["Encryption key"]=line.strip()[15:]
1063                                 elif line.strip().startswith("Bit Rates"):
1064                                         self.apList[current_ap_id]["BitRate"]=line.strip()[10:]
1065                         print self.apList
1066                         print len(self.apList)
1067                 self.configurationmsg.close(True)
1068                 self.displayApInfo()
1069
1070         def scanAPFailed(self):
1071                 self.session.openWithCallback(self.ScanAPclose,MessageBox, _("Scan AP Failed"), MessageBox.TYPE_ERROR,10)
1072
1073         def displayApInfo(self):
1074                 if len(self.apList) >0:
1075                         self["menulist"].setList(self.SetApList)
1076                         index = self["menulist"].getCurrent()[1]
1077                         for key in ["Address", "ESSID", "Protocol", "Frequency", "Encryption key", "BitRate"]:
1078                                 if self.apList[index].has_key(key):
1079                                         self[key].setText((key+":  "+self.apList[index][key]))
1080                                 else:
1081                                         self[key].setText(("None"))
1082                 else:
1083                         self.session.openWithCallback(self.ScanAPclose, MessageBox, _("No AP detected."), type = MessageBox.TYPE_INFO, timeout = 10)
1084
1085         def ScanAPclose(self,data):
1086                 self.close()
1087
1088         def cleanup(self):
1089                 self.stopwlanscanapConsole()
1090
1091         def stopwlanscanapConsole(self):
1092                 if self.wlanscanap is not None:
1093                         if len(self.wlanscanap.appContainers):
1094                                 for name in self.wlanscanap.appContainers.keys():
1095                                         self.wlanscanap.kill(name)
1096
1097 class NetworkAdapterTest(Screen):
1098         def __init__(self, session,iface):
1099                 Screen.__init__(self, session)
1100                 self.iface = iface
1101                 self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
1102                 self.setLabels()
1103                 self.onClose.append(self.cleanup)
1104                 self.onHide.append(self.cleanup)
1105                 
1106                 self["updown_actions"] = NumberActionMap(["WizardActions","ShortcutActions"],
1107                 {
1108                         "ok": self.KeyOK,
1109                         "blue": self.KeyOK,
1110                         "up": lambda: self.updownhandler('up'),
1111                         "down": lambda: self.updownhandler('down'),
1112                 
1113                 }, -2)
1114                 
1115                 self["shortcuts"] = ActionMap(["ShortcutActions","WizardActions"],
1116                 {
1117                         "red": self.cancel,
1118                         "back": self.cancel,
1119                 }, -2)
1120                 self["infoshortcuts"] = ActionMap(["ShortcutActions","WizardActions"],
1121                 {
1122                         "red": self.closeInfo,
1123                         "back": self.closeInfo,
1124                 }, -2)
1125                 self["shortcutsgreen"] = ActionMap(["ShortcutActions"],
1126                 {
1127                         "green": self.KeyGreen,
1128                 }, -2)
1129                 self["shortcutsgreen_restart"] = ActionMap(["ShortcutActions"],
1130                 {
1131                         "green": self.KeyGreenRestart,
1132                 }, -2)
1133                 self["shortcutsyellow"] = ActionMap(["ShortcutActions"],
1134                 {
1135                         "yellow": self.KeyYellow,
1136                 }, -2)
1137                 
1138                 self["shortcutsgreen_restart"].setEnabled(False)
1139                 self["updown_actions"].setEnabled(False)
1140                 self["infoshortcuts"].setEnabled(False)
1141                 self.onClose.append(self.delTimer)      
1142                 self.onLayoutFinish.append(self.layoutFinished)
1143                 self.steptimer = False
1144                 self.nextstep = 0
1145                 self.activebutton = 0
1146                 self.nextStepTimer = eTimer()
1147                 self.nextStepTimer.callback.append(self.nextStepTimerFire)
1148
1149         def cancel(self):
1150                 if self.oldInterfaceState is False:
1151                         iNetwork.setAdapterAttribute(self.iface, "up", self.oldInterfaceState)
1152                         iNetwork.deactivateInterface(self.iface)
1153                 self.close()
1154
1155         def closeInfo(self):
1156                 self["shortcuts"].setEnabled(True)              
1157                 self["infoshortcuts"].setEnabled(False)
1158                 self["InfoText"].hide()
1159                 self["InfoTextBorder"].hide()
1160                 self["key_red"].setText(_("Close"))
1161
1162         def delTimer(self):
1163                 del self.steptimer
1164                 del self.nextStepTimer
1165
1166         def nextStepTimerFire(self):
1167                 self.nextStepTimer.stop()
1168                 self.steptimer = False
1169                 self.runTest()
1170
1171         def updownhandler(self,direction):
1172                 if direction == 'up':
1173                         if self.activebutton >=2:
1174                                 self.activebutton -= 1
1175                         else:
1176                                 self.activebutton = 6
1177                         self.setActiveButton(self.activebutton)
1178                 if direction == 'down':
1179                         if self.activebutton <=5:
1180                                 self.activebutton += 1
1181                         else:
1182                                 self.activebutton = 1
1183                         self.setActiveButton(self.activebutton)
1184
1185         def setActiveButton(self,button):
1186                 if button == 1:
1187                         self["EditSettingsButton"].setPixmapNum(0)
1188                         self["EditSettings_Text"].setForegroundColorNum(0)
1189                         self["NetworkInfo"].setPixmapNum(0)
1190                         self["NetworkInfo_Text"].setForegroundColorNum(1)
1191                         self["AdapterInfo"].setPixmapNum(1)               # active
1192                         self["AdapterInfo_Text"].setForegroundColorNum(2) # active
1193                 if button == 2:
1194                         self["AdapterInfo_Text"].setForegroundColorNum(1)
1195                         self["AdapterInfo"].setPixmapNum(0)
1196                         self["DhcpInfo"].setPixmapNum(0)
1197                         self["DhcpInfo_Text"].setForegroundColorNum(1)
1198                         self["NetworkInfo"].setPixmapNum(1)               # active
1199                         self["NetworkInfo_Text"].setForegroundColorNum(2) # active
1200                 if button == 3:
1201                         self["NetworkInfo"].setPixmapNum(0)
1202                         self["NetworkInfo_Text"].setForegroundColorNum(1)
1203                         self["IPInfo"].setPixmapNum(0)
1204                         self["IPInfo_Text"].setForegroundColorNum(1)
1205                         self["DhcpInfo"].setPixmapNum(1)                  # active
1206                         self["DhcpInfo_Text"].setForegroundColorNum(2)    # active
1207                 if button == 4:
1208                         self["DhcpInfo"].setPixmapNum(0)
1209                         self["DhcpInfo_Text"].setForegroundColorNum(1)
1210                         self["DNSInfo"].setPixmapNum(0)
1211                         self["DNSInfo_Text"].setForegroundColorNum(1)
1212                         self["IPInfo"].setPixmapNum(1)                  # active
1213                         self["IPInfo_Text"].setForegroundColorNum(2)    # active                
1214                 if button == 5:
1215                         self["IPInfo"].setPixmapNum(0)
1216                         self["IPInfo_Text"].setForegroundColorNum(1)
1217                         self["EditSettingsButton"].setPixmapNum(0)
1218                         self["EditSettings_Text"].setForegroundColorNum(0)
1219                         self["DNSInfo"].setPixmapNum(1)                 # active
1220                         self["DNSInfo_Text"].setForegroundColorNum(2)   # active
1221                 if button == 6:
1222                         self["DNSInfo"].setPixmapNum(0)
1223                         self["DNSInfo_Text"].setForegroundColorNum(1)
1224                         self["EditSettingsButton"].setPixmapNum(1)         # active
1225                         self["EditSettings_Text"].setForegroundColorNum(2) # active
1226                         self["AdapterInfo"].setPixmapNum(0)
1227                         self["AdapterInfo_Text"].setForegroundColorNum(1)
1228                         
1229         def runTest(self):
1230                 next = self.nextstep
1231                 if next == 0:
1232                         self.doStep1()
1233                 elif next == 1:
1234                         self.doStep2()
1235                 elif next == 2:
1236                         self.doStep3()
1237                 elif next == 3:
1238                         self.doStep4()
1239                 elif next == 4:
1240                         self.doStep5()
1241                 elif next == 5:
1242                         self.doStep6()
1243                 self.nextstep += 1
1244
1245         def doStep1(self):
1246                 self.steptimer = True
1247                 self.nextStepTimer.start(3000)
1248                 self["key_yellow"].setText(_("Stop test"))
1249
1250         def doStep2(self):
1251                 self["Adapter"].setText(iNetwork.getFriendlyAdapterName(self.iface))
1252                 self["Adapter"].setForegroundColorNum(2)
1253                 self["Adaptertext"].setForegroundColorNum(1)
1254                 self["AdapterInfo_Text"].setForegroundColorNum(1)
1255                 self["AdapterInfo_OK"].show()
1256                 self.steptimer = True
1257                 self.nextStepTimer.start(3000)
1258
1259         def doStep3(self):
1260                 self["Networktext"].setForegroundColorNum(1)
1261                 self["Network"].setText(_("Please wait..."))
1262                 self.AccessPointInfo(self.iface)
1263                 self["NetworkInfo_Text"].setForegroundColorNum(1)
1264                 self.steptimer = True
1265                 self.nextStepTimer.start(3000)
1266
1267         def doStep4(self):
1268                 self["Dhcptext"].setForegroundColorNum(1)
1269                 if iNetwork.getAdapterAttribute(self.iface, 'dhcp') is True:
1270                         self["Dhcp"].setForegroundColorNum(2)
1271                         self["Dhcp"].setText(_("enabled"))
1272                         self["DhcpInfo_Check"].setPixmapNum(0)
1273                 else:
1274                         self["Dhcp"].setForegroundColorNum(1)
1275                         self["Dhcp"].setText(_("disabled"))
1276                         self["DhcpInfo_Check"].setPixmapNum(1)
1277                 self["DhcpInfo_Check"].show()
1278                 self["DhcpInfo_Text"].setForegroundColorNum(1)
1279                 self.steptimer = True
1280                 self.nextStepTimer.start(3000)
1281
1282         def doStep5(self):
1283                 self["IPtext"].setForegroundColorNum(1)
1284                 self["IP"].setText(_("Please wait..."))
1285                 iNetwork.checkNetworkState(self.NetworkStatedataAvail)
1286
1287         def doStep6(self):
1288                 self.steptimer = False
1289                 self.nextStepTimer.stop()
1290                 self["DNStext"].setForegroundColorNum(1)
1291                 self["DNS"].setText(_("Please wait..."))
1292                 iNetwork.checkDNSLookup(self.DNSLookupdataAvail)
1293
1294         def KeyGreen(self):
1295                 self["shortcutsgreen"].setEnabled(False)
1296                 self["shortcutsyellow"].setEnabled(True)
1297                 self["updown_actions"].setEnabled(False)
1298                 self["key_yellow"].setText("")
1299                 self["key_green"].setText("")
1300                 self.steptimer = True
1301                 self.nextStepTimer.start(1000)
1302
1303         def KeyGreenRestart(self):
1304                 self.nextstep = 0
1305                 self.layoutFinished()
1306                 self["Adapter"].setText((""))
1307                 self["Network"].setText((""))
1308                 self["Dhcp"].setText((""))
1309                 self["IP"].setText((""))
1310                 self["DNS"].setText((""))
1311                 self["AdapterInfo_Text"].setForegroundColorNum(0)
1312                 self["NetworkInfo_Text"].setForegroundColorNum(0)
1313                 self["DhcpInfo_Text"].setForegroundColorNum(0)
1314                 self["IPInfo_Text"].setForegroundColorNum(0)
1315                 self["DNSInfo_Text"].setForegroundColorNum(0)
1316                 self["shortcutsgreen_restart"].setEnabled(False)
1317                 self["shortcutsgreen"].setEnabled(False)
1318                 self["shortcutsyellow"].setEnabled(True)
1319                 self["updown_actions"].setEnabled(False)
1320                 self["key_yellow"].setText("")
1321                 self["key_green"].setText("")
1322                 self.steptimer = True
1323                 self.nextStepTimer.start(1000)
1324
1325         def KeyOK(self):
1326                 self["infoshortcuts"].setEnabled(True)
1327                 self["shortcuts"].setEnabled(False)
1328                 if self.activebutton == 1: # Adapter Check
1329                         self["InfoText"].setText(_("This test detects your configured Wireless LAN-Adapter."))
1330                         self["InfoTextBorder"].show()
1331                         self["InfoText"].show()
1332                         self["key_red"].setText(_("Back"))
1333                 if self.activebutton == 2: #LAN Check
1334                         self["InfoText"].setText(_("This test checks whether a network cable is connected to your Wireless LAN-Adapter."))
1335                         self["InfoTextBorder"].show()
1336                         self["InfoText"].show()
1337                         self["key_red"].setText(_("Back"))
1338                 if self.activebutton == 3: #DHCP Check
1339                         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."))
1340                         self["InfoTextBorder"].show()
1341                         self["InfoText"].show()
1342                         self["key_red"].setText(_("Back"))
1343                 if self.activebutton == 4: # IP Check
1344                         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"))
1345                         self["InfoTextBorder"].show()
1346                         self["InfoText"].show()
1347                         self["key_red"].setText(_("Back"))
1348                 if self.activebutton == 5: # DNS Check
1349                         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"))
1350                         self["InfoTextBorder"].show()
1351                         self["InfoText"].show()
1352                         self["key_red"].setText(_("Back"))
1353                 if self.activebutton == 6: # Edit Settings
1354                         self.cleanup()
1355                         self.session.open(WlanConfig,self.iface)
1356                         self["shortcuts"].setEnabled(True)              
1357                         self["infoshortcuts"].setEnabled(False)
1358
1359         def KeyYellow(self):
1360                 self.nextstep = 0
1361                 self["shortcutsgreen_restart"].setEnabled(True)
1362                 self["shortcutsgreen"].setEnabled(False)
1363                 self["shortcutsyellow"].setEnabled(False)
1364                 self["key_green"].setText(_("Restart test"))
1365                 self["key_yellow"].setText("")
1366                 self.steptimer = False
1367                 self.nextStepTimer.stop()
1368
1369         def layoutFinished(self):
1370                 self.setTitle(_("Network test: ") + iNetwork.getFriendlyAdapterName(self.iface) )
1371                 self["shortcutsyellow"].setEnabled(False)
1372                 self["AdapterInfo_OK"].hide()
1373                 self["NetworkInfo_Check"].hide()
1374                 self["DhcpInfo_Check"].hide()
1375                 self["IPInfo_Check"].hide()
1376                 self["DNSInfo_Check"].hide()
1377                 self["EditSettings_Text"].hide()
1378                 self["EditSettingsButton"].hide()
1379                 self["InfoText"].hide()
1380                 self["InfoTextBorder"].hide()
1381                 self["key_yellow"].setText("")
1382
1383         def setLabels(self):
1384                 self["Adaptertext"] = MultiColorLabel(_("LAN Adapter"))
1385                 self["Adapter"] = MultiColorLabel()
1386                 self["AdapterInfo"] = MultiPixmap()
1387                 self["AdapterInfo_Text"] = MultiColorLabel(_("Show Info"))
1388                 self["AdapterInfo_OK"] = Pixmap()
1389                 
1390                 if self.iface in iNetwork.wlan_interfaces:
1391                         self["Networktext"] = MultiColorLabel(_("Wireless Network"))
1392                 else:
1393                         self["Networktext"] = MultiColorLabel(_("Local Network"))
1394                 
1395                 self["Network"] = MultiColorLabel()
1396                 self["NetworkInfo"] = MultiPixmap()
1397                 self["NetworkInfo_Text"] = MultiColorLabel(_("Show Info"))
1398                 self["NetworkInfo_Check"] = MultiPixmap()
1399                 
1400                 self["Dhcptext"] = MultiColorLabel(_("DHCP"))
1401                 self["Dhcp"] = MultiColorLabel()
1402                 self["DhcpInfo"] = MultiPixmap()
1403                 self["DhcpInfo_Text"] = MultiColorLabel(_("Show Info"))
1404                 self["DhcpInfo_Check"] = MultiPixmap()
1405                 
1406                 self["IPtext"] = MultiColorLabel(_("IP Address"))
1407                 self["IP"] = MultiColorLabel()
1408                 self["IPInfo"] = MultiPixmap()
1409                 self["IPInfo_Text"] = MultiColorLabel(_("Show Info"))
1410                 self["IPInfo_Check"] = MultiPixmap()
1411                 
1412                 self["DNStext"] = MultiColorLabel(_("Nameserver"))
1413                 self["DNS"] = MultiColorLabel()
1414                 self["DNSInfo"] = MultiPixmap()
1415                 self["DNSInfo_Text"] = MultiColorLabel(_("Show Info"))
1416                 self["DNSInfo_Check"] = MultiPixmap()
1417                 
1418                 self["EditSettings_Text"] = MultiColorLabel(_("Edit settings"))
1419                 self["EditSettingsButton"] = MultiPixmap()
1420                 
1421                 self["key_red"] = StaticText(_("Close"))
1422                 self["key_green"] = StaticText(_("Start test"))
1423                 self["key_yellow"] = StaticText(_("Stop test"))
1424                 
1425                 self["InfoTextBorder"] = Pixmap()
1426                 self["InfoText"] = Label()
1427
1428         def NetworkStatedataAvail(self,data):
1429                 if data <= 2:
1430                         self["IP"].setForegroundColorNum(2)
1431                         self["IP"].setText(_("confirmed"))
1432                         self["IPInfo_Check"].setPixmapNum(0)
1433                 else:
1434                         self["IP"].setForegroundColorNum(1)
1435                         self["IP"].setText(_("unconfirmed"))
1436                         self["IPInfo_Check"].setPixmapNum(1)
1437                 self["IPInfo_Check"].show()
1438                 self["IPInfo_Text"].setForegroundColorNum(1)            
1439                 self.steptimer = True
1440                 self.nextStepTimer.start(3000)          
1441                 
1442         def DNSLookupdataAvail(self,data):
1443                 if data <= 2:
1444                         self["DNS"].setForegroundColorNum(2)
1445                         self["DNS"].setText(_("confirmed"))
1446                         self["DNSInfo_Check"].setPixmapNum(0)
1447                 else:
1448                         self["DNS"].setForegroundColorNum(1)
1449                         self["DNS"].setText(_("unconfirmed"))
1450                         self["DNSInfo_Check"].setPixmapNum(1)
1451                 self["DNSInfo_Check"].show()
1452                 self["DNSInfo_Text"].setForegroundColorNum(1)
1453                 self["EditSettings_Text"].show()
1454                 self["EditSettingsButton"].setPixmapNum(1)
1455                 self["EditSettings_Text"].setForegroundColorNum(2) # active
1456                 self["EditSettingsButton"].show()
1457                 self["key_yellow"].setText("")
1458                 self["key_green"].setText(_("Restart test"))
1459                 self["shortcutsgreen"].setEnabled(False)
1460                 self["shortcutsgreen_restart"].setEnabled(True)
1461                 self["shortcutsyellow"].setEnabled(False)
1462                 self["updown_actions"].setEnabled(True)
1463                 self.activebutton = 6
1464
1465         def getInfoCB(self,status):
1466                 if status is not None:
1467                         if status.startswith("No Connection") or status.startswith("Not-Associated") or status == False:
1468                                 self["Network"].setForegroundColorNum(1)
1469                                 self["Network"].setText(_("disconnected"))
1470                                 self["NetworkInfo_Check"].setPixmapNum(1)
1471                                 self["NetworkInfo_Check"].show()
1472                         else:
1473                                 self["Network"].setForegroundColorNum(2)
1474                                 self["Network"].setText(_("connected"))
1475                                 self["NetworkInfo_Check"].setPixmapNum(0)
1476                                 self["NetworkInfo_Check"].show()
1477                                                 
1478         def cleanup(self):
1479                 iNetwork.stopLinkStateConsole()
1480                 iNetwork.stopPingConsole()
1481                 iNetwork.stopDNSConsole()
1482
1483         def AccessPointInfo(self,iface):
1484                 cmd = "iwconfig %s"%iface
1485                 self.iwconfigConsole = Console()
1486                 self.iwconfigConsole.ePopen(cmd,self.readAP,self.getInfoCB)
1487
1488         def readAP(self,result,retval,extra_args):
1489                 (callback) = extra_args
1490                 self.apState = None
1491                 if self.iwconfigConsole is not None:
1492                         if retval == 0:
1493                                 self.iwconfigConsole = None
1494                                 for content in result.splitlines():
1495                                         if 'Access Point' in content:
1496                                                 self.apState = content.strip().split('Access Point: ')[1]
1497                                                 callback(self.apState)
1498                                                 return
1499                 callback(self.apState)
1500                 
1501 class Wlanstatus(Screen):
1502         skin = """
1503         <screen name="Wlanstatus" position="209,48" size="865,623" title="Wireless Network Configuration..." flags="wfNoBorder" backgroundColor="transparent">
1504                 <ePixmap pixmap="Vu_HD/Bg_EPG_view.png" zPosition="-1" position="0,0" size="865,623" alphatest="on" />
1505                 <ePixmap pixmap="Vu_HD/menu/ico_title_Setup.png" position="32,41" size="40,40" alphatest="blend"  transparent="1" />
1506                 <eLabel text="Wireless Network Status..." position="90,50" size="600,32" font="Semiboldit;32" foregroundColor="#5d5d5d" backgroundColor="#27b5b9bd" transparent="1" />
1507                 <ePixmap pixmap="Vu_HD/icons/clock.png" position="750,55" zPosition="1" size="20,20" alphatest="blend" />
1508                 <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">
1509                         <convert type="ClockToText">Format:%H:%M</convert>
1510                 </widget>
1511                 <ePixmap pixmap="Vu_HD/buttons/red.png" position="45,98" size="25,25" alphatest="blend" />
1512                 <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" />
1513                 <widget source="status" render="Label" position="110,200" size="650,400" transparent="1" font="Regular;20" foregroundColor="#1c1c1c" backgroundColor="#27d9dee2" zPosition="1" />
1514         </screen>"""
1515         def __init__(self, session,iface):
1516                 Screen.__init__(self,session)
1517                 self.session = session
1518                 self.iface = iface
1519                 self["status"] = StaticText(_("Wait a moment..."))
1520                 self["key_red"] = StaticText(_("Close"))
1521                 self["OkCancelActions"] = ActionMap(["ShortcutActions", "SetupActions" ],
1522                 {
1523                         "ok": self.ok,
1524                         "cancel": self.close,
1525                         "red": self.close,
1526                 }, -2)
1527                 self.readstatus()
1528                 self.onClose.append(self.cleanup)
1529
1530         def readstatus(self):
1531                 self.wlanstatus = Console()
1532                 cmd1 = "iwconfig "+self.iface
1533                 self.wlanstatus.ePopen(cmd1, self.iwconfigfinnished,self.statusdisplay)
1534
1535         def iwconfigfinnished(self, result, retval,extra_args):
1536                 try:
1537                         (statecallback) = extra_args
1538                         if self.wlanstatus is not None:
1539                                 if retval == 0:
1540                                         statecallback(result)
1541                                 else:
1542                                         statecallback(0)
1543                 except:
1544                         self.close()
1545
1546
1547         def statusdisplay(self,data):
1548                 if data == 0:
1549                         self["status"].setText(_("No information..."))
1550                 else:
1551                         self["status"].setText(data)
1552
1553         def ok(self):
1554                 pass
1555
1556         def cleanup(self):
1557                 self.stopWlanStatusConsole()
1558
1559         def stopWlanStatusConsole(self):
1560                 if self.wlanstatus is not None:
1561                         if len(self.wlanstatus.appContainers):
1562                                 for name in self.wlanstatus.appContainers.keys():
1563                                         self.wlanstatus.kill(name)
1564
1565 def openconfig(session, **kwargs):
1566         session.open(WlanSelection)
1567
1568 def selSetup(menuid, **kwargs):
1569         list=[]
1570         if menuid != "system":
1571                 return [ ]
1572         else:
1573                 for x in iNetwork.getInstalledAdapters():
1574                         if x.startswith('eth'):
1575                                 continue
1576                         list.append(x)
1577                 if len(list):
1578                         return [(_("Wireless LAN Setup"), openconfig, "wlansetup_config", 80)]
1579                 else:
1580                         return [ ]
1581         return [ ]
1582
1583 def Plugins(**kwargs):
1584         return  PluginDescriptor(name=_("Wireless LAN Setup"), description="Wireless LAN Setup", where = PluginDescriptor.WHERE_MENU, fnc=selSetup)