some fixes for the new network configuration
[vuplus_dvbapp] / lib / python / Plugins / SystemPlugins / WirelessLan / Wlan.py
1 from enigma import eListboxPythonMultiContent, eListbox, gFont, RT_HALIGN_LEFT, RT_HALIGN_RIGHT, RT_HALIGN_CENTER
2
3 from Components.MultiContent import MultiContentEntryText
4 from Components.GUIComponent import GUIComponent
5 from Components.HTMLComponent import HTMLComponent
6 from Components.config import config, ConfigYesNo, ConfigIP, NoSave, ConfigSubsection, ConfigMAC, ConfigEnableDisable, ConfigText, ConfigSelection
7
8 from pythonwifi import iwlibs
9
10 import os, string
11
12
13 list = []
14 list.append(_("WEP"))
15 list.append(_("WPA"))
16 list.append(_("WPA2"))
17
18 config.plugins.wlan = ConfigSubsection()
19 config.plugins.wlan.essid = NoSave(ConfigText(default = "home", fixed_size = False))
20
21 config.plugins.wlan.encryption = ConfigSubsection()
22 config.plugins.wlan.encryption.enabled = NoSave(ConfigYesNo(default = False))
23 config.plugins.wlan.encryption.type = NoSave(ConfigSelection(list, default = _("WPA")))
24 config.plugins.wlan.encryption.psk = NoSave(ConfigText(default = "mysecurewlan", fixed_size = False))
25
26 class Wlan:
27         def __init__(self):
28                 a = ''; b = ''
29                 
30                 for i in range(0, 255):
31                     a = a + chr(i)
32                     if i < 32 or i > 127:
33                         b = b + ' '
34                     else:
35                         b = b + chr(i)
36                 
37                 self.asciitrans = string.maketrans(a, b)
38
39         def asciify(self, str):
40                 return str.translate(self.asciitrans)
41         
42         def getWirelessInterfaces(self):
43                 iwifaces = None
44                 try:
45                         iwifaces = iwlibs.getNICnames()
46                 except:
47                         iwifaces = None
48                         "[Wlan.py] No Wireless Networkcards could be found"
49                 
50                 return iwifaces
51         
52         def getNetworkList(self, iface):
53
54                 ifobj = iwlibs.Wireless(iface) # a Wireless NIC Object
55                 
56                 #Association mappings
57                 stats, quality, discard, missed_beacon = ifobj.getStatistics()
58                 snr = quality.signallevel - quality.noiselevel
59                 
60                 try:
61                         scanresults = ifobj.scan()
62                 except:
63                         scanresults = None
64                         print "[Wlan.py] No Wireless Networks could be found"
65                 
66                 if scanresults is not None:
67                         aps = {}
68                         for result in scanresults:
69                                 
70                                 bssid = result.bssid
71                 
72                                 encryption = map(lambda x: hex(ord(x)), result.encode)
73                 
74                                 if encryption[-1] == "0x8":
75                                         encryption = True
76                                 else:
77                                         encryption = False
78                 
79                                 extra = []
80                                 for element in result.custom:
81                                         element = element.encode()
82                                         extra.append( string.strip(self.asciify(element)) )
83                 
84                                 aps[bssid] = {
85                                         'active' : True,
86                                         'bssid': result.bssid,
87                                         'channel': result.frequency.getChannel(result.frequency.getFrequency(), result.range),
88                                         'encrypted': encryption,
89                                         'essid': string.strip(self.asciify(result.essid)),
90                                         'iface': iface,
91                                         'maxrate' : result.rate[-1],
92                                         'noise' : result.quality.getNoiselevel(),
93                                         'quality' : result.quality.quality,
94                                         'signal' : result.quality.getSignallevel(),
95                                         'custom' : extra,
96                                 }
97                                 
98                         return aps
99                                 
100
101 class WlanList(HTMLComponent, GUIComponent):
102         
103         def __init__(self, session, iface = 'wlan0'):
104                 
105                 GUIComponent.__init__(self)
106                 self.w = Wlan()
107                 self.iface = iface
108                 
109                 self.l = None
110                 self.l = eListboxPythonMultiContent()
111                 
112                 self.l.setFont(0, gFont("Regular", 32))
113                 self.l.setFont(1, gFont("Regular", 18))
114                 self.l.setFont(2, gFont("Regular", 16))
115                 self.l.setBuildFunc(self.buildWlanListEntry)            
116                                 
117                 self.reload()
118         
119         def buildWlanListEntry(self, essid, bssid, encrypted, iface, maxrate):                                                                                                 
120                 
121                 res = [ (essid, encrypted, iface) ]
122                 e = encrypted and _("Yes") or _("No")
123                 res.append( MultiContentEntryText(pos=(0, 0), size=(570, 35), font=0, flags=RT_HALIGN_LEFT, text=essid) )
124                 res.append( MultiContentEntryText(pos=(0, 40), size=(180, 20), font=1, flags=RT_HALIGN_LEFT, text=_("Max. Bitrate: ")+maxrate) )
125                 res.append( MultiContentEntryText(pos=(190, 40), size=(180, 20), font=1, flags=RT_HALIGN_CENTER, text=_("Encrypted: ")+e) )
126                 res.append( MultiContentEntryText(pos=(380, 40), size=(190, 20), font=1, flags=RT_HALIGN_RIGHT, text=_("Interface: ")+iface) )
127                 return res
128                         
129         def reload(self):
130                 aps = self.w.getNetworkList(self.iface)
131                 list = []
132                 if aps is not None:
133                         print "[Wlan.py] got Accespoints!"
134                         for ap in aps:
135                                 a = aps[ap]
136                                 if a['active']:
137                                         list.append((a['essid'], a['bssid'], a['encrypted'], a['iface'], a['maxrate']))
138                 
139                 self.l.setList([])
140                 self.l.setList(list)
141                         
142         GUI_WIDGET = eListbox
143
144         def getCurrent(self):
145                 return self.l.getCurrentSelection()
146         
147         def postWidgetCreate(self, instance):
148                 instance.setContent(self.l)
149                 instance.setItemHeight(60)
150
151
152 class wpaSupplicant:
153         def __init__(self):
154                 pass
155                 
156         def writeConfig(self):  
157                         
158                         essid = config.plugins.wlan.essid.value
159                         encrypted = config.plugins.wlan.encryption.enabled.value
160                         encryption = config.plugins.wlan.encryption.type.value
161                         psk = config.plugins.wlan.encryption.psk.value
162
163                 
164                         fp = file('/etc/wpa_supplicant.conf', 'w')
165                         fp.write('#WPA Supplicant Configuration by enigma2\n\n')
166                         fp.write('ctrl_interface=/var/run/wpa_supplicant\n')
167                         fp.write('ctrl_interface_group=0\n')
168                         fp.write('network={\n')
169                         fp.write('\tssid="'+essid+'"\n')
170                         fp.write('\tscan_ssid=1\n')
171                         
172                         if encrypted:
173                                                         
174                                 if encryption == 'WPA' or encryption == 'WPA2':
175                                         fp.write('\tkey_mgmt=WPA-PSK\n')
176                                         
177                                         if encryption == 'WPA':
178                                                 fp.write('\tproto=WPA\n')
179                                                 fp.write('\tpairwise=TKIP\n')
180                                         else:
181                                                 fp.write('\tproto=WPA RSN\n')
182                                                 fp.write('\tpairwise=CCMP TKIP\n')
183                                         
184                                         fp.write('\tpsk="'+psk+'"\n')
185                                 
186                                 elif encryption == 'WEP':
187                                         fp.write('\tkey_mgmt=NONE\n')
188                                         fp.write('\twep_key0="'+psk+'"\n')
189                         
190                         fp.write('}')   
191                         fp.close()
192                                         
193                         
194         def loadConfig(self):
195
196                 try:
197                         #parse the wpasupplicant configfile
198                         fp = file('/etc/wpa_supplicant.conf', 'r')
199                         supplicant = fp.readlines()
200                         fp.close()
201                         
202                         for s in supplicant:
203                         
204                                 split = s.strip().split('=')
205                                 if split[0] == 'ssid':
206                                         print "[Wlan.py] Got SSID "+split[1][1:-1]
207                                         config.plugins.wlan.essid.value = split[1][1:-1]
208                                         
209                                 elif split[0] == 'proto':
210                                         config.plugins.wlan.encryption.enabled.value = True
211                                         if split[1] == "WPA RSN" : split[1] = 'WPA2'
212                                         config.plugins.wlan.encryption.type.value = split[1]
213                                         print "[Wlan.py] Got Encryption "+split[1]
214                                 
215                                 elif split[0] == 'psk':
216                                         config.plugins.wlan.encryption.psk.value = split[1][1:-1]
217                                         print "[Wlan.py] Got PSK "+split[1][1:-1]
218                                 else:
219                                         pass
220                                 
221                 except:
222                         print "[Wlan.py] Error parsing /etc/wpa_supplicant.conf"
223         
224         def restart(self, iface):
225                 import os
226                 os.system("start-stop-daemon -K -x /usr/sbin/wpa_supplicant")
227                 os.system("start-stop-daemon -S -x /usr/sbin/wpa_supplicant -- -B -i"+iface+" -c/etc/wpa_supplicant.conf")