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