-
Notifications
You must be signed in to change notification settings - Fork 0
/
receive.py
167 lines (139 loc) · 4.08 KB
/
receive.py
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
import websocket
import json
import uuid
import os
import hmac
import hashlib
import time
import threading
import re
import string
last_message = time.time()
def heartbeat():
while True:
if time.time() - last_message > 16:
print("heartbeat violation!")
os._exit(1)
time.sleep(1)
t = threading.Thread(target=heartbeat)
t.daemon = True
t.start()
def clean(s):
return ''.join([x for x in s.lower() if x in (string.ascii_lowercase + "_")])
fmt = open('fmt.txt').read()
a = re.findall(r'radio\.addVariable\(data\.(.*?)\s*,\s*(\-*\d+)\s*,\s*(\-*\d+)\s*,\s*(\-*\d+)\s*\);(.*?)$', fmt, re.MULTILINE)
vars = []
for var in a:
n = clean(var[0])
if var[4] != '':
n = var[4].replace('//','').rstrip().lstrip()
n = n.replace(' ','_')
vars.append([n, int(var[1]), int(var[2]), int(var[3])])
print(vars[-1])
lock = threading.Lock()
lock.acquire()
count = 0
recv = 0
def whine(ws, error):
print("[WS] Got error: "+str(error))
def ohp(ws):
print("[WS] Connection unexpectedly dropped. Retrying...")
ws.close()
def opened(ws):
print("[WS] Connection opened")
lock.release()
def msg(ws, message):
global count
global recv
if 'success' in message:
count += 1
if 'receive' in message:
recv += 1
#print("[WS] Got message", message)
global last_message
last_message = time.time()
def run_connection():
global ws
while True:
t = time.time()*1000.
sign = t, hmac.new(str.encode(os.environ['KAI_KEY']), str.encode(str(int(t))), hashlib.sha256).hexdigest()
ws = websocket.WebSocketApp("wss://nasonov-writer.herokuapp.com/%d/%s" % sign,
on_error=whine,
on_message=msg,
on_close=ohp,
on_open=opened)
ws.run_forever()
t = threading.Thread(target=run_connection)
t.daemon = True
t.start()
lock.acquire()
print("Okay, we're in business")
import serial
s = serial.Serial('/dev/ttyACM0', 57600)
rolling = []
START = [204, 105, 119, 82]
END = [162, 98, 128, 161]
parsing = False
message = []
import struct
def parse_message(msg):
#print("Parsing", msg, len(msg))
try:
#msg = list(map(chr, msg))
rssi = int(msg[0])
recc = struct.unpack('I', bytearray(msg[1:5]))[0]
drop = struct.unpack('I', bytearray(msg[5:9]))[0]
#print("RSSI", rssi)
print("Received", recc)
#print("Dropped", drop)
#ln = ord(sp[1])
aa = msg[9:]
inp = ""
for c in aa:
num = c
for i in [1,2,4,8,16,32,64,128][::-1]:
inp += ("1" if (num & i) else "0")
dd = {"id":str(uuid.uuid4()), "mission": 48, "timestamp": int(time.time()*1000), "msgs_received": recc, "msgs_lost": drop, "rssi": rssi}#, "received": msg[:ln].encode('hex')}
for name, min, max, bits in vars:
x = inp[0:bits]
inp = inp[bits:]
x = int(x, 2)
v = min + (max-min) * x / (2**bits - 1.)
dd[name] = v
#print(name, v)
#print(list(dd.keys()))
#print "actual thing received", msg[:ln]
#print "raw bytestring", msg[ln:]
ws.send(json.dumps(dd))
except ImportError:
print("Error parsing")
def check_comm():
while True:
with open("comm.txt") as c:
t = c.read().lstrip().rstrip()
if t != "":
print("SENDING MESSAGE"+"\n"*10)
s.write(str.encode(">"+t+"<"))
print("sent it a message")
with open("comm.txt","w") as c:
c.write("")
time.sleep(0.2)
t = threading.Thread(target=check_comm)
t.daemon = True
t.start()
import sys
while True:
b = ord(s.read(1))
rolling.append(b)
if len(rolling) > 4:
rolling = rolling[1:]
if rolling == START:
parsing = True
message = []
elif rolling == END:
parsing = False
parse_message(message[:-3])
elif parsing:
message.append(b)
else:
sys.stdout.write(chr(b))