dont use os.system when not needed,
[vuplus_dvbapp] / lib / python / Screens / NetworkSetup.py
1 from Screen import Screen
2 from Components.ActionMap import ActionMap,NumberActionMap
3 from Screens.MessageBox import MessageBox
4 from Screens.Standby import *
5 from Components.Network import iNetwork
6 from Components.Label import Label,MultiColorLabel
7 from Components.Pixmap import Pixmap,MultiPixmap
8 from Components.MenuList import MenuList
9 from Components.config import config, ConfigYesNo, ConfigIP, NoSave, ConfigText, ConfigSelection, getConfigListEntry
10 from Components.ConfigList import ConfigListScreen
11 from Components.PluginComponent import plugins
12 from Components.MultiContent import MultiContentEntryText, MultiContentEntryPixmapAlphaTest
13 from Plugins.Plugin import PluginDescriptor
14 from enigma import eTimer
15 from os import path as os_path, system as os_system, unlink
16 from re import compile as re_compile, search as re_search
17 from Tools.Directories import resolveFilename, SCOPE_PLUGINS
18
19 from Tools.Directories import SCOPE_SKIN_IMAGE,SCOPE_PLUGINS, resolveFilename
20 from Tools.LoadPixmap import LoadPixmap
21 from enigma import RT_HALIGN_LEFT, eListboxPythonMultiContent, gFont
22
23 class InterfaceList(MenuList):
24         def __init__(self, list, enableWrapAround=False):
25                 MenuList.__init__(self, list, enableWrapAround, eListboxPythonMultiContent)
26                 self.l.setFont(0, gFont("Regular", 20))
27                 self.l.setItemHeight(30)
28
29 def InterfaceEntryComponent(index,name,default,active ):
30         res = [ (index) ]
31         res.append(MultiContentEntryText(pos=(80, 5), size=(430, 25), font=0, text=name))
32         if default is True:
33                 png = LoadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, "skin_default/buttons/button_blue.png"))
34         if default is False:
35                 png = LoadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, "skin_default/buttons/button_blue_off.png"))
36         res.append(MultiContentEntryPixmapAlphaTest(pos=(10, 5), size=(25, 25), png = png))
37         if active is True:
38                 png2 = LoadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, "skin_default/icons/lock_on.png"))
39         if active is False:
40                 png2 = LoadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, "skin_default/icons/lock_error.png"))
41         res.append(MultiContentEntryPixmapAlphaTest(pos=(40, 1), size=(25, 25), png = png2))
42         return res
43
44
45 class NetworkAdapterSelection(Screen):
46         def __init__(self, session):
47                 Screen.__init__(self, session)
48                 iNetwork.getInterfaces()
49                 self.wlan_errortext = _("No working wireless networkadapter found.\nPlease verify that you have attached a compatible WLAN USB Stick and your Network is configured correctly.")
50                 self.lan_errortext = _("No working local networkadapter found.\nPlease verify that you have attached a network cable and your Network is configured correctly.")
51                 
52                 self["ButtonBluetext"] = Label(_("Set as default Interface"))
53                 self["ButtonRedtext"] = Label(_("Close"))
54                 self["introduction"] = Label(_("Press OK to edit the settings."))
55                 
56                 self.adapters = [(iNetwork.getFriendlyAdapterName(x),x) for x in iNetwork.getAdapterList()]
57
58                 if len(self.adapters) == 0:
59                         self.onFirstExecBegin.append(self.NetworkFallback)
60
61                 self.list = []
62                 self["list"] = InterfaceList(self.list)
63                 self.updateList()
64                 self["actions"] = ActionMap(["OkCancelActions", "ColorActions"],
65                 {
66                         "ok": self.okbuttonClick,
67                         "cancel": self.close,
68                         "blue": self.setDefaultInterface,                       
69                         "red": self.close
70                 }, -2)
71
72                 if len(self.adapters) == 1:
73                         self.onFirstExecBegin.append(self.okbuttonClick)
74
75         def updateList(self):
76                 print "update list"
77                 self.list = []
78                 default_gw = None
79                 if os_path.exists("/etc/default_gw"):
80                         fp = file('/etc/default_gw', 'r')
81                         result = fp.read()
82                         fp.close()
83                         default_gw = result
84
85                 if len(self.adapters) == 0: # no interface available => display only eth0
86                         self.list.append(InterfaceEntryComponent("eth0",iNetwork.getFriendlyAdapterName('eth0'),True,True ))
87                 else:
88                         for x in self.adapters:
89                                 if x[1] == default_gw:
90                                         default_int = True
91                                 else:
92                                         default_int = False
93                                 if iNetwork.getAdapterAttribute(x[1], 'up') is True:
94                                         active_int = True
95                                 else:
96                                         active_int = False
97                                 self.list.append(InterfaceEntryComponent(index = x[1],name = _(x[0]),default=default_int,active=active_int ))
98                 self["list"].l.setList(self.list)
99
100         def setDefaultInterface(self):
101                 selection = self["list"].getCurrent()
102                 num_if = len(self.list)
103                 old_default_gw = None
104                 if os_path.exists("/etc/default_gw"):
105                         fp = open('/etc/default_gw', 'r')
106                         old_default_gw = fp.read()
107                         fp.close()
108                 if num_if > 1 and (not old_default_gw or old_default_gw != selection[0]):
109                         fp = open('/etc/default_gw', 'w+')
110                         fp.write(selection[0])
111                         fp.close()
112                         iNetwork.restartNetwork()
113                 elif old_default_gw and num_if < 2:
114                         unlink("/etc/default_gw")
115                         iNetwork.restartNetwork()
116
117         def okbuttonClick(self):
118                 selection = self["list"].getCurrent()
119                 print "selection",selection
120                 if selection is not None:
121                         self.session.openWithCallback(self.AdapterSetupClosed, AdapterSetupConfiguration, selection[0])
122
123         def AdapterSetupClosed(self, *ret):
124                 if len(self.adapters) == 1:
125                         self.close()
126
127         def NetworkFallback(self):
128                 if iNetwork.configuredInterfaces.has_key('wlan0') is True:
129                         self.session.openWithCallback(self.ErrorMessageClosed, MessageBox, self.wlan_errortext, type = MessageBox.TYPE_INFO,timeout = 10)
130                 if iNetwork.configuredInterfaces.has_key('ath0') is True:
131                         self.session.openWithCallback(self.ErrorMessageClosed, MessageBox, self.wlan_errortext, type = MessageBox.TYPE_INFO,timeout = 10)
132                 else:
133                         self.session.openWithCallback(self.ErrorMessageClosed, MessageBox, self.lan_errortext, type = MessageBox.TYPE_INFO,timeout = 10)
134
135         def ErrorMessageClosed(self, *ret):
136                 if iNetwork.configuredInterfaces.has_key('wlan0') is True:
137                         self.session.openWithCallback(self.AdapterSetupClosed, AdapterSetupConfiguration, 'wlan0')
138                 elif iNetwork.configuredInterfaces.has_key('ath0') is True:
139                         self.session.openWithCallback(self.AdapterSetupClosed, AdapterSetupConfiguration, 'ath0')
140                 else:
141                         self.session.openWithCallback(self.AdapterSetupClosed, AdapterSetupConfiguration, 'eth0')
142
143 class NameserverSetup(Screen, ConfigListScreen):
144         def __init__(self, session):
145                 Screen.__init__(self, session)
146                 iNetwork.getInterfaces()
147                 self.backupNameserverList = iNetwork.getNameserverList()[:]
148                 print "backup-list:", self.backupNameserverList
149                 
150                 self["ButtonGreentext"] = Label(_("Add"))
151                 self["ButtonYellowtext"] = Label(_("Delete"))
152                 self["ButtonRedtext"] = Label(_("Close"))
153                 self["introduction"] = Label(_("Press OK to activate the settings."))
154                 self.createConfig()
155                 
156                 self["actions"] = ActionMap(["OkCancelActions", "ColorActions"],
157                 {
158                         "ok": self.ok,
159                         "cancel": self.cancel,
160                         "red": self.cancel,
161                         "green": self.add,
162                         "yellow": self.remove
163                 }, -2)
164                 
165                 self.list = []
166                 ConfigListScreen.__init__(self, self.list)
167                 self.createSetup()
168
169         def createConfig(self):
170                 self.nameservers = iNetwork.getNameserverList()
171                 self.nameserverEntries = []
172                 
173                 for nameserver in self.nameservers:
174                         self.nameserverEntries.append(NoSave(ConfigIP(default=nameserver)))
175
176         def createSetup(self):
177                 self.list = []
178                 
179                 for i in range(len(self.nameserverEntries)):
180                         self.list.append(getConfigListEntry(_("Nameserver %d") % (i + 1), self.nameserverEntries[i]))
181                 
182                 self["config"].list = self.list
183                 self["config"].l.setList(self.list)
184
185         def ok(self):
186                 iNetwork.clearNameservers()
187                 for nameserver in self.nameserverEntries:
188                         iNetwork.addNameserver(nameserver.value)
189                 iNetwork.writeNameserverConfig()
190                 self.close()
191
192         def run(self):
193                 self.ok()
194
195         def cancel(self):
196                 iNetwork.clearNameservers()
197                 print "backup-list:", self.backupNameserverList
198                 for nameserver in self.backupNameserverList:
199                         iNetwork.addNameserver(nameserver)
200                 self.close()
201
202         def add(self):
203                 iNetwork.addNameserver([0,0,0,0])
204                 self.createConfig()
205                 self.createSetup()
206
207         def remove(self):
208                 print "currentIndex:", self["config"].getCurrentIndex()
209                 
210                 index = self["config"].getCurrentIndex()
211                 if index < len(self.nameservers):
212                         iNetwork.removeNameserver(self.nameservers[index])
213                         self.createConfig()
214                         self.createSetup()
215         
216 class AdapterSetup(Screen, ConfigListScreen):
217         def __init__(self, session, iface,essid=None, aplist=None):
218                 Screen.__init__(self, session)
219                 self.session = session
220                 self.iface = iface
221                 self.essid = essid
222                 self.aplist = aplist
223                 self.extended = None
224                 iNetwork.getInterfaces()
225
226                 if self.iface == "wlan0" or self.iface == "ath0" :
227                         from Plugins.SystemPlugins.WirelessLan.Wlan import wpaSupplicant,Wlan
228                         self.ws = wpaSupplicant()
229                         list = []
230                         list.append(_("WEP"))
231                         list.append(_("WPA"))
232                         list.append(_("WPA2"))
233                         if self.aplist is not None:
234                                 self.nwlist = self.aplist
235                                 self.nwlist.sort(key = lambda x: x[0])
236                         else:
237                                 self.nwlist = []
238                                 self.w = None
239                                 self.aps = None
240                                 try:
241                                         self.w = Wlan(self.iface)
242                                         self.aps = self.w.getNetworkList()
243                                         if self.aps is not None:
244                                                 print "[Wlan.py] got Accespoints!"
245                                                 for ap in aps:
246                                                         a = aps[ap]
247                                                         if a['active']:
248                                                                 if a['essid'] == "":
249                                                                         a['essid'] = a['bssid']
250                                                                 self.nwlist.append( a['essid'])
251                                         self.nwlist.sort(key = lambda x: x[0])
252                                 except:
253                                         self.nwlist.append("No Networks found")
254
255                         wsconfig = self.ws.loadConfig()
256                         default = self.essid or wsconfig['ssid']
257                         if default not in self.nwlist:
258                                 self.nwlist.append(default)
259                         config.plugins.wlan.essid = NoSave(ConfigSelection(self.nwlist, default = default ))
260                         config.plugins.wlan.encryption.enabled = NoSave(ConfigYesNo(default = wsconfig['encryption'] ))
261                         config.plugins.wlan.encryption.type = NoSave(ConfigSelection(list, default = wsconfig['encryption_type'] ))
262                         config.plugins.wlan.encryption.psk = NoSave(ConfigText(default = wsconfig['key'], fixed_size = False,visible_width = 30))
263                 
264                 self.activateInterfaceEntry = NoSave(ConfigYesNo(default=iNetwork.getAdapterAttribute(self.iface, "up") or False))
265                 self.dhcpConfigEntry = NoSave(ConfigYesNo(default=iNetwork.getAdapterAttribute(self.iface, "dhcp") or False))
266                 self.ipConfigEntry = NoSave(ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "ip")) or [0,0,0,0])
267                 self.netmaskConfigEntry = NoSave(ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "netmask") or [255,0,0,0]))
268                 if iNetwork.getAdapterAttribute(self.iface, "gateway"):
269                         self.dhcpdefault=True
270                 else:
271                         self.dhcpdefault=False
272                 self.hasGatewayConfigEntry = NoSave(ConfigYesNo(default=self.dhcpdefault or False))
273                 self.gatewayConfigEntry = NoSave(ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "gateway") or [0,0,0,0]))
274                 nameserver = (iNetwork.getNameserverList() + [[0,0,0,0]] * 2)[0:2]
275                 self.primaryDNS = NoSave(ConfigIP(default=nameserver[0]))
276                 self.secondaryDNS = NoSave(ConfigIP(default=nameserver[1]))
277                 
278                 self["actions"] = ActionMap(["SetupActions","ShortcutActions"],
279                 {
280                         "ok": self.ok,
281                         "cancel": self.cancel,
282                         "red": self.cancel,
283                         "blue": self.KeyBlue,
284                 }, -2)
285                 
286                 self.list = []
287                 ConfigListScreen.__init__(self, self.list)
288                 self.createSetup()
289                 self.onLayoutFinish.append(self.layoutFinished)
290                 
291                 self["DNS1text"] = Label(_("Primary DNS"))
292                 self["DNS2text"] = Label(_("Secondary DNS"))
293                 self["DNS1"] = Label()
294                 self["DNS2"] = Label()
295                 
296                 self["introduction"] = Label(_("Current settings:"))
297                 
298                 self["IPtext"] = Label(_("IP Address"))
299                 self["Netmasktext"] = Label(_("Netmask"))
300                 self["Gatewaytext"] = Label(_("Gateway"))
301                 
302                 self["IP"] = Label()
303                 self["Mask"] = Label()
304                 self["Gateway"] = Label()
305                 
306                 self["BottomBG"] = Pixmap()
307                 self["Adaptertext"] = Label(_("Network:"))
308                 self["Adapter"] = Label()
309                 self["introduction2"] = Label(_("Press OK to activate the settings."))
310                 self["ButtonRed"] = Pixmap()
311                 self["ButtonRedtext"] = Label(_("Close"))
312                 self["ButtonBlue"] = Pixmap()
313                 self["ButtonBluetext"] = Label(_("Edit DNS"))
314
315         def layoutFinished(self):
316                 self["DNS1"].setText(self.primaryDNS.getText())
317                 self["DNS2"].setText(self.secondaryDNS.getText())
318                 if self.ipConfigEntry.getText() is not None:
319                         self["IP"].setText(self.ipConfigEntry.getText())
320                 else:
321                         self["IP"].setText([0,0,0,0])
322                 self["Mask"].setText(self.netmaskConfigEntry.getText())
323                 if iNetwork.getAdapterAttribute(self.iface, "gateway"):
324                         self["Gateway"].setText(self.gatewayConfigEntry.getText())
325                 else:
326                         self["Gateway"].hide()
327                         self["Gatewaytext"].hide()
328                 self["Adapter"].setText(iNetwork.getFriendlyAdapterName(self.iface))
329
330
331         def createSetup(self):
332                 self.list = []
333                 self.InterfaceEntry = getConfigListEntry(_("Use Interface"), self.activateInterfaceEntry)
334                 self.list.append(self.InterfaceEntry)
335                 if self.activateInterfaceEntry.value:
336                         self.dhcpEntry = getConfigListEntry(_("Use DHCP"), self.dhcpConfigEntry)
337                         self.list.append(self.dhcpEntry)
338                         if not self.dhcpConfigEntry.value:
339                                 self.list.append(getConfigListEntry(_('IP Address'), self.ipConfigEntry))
340                                 self.list.append(getConfigListEntry(_('Netmask'), self.netmaskConfigEntry))
341                                 self.list.append(getConfigListEntry(_('Use a gateway'), self.hasGatewayConfigEntry))
342                                 if self.hasGatewayConfigEntry.value:
343                                         self.list.append(getConfigListEntry(_('Gateway'), self.gatewayConfigEntry))
344                                         
345                         for p in plugins.getPlugins(PluginDescriptor.WHERE_NETWORKSETUP):
346                                 callFnc = p.__call__["ifaceSupported"](self.iface)
347                                 if callFnc is not None:
348                                         self.extended = callFnc
349                                         if p.__call__.has_key("configStrings"):
350                                                 self.configStrings = p.__call__["configStrings"]
351                                         else:
352                                                 self.configStrings = None
353                                                 
354                                         self.list.append(getConfigListEntry(_("Network SSID"), config.plugins.wlan.essid))
355                                         self.encryptionEnabled = getConfigListEntry(_("Encryption"), config.plugins.wlan.encryption.enabled)
356                                         self.list.append(self.encryptionEnabled)
357                                         
358                                         if config.plugins.wlan.encryption.enabled.value:
359                                                 self.list.append(getConfigListEntry(_("Encryption Type"), config.plugins.wlan.encryption.type))
360                                                 self.list.append(getConfigListEntry(_("Encryption Key"), config.plugins.wlan.encryption.psk))
361                 
362                 self["config"].list = self.list
363                 self["config"].l.setList(self.list)
364
365         def KeyBlue(self):
366                 self.session.openWithCallback(self.NameserverSetupClosed, NameserverSetup)
367
368         def newConfig(self):
369                 print self["config"].getCurrent()
370                 if self["config"].getCurrent() == self.dhcpEntry:
371                         self.createSetup()
372
373         def keyLeft(self):
374                 ConfigListScreen.keyLeft(self)
375                 self.createSetup()
376
377         def keyRight(self):
378                 ConfigListScreen.keyRight(self)
379                 self.createSetup()
380
381         def ok(self):
382                 iNetwork.setAdapterAttribute(self.iface, "up", self.activateInterfaceEntry.value)
383                 if self.activateInterfaceEntry.value is True:
384                         iNetwork.setAdapterAttribute(self.iface, "dhcp", self.dhcpConfigEntry.value)
385                         iNetwork.setAdapterAttribute(self.iface, "ip", self.ipConfigEntry.value)
386                         iNetwork.setAdapterAttribute(self.iface, "netmask", self.netmaskConfigEntry.value)
387                         if self.hasGatewayConfigEntry.value:
388                                 iNetwork.setAdapterAttribute(self.iface, "gateway", self.gatewayConfigEntry.value)
389                         else:
390                                 iNetwork.removeAdapterAttribute(self.iface, "gateway")
391                         if self.extended is not None and self.configStrings is not None:
392                                 iNetwork.setAdapterAttribute(self.iface, "configStrings", self.configStrings(self.iface))
393                                 self.ws.writeConfig()
394                 else:
395                         iNetwork.removeAdapterAttribute(self.iface, "ip")
396                         iNetwork.removeAdapterAttribute(self.iface, "netmask")
397                         iNetwork.removeAdapterAttribute(self.iface, "gateway")
398                         iNetwork.deactivateInterface(self.iface)
399
400                 iNetwork.deactivateNetworkConfig()
401                 iNetwork.writeNetworkConfig()
402                 iNetwork.activateNetworkConfig()
403                 self.close()
404
405         def cancel(self):
406                 if self.activateInterfaceEntry.value is False:
407                         iNetwork.deactivateInterface(self.iface)
408                 iNetwork.getInterfaces()
409                 self.close()
410
411         def run(self):
412                 self.ok()
413
414         def NameserverSetupClosed(self, *ret):
415                 iNetwork.loadNameserverConfig()
416                 nameserver = (iNetwork.getNameserverList() + [[0,0,0,0]] * 2)[0:2]
417                 self.primaryDNS = NoSave(ConfigIP(default=nameserver[0]))
418                 self.secondaryDNS = NoSave(ConfigIP(default=nameserver[1]))
419                 self.createSetup()
420                 self.layoutFinished()
421         
422
423 class AdapterSetupConfiguration(Screen):
424         def __init__(self, session,iface):
425                 Screen.__init__(self, session)
426                 self.session = session
427                 self.iface = iface
428                 self.mainmenu = self.genMainMenu()
429                 self["menulist"] = MenuList(self.mainmenu)
430                 self["description"] = Label()
431                 self["IFtext"] = Label()
432                 self["IF"] = Label()
433                 self["BottomBG"] = Label()
434                 self["Statustext"] = Label()
435                 self["statuspic"] = MultiPixmap()
436                 self["statuspic"].hide()
437                 self["BottomBG"] = Pixmap()
438                 self["ButtonRed"] = Pixmap()
439                 self["ButtonRedtext"] = Label(_("Close"))
440                 
441                 self.oktext = _("Press OK on your remote control to continue.")
442                 self.reboottext = _("Your Dreambox will restart after pressing OK on your remote control.")
443                 self.errortext = _("No working wireless interface found.\n Please verify that you have attached a compatible WLAN device or enable you local network interface.")       
444                 
445                 self["actions"] = NumberActionMap(["WizardActions","ShortcutActions"],
446                 {
447                         "ok": self.ok,
448                         "back": self.close,
449                         "up": self.up,
450                         "down": self.down,
451                         "red": self.close,
452                         "left": self.left,
453                         "right": self.right,
454                 }, -2)
455                 
456                 iNetwork.getInterfaces()
457                 self.onLayoutFinish.append(self.layoutFinished)
458                 self.updateStatusbar()
459
460         def ok(self):
461                 print "SELF.iFACE im OK Klick",self.iface
462                 print "self.menulist.getCurrent()[1]",self["menulist"].getCurrent()[1]
463                 if self["menulist"].getCurrent()[1] == 'edit':
464                         if self.iface == 'wlan0' or self.iface == 'ath0':
465                                 try:
466                                         from Plugins.SystemPlugins.WirelessLan.plugin import WlanScan
467                                         from Plugins.SystemPlugins.WirelessLan.iwlibs import Wireless
468                                 except ImportError:
469                                         self.session.open(MessageBox, _("The wireless LAN plugin is not installed!\nPlease install it."), type = MessageBox.TYPE_INFO,timeout = 10 )
470                                 else:
471                                         ifobj = Wireless(self.iface) # a Wireless NIC Object
472                                         self.wlanresponse = ifobj.getStatistics()
473                                         if self.wlanresponse[0] != 19: # Wlan Interface found.
474                                                 self.session.openWithCallback(self.AdapterSetupClosed, AdapterSetup,self.iface)
475                                         else:
476                                                 # Display Wlan not available Message
477                                                 self.showErrorMessage()
478                         else:
479                                 self.session.openWithCallback(self.AdapterSetupClosed, AdapterSetup,self.iface)
480                 if self["menulist"].getCurrent()[1] == 'test':
481                         self.session.open(NetworkAdapterTest,self.iface)
482                 if self["menulist"].getCurrent()[1] == 'dns':
483                         self.session.open(NameserverSetup)
484                 if self["menulist"].getCurrent()[1] == 'scanwlan':
485                         try:
486                                 from Plugins.SystemPlugins.WirelessLan.plugin import WlanScan
487                                 from Plugins.SystemPlugins.WirelessLan.iwlibs import Wireless
488                         except ImportError:
489                                 self.session.open(MessageBox, _("The wireless LAN plugin is not installed!\nPlease install it."), type = MessageBox.TYPE_INFO,timeout = 10 )
490                         else:
491                                 ifobj = Wireless(self.iface) # a Wireless NIC Object
492                                 self.wlanresponse = ifobj.getStatistics()
493                                 if self.wlanresponse[0] != 19:
494                                         self.session.openWithCallback(self.WlanScanClosed, WlanScan, self.iface)
495                                 else:
496                                         # Display Wlan not available Message
497                                         self.showErrorMessage()
498                 if self["menulist"].getCurrent()[1] == 'wlanstatus':
499                         try:
500                                 from Plugins.SystemPlugins.WirelessLan.plugin import WlanStatus
501                                 from Plugins.SystemPlugins.WirelessLan.iwlibs import Wireless
502                         except ImportError:
503                                 self.session.open(MessageBox, _("The wireless LAN plugin is not installed!\nPlease install it."), type = MessageBox.TYPE_INFO,timeout = 10 )
504                         else:   
505                                 ifobj = Wireless(self.iface) # a Wireless NIC Object
506                                 self.wlanresponse = ifobj.getStatistics()
507                                 if self.wlanresponse[0] != 19:
508                                         self.session.open(WlanStatus,self.iface)
509                                 else:
510                                         # Display Wlan not available Message
511                                         self.showErrorMessage()
512                 if self["menulist"].getCurrent()[1] == 'lanrestart':
513                         self.session.openWithCallback(self.restartLan, MessageBox, (_("Are you sure you want to restart your network interfaces?\n\n") + self.oktext ) )
514                 if self["menulist"].getCurrent()[1] == 'openwizard':
515                         from Plugins.SystemPlugins.NetworkWizard.NetworkWizard import NetworkWizard
516                         self.session.openWithCallback(self.AdapterSetupClosed, NetworkWizard)
517         
518         def up(self):
519                 self["menulist"].up()
520                 self.loadDescription()
521
522         def down(self):
523                 self["menulist"].down()
524                 self.loadDescription()
525
526         def left(self):
527                 self["menulist"].pageUp()
528                 self.loadDescription()
529
530         def right(self):
531                 self["menulist"].pageDown()
532                 self.loadDescription()
533
534         def layoutFinished(self):
535                 idx = 0
536                 self["menulist"].moveToIndex(idx)
537                 self.loadDescription()
538
539         def loadDescription(self):
540                 if self["menulist"].getCurrent()[1] == 'edit':
541                         self["description"].setText(_("Edit the network configuration of your Dreambox.\n" ) + self.oktext )
542                 if self["menulist"].getCurrent()[1] == 'test':
543                         self["description"].setText(_("Test the network configuration of your Dreambox.\n" ) + self.oktext )
544                 if self["menulist"].getCurrent()[1] == 'dns':
545                         self["description"].setText(_("Edit the Nameserver configuration of your Dreambox.\n" ) + self.oktext )
546                 if self["menulist"].getCurrent()[1] == 'scanwlan':
547                         self["description"].setText(_("Scan your network for wireless Access Points and connect to them using your WLAN USB Stick\n" ) + self.oktext )
548                 if self["menulist"].getCurrent()[1] == 'wlanstatus':
549                         self["description"].setText(_("Shows the state of your wireless LAN connection.\n" ) + self.oktext )
550                 if self["menulist"].getCurrent()[1] == 'lanrestart':
551                         self["description"].setText(_("Restart your network connection and interfaces.\n" ) + self.oktext )
552                 if self["menulist"].getCurrent()[1] == 'openwizard':
553                         self["description"].setText(_("Use the Networkwizard to configure your Network\n" ) + self.oktext )
554
555         def updateStatusbar(self):
556                 self["IFtext"].setText(_("Network:"))
557                 self["IF"].setText(iNetwork.getFriendlyAdapterName(self.iface))
558                 self["Statustext"].setText(_("Link:"))
559                 
560                 if self.iface == 'wlan0' or self.iface == 'ath0':
561                         try:
562                                 from Plugins.SystemPlugins.WirelessLan.Wlan import Wlan
563                                 w = Wlan(self.iface)
564                                 stats = w.getStatus()
565                                 if stats['BSSID'] == "00:00:00:00:00:00":
566                                         self["statuspic"].setPixmapNum(1)
567                                 else:
568                                         self["statuspic"].setPixmapNum(0)
569                                 self["statuspic"].show()
570                         except:
571                                         self["statuspic"].setPixmapNum(1)
572                                         self["statuspic"].show()
573                 else:
574                         self.getLinkState(self.iface)
575
576         def doNothing(self):
577                 pass
578
579         def genMainMenu(self):
580                 menu = []
581                 menu.append((_("Adapter settings"), "edit"))
582                 menu.append((_("Nameserver settings"), "dns"))
583                 menu.append((_("Network test"), "test"))
584                 menu.append((_("Restart network"), "lanrestart"))
585                 
586                 for p in plugins.getPlugins(PluginDescriptor.WHERE_NETWORKSETUP):
587                         callFnc = p.__call__["ifaceSupported"](self.iface)
588                         if callFnc is not None:
589                                 menu.append((_("Scan Wireless Networks"), "scanwlan"))
590                                 if iNetwork.getAdapterAttribute(self.iface, "up"):
591                                         menu.append((_("Show WLAN Status"), "wlanstatus"))
592                                 
593                 if os_path.exists(resolveFilename(SCOPE_PLUGINS, "SystemPlugins/NetworkWizard/networkwizard.xml")):
594                         menu.append((_("NetworkWizard"), "openwizard"));
595                 return menu
596
597         def AdapterSetupClosed(self, *ret):
598                 self.mainmenu = self.genMainMenu()
599                 self["menulist"].l.setList(self.mainmenu)
600                 iNetwork.getInterfaces()
601                 self.updateStatusbar()
602
603         def WlanScanClosed(self,*ret):
604                 if ret[0] is not None:
605                         self.session.openWithCallback(self.AdapterSetupClosed, AdapterSetup, self.iface,ret[0],ret[1])
606                 else:
607                         self.session.openWithCallback(self.AdapterSetupClosed, AdapterSetup, self.iface,None,ret[0])
608
609
610         def restartLan(self, ret = False):
611                 if (ret == True):
612                         iNetwork.restartNetwork()
613
614         def getLinkState(self,iface):
615                 iNetwork.getLinkState(iface,self.dataAvail)
616
617         def dataAvail(self,data):
618                 self.output = data.strip()
619                 result = self.output.split('\n')
620                 pattern = re_compile("Link detected: yes")
621                 for item in result:
622                         if re_search(pattern, item):
623                                 self["statuspic"].setPixmapNum(0)
624                         else:
625                                 self["statuspic"].setPixmapNum(1)
626                 self["statuspic"].show()
627
628         def showErrorMessage(self):
629                 self.session.open(MessageBox, self.errortext, type = MessageBox.TYPE_INFO,timeout = 10 )
630
631
632 class NetworkAdapterTest(Screen):       
633         def __init__(self, session,iface):
634                 Screen.__init__(self, session)
635                 self.iface = iface
636                 iNetwork.getInterfaces()
637                 self.setLabels()
638                 
639                 self["updown_actions"] = NumberActionMap(["WizardActions","ShortcutActions"],
640                 {
641                         "ok": self.KeyOK,
642                         "blue": self.KeyOK,
643                         "up": lambda: self.updownhandler('up'),
644                         "down": lambda: self.updownhandler('down'),
645                 
646                 }, -2)
647                 
648                 self["shortcuts"] = ActionMap(["ShortcutActions","WizardActions"],
649                 {
650                         "red": self.close,
651                         "back": self.close,
652                 }, -2)
653                 self["infoshortcuts"] = ActionMap(["ShortcutActions","WizardActions"],
654                 {
655                         "red": self.closeInfo,
656                         "back": self.closeInfo,
657                 }, -2)
658                 self["shortcutsgreen"] = ActionMap(["ShortcutActions"],
659                 {
660                         "green": self.KeyGreen,
661                 }, -2)
662                 self["shortcutsgreen_restart"] = ActionMap(["ShortcutActions"],
663                 {
664                         "green": self.KeyGreenRestart,
665                 }, -2)
666                 self["shortcutsyellow"] = ActionMap(["ShortcutActions"],
667                 {
668                         "yellow": self.KeyYellow,
669                 }, -2)
670                 
671                 self["shortcutsgreen_restart"].setEnabled(False)
672                 self["updown_actions"].setEnabled(False)
673                 self["infoshortcuts"].setEnabled(False)
674                 self.onClose.append(self.delTimer)      
675                 self.onLayoutFinish.append(self.layoutFinished)
676                 self.steptimer = False
677                 self.nextstep = 0
678                 self.activebutton = 0
679                 self.nextStepTimer = eTimer()
680                 self.nextStepTimer.callback.append(self.nextStepTimerFire)
681
682         def closeInfo(self):
683                 self["shortcuts"].setEnabled(True)              
684                 self["infoshortcuts"].setEnabled(False)
685                 self["InfoText"].hide()
686                 self["InfoTextBorder"].hide()
687                 self["ButtonRedtext"].setText(_("Close"))
688
689         def delTimer(self):
690                 del self.steptimer
691                 del self.nextStepTimer
692
693         def nextStepTimerFire(self):
694                 self.nextStepTimer.stop()
695                 self.steptimer = False
696                 self.runTest()
697
698         def updownhandler(self,direction):
699                 if direction == 'up':
700                         if self.activebutton >=2:
701                                 self.activebutton -= 1
702                         else:
703                                 self.activebutton = 6
704                         self.setActiveButton(self.activebutton)
705                 if direction == 'down':
706                         if self.activebutton <=5:
707                                 self.activebutton += 1
708                         else:
709                                 self.activebutton = 1
710                         self.setActiveButton(self.activebutton)
711
712         def setActiveButton(self,button):
713                 if button == 1:
714                         self["EditSettingsButton"].setPixmapNum(0)
715                         self["EditSettings_Text"].setForegroundColorNum(0)
716                         self["NetworkInfo"].setPixmapNum(0)
717                         self["NetworkInfo_Text"].setForegroundColorNum(1)
718                         self["AdapterInfo"].setPixmapNum(1)               # active
719                         self["AdapterInfo_Text"].setForegroundColorNum(2) # active
720                 if button == 2:
721                         self["AdapterInfo_Text"].setForegroundColorNum(1)
722                         self["AdapterInfo"].setPixmapNum(0)
723                         self["DhcpInfo"].setPixmapNum(0)
724                         self["DhcpInfo_Text"].setForegroundColorNum(1)
725                         self["NetworkInfo"].setPixmapNum(1)               # active
726                         self["NetworkInfo_Text"].setForegroundColorNum(2) # active
727                 if button == 3:
728                         self["NetworkInfo"].setPixmapNum(0)
729                         self["NetworkInfo_Text"].setForegroundColorNum(1)
730                         self["IPInfo"].setPixmapNum(0)
731                         self["IPInfo_Text"].setForegroundColorNum(1)
732                         self["DhcpInfo"].setPixmapNum(1)                  # active
733                         self["DhcpInfo_Text"].setForegroundColorNum(2)    # active
734                 if button == 4:
735                         self["DhcpInfo"].setPixmapNum(0)
736                         self["DhcpInfo_Text"].setForegroundColorNum(1)
737                         self["DNSInfo"].setPixmapNum(0)
738                         self["DNSInfo_Text"].setForegroundColorNum(1)
739                         self["IPInfo"].setPixmapNum(1)                  # active
740                         self["IPInfo_Text"].setForegroundColorNum(2)    # active                
741                 if button == 5:
742                         self["IPInfo"].setPixmapNum(0)
743                         self["IPInfo_Text"].setForegroundColorNum(1)
744                         self["EditSettingsButton"].setPixmapNum(0)
745                         self["EditSettings_Text"].setForegroundColorNum(0)
746                         self["DNSInfo"].setPixmapNum(1)                 # active
747                         self["DNSInfo_Text"].setForegroundColorNum(2)   # active
748                 if button == 6:
749                         self["DNSInfo"].setPixmapNum(0)
750                         self["DNSInfo_Text"].setForegroundColorNum(1)
751                         self["EditSettingsButton"].setPixmapNum(1)         # active
752                         self["EditSettings_Text"].setForegroundColorNum(2) # active
753                         self["AdapterInfo"].setPixmapNum(0)
754                         self["AdapterInfo_Text"].setForegroundColorNum(1)
755                         
756         def runTest(self):
757                 next = self.nextstep
758                 if next == 0:
759                         self.doStep1()
760                 elif next == 1:
761                         self.doStep2()
762                 elif next == 2:
763                         self.doStep3()
764                 elif next == 3:
765                         self.doStep4()
766                 elif next == 4:
767                         self.doStep5()
768                 elif next == 5:
769                         self.doStep6()
770                 self.nextstep += 1
771
772         def doStep1(self):
773                 self.steptimer = True
774                 self.nextStepTimer.start(3000)
775
776         def doStep2(self):
777                 self["Adapter"].setText(iNetwork.getFriendlyAdapterName(self.iface))
778                 self["Adapter"].setForegroundColorNum(2)
779                 self["Adaptertext"].setForegroundColorNum(1)
780                 self["AdapterInfo_Text"].setForegroundColorNum(1)
781                 self["AdapterInfo_OK"].show()
782                 self.steptimer = True
783                 self.nextStepTimer.start(3000)
784
785         def doStep3(self):
786                 self["Networktext"].setForegroundColorNum(1)
787                 self.getLinkState(self.iface)
788                 self["NetworkInfo_Text"].setForegroundColorNum(1)
789                 self.steptimer = True
790                 self.nextStepTimer.start(3000)
791
792         def doStep4(self):
793                 self["Dhcptext"].setForegroundColorNum(1)
794                 if iNetwork.getAdapterAttribute(self.iface, 'dhcp') is True:
795                         self["Dhcp"].setForegroundColorNum(2)
796                         self["Dhcp"].setText(_("enabled"))
797                         self["DhcpInfo_Check"].setPixmapNum(0)
798                 else:
799                         self["Dhcp"].setForegroundColorNum(1)
800                         self["Dhcp"].setText(_("disabled"))
801                         self["DhcpInfo_Check"].setPixmapNum(1)
802                 self["DhcpInfo_Check"].show()
803                 self["DhcpInfo_Text"].setForegroundColorNum(1)
804                 self.steptimer = True
805                 self.nextStepTimer.start(3000)
806
807         def doStep5(self):
808                 self["IPtext"].setForegroundColorNum(1)
809                 ret = iNetwork.checkNetworkState()
810                 if ret == True:
811                         self["IP"].setForegroundColorNum(2)
812                         self["IP"].setText(_("confirmed"))
813                         self["IPInfo_Check"].setPixmapNum(0)
814                 else:
815                         self["IP"].setForegroundColorNum(1)
816                         self["IP"].setText(_("unconfirmed"))
817                         self["IPInfo_Check"].setPixmapNum(1)
818                 self["IPInfo_Check"].show()
819                 self["IPInfo_Text"].setForegroundColorNum(1)
820                 self.steptimer = True
821                 self.nextStepTimer.start(3000)
822
823         def doStep6(self):
824                 self.steptimer = False
825                 self.nextStepTimer.stop()
826                 self["DNStext"].setForegroundColorNum(1)
827                 ret = iNetwork.checkDNSLookup()
828                 if ret == True:
829                         self["DNS"].setForegroundColorNum(2)
830                         self["DNS"].setText(_("confirmed"))
831                         self["DNSInfo_Check"].setPixmapNum(0)
832                 else:
833                         self["DNS"].setForegroundColorNum(1)
834                         self["DNS"].setText(_("unconfirmed"))
835                         self["DNSInfo_Check"].setPixmapNum(1)
836                 self["DNSInfo_Check"].show()
837                 self["DNSInfo_Text"].setForegroundColorNum(1)
838                 
839                 self["EditSettings_Text"].show()
840                 self["EditSettingsButton"].setPixmapNum(1)
841                 self["EditSettings_Text"].setForegroundColorNum(2) # active
842                 self["EditSettingsButton"].show()
843                 self["ButtonYellow_Check"].setPixmapNum(1)
844                 self["ButtonGreentext"].setText(_("Restart test"))
845                 self["ButtonGreen_Check"].setPixmapNum(0)
846                 self["shortcutsgreen"].setEnabled(False)
847                 self["shortcutsgreen_restart"].setEnabled(True)
848                 self["shortcutsyellow"].setEnabled(False)
849                 self["updown_actions"].setEnabled(True)
850                 self.activebutton = 6
851
852         def KeyGreen(self):
853                 self["shortcutsgreen"].setEnabled(False)
854                 self["shortcutsyellow"].setEnabled(True)
855                 self["updown_actions"].setEnabled(False)
856                 self["ButtonYellow_Check"].setPixmapNum(0)
857                 self["ButtonGreen_Check"].setPixmapNum(1)
858                 self.steptimer = True
859                 self.nextStepTimer.start(1000)
860
861         def KeyGreenRestart(self):
862                 self.nextstep = 0
863                 self.layoutFinished()
864                 self["Adapter"].setText((""))
865                 self["Network"].setText((""))
866                 self["Dhcp"].setText((""))
867                 self["IP"].setText((""))
868                 self["DNS"].setText((""))
869                 self["AdapterInfo_Text"].setForegroundColorNum(0)
870                 self["NetworkInfo_Text"].setForegroundColorNum(0)
871                 self["DhcpInfo_Text"].setForegroundColorNum(0)
872                 self["IPInfo_Text"].setForegroundColorNum(0)
873                 self["DNSInfo_Text"].setForegroundColorNum(0)
874                 self["shortcutsgreen_restart"].setEnabled(False)
875                 self["shortcutsgreen"].setEnabled(False)
876                 self["shortcutsyellow"].setEnabled(True)
877                 self["updown_actions"].setEnabled(False)
878                 self["ButtonYellow_Check"].setPixmapNum(0)
879                 self["ButtonGreen_Check"].setPixmapNum(1)
880                 self.steptimer = True
881                 self.nextStepTimer.start(1000)
882
883         def KeyOK(self):
884                 self["infoshortcuts"].setEnabled(True)
885                 self["shortcuts"].setEnabled(False)
886                 if self.activebutton == 1: # Adapter Check
887                         self["InfoText"].setText(_("This test detects your configured LAN-Adapter."))
888                         self["InfoTextBorder"].show()
889                         self["InfoText"].show()
890                         self["ButtonRedtext"].setText(_("Back"))
891                 if self.activebutton == 2: #LAN Check
892                         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"))
893                         self["InfoTextBorder"].show()
894                         self["InfoText"].show()
895                         self["ButtonRedtext"].setText(_("Back"))
896                 if self.activebutton == 3: #DHCP Check
897                         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."))
898                         self["InfoTextBorder"].show()
899                         self["InfoText"].show()
900                         self["ButtonRedtext"].setText(_("Back"))
901                 if self.activebutton == 4: # IP Check
902                         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"))
903                         self["InfoTextBorder"].show()
904                         self["InfoText"].show()
905                         self["ButtonRedtext"].setText(_("Back"))
906                 if self.activebutton == 5: # DNS Check
907                         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"))
908                         self["InfoTextBorder"].show()
909                         self["InfoText"].show()
910                         self["ButtonRedtext"].setText(_("Back"))
911                 if self.activebutton == 6: # Edit Settings
912                         self.session.open(AdapterSetup,self.iface)
913
914         def KeyYellow(self):
915                 self.nextstep = 0
916                 self["shortcutsgreen_restart"].setEnabled(True)
917                 self["shortcutsgreen"].setEnabled(False)
918                 self["shortcutsyellow"].setEnabled(False)
919                 self["ButtonGreentext"].setText(_("Restart test"))
920                 self["ButtonYellow_Check"].setPixmapNum(1)
921                 self["ButtonGreen_Check"].setPixmapNum(0)
922                 self.steptimer = False
923                 self.nextStepTimer.stop()
924
925         def layoutFinished(self):
926                 self["shortcutsyellow"].setEnabled(False)
927                 self["AdapterInfo_OK"].hide()
928                 self["NetworkInfo_Check"].hide()
929                 self["DhcpInfo_Check"].hide()
930                 self["IPInfo_Check"].hide()
931                 self["DNSInfo_Check"].hide()
932                 self["EditSettings_Text"].hide()
933                 self["EditSettingsButton"].hide()
934                 self["InfoText"].hide()
935                 self["InfoTextBorder"].hide()
936
937         def setLabels(self):
938                 self["Adaptertext"] = MultiColorLabel(_("LAN Adapter"))
939                 self["Adapter"] = MultiColorLabel()
940                 self["AdapterInfo"] = MultiPixmap()
941                 self["AdapterInfo_Text"] = MultiColorLabel(_("Show Info"))
942                 self["AdapterInfo_OK"] = Pixmap()
943                 
944                 if self.iface == 'wlan0' or self.iface == 'ath0':
945                         self["Networktext"] = MultiColorLabel(_("Wireless Network"))
946                 else:
947                         self["Networktext"] = MultiColorLabel(_("Local Network"))
948                 
949                 self["Network"] = MultiColorLabel()
950                 self["NetworkInfo"] = MultiPixmap()
951                 self["NetworkInfo_Text"] = MultiColorLabel(_("Show Info"))
952                 self["NetworkInfo_Check"] = MultiPixmap()
953                 
954                 self["Dhcptext"] = MultiColorLabel(_("DHCP"))
955                 self["Dhcp"] = MultiColorLabel()
956                 self["DhcpInfo"] = MultiPixmap()
957                 self["DhcpInfo_Text"] = MultiColorLabel(_("Show Info"))
958                 self["DhcpInfo_Check"] = MultiPixmap()
959                 
960                 self["IPtext"] = MultiColorLabel(_("IP Address"))
961                 self["IP"] = MultiColorLabel()
962                 self["IPInfo"] = MultiPixmap()
963                 self["IPInfo_Text"] = MultiColorLabel(_("Show Info"))
964                 self["IPInfo_Check"] = MultiPixmap()
965                 
966                 self["DNStext"] = MultiColorLabel(_("Nameserver"))
967                 self["DNS"] = MultiColorLabel()
968                 self["DNSInfo"] = MultiPixmap()
969                 self["DNSInfo_Text"] = MultiColorLabel(_("Show Info"))
970                 self["DNSInfo_Check"] = MultiPixmap()
971                 
972                 self["EditSettings_Text"] = MultiColorLabel(_("Edit settings"))
973                 self["EditSettingsButton"] = MultiPixmap()
974                 
975                 self["ButtonRedtext"] = Label(_("Close"))
976                 self["ButtonRed"] = Pixmap()
977
978                 self["ButtonGreentext"] = Label(_("Start test"))
979                 self["ButtonGreen_Check"] = MultiPixmap()
980                 
981                 self["ButtonYellowtext"] = Label(_("Stop test"))
982                 self["ButtonYellow_Check"] = MultiPixmap()
983                 
984                 self["InfoTextBorder"] = Pixmap()
985                 self["InfoText"] = Label()
986
987         def getLinkState(self,iface):
988                 if iface == 'wlan0' or iface == 'ath0':
989                         try:
990                                 from Plugins.SystemPlugins.WirelessLan.Wlan import Wlan
991                                 w = Wlan(iface)
992                                 stats = w.getStatus()
993                                 if stats['BSSID'] == "00:00:00:00:00:00":
994                                         self["Network"].setForegroundColorNum(1)
995                                         self["Network"].setText(_("disconnected"))
996                                         self["NetworkInfo_Check"].setPixmapNum(1)
997                                         self["NetworkInfo_Check"].show()
998                                 else:
999                                         self["Network"].setForegroundColorNum(2)
1000                                         self["Network"].setText(_("connected"))
1001                                         self["NetworkInfo_Check"].setPixmapNum(0)
1002                                         self["NetworkInfo_Check"].show()
1003                         except:
1004                                         self["Network"].setForegroundColorNum(1)
1005                                         self["Network"].setText(_("disconnected"))
1006                                         self["NetworkInfo_Check"].setPixmapNum(1)
1007                                         self["NetworkInfo_Check"].show()
1008                 else:
1009                         iNetwork.getLinkState(iface,self.dataAvail)
1010
1011         def dataAvail(self,data):
1012                 self.output = data.strip()
1013                 result = self.output.split('\n')
1014                 pattern = re_compile("Link detected: yes")
1015                 for item in result:
1016                         if re_search(pattern, item):
1017                                 self["Network"].setForegroundColorNum(2)
1018                                 self["Network"].setText(_("connected"))
1019                                 self["NetworkInfo_Check"].setPixmapNum(0)
1020                         else:
1021                                 self["Network"].setForegroundColorNum(1)
1022                                 self["Network"].setText(_("disconnected"))
1023                                 self["NetworkInfo_Check"].setPixmapNum(1)
1024                 self["NetworkInfo_Check"].show()
1025
1026