-support new zydas driver
[enigma2-plugins.git] / wirelesslan / src / Wlan.py
1 # for localized messages
2 from __init__ import _
3
4 from enigma import eListboxPythonMultiContent, eListbox, gFont, RT_HALIGN_LEFT, RT_HALIGN_RIGHT, RT_HALIGN_CENTER
5 from Components.MultiContent import MultiContentEntryText
6 from Components.GUIComponent import GUIComponent
7 from Components.HTMLComponent import HTMLComponent
8 from Components.config import config, ConfigYesNo, NoSave, ConfigSubsection, ConfigText, ConfigSelection
9
10 from os import system
11 from string import maketrans, strip
12 from iwlibs import getNICnames, Wireless, Iwfreq
13
14 list = []
15 list.append(_("WEP"))
16 list.append(_("WPA"))
17 list.append(_("WPA2"))
18
19 config.plugins.wlan = ConfigSubsection()
20 config.plugins.wlan.essid = NoSave(ConfigText(default = "home", fixed_size = False))
21
22 config.plugins.wlan.encryption = ConfigSubsection()
23 config.plugins.wlan.encryption.enabled = NoSave(ConfigYesNo(default = False))
24 config.plugins.wlan.encryption.type = NoSave(ConfigSelection(list, default = _("WPA")))
25 config.plugins.wlan.encryption.psk = NoSave(ConfigText(default = "mysecurewlan", fixed_size = False))
26
27 class Wlan:
28         def __init__(self, iface):
29                 a = ''; b = ''
30                 
31                 for i in range(0, 255):
32                     a = a + chr(i)
33                     if i < 32 or i > 127:
34                         b = b + ' '
35                     else:
36                         b = b + chr(i)
37                 
38                 self.iface = iface
39                 self.asciitrans = maketrans(a, b)
40
41         
42         def asciify(self, str):
43                 return str.translate(self.asciitrans)
44
45         
46         def getWirelessInterfaces(self):
47                 iwifaces = None
48                 try:
49                         iwifaces = getNICnames()
50                 except:
51                         print "[Wlan.py] No Wireless Networkcards could be found"
52                 
53                 return iwifaces
54
55         
56         def getNetworkList(self):
57                 ifobj = Wireless(self.iface) # a Wireless NIC Object
58                 print "ifobj.getStatistics(): ", ifobj.getStatistics()
59                 
60                 #Association mappings
61                 stats, quality, discard, missed_beacon = ifobj.getStatistics()
62                 snr = quality.signallevel - quality.noiselevel
63                 system("ifconfig "+self.iface+" up")
64                 
65                 try:
66                         scanresults = ifobj.scan()
67                 except:
68                         scanresults = None
69                         print "[Wlan.py] No Wireless Networks could be found"
70                 
71                 if scanresults is not None:
72                         aps = {}
73                         for result in scanresults:
74                                 
75                                 bssid = result.bssid
76                 
77                                 encryption = map(lambda x: hex(ord(x)), result.encode)
78                 
79                                 if encryption[-1] == "0x8":
80                                         encryption = True
81                                 else:
82                                         encryption = False
83                 
84                                 extra = []
85                                 for element in result.custom:
86                                         element = element.encode()
87                                         extra.append( strip(self.asciify(element)) )
88                                 
89                                 print result.quality.getSignallevel()
90                                 
91                                 if result.quality.sl is 0 and len(extra) > 0:
92                                         begin = extra[0].find('SignalStrength=')+15
93                                                                         
94                                         done = False
95                                         end = begin+1
96                                         
97                                         while not done:
98                                                 if extra[0][begin:end].isdigit():
99                                                         end += 1
100                                                 else:
101                                                         done = True
102                                                         end -= 1
103                                         
104                                         signal = extra[0][begin:end]
105                                         print "[Wlan.py] signal is:" + str(signal)
106
107                                 else:
108                                         signal = str(result.quality.sl)
109                                 
110                                 aps[bssid] = {
111                                         'active' : True,
112                                         'bssid': result.bssid,
113                                         'channel': result.frequency.getChannel(result.frequency.getFrequency()),
114                                         'encrypted': encryption,
115                                         'essid': strip(self.asciify(result.essid)),
116                                         'iface': self.iface,
117                                         'maxrate' : result.rate[-1],
118                                         'noise' : result.quality.getNoiselevel(),
119                                         'quality' : str(result.quality.quality),
120                                         'signal' : signal,
121                                         'custom' : extra,
122                                 }
123                                 print aps[bssid]
124                         return aps
125
126                 
127         def getStatus(self):
128                 ifobj = Wireless(self.iface)
129                 fq = Iwfreq()
130                 
131                 status = {
132                                   'BSSID': str(ifobj.getAPaddr()),
133                                   'ESSID': str(ifobj.getEssid()),
134                                   'quality': str(ifobj.getStatistics()[1].quality),
135                                   'signal': str(ifobj.getStatistics()[1].sl),
136                                   'bitrate': str(ifobj.getBitrate()),
137                                   'channel': str(fq.getChannel(str(ifobj.getFrequency()[0:-3]))),
138                 }
139                 
140                 for (key, item) in status.items():
141                         if item is "None" or item is "":
142                                         status[key] = _("N/A")
143                                 
144                 return status
145
146
147
148 class WlanList(HTMLComponent, GUIComponent):
149         def __init__(self, session, iface):
150                 
151                 GUIComponent.__init__(self)
152                 self.w = Wlan(iface)
153                 self.iface = iface
154                 
155                 self.length = 0
156                 self.aplist = None
157                 self.l = None
158                 self.l = eListboxPythonMultiContent()
159                 
160                 self.l.setFont(0, gFont("Regular", 32))
161                 self.l.setFont(1, gFont("Regular", 18))
162                 self.l.setFont(2, gFont("Regular", 16))
163                 self.l.setBuildFunc(self.buildWlanListEntry)            
164                                 
165                 self.reload()
166         
167         
168         def buildWlanListEntry(self, essid, bssid, encrypted, iface, maxrate, signal):                                                                                                 
169                 
170                 res = [ (essid, encrypted, iface) ]
171                 
172                 if essid == "":
173                         essid = bssid
174                 
175                 e = encrypted and _("Yes") or _("No")
176                 res.append( MultiContentEntryText(pos=(0, 0), size=(470, 35), font=0, flags=RT_HALIGN_LEFT, text=essid) )
177                 res.append( MultiContentEntryText(pos=(425, 0), size=(60, 20), font=1, flags=RT_HALIGN_LEFT, text=_("Signal: ")))
178                 res.append( MultiContentEntryText(pos=(480, 0), size=(70, 35), font=0, flags=RT_HALIGN_RIGHT, text="%s" %signal))
179                 res.append( MultiContentEntryText(pos=(0, 40), size=(180, 20), font=1, flags=RT_HALIGN_LEFT, text=_("Max. Bitrate: %s") %maxrate ))
180                 res.append( MultiContentEntryText(pos=(190, 40), size=(180, 20), font=1, flags=RT_HALIGN_CENTER, text=_("Encrypted: %s") %e ))
181                 res.append( MultiContentEntryText(pos=(360, 40), size=(190, 20), font=1, flags=RT_HALIGN_RIGHT, text=_("Interface: %s") %iface ))
182                 return res
183                 
184                         
185         def reload(self):
186                 aps = self.w.getNetworkList()
187                 list = []
188                 self.aplist = []
189                 if aps is not None:
190                         print "[Wlan.py] got Accespoints!"
191                         for ap in aps:
192                                 a = aps[ap]
193                                 if a['active']:
194                                         if a['essid'] == "":
195                                                 a['essid'] = a['bssid']
196                                         list.append( (a['essid'], a['bssid'], a['encrypted'], a['iface'], a['maxrate'], a['signal']) )
197                                         self.aplist.append( a['essid'])
198                 
199                 self.length = len(list)
200                 self.l.setList([])
201                 self.l.setList(list)
202                         
203         GUI_WIDGET = eListbox
204
205
206         def getCurrent(self):
207                 return self.l.getCurrentSelection()
208         
209         
210         def postWidgetCreate(self, instance):
211                 instance.setContent(self.l)
212                 instance.setItemHeight(60)
213         
214         
215         def getLength(self):
216                 return self.length
217         
218         def getList(self):
219                 return self.aplist
220
221
222 class wpaSupplicant:
223         def __init__(self):
224                 pass
225         
226                 
227         def writeConfig(self):  
228                         
229                         essid = config.plugins.wlan.essid.value
230                         encrypted = config.plugins.wlan.encryption.enabled.value
231                         encryption = config.plugins.wlan.encryption.type.value
232                         psk = config.plugins.wlan.encryption.psk.value
233
234
235                         fp = file('/etc/wpa_supplicant.conf', 'w')
236                         fp.write('#WPA Supplicant Configuration by enigma2\n\n')
237                         fp.write('ctrl_interface=/var/run/wpa_supplicant\n')
238                         fp.write('ctrl_interface_group=0\n')
239                         fp.write('eapol_version=1\n')
240                         fp.write('ap_scan=2\n')
241                         fp.write('fast_reauth=1\n')                     
242                         fp.write('network={\n')
243                         fp.write('\tssid="'+essid+'"\n')
244                         fp.write('\tscan_ssid=0\n')
245                         
246                         if encrypted:
247                                                         
248                                 if encryption == 'WPA' or encryption == 'WPA2':
249                                         fp.write('\tkey_mgmt=WPA-PSK\n')
250                                         
251                                         if encryption == 'WPA':
252                                                 fp.write('\tproto=WPA\n')
253                                                 fp.write('\tpairwise=TKIP\n')
254                                                 fp.write('\tgroup=TKIP\n')
255                                         else:
256                                                 fp.write('\tproto=WPA RSN\n')
257                                                 fp.write('\tpairwise=CCMP TKIP\n')
258                                                 fp.write('\tgroup=CCMP TKIP\n')
259                                         
260                                         fp.write('\tpsk="'+psk+'"\n')
261                                 
262                                 elif encryption == 'WEP':
263                                         fp.write('\tkey_mgmt=NONE\n')
264                                         fp.write('\twep_key0="'+psk+'"\n')
265                         else:
266                                 fp.write('\tkey_mgmt=NONE\n')                   
267                         fp.write('}')   
268                         fp.close()
269                                 
270                         
271         def loadConfig(self):
272                 try:
273                         #parse the wpasupplicant configfile
274                         fp = file('/etc/wpa_supplicant.conf', 'r')
275                         supplicant = fp.readlines()
276                         fp.close()
277
278                         for s in supplicant:
279                                 split = s.strip().split('=',1)
280                                 if split[0] == 'ssid':
281                                         print "[Wlan.py] Got SSID "+split[1][1:-1]
282                                         config.plugins.wlan.essid.value = split[1][1:-1]
283                                         
284                                 elif split[0] == 'proto':
285                                         config.plugins.wlan.encryption.enabled.value = True
286                                         if split[1] == "WPA RSN" : split[1] = 'WPA2'
287                                         config.plugins.wlan.encryption.type.value = split[1]
288                                         print "[Wlan.py] Got Encryption: "+split[1]
289                                         
290                                 elif split[0] == 'wep_key0':
291                                         config.plugins.wlan.encryption.enabled.value = True
292                                         config.plugins.wlan.encryption.type.value = 'WEP'
293                                         config.plugins.wlan.encryption.psk.value = split[1][1:-1]
294                                         print "[Wlan.py] Got Encryption: WEP - key0 is: "+split[1][1:-1]
295                                         
296                                 elif split[0] == 'psk':
297                                         config.plugins.wlan.encryption.psk.value = split[1][1:-1]
298                                         print "[Wlan.py] Got PSK: "+split[1][1:-1]
299                                 else:
300                                         pass
301                                 
302                         wsconfig = {
303                                         'ssid': config.plugins.wlan.essid.value,
304                                         'encryption': config.plugins.wlan.encryption.enabled.value,
305                                         'encryption_type': config.plugins.wlan.encryption.type.value,
306                                         'key': config.plugins.wlan.encryption.psk.value,
307                                 }
308                 
309                         for (key, item) in wsconfig.items():
310                                 if item is "None" or item is "":
311                                         if key == 'ssid':
312                                                 wsconfig['ssid'] = "home"
313                                         if key == 'encryption':
314                                                 wsconfig['encryption'] = False                          
315                                         if key == 'encryption':
316                                                 wsconfig['encryption_type'] = "WPA"
317                                         if key == 'encryption':
318                                                 wsconfig['key'] = "mysecurewlan"
319
320                 except:
321                         print "[Wlan.py] Error parsing /etc/wpa_supplicant.conf"
322                         wsconfig = {
323                                         'ssid': "home",
324                                         'encryption': False,
325                                         'encryption_type': "WPA",
326                                         'key': "mysecurewlan",
327                                 }
328                 print "WS-CONFIG-->",wsconfig
329                 return wsconfig
330
331         
332         def restart(self, iface):
333                 system("start-stop-daemon -K -x /usr/sbin/wpa_supplicant")
334                 system("start-stop-daemon -S -x /usr/sbin/wpa_supplicant -- -B -i"+iface+" -c/etc/wpa_supplicant.conf")
335
336