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