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