-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsonoff_server.py
More file actions
186 lines (165 loc) · 6.13 KB
/
Copy pathsonoff_server.py
File metadata and controls
186 lines (165 loc) · 6.13 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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
from flask import Flask, request, make_response, jsonify
from flask_sockets import Sockets
from geventwebsocket.exceptions import WebSocketError
import gevent, requests
import json, time
from datetime import datetime
from uuid import uuid4
app = Flask(__name__)
sockets = Sockets(app)
ws_ref = None
device_id = None
device_ip = None
with open('config.json') as config_f:
configs = json.load(config_f)
wifi_ssid = configs['network']['SSID']
wifi_password = configs['network']['password']
wifi_server_name = configs['server']['IP']
wifi_server_port = configs['server']['port']
uuidkey = str(uuid4())
def generate_switch_payload(dev_id, state1=False, state2=False):
switch1_state = "on" if state1 else "off"
switch2_state = "on" if state2 else "off"
payload = {
"action": "update",
"deviceid": dev_id,
"apikey": uuidkey,
"userAgent": "app",
"sequence": str(int(time.time() * 1000)),
"ts": 0,
"params": {
"switches": [
{
"switch": switch1_state,
"outlet": 0
},
{
"switch": switch2_state,
"outlet": 1
},
{
"switch": "off",
"outlet": 2
},
{
"switch": "off",
"outlet": 3
}
]
},
"from": "app"
}
return payload
@app.route('/')
def main_route():
return make_response('OK')
@app.route('/state', methods=['POST'])
def state_switches():
global device_id, ws_ref
if ws_ref == None or device_id == None:
return make_response("Websockets connection not established. Unable to control switch")
else:
command = request.json
payload = generate_switch_payload(device_id, command['0'], command['1'])
ws_ref.send(json.dumps(payload))
return make_response('STATE')
@app.route('/on', methods=['GET'])
def on_switches():
global device_id, ws_ref
if ws_ref == None or device_id == None:
return make_response("Websockets connection not established. Unable to control switch")
else:
payload = generate_switch_payload(device_id, True, True)
ws_ref.send(json.dumps(payload))
return make_response("on")
@app.route('/off', methods=['GET'])
def off_switches():
global device_id, ws_ref
if ws_ref == None or device_id == None:
return make_response("Websockets connection not established. Unable to control switch")
else:
payload = generate_switch_payload(device_id)
ws_ref.send(json.dumps(payload))
return make_response("off")
@app.route('/dispatch/device', methods=['POST'])
def ws_config():
global device_ip
print("REQ | {} | {} | {}".format(request.method, request.url, request.remote_addr))
print("REQ | {}".format(request.json))
payload = {
"error": 0,
"reason": "ok",
"IP": wifi_server_name,
"port": wifi_server_port
}
if device_ip == None:
device_ip = request.remote_addr
resp = make_response(json.dumps(payload))
resp.headers['Content-Type'] = 'application/json'
return resp
@sockets.route('/api/ws')
def print_socket(websocket):
global ws_ref, device_id
ws_ref = websocket
print("WS | Initiated")
while not websocket.closed:
message = websocket.receive()
print("WS | INCOMING: {}".format(message))
if message != None:
mjson = json.loads(message)
if 'deviceid' in mjson:
device_id = mjson['deviceid']
if 'action' in mjson:
print("WS | Action {} requested".format(mjson['action']))
if mjson['action'] == "register":
if "model" in mjson and mjson["model"]:
device_model = mjson["model"]
print("We are dealing with a {} model.".format(device_model))
payload = {
"error": 0,
"deviceid": mjson['deviceid'],
"apikey": uuidkey,
"config": {
"hb": 1,
"hbInterval": 145
}
}
print("WS | register | Sending: {}".format(payload))
websocket.send(json.dumps(payload))
if mjson['action'] == 'date':
payload = {
"error": 0,
"deviceid": mjson['deviceid'],
"apikey": uuidkey,
"date": datetime.isoformat(datetime.today())[:-3] + 'Z'
}
print("WSR | date | Sending: {}".format(payload))
websocket.send(json.dumps(payload))
if mjson['action'] == "query":
payload = {
"error": 0,
"deviceid": mjson['deviceid'],
"apikey": uuidkey,
"params": 0
}
print("WS | query | Sending: {}".format(payload))
websocket.send(json.dumps(payload))
if mjson['action'] == "update":
payload = {
"error": 0,
"deviceid": mjson['deviceid'],
"apikey": uuidkey
}
print("WS | update | Sending: {}".format(payload))
websocket.send(json.dumps(payload))
else:
print("WSR | unknown | {}".format(message))
if websocket.closed:
print("WS | Closed")
if __name__ == '__main__':
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler as WSH
app.config['SECRET_KEY'] = 'zippedi'
print("HTTPS | Starting web server on {}:{}".format(wifi_server_name, wifi_server_port))
server = pywsgi.WSGIServer(('0.0.0.0', wifi_server_port), app, handler_class=WSH, keyfile=configs['ssl']['key'], certfile=configs['ssl']['cert'])
server.serve_forever()