forked from CoderBotOrg/backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwifi.py
More file actions
executable file
·172 lines (150 loc) · 4.6 KB
/
wifi.py
File metadata and controls
executable file
·172 lines (150 loc) · 4.6 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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
#!/usr/bin/python
import socket
import subprocess
import shutil
import sys
import os
import time
import urllib2
import fcntl
import struct
import json
class WiFi():
CONFIG_FILE = "/etc/coderbot_wifi.conf"
adapters = ["RT5370", "RTL8188CUS"]
hostapds = {"RT5370": "hostapd.RT5370", "RTL8188CUS": "hostapd.RTL8188"}
web_url = "http://coderbotsrv.appspot.com/register_ip"
wifi_client_conf_file = "/etc/wpa_supplicant/wpa_supplicant.conf"
_config = {}
@classmethod
def load_config(cls):
f = open(cls.CONFIG_FILE)
cls._config = json.load(f)
return cls._config
@classmethod
def save_config(cls):
f = open(cls.CONFIG_FILE, 'w')
json.dump(cls._config, f)
return cls._config
@classmethod
def get_config(cls):
return cls._config
@classmethod
def get_adapter_type(cls):
lsusb_out = subprocess.check_output("lsusb")
for a in cls.adapters:
if a in lsusb_out:
return a
return cls.adapters[0]
@classmethod
def start_hostapd(cls):
adapter = cls.get_adapter_type()
hostapd_type = cls.hostapds.get(adapter)
try:
print "starting hostapd..."
out = os.system("/usr/sbin/" + hostapd_type + " /etc/hostapd/" + hostapd_type + " -B")
print "hostapd out: " + str(out)
except subprocess.CalledProcessError as e:
print e.output
@classmethod
def stop_hostapd(cls):
try:
print "stopping hostapd..."
out = subprocess.check_output(["sudo", "pkill", "-9", "hostapd"])
print "hostapd out: " + str(out)
except subprocess.CalledProcessError as e:
print e.output
@classmethod
def get_ipaddr(cls, ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
@classmethod
def register_ipaddr(cls, botname, ipaddr):
try:
ret = urllib2.urlopen(cls.web_url + "?name=" + botname + "&ipaddr=" + ipaddr)
if ret.getcode() != 200:
raise Exception()
except URLError as e:
print "except: " + str(e)
raise
@classmethod
def get_wlans(cls):
out = subprocess.check_output(["iwlist", "wlan0", "scan"])
@classmethod
def set_client_params(cls, wssid, wpsk):
f = open (cls.wifi_client_conf_file, "w+")
f.write("""ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
network={\n""")
f.write(" ssid=\""+wssid+"\"\n")
f.write(" psk=\""+wpsk+"\"\n")
f.write("}")
@classmethod
def set_start_as_client(cls):
shutil.copy("/etc/network/interfaces_cli", "/etc/network/interfaces")
cls._config["wifi_mode"] = "client"
cls.save_config()
@classmethod
def start_as_client(cls):
cls.stop_hostapd()
try:
time.sleep(1.0)
out = subprocess.check_output(["ifdown", "--force", "wlan0"])
out = subprocess.check_output(["ifup", "wlan0"])
cls.register_ipaddr(cls.get_config().get('bot_name', 'CoderBot'), cls.get_ipaddr("wlan0"))
print "registered bot, ip: " + str(cls.get_ipaddr("wlan0") + " name: " + cls.get_config().get('bot_name', 'CoderBot'))
except subprocess.CalledProcessError as e:
print e.output
raise
@classmethod
def set_start_as_ap(cls):
shutil.copy("/etc/network/interfaces_ap", "/etc/network/interfaces")
cls._config["wifi_mode"] = "ap"
cls.save_config()
@classmethod
def start_as_ap(cls):
time.sleep(1.0)
out = subprocess.check_output(["ifdown", "--force", "wlan0"])
out = subprocess.check_output(["ifup", "wlan0"])
cls.start_hostapd()
@classmethod
def start_service(cls):
config = cls.load_config()
if config["wifi_mode"] == "ap":
print "starting as ap..."
cls.start_as_ap()
elif config["wifi_mode"] == "client":
print "starting as client..."
try:
cls.start_as_client()
except:
print "Unable to register ip, revert to ap mode"
cls.start_as_ap()
def main():
w = WiFi()
if len(sys.argv) > 2 and sys.argv[1] == "updatecfg":
if len(sys.argv) > 2 and sys.argv[2] == "ap":
w.set_start_as_ap()
#w.start_as_ap()
elif len(sys.argv) > 2 and sys.argv[2] == "client":
if len(sys.argv) > 3:
w.set_client_params(sys.argv[3], sys.argv[4])
w.set_start_as_client()
"""
try:
w.start_as_client()
except:
print "Unable to register ip, revert to ap mode"
w.start_as_ap()
"""
elif len(sys.argv) > 3 and sys.argv[2] == "bot_name":
WiFi.get_config()['bot_name'] = sys.argv[3]
WiFi.save_config()
else:
w.start_service()
if __name__ == "__main__":
main()