-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathwifi.py
More file actions
149 lines (120 loc) · 4.31 KB
/
wifi.py
File metadata and controls
149 lines (120 loc) · 4.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
"""
netstat -i
iwconfig wlan0 essid NETWORK_NAME key WIRELESS_KEY
dhclient wlan0
"""
import subprocess
import sys
import time
import urllib
from functools import wraps
from subprocess import CalledProcessError
from amazon_dash.exceptions import ConfigWifiError
from bs4 import BeautifulSoup
import requests
CONFIGURE_URL = 'http://192.168.0.1/'
if sys.version_info < (3,2):
FileNotFoundError = OSError
def get_cmd_output(cmd, split_lines=True, decode='utf-8'):
output = subprocess.check_output(cmd)
if decode:
output = output.decode('utf-8')
if split_lines:
output = [line.rstrip('\n') for line in output.split('\n')]
return output
def get_wifi_class():
try:
subprocess.check_call(['nmcli', 'general', 'status'])
except (FileNotFoundError, CalledProcessError):
return Wifi
else:
return NetworkManagerWifi
def retry(exceptions=(Exception,), tries=5):
def wrap(fn):
@wraps(fn)
def f_retry(*args, **kwargs):
for i in range(1, tries + 1):
try:
return fn(*args, **kwargs)
except exceptions:
time.sleep(3 * i)
if i + 1 >= tries:
raise
return f_retry
return wrap
class Wifi(object):
def __init__(self, device=None):
self.device = device or next(self.get_wireless_devices(), None)
if self.device is None:
raise ConfigWifiError('Wireless card is not available.')
def get_wireless_devices(self):
devices = get_cmd_output(['ip', 'a'])
devices = map(lambda x: x.split(' ')[1].rstrip(':'), filter(lambda x: not x.startswith(' ') and x, devices))
return iter(filter(lambda x: x.startswith('wl'), devices))
@retry(ConfigWifiError)
def connect(self, essid, key=None):
cmd = ['iwconfig', self.device, 'essid', essid]
if key:
cmd += ['key', key]
get_cmd_output(cmd)
self.wait_up()
def get_network_state(self):
return open('/sys/class/net/{}/operstate'.format(self.device)).read().rstrip('\n')
def wait_up(self, timeout=5):
for i in range(timeout * 10):
if self.get_network_state() == 'up':
return
time.sleep(.1)
raise ConfigWifiError('Timeout connecting to network')
def dhcp(self):
get_cmd_output(['dhclient', self.device])
class NetworkManagerWifi(Wifi):
@retry()
def connect(self, essid, key=None):
cmd = ['nmcli', 'device', 'wifi', 'connect', essid]
if key:
cmd += ['password', key]
get_cmd_output(cmd)
def dhcp(self):
pass
class ConfigureAmazonDash(object):
def __init__(self):
pass
@retry((ConfigWifiError, requests.exceptions.BaseHTTPError))
def get_info(self):
r = requests.get(CONFIGURE_URL)
r.raise_for_status()
soup = BeautifulSoup(r.text, 'html.parser')
items = soup.find_all('td')
return {
'serial_number': items[0].string,
'mac_address': items[1].string,
'firmware': items[2].string,
'battery': items[3].string,
}
def get_networks_availables(self):
r = requests.get(CONFIGURE_URL, headers={'Content-Type': 'application/json'}, timeout=5)
r.raise_for_status()
data = r.json()
return iter(data['amzn_networks'])
def configure(self, ssid, password):
networks = self.get_networks_availables()
# Escape the ssid for the search
xssid = urllib.parse.quote(ssid)
if not next(iter(filter(lambda x: x['ssid'] == xssid, networks)), None):
raise ConfigWifiError('Network {} is not available.'.format(ssid))
# Use %20 instead of + to escape space
payload = {'amzn_ssid': ssid, 'amzn_pw': password}
params = urllib.parse.urlencode(payload, quote_via=urllib.parse.quote)
r = requests.get(CONFIGURE_URL, params=params)
r.raise_for_status()
def enable_wifi():
wifi_class = get_wifi_class()
w = wifi_class()
essid = 'Amazon ConfigureMe'
try:
w.connect(essid)
except CalledProcessError:
raise ConfigWifiError('Error connecting to amazon-dash. '
'Is the led flashing blue on the amazon-dash button?'.format(essid))
w.dhcp()