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