NetworkWizard: follow network.py to improve wireless interface/module detection....
[enigma2.git] / lib / python / Plugins / SystemPlugins / NetworkWizard / NetworkWizard.py
1 from Screens.Wizard import wizardManager, WizardSummary
2 from Screens.WizardLanguage import WizardLanguage
3 from Screens.Rc import Rc
4 from Screens.MessageBox import MessageBox
5 from Components.Pixmap import Pixmap, MovingPixmap, MultiPixmap
6 from Components.Sources.Boolean import Boolean
7 from Components.config import config, ConfigBoolean, configfile, ConfigYesNo, NoSave, ConfigSubsection, ConfigText, getConfigListEntry, ConfigSelection, ConfigPassword
8 from Components.Network import iNetwork
9 from Tools.Directories import resolveFilename, SCOPE_PLUGINS, SCOPE_SKIN_IMAGE
10 from enigma import eTimer
11
12 config.misc.firstrun = ConfigBoolean(default = True)
13 list = []
14 list.append("WEP")
15 list.append("WPA")
16 list.append("WPA2")
17 list.append("WPA/WPA2")
18
19 weplist = []
20 weplist.append("ASCII")
21 weplist.append("HEX")
22
23 config.plugins.wlan = ConfigSubsection()
24 config.plugins.wlan.essid = NoSave(ConfigText(default = "home", fixed_size = False))
25 config.plugins.wlan.hiddenessid = NoSave(ConfigText(default = "home", fixed_size = False))
26
27 config.plugins.wlan.encryption = ConfigSubsection()
28 config.plugins.wlan.encryption.enabled = NoSave(ConfigYesNo(default = False))
29 config.plugins.wlan.encryption.type = NoSave(ConfigSelection(list, default = "WPA/WPA2" ))
30 config.plugins.wlan.encryption.wepkeytype = NoSave(ConfigSelection(weplist, default = "ASCII"))
31 config.plugins.wlan.encryption.psk = NoSave(ConfigPassword(default = "mysecurewlan", fixed_size = False))
32
33 class NetworkWizard(WizardLanguage, Rc):
34         skin = """
35                 <screen position="0,0" size="720,576" title="Welcome..." flags="wfNoBorder" >
36                         <widget name="text" position="153,40" size="340,300" font="Regular;22" />
37                         <widget source="list" render="Listbox" position="53,340" size="440,180" scrollbarMode="showOnDemand" >
38                                 <convert type="StringList" />
39                         </widget>
40                         <widget name="config" position="53,340" zPosition="1" size="440,180" transparent="1" scrollbarMode="showOnDemand" />
41                         <ePixmap pixmap="skin_default/buttons/button_red.png" position="40,225" zPosition="0" size="15,16" transparent="1" alphatest="on" />
42                         <widget name="languagetext" position="55,225" size="95,30" font="Regular;18" />
43                         <widget name="wizard" pixmap="skin_default/wizard.png" position="40,50" zPosition="10" size="110,174" alphatest="on" />
44                         <widget name="rc" pixmaps="skin_default/rc.png,skin_default/rcold.png" position="500,50" zPosition="10" size="154,500" alphatest="on" />
45                         <widget name="arrowdown" pixmap="skin_default/arrowdown.png" position="-100,-100" zPosition="11" size="37,70" alphatest="on" />
46                         <widget name="arrowdown2" pixmap="skin_default/arrowdown.png" position="-100,-100" zPosition="11" size="37,70" alphatest="on" />
47                         <widget name="arrowup" pixmap="skin_default/arrowup.png" position="-100,-100" zPosition="11" size="37,70" alphatest="on" />
48                         <widget name="arrowup2" pixmap="skin_default/arrowup.png" position="-100,-100" zPosition="11" size="37,70" alphatest="on" />
49                         <widget source="VKeyIcon" render="Pixmap" pixmap="skin_default/buttons/key_text.png" position="40,260" zPosition="0" size="35,25" transparent="1" alphatest="on" >
50                                 <convert type="ConditionalShowHide" />
51                         </widget>
52                         <widget name="HelpWindow" pixmap="skin_default/buttons/key_text.png" position="125,170" zPosition="1" size="1,1" transparent="1" alphatest="on" />      
53                 </screen>"""
54         def __init__(self, session, interface = None):
55                 self.xmlfile = resolveFilename(SCOPE_PLUGINS, "SystemPlugins/NetworkWizard/networkwizard.xml")
56                 WizardLanguage.__init__(self, session, showSteps = False, showStepSlider = False)
57                 Rc.__init__(self)
58                 self.session = session
59                 self["wizard"] = Pixmap()
60                 self["HelpWindow"] = Pixmap()
61                 self["HelpWindow"].hide()
62                 self["VKeyIcon"] = Boolean(False)
63
64                 self.InstalledInterfaceCount = None
65                 self.Adapterlist = None
66                 self.InterfaceState = None
67                 self.isInterfaceUp = None
68                 self.WlanPluginInstalled = None
69                 self.ap = None
70                 if interface is not None:
71                         self.selectedInterface = interface
72                 else:
73                         self.selectedInterface = None
74                 self.NextStep = None
75                 self.resetRef = None
76                 self.checkRef = None
77                 self.AdapterRef = None
78                 self.APList = None
79                 self.newAPlist = None
80                 self.WlanList = None
81                 self.oldlist = None
82                 self.originalAth0State = None
83                 self.originalEth0State = None
84                 self.originalWlan0State = None
85                 self.originalRa0State = None
86                 self.originalInterfaceStateChanged = False
87                 self.Text = None
88                 self.rescanTimer = eTimer()
89                 self.rescanTimer.callback.append(self.rescanTimerFired)
90                 self.getInstalledInterfaceCount()
91                 self.isWlanPluginInstalled()
92                 
93         def exitWizardQuestion(self, ret = False):
94                 if (ret):
95                         self.markDone()
96                         self.close()
97                 
98         def markDone(self):
99                 self.rescanTimer.stop()
100                 del self.rescanTimer
101                 self.checkOldInterfaceState()
102                 pass
103
104         def getInstalledInterfaceCount(self):
105                 self.rescanTimer.stop()
106                 self.Adapterlist = iNetwork.getAdapterList()
107                 self.InstalledInterfaceCount = len(self.Adapterlist)
108                 if self.Adapterlist is not None:
109                         if self.InstalledInterfaceCount == 1 and self.selectedInterface is None:
110                                         self.selectedInterface = self.Adapterlist[0]
111                 self.originalAth0State = iNetwork.getAdapterAttribute('ath0', 'up')
112                 self.originalEth0State = iNetwork.getAdapterAttribute('eth0', 'up')
113                 self.originalWlan0State = iNetwork.getAdapterAttribute('wlan0', 'up')
114                 self.originalRa0State = iNetwork.getAdapterAttribute('ra0', 'up')
115
116         def selectInterface(self):
117                 self.InterfaceState = None
118                 if self.selectedInterface is None and self.InstalledInterfaceCount <= 1:
119                         if self.selectedInterface == 'eth0':
120                                 self.NextStep = 'nwconfig'
121                         else:
122                                 self.NextStep = 'scanwlan'
123                         self.checkInterface(self.selectedInterface)
124                 elif self.selectedInterface is not None and self.InstalledInterfaceCount <= 1:
125                         if self.selectedInterface == 'eth0':
126                                 self.NextStep = 'nwconfig'
127                         else:
128                                 self.NextStep = 'scanwlan'
129                         self.checkInterface(self.selectedInterface)
130                 elif self.selectedInterface is None and self.InstalledInterfaceCount > 1:
131                         self.NextStep = 'selectinterface'
132                         self.currStep = self.getStepWithID(self.NextStep)
133                         self.afterAsyncCode()
134                 elif self.selectedInterface is not None and self.InstalledInterfaceCount > 1:
135                         if self.selectedInterface == 'eth0':
136                                 self.NextStep = 'nwconfig'
137                         else:
138                                 self.NextStep = 'scanwlan'
139                         self.checkInterface(self.selectedInterface)
140                 else:
141                         self.NextStep = 'selectinterface'
142                         self.currStep = self.getStepWithID(self.NextStep)
143                         self.afterAsyncCode()                   
144
145         def checkOldInterfaceState(self):
146                 # disable up interface if it was originally down and config is unchanged.
147                 if self.originalAth0State is False and self.originalInterfaceStateChanged is False:
148                         if iNetwork.checkforInterface('ath0') is True:
149                                 iNetwork.deactivateInterface('ath0')            
150                 if self.originalEth0State is False and self.originalInterfaceStateChanged is False:
151                         if iNetwork.checkforInterface('eth0') is True:
152                                 iNetwork.deactivateInterface('eth0')
153                 if self.originalWlan0State is False and self.originalInterfaceStateChanged is False:
154                         if iNetwork.checkforInterface('wlan0') is True:
155                                 iNetwork.deactivateInterface('wlan0')
156                 if self.originalRa0State is False and self.originalInterfaceStateChanged is False:
157                         if iNetwork.checkforInterface('ra0') is True:
158                                 iNetwork.deactivateInterface('ra0')
159         def listInterfaces(self):
160                 self.rescanTimer.stop()
161                 self.checkOldInterfaceState()
162                 list = [(iNetwork.getFriendlyAdapterName(x),x) for x in iNetwork.getAdapterList()]
163                 list.append((_("Exit network wizard"), "end"))
164                 return list
165
166         def InterfaceSelectionMade(self, index):
167                 self.selectedInterface = index
168                 self.InterfaceSelect(index)
169
170         def InterfaceSelect(self, index):
171                 if index == 'end':
172                         self.NextStep = 'end'
173                 elif index == 'eth0':
174                         self.NextStep = 'nwconfig'
175                 else:
176                         self.NextStep = 'scanwlan'
177
178         def InterfaceSelectionMoved(self):
179                 self.InterfaceSelect(self.selection)
180                 
181         def checkInterface(self,iface):
182                 self.rescanTimer.stop()
183                 if self.Adapterlist is None:
184                         self.Adapterlist = iNetwork.getAdapterList()
185                 if self.NextStep is not 'end':
186                         if len(self.Adapterlist) == 0:
187                                 #Reset Network to defaults if network broken
188                                 iNetwork.resetNetworkConfig('lan', self.resetNetworkConfigCB)
189                                 self.resetRef = self.session.openWithCallback(self.resetNetworkConfigFinished, MessageBox, _("Please wait while we prepare your network interfaces..."), type = MessageBox.TYPE_INFO, enable_input = False)
190                         if iface in ('eth0', 'wlan0', 'ath0', 'ra0'):
191                                 if iface in iNetwork.configuredNetworkAdapters and len(iNetwork.configuredNetworkAdapters) == 1:
192                                         if iNetwork.getAdapterAttribute(iface, 'up') is True:
193                                                 self.isInterfaceUp = True
194                                         else:
195                                                 self.isInterfaceUp = False
196                                         self.currStep = self.getStepWithID(self.NextStep)
197                                         self.afterAsyncCode()
198                                 else:
199                                         self.isInterfaceUp = iNetwork.checkforInterface(iface)
200                                         self.currStep = self.getStepWithID(self.NextStep)
201                                         self.afterAsyncCode()
202                 else:
203                         self.resetNetworkConfigFinished(False)
204                         
205         def resetNetworkConfigFinished(self,data):
206                 if data is True:
207                         self.currStep = self.getStepWithID(self.NextStep)
208                         self.afterAsyncCode()
209                 else:
210                         self.currStep = self.getStepWithID(self.NextStep)
211                         self.afterAsyncCode()
212
213         def resetNetworkConfigCB(self,callback,iface):
214                 if callback is not None:
215                         if callback is True:
216                                 iNetwork.getInterfaces(self.getInterfacesFinished)
217                                 
218         def getInterfacesFinished(self, data):
219                 if data is True:
220                         if iNetwork.getAdapterAttribute(self.selectedInterface, 'up') is True:
221                                 self.isInterfaceUp = True
222                         else:
223                                 self.isInterfaceUp = False
224                         self.resetRef.close(True)
225                 else:
226                         print "we should never come here!"
227
228         def AdapterSetupEnd(self, iface):
229                 self.originalInterfaceStateChanged = True
230                 if iNetwork.getAdapterAttribute(iface, "dhcp") is True:
231                         iNetwork.checkNetworkState(self.AdapterSetupEndFinished)
232                         self.AdapterRef = self.session.openWithCallback(self.AdapterSetupEndCB, MessageBox, _("Please wait while we test your network..."), type = MessageBox.TYPE_INFO, enable_input = False)
233                 else:
234                         self.currStep = self.getStepWithID("confdns")
235                         self.afterAsyncCode()
236
237         def AdapterSetupEndCB(self,data):
238                 if data is True:
239                         if iNetwork.isWirelessInterface(self.selectedInterface):
240                                 if self.WlanPluginInstalled == True:
241                                         from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus
242                                         iStatus.getDataForInterface(self.selectedInterface,self.checkWlanStateCB)
243                                 else:
244                                         self.currStep = self.getStepWithID("checklanstatusend")
245                                         self.afterAsyncCode()                                   
246                         else:
247                                 self.currStep = self.getStepWithID("checklanstatusend")
248                                 self.afterAsyncCode()
249
250         def AdapterSetupEndFinished(self,data):
251                 if data <= 2:
252                         self.InterfaceState = True
253                 else:
254                         self.InterfaceState = False
255                 self.AdapterRef.close(True)
256                         
257         def checkWlanStateCB(self,data,status):
258                 if data is not None:
259                         if data is True:
260                                 if status is not None:
261                                         text1 = _("Your Dreambox is now ready to use.\n\nYour internet connection is working now.\n\n")
262                                         text2 = _('Accesspoint:') + "\t" + str(status[self.selectedInterface]["acesspoint"]) + "\n"
263                                         text3 = _('SSID:') + "\t" + str(status[self.selectedInterface]["essid"]) + "\n"
264                                         text4 = _('Link Quality:') + "\t" + str(status[self.selectedInterface]["quality"])+ "\n"
265                                         text5 = _('Signal Strength:') + "\t" + str(status[self.selectedInterface]["signal"]) + "\n"
266                                         text6 = _('Bitrate:') + "\t" + str(status[self.selectedInterface]["bitrate"]) + "\n"
267                                         text7 = _('Encryption:') + " " + str(status[self.selectedInterface]["encryption"]) + "\n"
268                                         text8 = _("Please press OK to continue.")
269                                         infotext = text1 + text2 + text3 + text4 + text5 + text7 +"\n" + text8
270                                         self.currStep = self.getStepWithID("checkWlanstatusend")
271                                         self.Text = infotext
272                                         if str(status[self.selectedInterface]["acesspoint"]) == "Not-Associated":
273                                                 self.InterfaceState = False
274                                         self.afterAsyncCode()
275
276         def checkNetwork(self):
277                 iNetwork.checkNetworkState(self.checkNetworkStateCB)
278                 self.checkRef = self.session.openWithCallback(self.checkNetworkCB, MessageBox, _("Please wait while we test your network..."), type = MessageBox.TYPE_INFO, enable_input = False)
279
280         def checkNetworkCB(self,data):
281                 if data is True:
282                         if iNetwork.isWirelessInterface(self.selectedInterface):
283                                 if self.WlanPluginInstalled == True:
284                                         from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus
285                                         iStatus.getDataForInterface(self.selectedInterface,self.checkWlanStateCB)
286                                 else:
287                                         self.currStep = self.getStepWithID("checklanstatusend")
288                                         self.afterAsyncCode()                                   
289                         else:
290                                 self.currStep = self.getStepWithID("checklanstatusend")
291                                 self.afterAsyncCode()
292
293         def checkNetworkStateCB(self,data):
294                 if data <= 2:
295                         self.InterfaceState = True
296                 else:
297                         self.InterfaceState = False
298                 self.checkRef.close(True)
299         
300         def rescanTimerFired(self):
301                 self.rescanTimer.stop()
302                 self.updateAPList()
303
304         def updateAPList(self):
305                 self.oldlist = self.APList
306                 self.newAPlist = []
307                 newList = []
308                 newListIndex = None
309                 currentListEntry = None
310                 newList = self.listAccessPoints()
311
312                 for oldentry in self.oldlist:
313                         if oldentry not in newList:
314                                 newList.append(oldentry)
315                                 
316                 for newentry in newList:
317                         if newentry[1] == "hidden...":
318                                 continue
319                         self.newAPlist.append(newentry)
320                 
321                 if len(self.newAPlist):
322                         if "hidden..." not in self.newAPlist:
323                                 self.newAPlist.append(( _("enter hidden network SSID"), "hidden..." ))
324
325                         if (self.wizard[self.currStep].has_key("dynamiclist")):
326                                 currentListEntry = self["list"].getCurrent()
327                                 idx = 0
328                                 for entry in self.newAPlist:
329                                         if entry == currentListEntry:
330                                                 newListIndex = idx
331                                         idx +=1
332                                 self.wizard[self.currStep]["evaluatedlist"] = self.newAPlist
333                                 self['list'].setList(self.newAPlist)
334                                 self["list"].setIndex(newListIndex)
335                                 self["list"].updateList(self.newAPlist)
336
337         def listAccessPoints(self):
338                 self.APList = []
339                 try:
340                         from Plugins.SystemPlugins.WirelessLan.Wlan import Wlan
341                 except ImportError:
342                         self.APList.append( ( _("No networks found"),_("unavailable") ) )
343                         return self.APList
344                 else:
345                         try:
346                                 self.w = Wlan(self.selectedInterface)
347                                 aps = self.w.getNetworkList()
348                         except ValueError:
349                                 self.APList = []
350                                 self.APList.append( ( _("No networks found"),_("unavailable") ) )
351                                 return self.APList
352                         else:
353                                 if aps is not None:
354                                         print "[NetworkWizard.py] got Accespoints!"
355                                         tmplist = []
356                                         complist = []
357                                         for ap in aps:
358                                                 a = aps[ap]
359                                                 if a['active']:
360                                                         tmplist.append( (a['bssid'], a['essid']) )
361                                                         complist.append( (a['bssid'], a['essid']) )
362                                         
363                                         for entry in tmplist:
364                                                 if entry[1] == "":
365                                                         for compentry in complist:
366                                                                 if compentry[0] == entry[0]:
367                                                                         complist.remove(compentry)
368                                         for entry in complist:
369                                                 self.APList.append( (entry[1], entry[1]) )
370         
371                                 if "hidden..." not in self.APList:
372                                         self.APList.append(( _("enter hidden network SSID"), "hidden..." ))
373                         
374                                 self.rescanTimer.start(3000)
375                                 return self.APList
376
377         def AccessPointsSelectionMade(self, index):
378                 self.ap = index
379                 self.WlanList = []
380                 currList = []
381                 if (self.wizard[self.currStep].has_key("dynamiclist")):
382                         currList = self['list'].list
383                         for entry in currList:
384                                 self.WlanList.append( (entry[1], entry[0]) )
385                 self.AccessPointsSelect(index)
386
387         def AccessPointsSelect(self, index):
388                 self.NextStep = 'wlanconfig'
389
390         def AccessPointsSelectionMoved(self):
391                 self.AccessPointsSelect(self.selection)
392
393         def checkWlanSelection(self):
394                 self.rescanTimer.stop()
395                 self.currStep = self.getStepWithID(self.NextStep)
396
397         def isWlanPluginInstalled(self):
398                 try:
399                         from Plugins.SystemPlugins.WirelessLan.Wlan import Wlan
400                 except ImportError:
401                         self.WlanPluginInstalled = False
402                 else:
403                         self.WlanPluginInstalled = True
404
405         def listChoices(self):
406                 self.rescanTimer.stop()
407                 list = []
408                 if self.WlanPluginInstalled == True:
409                         list.append((_("Configure your wireless LAN again"), "scanwlan"))
410                 list.append((_("Configure your internal LAN"), "nwconfig"))
411                 list.append((_("Exit network wizard"), "end"))          
412                 return list
413
414         def ChoicesSelectionMade(self, index):
415                 self.ChoicesSelect(index)
416
417         def ChoicesSelect(self, index):
418                 if index == 'end':
419                         self.NextStep = 'end'
420                 elif index == 'nwconfig':
421                         self.selectedInterface = "eth0"
422                         self.NextStep = 'nwconfig'
423                 else:
424                         self.NextStep = 'scanwlan'
425
426         def ChoicesSelectionMoved(self):
427                 pass
428