* show number of found Networks in Scan Window
[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 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                 print "ifobj.getStatistics(): ", ifobj.getStatistics()
56                 
57                 #Association mappings
58                 stats, quality, discard, missed_beacon = ifobj.getStatistics()
59                 snr = quality.signallevel - quality.noiselevel
60                 os.system("ifconfig "+iface+" up")
61                 
62                 try:
63                         scanresults = ifobj.scan()
64                 except:
65                         scanresults = None
66                         print "[Wlan.py] No Wireless Networks could be found"
67                 
68                 if scanresults is not None:
69                         aps = {}
70                         for result in scanresults:
71                                 
72                                 bssid = result.bssid
73                 
74                                 encryption = map(lambda x: hex(ord(x)), result.encode)
75                 
76                                 if encryption[-1] == "0x8":
77                                         encryption = True
78                                 else:
79                                         encryption = False
80                 
81                                 extra = []
82                                 for element in result.custom:
83                                         element = element.encode()
84                                         extra.append( string.strip(self.asciify(element)) )
85
86                                 aps[bssid] = {
87                                         'active' : True,
88                                         'bssid': result.bssid,
89                                         'channel': result.frequency.getChannel(result.frequency.getFrequency(), result.range),
90                                         'encrypted': encryption,
91                                         'essid': string.strip(self.asciify(result.essid)),
92                                         'iface': iface,
93                                         'maxrate' : result.rate[-1],
94                                         'noise' : result.quality.getNoiselevel(),
95                                         'quality' : result.quality.quality,
96                                         'signal' : result.quality.getSignallevel(),
97                                         'custom' : extra,
98                                 }
99                                 
100                         return aps
101                                 
102
103 class WlanList(HTMLComponent, GUIComponent):
104         
105         def __init__(self, session, iface):
106                 
107                 GUIComponent.__init__(self)
108                 self.w = Wlan()
109                 self.iface = iface
110                 
111                 self.length = 0
112                 
113                 self.l = None
114                 self.l = eListboxPythonMultiContent()
115                 
116                 self.l.setFont(0, gFont("Regular", 32))
117                 self.l.setFont(1, gFont("Regular", 18))
118                 self.l.setFont(2, gFont("Regular", 16))
119                 self.l.setBuildFunc(self.buildWlanListEntry)            
120                                 
121                 self.reload()
122         
123         def buildWlanListEntry(self, essid, bssid, encrypted, iface, maxrate):                                                                                                 
124                 
125                 res = [ (essid, encrypted, iface) ]
126                 
127                 if essid == "":
128                         essid = bssid
129                 
130                 e = encrypted and _("Yes") or _("No")
131                 res.append( MultiContentEntryText(pos=(0, 0), size=(570, 35), font=0, flags=RT_HALIGN_LEFT, text=essid) )
132                 res.append( MultiContentEntryText(pos=(0, 40), size=(180, 20), font=1, flags=RT_HALIGN_LEFT, text=_("Max. Bitrate: ")+maxrate) )
133                 res.append( MultiContentEntryText(pos=(190, 40), size=(180, 20), font=1, flags=RT_HALIGN_CENTER, text=_("Encrypted: ")+e) )
134                 res.append( MultiContentEntryText(pos=(380, 40), size=(190, 20), font=1, flags=RT_HALIGN_RIGHT, text=_("Interface: ")+iface) )
135                 return res
136                         
137         def reload(self):
138                 aps = self.w.getNetworkList(self.iface)
139                 list = []
140                 if aps is not None:
141                         print "[Wlan.py] got Accespoints!"
142                         for ap in aps:
143                                 a = aps[ap]
144                                 if a['active']:
145                                         list.append((a['essid'], a['bssid'], a['encrypted'], a['iface'], a['maxrate']))
146                 
147                 self.length = len(list)
148                 self.l.setList([])
149                 self.l.setList(list)
150                         
151         GUI_WIDGET = eListbox
152
153         def getCurrent(self):
154                 return self.l.getCurrentSelection()
155         
156         def postWidgetCreate(self, instance):
157                 instance.setContent(self.l)
158                 instance.setItemHeight(60)
159         
160         def getLength(self):
161                 return self.length
162
163 class wpaSupplicant:
164         def __init__(self):
165                 pass
166                 
167         def writeConfig(self):  
168                         
169                         essid = config.plugins.wlan.essid.value
170                         encrypted = config.plugins.wlan.encryption.enabled.value
171                         encryption = config.plugins.wlan.encryption.type.value
172                         psk = config.plugins.wlan.encryption.psk.value
173
174                 
175                         fp = file('/etc/wpa_supplicant.conf', 'w')
176                         fp.write('#WPA Supplicant Configuration by enigma2\n\n')
177                         fp.write('ctrl_interface=/var/run/wpa_supplicant\n')
178                         fp.write('ctrl_interface_group=0\n')
179                         fp.write('network={\n')
180                         fp.write('\tssid="'+essid+'"\n')
181                         fp.write('\tscan_ssid=1\n')
182                         
183                         if encrypted:
184                                                         
185                                 if encryption == 'WPA' or encryption == 'WPA2':
186                                         fp.write('\tkey_mgmt=WPA-PSK\n')
187                                         
188                                         if encryption == 'WPA':
189                                                 fp.write('\tproto=WPA\n')
190                                                 fp.write('\tpairwise=TKIP\n')
191                                         else:
192                                                 fp.write('\tproto=WPA RSN\n')
193                                                 fp.write('\tpairwise=CCMP TKIP\n')
194                                         
195                                         fp.write('\tpsk="'+psk+'"\n')
196                                 
197                                 elif encryption == 'WEP':
198                                         fp.write('\tkey_mgmt=NONE\n')
199                                         fp.write('\twep_key0="'+psk+'"\n')
200                         
201                         fp.write('}')   
202                         fp.close()
203                                         
204                         
205         def loadConfig(self):
206
207                 try:
208                         #parse the wpasupplicant configfile
209                         fp = file('/etc/wpa_supplicant.conf', 'r')
210                         supplicant = fp.readlines()
211                         fp.close()
212                         
213                         for s in supplicant:
214                         
215                                 split = s.strip().split('=')
216                                 if split[0] == 'ssid':
217                                         print "[Wlan.py] Got SSID "+split[1][1:-1]
218                                         config.plugins.wlan.essid.value = split[1][1:-1]
219                                         
220                                 elif split[0] == 'proto':
221                                         config.plugins.wlan.encryption.enabled.value = True
222                                         if split[1] == "WPA RSN" : split[1] = 'WPA2'
223                                         config.plugins.wlan.encryption.type.value = split[1]
224                                         print "[Wlan.py] Got Encryption "+split[1]
225                                 
226                                 elif split[0] == 'psk':
227                                         config.plugins.wlan.encryption.psk.value = split[1][1:-1]
228                                         print "[Wlan.py] Got PSK "+split[1][1:-1]
229                                 else:
230                                         pass
231                                 
232                 except:
233                         print "[Wlan.py] Error parsing /etc/wpa_supplicant.conf"
234         
235         def restart(self, iface):
236                 import os
237                 os.system("start-stop-daemon -K -x /usr/sbin/wpa_supplicant")
238                 os.system("start-stop-daemon -S -x /usr/sbin/wpa_supplicant -- -B -i"+iface+" -c/etc/wpa_supplicant.conf")