formatip func : iplist is None error
[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, NetworkAdapterTest
9 from Screens.NetworkSetup import NameserverSetup
10 from Components.Sources.StaticText import StaticText
11 from Components.Sources.Boolean import Boolean
12 from Components.Sources.List import List
13 from Components.Label import Label,MultiColorLabel
14 from Components.Pixmap import Pixmap,MultiPixmap
15 from Components.MenuList import MenuList
16 from Components.config import config, ConfigYesNo, ConfigIP, NoSave, ConfigText, ConfigPassword, ConfigSelection, getConfigListEntry, ConfigNothing
17 from Components.config import ConfigInteger, ConfigSubsection
18 from Components.ConfigList import ConfigListScreen
19 from Components.PluginComponent import plugins
20 from Components.MultiContent import MultiContentEntryText, MultiContentEntryPixmapAlphaTest
21 from Components.ActionMap import ActionMap, NumberActionMap, HelpableActionMap
22 from Components.Console import Console
23 from Tools.Directories import resolveFilename, SCOPE_PLUGINS, SCOPE_CURRENT_SKIN
24 from Tools.LoadPixmap import LoadPixmap
25 from Plugins.Plugin import PluginDescriptor
26 from enigma import eTimer, ePoint, eSize, RT_HALIGN_LEFT, eListboxPythonMultiContent, gFont
27 from os import path as os_path, system as os_system, unlink
28 from re import compile as re_compile, search as re_search
29 from Tools.Directories import fileExists
30 import time
31
32 class WlanSelection(Screen):
33         skin = """
34         <screen name="WlanSelection" position="209,48" size="865,623" title="Wireless Network Selection..." flags="wfNoBorder" backgroundColor="transparent">   
35                 <ePixmap pixmap="Vu_HD/Bg_EPG_view.png" zPosition="-1" position="0,0" size="865,623" alphatest="on" />
36                 <ePixmap pixmap="Vu_HD/menu/ico_title_Setup.png" position="32,41" size="40,40" alphatest="blend"  transparent="1" />
37                 <eLabel text="Wireless Network Selection..." position="90,50" size="600,32" font="Semiboldit;32" foregroundColor="#5d5d5d" backgroundColor="#27b5b9bd" transparent="1" />
38                 <ePixmap pixmap="Vu_HD/icons/clock.png" position="750,55" zPosition="1" size="20,20" alphatest="blend" />
39                 <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">
40                         <convert type="ClockToText">Format:%H:%M</convert>
41                 </widget>
42                 <ePixmap pixmap="Vu_HD/buttons/red.png" position="45,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                 <ePixmap pixmap="Vu_HD/border_menu.png" position="120,140" zPosition="-1" size="342,358" transparent="1" alphatest="blend" />
45                 <widget name="menulist" position="130,150" size="322,338" transparent="1" backgroundColor="#27d9dee2" zPosition="10" scrollbarMode="showOnDemand" />
46         </screen>"""
47         
48         def __init__(self, session):
49                 Screen.__init__(self,session)
50                 self.mainmenu = self.getWlandevice()
51                 self["menulist"] = MenuList(self.mainmenu)
52                 self["key_red"] = StaticText(_("Close"))                
53                 self["OkCancelActions"] = ActionMap(["ShortcutActions", "SetupActions" ],
54                 {
55                         "ok": self.ok,
56                         "cancel": self.close,
57                         "red": self.close,
58                 }, -2)
59
60         def ok(self):
61                 ifaces=self["menulist"].getCurrent()[1]
62                 if ifaces == None:
63                         pass
64                 else:
65                         self.session.open(WlanSetup,ifaces)
66
67
68         def getWlandevice(self):
69                 list = []
70                 for x in iNetwork.getAdapterList():
71                         if x.startswith('eth'):
72                                 continue
73                         list.append((iNetwork.getFriendlyAdapterName(x),x))
74                 return list
75 #               self.adapters = [(iNetwork.getFriendlyAdapterName(x),x) for x in iNetwork.getAdapterList()]
76 #               print self.adapters
77 #               return self.adapters
78                 
79
80
81 class WlanSetup(Screen,HelpableScreen):
82         skin = """
83         <screen name="WlanSetup" position="209,48" size="865,623" title="Wireless Network Configuration..." flags="wfNoBorder" backgroundColor="transparent">   
84                 <ePixmap pixmap="Vu_HD/Bg_EPG_view.png" zPosition="-1" position="0,0" size="865,623" alphatest="on" />
85                 <ePixmap pixmap="Vu_HD/menu/ico_title_Setup.png" position="32,41" size="40,40" alphatest="blend"  transparent="1" />
86                 <eLabel text="Wireless Network Configuration..." position="90,50" size="600,32" font="Semiboldit;32" foregroundColor="#5d5d5d" backgroundColor="#27b5b9bd" transparent="1" />
87                 <ePixmap pixmap="Vu_HD/icons/clock.png" position="750,55" zPosition="1" size="20,20" alphatest="blend" />
88                 <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">
89                         <convert type="ClockToText">Format:%H:%M</convert>
90                 </widget>
91                 <ePixmap pixmap="Vu_HD/buttons/red.png" position="45,98" size="25,25" alphatest="blend" />
92                 <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" />
93                 <ePixmap pixmap="Vu_HD/border_menu.png" position="120,140" zPosition="-1" size="342,358" transparent="1" alphatest="blend" />
94                 <widget name="menulist" position="130,150" size="322,338" transparent="1" backgroundColor="#27d9dee2" zPosition="10" scrollbarMode="showOnDemand" />
95         </screen>"""
96         def __init__(self, session, ifaces):
97                 Screen.__init__(self, session)
98                 HelpableScreen.__init__(self)
99                 self.session = session
100                 self.iface = ifaces
101                 self.restartLanRef = None
102                 self.LinkState = None
103                 self.mainmenu = self.MakeMenu()
104                 self["menulist"] = MenuList(self.mainmenu)
105                 self["key_red"] = StaticText(_("Close"))
106                 self["description"] = StaticText()
107                 self["IFtext"] = StaticText()
108                 self["IF"] = StaticText()
109                 self["Statustext"] = StaticText()
110                 self["statuspic"] = MultiPixmap()
111                 self["statuspic"].hide()
112                 
113                 self.oktext = _("Press OK on your remote control to continue.")
114                 self.reboottext = _("Your STB will restart after pressing OK on your remote control.")
115                 self.errortext = _("No working wireless network interface found.\n Please verify that you have attached a compatible WLAN device or enable your local network interface.")      
116                 
117                 self["WizardActions"] = HelpableActionMap(self, "WizardActions",
118                         {
119                         "up": (self.up, _("move up to previous entry")),
120                         "down": (self.down, _("move down to next entry")),
121                         "left": (self.left, _("move up to first entry")),
122                         "right": (self.right, _("move down to last entry")),
123                         })
124                 
125                 self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
126                         {
127                         "cancel": (self.close, _("exit networkadapter setup menu")),
128                         "ok": (self.ok, _("select menu entry")),
129                         })
130
131                 self["ColorActions"] = HelpableActionMap(self, "ColorActions",
132                         {
133                         "red": (self.close, _("exit networkadapter setup menu")),       
134                         })
135
136                 self["actions"] = NumberActionMap(["WizardActions","ShortcutActions"],
137                 {
138                         "ok": self.ok,
139                         "back": self.close,
140                         "up": self.up,
141                         "down": self.down,
142                         "red": self.close,
143                         "left": self.left,
144                         "right": self.right,
145                 }, -2)
146         def up(self):
147                 self["menulist"].up()
148         def down(self):
149                 self["menulist"].down()
150         def left(self):
151                 self["menulist"].pageUp()
152         def right(self):
153                 self["menulist"].pageDown()
154         def ok(self):
155                 if self["menulist"].getCurrent()[1] == 'setting':
156                         self.session.openWithCallback(self.checklist, WlanConfig, self.iface)
157                 elif self["menulist"].getCurrent()[1] == 'scanap':
158                         self.session.open(WlanScanAp, self.iface)
159                 elif self["menulist"].getCurrent()[1] == 'dns':
160                         self.session.open(NameserverSetup)
161                 elif self["menulist"].getCurrent()[1] == 'status':
162                         self.session.open(Wlanstatus, self.iface)
163                 elif self["menulist"].getCurrent()[1] == 'test':
164                         self.session.openWithCallback(self.checklist,NetworkAdapterTest,self.iface)
165                 elif self["menulist"].getCurrent()[1] == 'restart':
166                         self.session.openWithCallback(self.restartNet, MessageBox, (_("Are you sure you want to restart your network interfaces?\n\n") + self.oktext ) )
167
168         def checklist(self):
169                 self["menulist"].setList(self.MakeMenu())
170
171         def MakeMenu(self):
172                 menu = []
173                 menu.append((_("Adapter settings"), "setting"))
174                 menu.append((_("Scan Wireless AP"), "scanap"))
175                 menu.append((_("Nameserver settings"), "dns"))
176                 if iNetwork.getAdapterAttribute(self.iface, "up"):
177                         menu.append((_("Show WLAN Status"), "status"))
178                 menu.append((_("Network test"), "test"))
179                 menu.append((_("Restart network"), "restart"))
180
181                 return menu
182                 
183         def restartNet(self,ret = False):
184                 if ret == True:
185                         os_system('/etc/init.d/networking restart')
186 #               self.updateStatusbar()
187 #               self.onLayoutFinish.append(self.layoutFinished)
188 #               self.onClose.append(self.cleanup)
189
190 wlanconfig = ConfigSubsection()
191 wlanconfig.usedevice = ConfigSelection(default = "off", choices = [
192         ("off", _("off")), ("on", _("on"))])
193 wlanconfig.usedhcp = ConfigSelection(default = "off", choices = [
194         ("off", _("no")), ("on", _("yes"))])
195 wlanconfig.essid = ConfigSelection(default = "none", choices = ["none"])
196 wlanconfig.encrypt = ConfigSelection(default = "off", choices = [
197         ("off", _("no")), ("on", _("yes"))])
198 wlanconfig.method = ConfigSelection(default = "wep", choices = [
199         ("wep", _("WEP")), ("wpa", _("WPA")), ("wpa2", _("WPA2")),("wpa/wpa2", _("WPA/WPA2"))])
200 wlanconfig.keytype = ConfigSelection(default = "ascii", choices = [
201         ("ascii", _("ASCII")), ("hex", _("HEX"))])
202 wlanconfig.key = ConfigText(default = "XXXXXXXX", visible_width = 50, fixed_size = False)
203 wlanconfig.usegateway = ConfigSelection(default = "off", choices = [
204         ("off", _("no")), ("on", _("yes"))])
205 wlanconfig.ip    = ConfigIP([0,0,0,0])
206 wlanconfig.netmask = ConfigIP([0,0,0,0])
207 wlanconfig.gateway = ConfigIP([0,0,0,0])
208
209 selectap = None 
210 class WlanConfig(Screen, ConfigListScreen, HelpableScreen):
211         skin = """
212         <screen name="WlanConfig" position="209,48" size="865,623" title="Wireless Network Configuration..." flags="wfNoBorder" backgroundColor="transparent">  
213                 <ePixmap pixmap="Vu_HD/Bg_EPG_view.png" zPosition="-1" position="0,0" size="865,623" alphatest="on" />
214                 <ePixmap pixmap="Vu_HD/menu/ico_title_Setup.png" position="32,41" size="40,40" alphatest="blend"  transparent="1" />
215                 <eLabel text="Wireless Network Configuration..." position="90,50" size="600,32" font="Semiboldit;32" foregroundColor="#5d5d5d" backgroundColor="#27b5b9bd" transparent="1" />
216                 <ePixmap pixmap="Vu_HD/icons/clock.png" position="750,55" zPosition="1" size="20,20" alphatest="blend" />
217                 <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">
218                         <convert type="ClockToText">Format:%H:%M</convert>
219                 </widget>
220                 <ePixmap pixmap="Vu_HD/buttons/red.png" position="45,98" size="25,25" alphatest="blend" />
221                 <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" />
222                 <ePixmap pixmap="Vu_HD/border_menu.png" position="120,140" zPosition="-1" size="342,358" transparent="1" alphatest="blend" />
223                 <widget name="config" position="130,150" size="322,338" transparent="1" backgroundColor="#27d9dee2" zPosition="10" scrollbarMode="showOnDemand" />
224                 <eLabel text="IP Address : " position="500,160" size="200,26" font="Semiboldit;22" foregroundColor="#5d5d5d" backgroundColor="#27b5b9bd" transparent="1" />             
225                 <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" />             
226                 <eLabel text="NetMask : " position="500,220" size="200,26" font="Semiboldit;22" foregroundColor="#5d5d5d" backgroundColor="#27b5b9bd" transparent="1" />                
227                 <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" />               
228                 <eLabel text="Gateway : " position="500,280" size="200,26" font="Semiboldit;22" foregroundColor="#5d5d5d" backgroundColor="#27b5b9bd" transparent="1" />                
229                 <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" />               
230         </screen>"""
231         def __init__(self, session, iface):
232                 Screen.__init__(self,session)
233                 self.session = session
234                 self.mainmenu = []
235                 self["key_red"] = StaticText(_("Close"))                
236                 self["ipaddress"] = StaticText(_("[ N/A ]"))
237                 self["netmask"] = StaticText(_("[ N/A ]"))              
238                 self["gateway"] = StaticText(_("[ N/A ]"))
239                 self["OkCancelActions"] = ActionMap(["ShortcutActions", "SetupActions" ],
240                 {
241                         "ok": self.ok,
242                         "cancel": self.close,
243                         "red": self.close,
244                 }, -2)
245                 self.iface = iface
246                 self.ssid = None
247                 self.scan_ssid = None
248                 self.key_mgmt = None
249                 self.proto = None
250                 self.key_type = None
251                 self.wep_key = None
252                 
253                 self.list = []
254                 self.wlanscanap = None
255                 ConfigListScreen.__init__(self, self.list,session = self.session)
256                 self.readifSetting()
257
258
259         def keyLeft(self):
260                 ConfigListScreen.keyLeft(self)
261                 self.newConfig()
262
263         def keyRight(self):
264                 ConfigListScreen.keyRight(self)
265                 self.newConfig()
266
267
268         def ok(self):
269                 if self["config"].isChanged():
270                         self.session.openWithCallback(self.confirmactive, MessageBox, (_("Are you sure you want to restart your network interfaces?\n") ) )
271
272         def confirmactive(self, ret = False):
273                 if ret == False:
274                         return
275                 else:
276                         num_configured_if = len(iNetwork.getConfiguredAdapters())
277                         if num_configured_if >= 1:
278                                 if num_configured_if == 1 and self.iface in iNetwork.getConfiguredAdapters():
279                                         self.saveif(False)
280                                 else:
281                                         self.session.openWithCallback(self.saveif, MessageBox, (_("Are you sure you want to deactive another network interfaces?\n") ) )
282                         else:
283                                 self.saveif(False)
284                                 
285         def saveif(self,ret = False):
286                 self["OkCancelActions"].setEnabled(False)
287                 self["config_actions"].setEnabled(False)
288                 if ret == True:
289                         configuredInterfaces = iNetwork.getConfiguredAdapters()
290                         for interface in configuredInterfaces:
291                                 if interface == self.iface:
292                                         continue
293                                 iNetwork.setAdapterAttribute(interface, "up", False)
294                                 iNetwork.deactivateInterface(interface)
295                 wpafd = open("/etc/wpa_supplicant.conf","w")
296                 if wpafd > 0:
297                         contents = "#WPA Supplicant Configuration by enigma2\n"
298                         contents += "ctrl_interface=/var/run/wpa_supplicant\n"
299                         contents += "eapol_version=1\n"
300                         contents += "fast_reauth=1\n"
301                         contents += "ap_scan=1\n"
302                         contents += "network={\n"
303                         contents += "\tssid=\""+wlanconfig.essid.value+"\"\n"
304                         contents += "\tscan_ssid=0\n"
305                         if wlanconfig.encrypt.value == "on":
306                                 if wlanconfig.method.value =="wep":
307                                         contents += "\tkey_mgmt=NONE\n"
308                                         contents += "\twep_key0="
309                                 elif wlanconfig.method.value == "wpa":
310                                         contents += "\tkey_mgmt=WPA-PSK\n"
311                                         contents += "\tproto=WPA\n"
312                                         contents += "\tpairwise=CCMP TKIP\n"
313                                         contents += "\tgroup=CCMP TKIP\n"
314                                         contents += "\tpsk="                                    
315                                 elif wlanconfig.method.value == "wpa2":
316                                         contents += "\tkey_mgmt=WPA-PSK\n"
317                                         contents += "\tproto=WPA RSN\n"
318                                         contents += "\tpairwise=CCMP TKIP\n"
319                                         contents += "\tgroup=CCMP TKIP\n"
320                                         contents += "\tpsk="
321                                 elif wlanconfig.method.value == "wpa/wpa2":
322                                         contents += "\tkey_mgmt=WPA-PSK\n"
323                                         contents += "\tproto=WPA WPA2\n"
324                                         contents += "\tpairwise=CCMP TKIP\n"
325                                         contents += "\tgroup=CCMP TKIP\n"
326                                         contents += "\tpsk="
327                                 if wlanconfig.keytype.value == "ascii":
328                                         contents += "\""+wlanconfig.key.value+"\"\n"            
329                                 else:
330                                         contents += wlanconfig.key.value+"\n"
331                         else:
332                                 contents += "\tkey_mgmt=NONE\n"                 
333                         contents += "}\n"
334                         print "content = \n"+contents
335                         wpafd.write(contents)
336                         wpafd.close()
337                 iffd = open("/etc/network/interfaces","r")
338                 if iffd > 0:
339                         prev_content = ""
340                         next_content = ""
341                         data = iffd.readline()
342                         status = 0
343                         while len(data) >0 :
344                                 if data.startswith('iface '+self.iface) or data.startswith('auto '+self.iface):
345                                         status = 1
346                                         data = iffd.readline()
347                                         continue
348                                 elif not data.startswith('auto lo') and data.startswith('auto '):
349                                         if ret == True or data[5:] not in iNetwork.getConfiguredAdapters():
350                                                 data = iffd.readline()
351                                                 continue
352                                 if status == 1 and data.startswith('iface ') or data.startswith('auto '):
353                                         status = 2
354                                 if status == 0:
355                                         prev_content += data
356                                 elif status == 2:
357                                         next_content += data
358                                 data = iffd.readline()
359                         iffd.close()
360                         iffd = open("/etc/network/interfaces","w")
361                         if iffd > 0 :
362                                 if prev_content == "":
363                                         prev_content = "# automatically generated by enigma2\n"
364                                         prev_content += "# do Not change manually!\n\n"
365                                         prev_content += "auto lo\n"
366                                         prev_content += "iface lo inet loopback\n\n"
367                                 iffd.write(prev_content)
368                                 if wlanconfig.usedevice.value=="on":
369                                         iNetwork.setAdapterAttribute(self.iface, "up", True)
370                                         contents = "auto "+self.iface+"\n"
371                                         contents += "iface "+self.iface+" inet "
372                                         if wlanconfig.usedhcp.value =="on":
373                                                 iNetwork.setAdapterAttribute(self.iface, "dhcp", True)                                  
374                                                 contents +="dhcp\n"
375                                         else:
376                                                 iNetwork.setAdapterAttribute(self.iface, "dhcp", False)
377                                                 contents +="static\n"
378                                                 print wlanconfig.ip.value
379                                                 iNetwork.setAdapterAttribute(self.iface, "ip", wlanconfig.ip.value)
380                                                 iNetwork.setAdapterAttribute(self.iface, "netmask", wlanconfig.netmask.value)                                           
381                                                 contents +="\taddress "+ self.formatip(wlanconfig.ip.value)+"\n"
382                                                 contents +="\tnetmask "+ self.formatip(wlanconfig.netmask.value)+"\n"
383                                                 if wlanconfig.usegateway.value == "on":
384                                                         iNetwork.setAdapterAttribute(self.iface, "gateway", wlanconfig.gateway.value)                   
385                                                         contents +="\tgateway "+ self.formatip(wlanconfig.gateway.value)+"\n"
386                                         contents += "\n\tpre-up /usr/sbin/wpa_supplicant -i"+self.iface+" -c/etc/wpa_supplicant.conf -B -D"+iNetwork.detectWlanModule(self.iface)+"\n"
387                                         contents += "\tpost-down wpa_cli terminate\n\n"
388                                         iffd.write(contents)
389                                 else:
390                                         iNetwork.setAdapterAttribute(self.iface, "up", False)
391                                         iNetwork.deactivateInterface(self.iface)
392                                 iffd.write(next_content)
393                                 iffd.close()
394                 self.restartNetwork(self.ConfigDataApply)
395                 self.configurationmsg = self.session.openWithCallback(self.WlanConfigClose, MessageBox, _("Please wait for activation of your network configuration..."), type = MessageBox.TYPE_INFO, enable_input = False)
396
397         def restartNetwork(self,callback=None):
398                 self.restartConsole = Console()
399                 cmd="/etc/init.d/networking restart"
400                 self.restartConsole.ePopen(cmd, self.restartNetworkFinished, callback)
401
402         def restartNetworkFinished(self, result, retval,extra_args):
403                 ( callback ) = extra_args
404                 if callback is not None:
405                         callback(True)
406
407         def ConfigDataApply(self,ret):
408                 if ret is True:
409                         iNetwork.getInterfaces(self.configurationmsgClose)
410
411         def configurationmsgClose(self,ret):
412                 if ret is True:
413                         self.configurationmsg.close(True)
414                         
415         def WlanConfigClose(self,ret):
416                 if ret is True:
417                         self.close()
418         
419         def formatip(self, iplist):
420                 list = []
421                 list = iplist
422                 try:
423                         if len(iplist) == 4:
424                                 result = str(iplist[0])+"."+str(iplist[1])+"."+str(iplist[2])+"."+str(iplist[3])
425                         else:
426                                 result ="0.0.0.0"
427                         return result
428                 except:
429                         return "[N/A]"
430                         
431         def createConfig(self):
432 #               wlanconfig.essid = ConfigSelection(default = "none", choices = ["maruap3","maruap2","none"])
433                         
434                 self.tlist=[]
435                 self.usedeviceEntry = getConfigListEntry(_("Use Device"), wlanconfig.usedevice)
436                 self.usedhcpEntry = getConfigListEntry(_("Use DHCP"), wlanconfig.usedhcp)
437                 self.essidEntry = getConfigListEntry(_("ESSID"), wlanconfig.essid)
438                 self.encryptEntry = getConfigListEntry(_("Encrypt"), wlanconfig.encrypt)
439                 self.methodEntry = getConfigListEntry(_("Method"), wlanconfig.method)
440                 self.keytypeEntry = getConfigListEntry(_("Key Type"), wlanconfig.keytype)               
441                 self.keyEntry = getConfigListEntry(_("KEY"), wlanconfig.key)
442
443                 self.ipEntry = getConfigListEntry(_("IP"), wlanconfig.ip)
444                 self.netmaskEntry = getConfigListEntry(_("NetMask"), wlanconfig.netmask)
445
446                 self.usegatewayEntry = getConfigListEntry(_("Use Gateway"), wlanconfig.usegateway)
447                 self.gatewayEntry = getConfigListEntry(_("Gateway"), wlanconfig.gateway)
448                 
449                 self.tlist.append( self.usedeviceEntry )
450                 if wlanconfig.usedevice.value is "on":
451                         self.tlist.append( self.usedhcpEntry )
452                         if wlanconfig.usedhcp.value is "off":
453                                 self.tlist.append(self.ipEntry)
454                                 self.tlist.append(self.netmaskEntry)
455                                 self.tlist.append(self.usegatewayEntry)
456                                 if wlanconfig.usegateway.value is "on":
457                                         self.tlist.append(self.gatewayEntry)
458                         self.tlist.append( self.essidEntry )
459                         self.tlist.append( self.encryptEntry )
460                         if wlanconfig.encrypt.value is "on" :
461                                 self.tlist.append( self.methodEntry )
462                                 self.tlist.append( self.keytypeEntry )
463                                 self.tlist.append( self.keyEntry )
464                 
465                 self["config"].list = self.tlist
466                 self["config"].l.setList(self.tlist)
467                 if not self.selectionChanged in self["config"].onSelectionChanged:
468                         self["config"].onSelectionChanged.append(self.selectionChanged)
469
470         def readifSetting(self):
471                 try:
472                         if fileExists("/etc/wpa_supplicant.conf"):
473                                 wpafd = open("/etc/wpa_supplicant.conf","r")
474                                 if wpafd >0:
475                                         data = wpafd.readline()
476                                         while len(data) > 0:
477                                                 data = data.lstrip()
478                                                 if len(data) == 0:
479                                                         data = wpafd.readline()
480                                                         continue
481                                                 if data.startswith('ssid=') and len(data) > 6:
482                                                         self.ssid = data[6:-2]
483                                                 elif data.startswith('scan_ssid=') and len(data) > 10:
484                                                         self.scan_ssid = data[10:-1]
485                                                 elif data.startswith('key_mgmt=') and len(data) > 9:
486                                                         self.key_mgmt = data[9:-1]
487                                                 elif data.startswith('proto=') and len(data) > 6:
488                                                         self.proto = data[6:-1]
489                                                 elif data.startswith('wep_key0="') and len(data) > 11:
490                                                         self.key_type = 1
491                                                         self.wep_key = data[10:-2]
492                                                 elif data.startswith('wep_key0=') and len(data) > 9:
493                                                         self.key_type = 0
494                                                         self.wep_key = data[9:-1]
495                                                 elif data.startswith('psk="') and len(data) > 6:
496                                                         self.key_type = 1
497                                                         self.wep_key = data[5:-2]
498                                                 elif data.startswith('psk=') and len(data) > 4:
499                                                         self.key_type = 0
500                                                         self.wep_key = data[4:-1]
501                                                         
502                                                 data = wpafd.readline()
503                                         print self.ssid,self.scan_ssid,self.key_mgmt,self.proto,self.key_type,self.wep_key
504                                         wpafd.close()
505                                         self.setfromread()
506                                 else:
507                                         print 'read error'
508                         else:
509                                 self.setfromread()
510                 except:
511                         print 'open error'
512
513         def setfromread(self):
514                 iNetwork.getInterfaces()
515                 
516                 if iNetwork.getAdapterAttribute(self.iface, "up") == True:
517                         default_tmp = "on"
518                 else:
519                         default_tmp = "off"
520                 wlanconfig.usedevice = ConfigSelection(default=default_tmp, choices = [
521                         ("off", _("off")), ("on", _("on"))])
522                 if iNetwork.getAdapterAttribute(self.iface, "dhcp"):
523                         default_tmp = "on"
524                 else:
525                         default_tmp = "off"
526                 wlanconfig.usedhcp = ConfigSelection(default=default_tmp, choices = [
527                         ("off", _("no")), ("on", _("yes"))])
528                 wlanconfig      .ip = ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "ip")) or [0,0,0,0]
529                 wlanconfig.netmask = ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "netmask") or [255,0,0,0])
530                 if iNetwork.getAdapterAttribute(self.iface, "gateway"):
531                         default_tmp = "on"
532                 else:
533                         default_tmp = "off"
534                 wlanconfig.usegateway = ConfigSelection(default = default_tmp, choices = [
535                         ("off", _("no")), ("on", _("yes"))])
536                 wlanconfig.gateway = ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "gateway") or [0,0,0,0])
537
538                 self["ipaddress"] = StaticText(_(self.formatip(iNetwork.getAdapterAttribute(self.iface, "ip"))))
539                 self["netmask"] = StaticText(_(self.formatip(iNetwork.getAdapterAttribute(self.iface, "netmask"))))
540                 self["gateway"] = StaticText(_(self.formatip(iNetwork.getAdapterAttribute(self.iface, "gateway"))))
541
542                 if self.wep_key is not None:
543                         default_tmp = "on"
544                 else:
545                         default_tmp = "off"
546                 wlanconfig.encrypt = ConfigSelection(default = default_tmp, choices = [
547                         ("off", _("no")), ("on", _("yes"))])
548
549                 if self.key_mgmt=="NONE":
550                         default_tmp = "wep"
551                 elif self.key_mgmt == "WPA-PSK":
552                         if self.proto == "WPA":
553                                 default_tmp = "wpa"
554                         elif self.proto == "WPA RSN":
555                                 default_tmp = "wpa2"
556                         elif self.proto == "WPA WPA2":
557                                 default_tmp = "wpa/wpa2"
558                         else:
559                                 default_tmp = "wpa"
560                 else:
561                         default_tmp = "wep"
562                         
563                 wlanconfig.method = ConfigSelection(default = default_tmp, choices = [
564                         ("wep", _("WEP")), ("wpa", _("WPA")), ("wpa2", _("WPA2")),("wpa/wpa2", _("WPA/WPA2"))])
565                         
566                 if self.key_type == 0:
567                         default_tmp = "hex"
568                 else:
569                         default_tmp = "ascii"
570                 wlanconfig.keytype = ConfigSelection(default = default_tmp, choices = [
571                         ("ascii", _("ASCII")), ("hex", _("HEX"))])                      
572                 default_tmp = self.wep_key or "XXXXXXXX"
573                 wlanconfig.key = ConfigText(default = default_tmp, visible_width = 50, fixed_size = False)
574                 
575                 if wlanconfig.usedevice.value is "on":
576                         self.getAplist()
577                 else:
578                         self.createConfig()
579                 
580
581         def newConfig(self):
582                 if self["config"].getCurrent() == self.usedeviceEntry :
583                         if wlanconfig.usedevice.value is "on":
584                                 self.getAplist()
585                         else:
586                                 if iNetwork.getAdapterAttribute(self.iface, "up"):
587                                         iNetwork.setAdapterAttribute(self.iface, "up",False)
588                                         iNetwork.deactivateInterface(self.iface)
589                                 self.createConfig()
590                 elif self["config"].getCurrent() == self.encryptEntry or self["config"].getCurrent() == self.usedhcpEntry \
591                 or self["config"].getCurrent() == self.usegatewayEntry :
592                         self.createConfig()
593
594         def selectionChanged(self):
595                 current = self["config"].getCurrent()
596                 print current
597
598         def getAplist(self):
599                 self["OkCancelActions"].setEnabled(False) #chang
600                 self["config_actions"].setEnabled(False) #chang
601                 if iNetwork.getAdapterAttribute(self.iface, "up") is not True:
602                         os_system('ifconfig '+self.iface+" up")
603                         iNetwork.setAdapterAttribute(self.iface, "up",True)
604                         time.sleep(1.5)
605                 self.wlanscanap = Console()
606                 cmd1 = "iwlist "+self.iface+" scan"
607                 print 'cmd',cmd1
608                 self.wlanscanap.ePopen(cmd1, self.iwlistfinnished,self.aplistparse)
609
610         def iwlistfinnished(self, result, retval,extra_args):
611                 (statecallback) = extra_args
612                 try:
613                         if self.wlanscanap is not None:
614                                 if retval == 0:
615                                         self.wlanscanap = None
616                                         content = result.splitlines()
617                                         first = content[0].split()
618                                         completed = False
619                                         for x in first:
620                                                 if x == 'completed':
621                                                         completed = True
622                                         if completed == True:
623                                                 statecallback(result)
624                                         else:
625                                                 statecallback(0)                                        
626                                 else:
627                                         statecallback(0)
628                 except:
629                         self.close()
630
631
632         def aplistparse(self,data):
633                 global selectap
634                 if data == 0:
635 #                       self.session.openWithCallback(self.createConfig ,MessageBox, _("Scan AP Failed"), MessageBox.TYPE_INFO,2)               
636                         self.session.open(MessageBox, _("Scan AP Failed"), MessageBox.TYPE_INFO,2)      
637                 else:
638                         self.aplist = []
639                         list = data.splitlines()
640 #                       print 'aplistparse',list
641                         for x in list:
642                                 xx = x.lstrip()
643                                 if xx.startswith('ESSID:') and len(xx)>8:
644                                         self.aplist.append(xx[7:-1])
645 #                       print 'rlist\n',rlist
646                         if len(self.aplist) ==0:
647                                 self.aplist.append('none')
648 #                       print 'aplist', self.aplist
649                         defaultap = None
650                         for x in self.aplist:
651                                 if x == selectap:
652                                         defaultap = x
653                         print 'defaultap',defaultap,self.aplist,selectap
654                         if selectap is None and self.ssid is not None and self.ssid in self.aplist:
655                                 wlanconfig.essid = ConfigSelection(default=self.ssid,choices = self.aplist)
656                         elif defaultap == selectap and selectap is not None:
657                                 wlanconfig.essid = ConfigSelection(default=selectap,choices = self.aplist)
658                         else:
659                                 wlanconfig.essid = ConfigSelection(choices = self.aplist)
660                         
661                 self.createConfig()
662                 self["OkCancelActions"].setEnabled(True)
663                 self["config_actions"].setEnabled(True)
664                 if iNetwork.getAdapterAttribute(self.iface, "up"):
665                         pass
666                 else:
667                         os_system('ifconfig '+self.iface+" down")
668
669 class WlanScanAp(Screen):
670         skin = """
671         <screen name="WlanScanAp" position="209,48" size="865,623" title="Wireless Network Scan..." flags="wfNoBorder" backgroundColor="transparent">   
672                 <ePixmap pixmap="Vu_HD/Bg_EPG_view.png" zPosition="-1" position="0,0" size="865,623" alphatest="on" />
673                 <ePixmap pixmap="Vu_HD/menu/ico_title_Setup.png" position="32,41" size="40,40" alphatest="blend"  transparent="1" />
674                 <eLabel text="Wireless Network Scan..." position="90,50" size="600,32" font="Semiboldit;32" foregroundColor="#5d5d5d" backgroundColor="#27b5b9bd" transparent="1" />
675                 <ePixmap pixmap="Vu_HD/icons/clock.png" position="750,55" zPosition="1" size="20,20" alphatest="blend" />
676                 <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">
677                         <convert type="ClockToText">Format:%H:%M</convert>
678                 </widget>
679                 <ePixmap pixmap="Vu_HD/buttons/red.png" position="45,98" size="25,25" alphatest="blend" />
680                 <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" />
681                 <ePixmap pixmap="Vu_HD/border_menu.png" position="120,140" zPosition="-1" size="342,358" transparent="1" alphatest="blend" />
682                 <widget name="menulist" position="130,150" size="322,338" transparent="1" backgroundColor="#27d9dee2" zPosition="10" scrollbarMode="showOnDemand" />
683                 <widget source="ap_strength" render="Label" position="490,250" zPosition="1" size="300,30" font="Regular;20" halign="center" valign="center" backgroundColor="#27b5b9bd" foregroundColor="#1c1c1c" transparent="1" />           
684                 <widget source="ap_quality" render="Label" position="490,280" zPosition="1" size="300,30" font="Regular;20" halign="center" valign="center" backgroundColor="#27b5b9bd" foregroundColor="#1c1c1c" transparent="1" />            
685         </screen>"""
686         def __init__(self, session, iface):
687                 Screen.__init__(self,session)
688                 self.session = session
689 #               self.aplist = []
690                 self.iface = iface
691                 self.mainmenu = []
692                 self.ap_extra = []
693                 self.ap_quality = []
694                 self.wlanscanap = None
695                 self["OkCancelActions"] = ActionMap(["ShortcutActions", "SetupActions","WizardActions" ],
696                 {
697                         "ok": self.ok,
698                         "cancel": self.close,
699                         "red": self.close,
700                         "up": self.up,
701                         "down": self.down,
702                         "left": self.left,
703                         "right": self.right,
704                 }, -2)
705                 self.getAplist()
706                 print 'getAplist',self.mainmenu
707                 self["menulist"] = MenuList(self.mainmenu)
708                 self["key_red"] = StaticText(_("Close"))
709                 self["ap_strength"] = StaticText(_("Scanning AP List..")) 
710                 self["ap_quality"] = StaticText(_("Wait a moment")) 
711                 
712
713         def left(self):
714                 self["menulist"].pageUp()
715                 if len(self.ap_extra) > self["menulist"].getSelectionIndex():
716                         self["ap_strength"].setText((self.ap_extra[self["menulist"].getSelectionIndex()])+"%") 
717                         self["ap_quality"].setText(self.ap_quality[self["menulist"].getSelectionIndex()]) 
718         
719         def right(self):
720                 self["menulist"].pageDown()
721                 if len(self.ap_extra) > self["menulist"].getSelectionIndex():
722                         self["ap_strength"].setText((self.ap_extra[self["menulist"].getSelectionIndex()])+"%") 
723                         self["ap_quality"].setText(self.ap_quality[self["menulist"].getSelectionIndex()]) 
724
725         def up(self):
726                 self["menulist"].up()
727                 if len(self.ap_extra) > self["menulist"].getSelectionIndex():
728                         self["ap_strength"].setText((self.ap_extra[self["menulist"].getSelectionIndex()])+"%") 
729                         self["ap_quality"].setText(self.ap_quality[self["menulist"].getSelectionIndex()]) 
730                 
731         def down(self):
732                 self["menulist"].down()
733                 if len(self.ap_extra) > self["menulist"].getSelectionIndex():
734                         self["ap_strength"].setText((self.ap_extra[self["menulist"].getSelectionIndex()])+"%")
735                         self["ap_quality"].setText(self.ap_quality[self["menulist"].getSelectionIndex()])               
736
737         def ok(self):
738                 global selectap
739                 ifaces=self["menulist"].getCurrent()
740                 print 'select', ifaces
741                 selectap = ifaces
742                 self.close()
743
744         def getAplist(self):
745                 self["OkCancelActions"].setEnabled(False)
746                 if iNetwork.getAdapterAttribute(self.iface, "up"):
747                         pass
748                 else:
749                         os_system('ifconfig '+self.iface+" up")
750                         time.sleep(1.5)
751                 self.wlanscanap = Console()
752                 cmd1 = "iwlist "+self.iface+" scan"
753                 self.wlanscanap.ePopen(cmd1, self.iwlistfinnished,self.aplistparse)
754
755         def iwlistfinnished(self, result, retval,extra_args):
756                 (statecallback) = extra_args
757                 try:
758                         if self.wlanscanap is not None:
759                                 if retval == 0:
760                                         self.wlanscanap = None
761                                         content = result.splitlines()
762                                         first = content[0].split()
763                                         completed = False
764                                         for x in first:
765                                                 if x == 'completed':
766                                                         completed = True
767                                         if completed == True:
768                                                 statecallback(result)
769                                         else:
770                                                 statecallback(0)                                        
771                                 else:
772                                         statecallback(0)
773                 except:
774                         self.close()
775
776
777         def aplistparse(self,data):
778                 rlist = []
779                 essid_on = 0
780                 if data == 0:
781                         self.session.open(MessageBox, _("Scan AP Failed"), MessageBox.TYPE_INFO,2)
782                         self["menulist"].setList(rlist)
783                 else:
784                         list = data.splitlines()
785                         for x in list:
786                                 for xx in x.split():
787                                         if xx.startswith('ESSID:') and len(xx)>8:
788                                                 rlist.append(xx[7:-1])
789                                                 essid_on = 1
790                                         if essid_on == 1 and xx.startswith('Extra:SignalStrength=') and len(xx)>21:
791                                                 self.ap_extra.append(xx[6:])
792                                         if essid_on == 1 and xx.startswith('%,LinkQuality:') and len(xx)>14:
793                                                 self.ap_quality.append(xx[2:])
794                                                 essid_pm = 0
795                         if len(rlist) >0:
796                                 self["menulist"].setList(rlist)
797                                 if len(self.ap_extra) > 0 and len(self.ap_quality) > 0:
798                                         self["ap_strength"].setText((self.ap_extra[self["menulist"].getSelectionIndex()])+"%")
799                                         self["ap_quality"].setText(self.ap_quality[self["menulist"].getSelectionIndex()]) 
800                                 else:
801                                         self["ap_strength"].setText("Select AP")
802                                         self["ap_quality"].setText(" ")
803                 if iNetwork.getAdapterAttribute(self.iface, "up"):
804                         pass
805                 else:
806                         os_system('ifconfig '+self.iface+" down")
807                 self["OkCancelActions"].setEnabled(True)
808
809 class NetworkAdapterTest(Screen):       
810         def __init__(self, session,iface):
811                 Screen.__init__(self, session)
812                 self.iface = iface
813                 self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
814                 self.setLabels()
815                 self.onClose.append(self.cleanup)
816                 self.onHide.append(self.cleanup)
817                 
818                 self["updown_actions"] = NumberActionMap(["WizardActions","ShortcutActions"],
819                 {
820                         "ok": self.KeyOK,
821                         "blue": self.KeyOK,
822                         "up": lambda: self.updownhandler('up'),
823                         "down": lambda: self.updownhandler('down'),
824                 
825                 }, -2)
826                 
827                 self["shortcuts"] = ActionMap(["ShortcutActions","WizardActions"],
828                 {
829                         "red": self.cancel,
830                         "back": self.cancel,
831                 }, -2)
832                 self["infoshortcuts"] = ActionMap(["ShortcutActions","WizardActions"],
833                 {
834                         "red": self.closeInfo,
835                         "back": self.closeInfo,
836                 }, -2)
837                 self["shortcutsgreen"] = ActionMap(["ShortcutActions"],
838                 {
839                         "green": self.KeyGreen,
840                 }, -2)
841                 self["shortcutsgreen_restart"] = ActionMap(["ShortcutActions"],
842                 {
843                         "green": self.KeyGreenRestart,
844                 }, -2)
845                 self["shortcutsyellow"] = ActionMap(["ShortcutActions"],
846                 {
847                         "yellow": self.KeyYellow,
848                 }, -2)
849                 
850                 self["shortcutsgreen_restart"].setEnabled(False)
851                 self["updown_actions"].setEnabled(False)
852                 self["infoshortcuts"].setEnabled(False)
853                 self.onClose.append(self.delTimer)      
854                 self.onLayoutFinish.append(self.layoutFinished)
855                 self.steptimer = False
856                 self.nextstep = 0
857                 self.activebutton = 0
858                 self.nextStepTimer = eTimer()
859                 self.nextStepTimer.callback.append(self.nextStepTimerFire)
860
861         def cancel(self):
862                 if self.oldInterfaceState is False:
863                         iNetwork.setAdapterAttribute(self.iface, "up", self.oldInterfaceState)
864                         iNetwork.deactivateInterface(self.iface)
865                 self.close()
866
867         def closeInfo(self):
868                 self["shortcuts"].setEnabled(True)              
869                 self["infoshortcuts"].setEnabled(False)
870                 self["InfoText"].hide()
871                 self["InfoTextBorder"].hide()
872                 self["key_red"].setText(_("Close"))
873
874         def delTimer(self):
875                 del self.steptimer
876                 del self.nextStepTimer
877
878         def nextStepTimerFire(self):
879                 self.nextStepTimer.stop()
880                 self.steptimer = False
881                 self.runTest()
882
883         def updownhandler(self,direction):
884                 if direction == 'up':
885                         if self.activebutton >=2:
886                                 self.activebutton -= 1
887                         else:
888                                 self.activebutton = 6
889                         self.setActiveButton(self.activebutton)
890                 if direction == 'down':
891                         if self.activebutton <=5:
892                                 self.activebutton += 1
893                         else:
894                                 self.activebutton = 1
895                         self.setActiveButton(self.activebutton)
896
897         def setActiveButton(self,button):
898                 if button == 1:
899                         self["EditSettingsButton"].setPixmapNum(0)
900                         self["EditSettings_Text"].setForegroundColorNum(0)
901                         self["NetworkInfo"].setPixmapNum(0)
902                         self["NetworkInfo_Text"].setForegroundColorNum(1)
903                         self["AdapterInfo"].setPixmapNum(1)               # active
904                         self["AdapterInfo_Text"].setForegroundColorNum(2) # active
905                 if button == 2:
906                         self["AdapterInfo_Text"].setForegroundColorNum(1)
907                         self["AdapterInfo"].setPixmapNum(0)
908                         self["DhcpInfo"].setPixmapNum(0)
909                         self["DhcpInfo_Text"].setForegroundColorNum(1)
910                         self["NetworkInfo"].setPixmapNum(1)               # active
911                         self["NetworkInfo_Text"].setForegroundColorNum(2) # active
912                 if button == 3:
913                         self["NetworkInfo"].setPixmapNum(0)
914                         self["NetworkInfo_Text"].setForegroundColorNum(1)
915                         self["IPInfo"].setPixmapNum(0)
916                         self["IPInfo_Text"].setForegroundColorNum(1)
917                         self["DhcpInfo"].setPixmapNum(1)                  # active
918                         self["DhcpInfo_Text"].setForegroundColorNum(2)    # active
919                 if button == 4:
920                         self["DhcpInfo"].setPixmapNum(0)
921                         self["DhcpInfo_Text"].setForegroundColorNum(1)
922                         self["DNSInfo"].setPixmapNum(0)
923                         self["DNSInfo_Text"].setForegroundColorNum(1)
924                         self["IPInfo"].setPixmapNum(1)                  # active
925                         self["IPInfo_Text"].setForegroundColorNum(2)    # active                
926                 if button == 5:
927                         self["IPInfo"].setPixmapNum(0)
928                         self["IPInfo_Text"].setForegroundColorNum(1)
929                         self["EditSettingsButton"].setPixmapNum(0)
930                         self["EditSettings_Text"].setForegroundColorNum(0)
931                         self["DNSInfo"].setPixmapNum(1)                 # active
932                         self["DNSInfo_Text"].setForegroundColorNum(2)   # active
933                 if button == 6:
934                         self["DNSInfo"].setPixmapNum(0)
935                         self["DNSInfo_Text"].setForegroundColorNum(1)
936                         self["EditSettingsButton"].setPixmapNum(1)         # active
937                         self["EditSettings_Text"].setForegroundColorNum(2) # active
938                         self["AdapterInfo"].setPixmapNum(0)
939                         self["AdapterInfo_Text"].setForegroundColorNum(1)
940                         
941         def runTest(self):
942                 next = self.nextstep
943                 if next == 0:
944                         self.doStep1()
945                 elif next == 1:
946                         self.doStep2()
947                 elif next == 2:
948                         self.doStep3()
949                 elif next == 3:
950                         self.doStep4()
951                 elif next == 4:
952                         self.doStep5()
953                 elif next == 5:
954                         self.doStep6()
955                 self.nextstep += 1
956
957         def doStep1(self):
958                 self.steptimer = True
959                 self.nextStepTimer.start(3000)
960                 self["key_yellow"].setText(_("Stop test"))
961
962         def doStep2(self):
963                 self["Adapter"].setText(iNetwork.getFriendlyAdapterName(self.iface))
964                 self["Adapter"].setForegroundColorNum(2)
965                 self["Adaptertext"].setForegroundColorNum(1)
966                 self["AdapterInfo_Text"].setForegroundColorNum(1)
967                 self["AdapterInfo_OK"].show()
968                 self.steptimer = True
969                 self.nextStepTimer.start(3000)
970
971         def doStep3(self):
972                 self["Networktext"].setForegroundColorNum(1)
973                 self["Network"].setText(_("Please wait..."))
974                 self.AccessPointInfo(self.iface)
975                 self["NetworkInfo_Text"].setForegroundColorNum(1)
976                 self.steptimer = True
977                 self.nextStepTimer.start(3000)
978
979         def doStep4(self):
980                 self["Dhcptext"].setForegroundColorNum(1)
981                 if iNetwork.getAdapterAttribute(self.iface, 'dhcp') is True:
982                         self["Dhcp"].setForegroundColorNum(2)
983                         self["Dhcp"].setText(_("enabled"))
984                         self["DhcpInfo_Check"].setPixmapNum(0)
985                 else:
986                         self["Dhcp"].setForegroundColorNum(1)
987                         self["Dhcp"].setText(_("disabled"))
988                         self["DhcpInfo_Check"].setPixmapNum(1)
989                 self["DhcpInfo_Check"].show()
990                 self["DhcpInfo_Text"].setForegroundColorNum(1)
991                 self.steptimer = True
992                 self.nextStepTimer.start(3000)
993
994         def doStep5(self):
995                 self["IPtext"].setForegroundColorNum(1)
996                 self["IP"].setText(_("Please wait..."))
997                 iNetwork.checkNetworkState(self.NetworkStatedataAvail)
998
999         def doStep6(self):
1000                 self.steptimer = False
1001                 self.nextStepTimer.stop()
1002                 self["DNStext"].setForegroundColorNum(1)
1003                 self["DNS"].setText(_("Please wait..."))
1004                 iNetwork.checkDNSLookup(self.DNSLookupdataAvail)
1005
1006         def KeyGreen(self):
1007                 self["shortcutsgreen"].setEnabled(False)
1008                 self["shortcutsyellow"].setEnabled(True)
1009                 self["updown_actions"].setEnabled(False)
1010                 self["key_yellow"].setText("")
1011                 self["key_green"].setText("")
1012                 self.steptimer = True
1013                 self.nextStepTimer.start(1000)
1014
1015         def KeyGreenRestart(self):
1016                 self.nextstep = 0
1017                 self.layoutFinished()
1018                 self["Adapter"].setText((""))
1019                 self["Network"].setText((""))
1020                 self["Dhcp"].setText((""))
1021                 self["IP"].setText((""))
1022                 self["DNS"].setText((""))
1023                 self["AdapterInfo_Text"].setForegroundColorNum(0)
1024                 self["NetworkInfo_Text"].setForegroundColorNum(0)
1025                 self["DhcpInfo_Text"].setForegroundColorNum(0)
1026                 self["IPInfo_Text"].setForegroundColorNum(0)
1027                 self["DNSInfo_Text"].setForegroundColorNum(0)
1028                 self["shortcutsgreen_restart"].setEnabled(False)
1029                 self["shortcutsgreen"].setEnabled(False)
1030                 self["shortcutsyellow"].setEnabled(True)
1031                 self["updown_actions"].setEnabled(False)
1032                 self["key_yellow"].setText("")
1033                 self["key_green"].setText("")
1034                 self.steptimer = True
1035                 self.nextStepTimer.start(1000)
1036
1037         def KeyOK(self):
1038                 self["infoshortcuts"].setEnabled(True)
1039                 self["shortcuts"].setEnabled(False)
1040                 if self.activebutton == 1: # Adapter Check
1041                         self["InfoText"].setText(_("This test detects your configured LAN-Adapter."))
1042                         self["InfoTextBorder"].show()
1043                         self["InfoText"].show()
1044                         self["key_red"].setText(_("Back"))
1045                 if self.activebutton == 2: #LAN Check
1046                         self["InfoText"].setText(_("This test checks whether a network cable is connected to your LAN-Adapter.\nIf you get a \"disconnected\" message:\n- verify that a network cable is attached\n- verify that the cable is not broken"))
1047                         self["InfoTextBorder"].show()
1048                         self["InfoText"].show()
1049                         self["key_red"].setText(_("Back"))
1050                 if self.activebutton == 3: #DHCP Check
1051                         self["InfoText"].setText(_("This test checks whether your LAN Adapter is set up for automatic IP Address configuration with DHCP.\nIf you get a \"disabled\" message:\n - then your 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."))
1052                         self["InfoTextBorder"].show()
1053                         self["InfoText"].show()
1054                         self["key_red"].setText(_("Back"))
1055                 if self.activebutton == 4: # IP Check
1056                         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"))
1057                         self["InfoTextBorder"].show()
1058                         self["InfoText"].show()
1059                         self["key_red"].setText(_("Back"))
1060                 if self.activebutton == 5: # DNS Check
1061                         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"))
1062                         self["InfoTextBorder"].show()
1063                         self["InfoText"].show()
1064                         self["key_red"].setText(_("Back"))
1065                 if self.activebutton == 6: # Edit Settings
1066                         self.session.open(WlanConfig,self.iface)
1067                         self["shortcuts"].setEnabled(True)              
1068                         self["infoshortcuts"].setEnabled(False)
1069
1070         def KeyYellow(self):
1071                 self.nextstep = 0
1072                 self["shortcutsgreen_restart"].setEnabled(True)
1073                 self["shortcutsgreen"].setEnabled(False)
1074                 self["shortcutsyellow"].setEnabled(False)
1075                 self["key_green"].setText(_("Restart test"))
1076                 self["key_yellow"].setText("")
1077                 self.steptimer = False
1078                 self.nextStepTimer.stop()
1079
1080         def layoutFinished(self):
1081                 self.setTitle(_("Network test: ") + iNetwork.getFriendlyAdapterName(self.iface) )
1082                 self["shortcutsyellow"].setEnabled(False)
1083                 self["AdapterInfo_OK"].hide()
1084                 self["NetworkInfo_Check"].hide()
1085                 self["DhcpInfo_Check"].hide()
1086                 self["IPInfo_Check"].hide()
1087                 self["DNSInfo_Check"].hide()
1088                 self["EditSettings_Text"].hide()
1089                 self["EditSettingsButton"].hide()
1090                 self["InfoText"].hide()
1091                 self["InfoTextBorder"].hide()
1092                 self["key_yellow"].setText("")
1093
1094         def setLabels(self):
1095                 self["Adaptertext"] = MultiColorLabel(_("LAN Adapter"))
1096                 self["Adapter"] = MultiColorLabel()
1097                 self["AdapterInfo"] = MultiPixmap()
1098                 self["AdapterInfo_Text"] = MultiColorLabel(_("Show Info"))
1099                 self["AdapterInfo_OK"] = Pixmap()
1100                 
1101                 if self.iface in iNetwork.wlan_interfaces:
1102                         self["Networktext"] = MultiColorLabel(_("Wireless Network"))
1103                 else:
1104                         self["Networktext"] = MultiColorLabel(_("Local Network"))
1105                 
1106                 self["Network"] = MultiColorLabel()
1107                 self["NetworkInfo"] = MultiPixmap()
1108                 self["NetworkInfo_Text"] = MultiColorLabel(_("Show Info"))
1109                 self["NetworkInfo_Check"] = MultiPixmap()
1110                 
1111                 self["Dhcptext"] = MultiColorLabel(_("DHCP"))
1112                 self["Dhcp"] = MultiColorLabel()
1113                 self["DhcpInfo"] = MultiPixmap()
1114                 self["DhcpInfo_Text"] = MultiColorLabel(_("Show Info"))
1115                 self["DhcpInfo_Check"] = MultiPixmap()
1116                 
1117                 self["IPtext"] = MultiColorLabel(_("IP Address"))
1118                 self["IP"] = MultiColorLabel()
1119                 self["IPInfo"] = MultiPixmap()
1120                 self["IPInfo_Text"] = MultiColorLabel(_("Show Info"))
1121                 self["IPInfo_Check"] = MultiPixmap()
1122                 
1123                 self["DNStext"] = MultiColorLabel(_("Nameserver"))
1124                 self["DNS"] = MultiColorLabel()
1125                 self["DNSInfo"] = MultiPixmap()
1126                 self["DNSInfo_Text"] = MultiColorLabel(_("Show Info"))
1127                 self["DNSInfo_Check"] = MultiPixmap()
1128                 
1129                 self["EditSettings_Text"] = MultiColorLabel(_("Edit settings"))
1130                 self["EditSettingsButton"] = MultiPixmap()
1131                 
1132                 self["key_red"] = StaticText(_("Close"))
1133                 self["key_green"] = StaticText(_("Start test"))
1134                 self["key_yellow"] = StaticText(_("Stop test"))
1135                 
1136                 self["InfoTextBorder"] = Pixmap()
1137                 self["InfoText"] = Label()
1138
1139         def NetworkStatedataAvail(self,data):
1140                 if data <= 2:
1141                         self["IP"].setForegroundColorNum(2)
1142                         self["IP"].setText(_("confirmed"))
1143                         self["IPInfo_Check"].setPixmapNum(0)
1144                 else:
1145                         self["IP"].setForegroundColorNum(1)
1146                         self["IP"].setText(_("unconfirmed"))
1147                         self["IPInfo_Check"].setPixmapNum(1)
1148                 self["IPInfo_Check"].show()
1149                 self["IPInfo_Text"].setForegroundColorNum(1)            
1150                 self.steptimer = True
1151                 self.nextStepTimer.start(3000)          
1152                 
1153         def DNSLookupdataAvail(self,data):
1154                 if data <= 2:
1155                         self["DNS"].setForegroundColorNum(2)
1156                         self["DNS"].setText(_("confirmed"))
1157                         self["DNSInfo_Check"].setPixmapNum(0)
1158                 else:
1159                         self["DNS"].setForegroundColorNum(1)
1160                         self["DNS"].setText(_("unconfirmed"))
1161                         self["DNSInfo_Check"].setPixmapNum(1)
1162                 self["DNSInfo_Check"].show()
1163                 self["DNSInfo_Text"].setForegroundColorNum(1)
1164                 self["EditSettings_Text"].show()
1165                 self["EditSettingsButton"].setPixmapNum(1)
1166                 self["EditSettings_Text"].setForegroundColorNum(2) # active
1167                 self["EditSettingsButton"].show()
1168                 self["key_yellow"].setText("")
1169                 self["key_green"].setText(_("Restart test"))
1170                 self["shortcutsgreen"].setEnabled(False)
1171                 self["shortcutsgreen_restart"].setEnabled(True)
1172                 self["shortcutsyellow"].setEnabled(False)
1173                 self["updown_actions"].setEnabled(True)
1174                 self.activebutton = 6
1175
1176         def getInfoCB(self,status):
1177                 if status is not None:
1178                         if status == "No Connection" or status == "Not-Associated" or status == False:
1179                                 self["Network"].setForegroundColorNum(1)
1180                                 self["Network"].setText(_("disconnected"))
1181                                 self["NetworkInfo_Check"].setPixmapNum(1)
1182                                 self["NetworkInfo_Check"].show()
1183                         else:
1184                                 self["Network"].setForegroundColorNum(2)
1185                                 self["Network"].setText(_("connected"))
1186                                 self["NetworkInfo_Check"].setPixmapNum(0)
1187                                 self["NetworkInfo_Check"].show()
1188                                                 
1189         def cleanup(self):
1190                 iNetwork.stopLinkStateConsole()
1191                 iNetwork.stopDNSConsole()
1192
1193         def AccessPointInfo(self,iface):
1194                 cmd = "iwconfig %s"%iface
1195                 self.iwconfigConsole = Console()
1196                 self.iwconfigConsole.ePopen(cmd,self.readAP,self.getInfoCB)
1197
1198         def readAP(self,result,retval,extra_args):
1199                 (callback) = extra_args
1200                 self.apState = False
1201                 if self.iwconfigConsole is not None:
1202                         if retval == 0:
1203                                 self.iwconfigConsole = None
1204                                 content=result.splitlines()
1205                                 for x in content:
1206                                         if 'Access Point' in x:
1207                                                 self.apState = x[x.find('Access Point')+len('Access Point'):].strip(':').strip()
1208                                 callback(self.apState)
1209                 
1210 class Wlanstatus(Screen):
1211         skin = """
1212         <screen name="Wlanstatus" position="209,48" size="865,623" title="Wireless Network Status..." flags="wfNoBorder" backgroundColor="transparent"> 
1213                 <ePixmap pixmap="Vu_HD/Bg_EPG_view.png" zPosition="-1" position="0,0" size="865,623" alphatest="on" />
1214                 <ePixmap pixmap="Vu_HD/menu/ico_title_Setup.png" position="32,41" size="40,40" alphatest="blend"  transparent="1" />
1215                 <eLabel text="Wireless Network Status..." position="90,50" size="600,32" font="Semiboldit;32" foregroundColor="#5d5d5d" backgroundColor="#27b5b9bd" transparent="1" />
1216                 <ePixmap pixmap="Vu_HD/icons/clock.png" position="750,55" zPosition="1" size="20,20" alphatest="blend" />
1217                 <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">
1218                         <convert type="ClockToText">Format:%H:%M</convert>
1219                 </widget>
1220                 <ePixmap pixmap="Vu_HD/buttons/red.png" position="45,98" size="25,25" alphatest="blend" />
1221                 <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" />
1222                 <widget source="status" render="Label" position="110,200" size="650,400" transparent="1" font="Regular;22" foregroundColor="#1c1c1c" backgroundColor="#27d9dee2" zPosition="1" />
1223         </screen>"""
1224         def __init__(self, session,iface):
1225                 Screen.__init__(self,session)
1226                 self.session = session
1227 #               self.aplist = []
1228                 self.iface = iface
1229                 self["status"] = StaticText(_("Wait a moment..."))
1230                 self["key_red"] = StaticText(_("Close"))
1231                 self["OkCancelActions"] = ActionMap(["ShortcutActions", "SetupActions" ],
1232                 {
1233                         "ok": self.ok,
1234                         "cancel": self.close,
1235                         "red": self.close,
1236                 }, -2)
1237                 self.readstatus()
1238
1239         def readstatus(self):
1240                 self.wlanstatus = Console()
1241                 cmd1 = "iwconfig "+self.iface
1242                 self.wlanstatus.ePopen(cmd1, self.iwconfigfinnished,self.statusdisplay)
1243
1244         def iwconfigfinnished(self, result, retval,extra_args):
1245                 try:
1246                         (statecallback) = extra_args
1247                         if self.wlanstatus is not None:
1248                                 if retval == 0:
1249                                         statecallback(result)
1250                                 else:
1251                                         statecallback(0)
1252                 except:
1253                         self.close()
1254
1255
1256         def statusdisplay(self,data):
1257                 rlist = []              
1258                 if data == 0:
1259                         self["status"].setText(_("No information..."))
1260                 else:
1261                         self["status"].setText(data)
1262
1263         def ok(self):
1264                 pass
1265
1266 def openconfig(session, **kwargs):
1267 #       session.open(WlanSetup)
1268         session.open(WlanSelection)
1269
1270 def selSetup(menuid, **kwargs):
1271         if menuid != "system":
1272                 return [ ]
1273
1274         return [(_("Wireless LAN Setup"), openconfig, "wlansetup_config", 80)]
1275
1276 def Plugins(**kwargs):
1277         return  PluginDescriptor(name=_("Wireless LAN Setup"), description="Fan Control", where = PluginDescriptor.WHERE_MENU, fnc=selSetup);
1278 #       return [PluginDescriptor(name = "Fancontrols", description = "check Fan Control settings", where = PluginDescriptor.WHERE_AUTOSTART, fnc = setfancontrol),
1279 #       PluginDescriptor(name=_("Wireless LAN Setup"), description="Fan Control", where = PluginDescriptor.WHERE_MENU, fnc=selSetup)]