-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwhat_epy_block_0.py
313 lines (245 loc) · 8.75 KB
/
what_epy_block_0.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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
import numpy as np
from gnuradio import gr
import time, socket
from collections import deque
ip = "127.0.0.1"
destip = "10.0.0.42"
port = 42069
testing_check = False
good_packets, bad_packets = 0, 0
prevTime = 0
packetDict = {}
def checkErrorRate(self):
if (time.time() - self.prevTime) > 2:
tP = (self.good_packets + self.bad_packets)
if (tP > 0):
erate = self.good_packets / tP
print(f"% good in last 2 seconds: {erate*100}, total good packets: {self.good_packets}, effective kBps: {self.lastSecondBytes / 1000}")
else:
print(f"% good in last 2 seconds: --")
self.prevTime = time.time()
self.good_packets, self.bad_packets, self.lastSecondBytes = 0, 0, 0
def clean(i, cumctr, preval):
#decimates by a factor of 25-ish to eliminated repeated sampling
#should've just sampled slower ¯\_(ツ)_/¯
#f = open("/Users/sekharm/wtf.txt", "a")
#print(i, end = "", file=f)
#f.close()
if len(i) == 0: return
out = []
ctr = 1
cumctr = cumctr
preval = preval
while (ctr < len(i)):
val = i[ctr]
if val == '': continue
if (val != preval):
#print(cumctr/25)
out += [preval]*int(round(cumctr/(25 * (0.5))))
cumctr = 0
cumctr += 1
ctr += 1
preval = val
return ("".join(out), cumctr, preval)
def computeChecksum(buff):
sum1, sum2 = 0, 0
id = buff[0]
length = buff[1]
timestamp = buff[2:6]
checksum = buff[6:8]
data = buff[8:]
sum1 = sum1 + id
sum2 = sum2 + sum1
sum1, sum2 = (sum1%256), (sum2%256)
sum1 = sum1 + length
sum2 = sum2 + sum1
sum1, sum2 = (sum1%256), (sum2%256)
for i in range(4):
sum1 = sum1 + timestamp[i]
sum2 = sum2 + sum1
sum1, sum2 = (sum1%256), (sum2%256)
for i in range(length):
sum1 = sum1 + data[i]
sum2 = sum2 + sum1
sum1, sum2 = (sum1%256), (sum2%256)
return ((sum2 << 8)|sum1)
def split(self, buff):
#*flight* packets are combined into one radio packet (max 128 bytes)
#so this function splits them into flight packets
ctr = 0
try:
while True:
if (len(buff) < 8):
return
id = buff[0]
length = buff[1]
timestamp = (buff[2] << 24) + (buff[3] << 16) + (buff[4] << 8) + (buff[5])
checksum = (buff[7] << 8) + buff[6]
#print(f"id: {id}, length: {length}, timestamp: {timestamp}, checksum: {checksum}, expected checkum: {computeChecksum(buff)}")
#print(f"buffer length {len(buff)}, expected length {length + 8}")
if (computeChecksum(buff) == checksum):
ctr += 1
#print(f"sending packet #{ctr} with id: {id}, length: {length}")
self.good_packets += 1
try:
if (packetDict[id] != timestamp):
sendover(self, buff)
packetDict[id] = timestamp
except KeyError:
packetDict[id] = timestamp
else:
# print("CHECKSUM ERROR")
self.bad_packets += 1
buff = buff[8+length:]
except Exception as e:
return
def testing_add(self, i):
#print(i)
self.lastPacketTime = time.time()
check = True
packet_start = i[0]
if (68 < packet_start < 71):
f = i[1]
for j in range(1, i+[0]*100):
if (i[j] != f+j-1):
check = False
else:
check = False
if check : self.testctr+=1
def sendRssiPacket(self, rssi):
buff = []
buff.append(56)
buff.append(2)
buff += [0]*6
buff.append(int(rssi) % 256)
buff.append(min(255, abs(int(rssi) >> 8)))
i = computeChecksum(buff)
buff[6] = min(255, abs(int(i % 256)))
buff[7] = min(255, abs(int(i >> 8)))
# print(buff)
sendover(self, buff)
def sendover(self, buff):
#sends a flight packet to the GS
if testing_check:
testing_add(self, buff)
realBuff = buff[:8+buff[1]]
f = list(destip)
f = [ord(i) for i in f]
f = [len(f)] + f
f += realBuff
self.lastSecondBytes += buff[1]
self.sock.sendto(bytes(f), (ip, port))
def checkPacketTime(self):
if (self.testctr == 0): return
if (time.time() - self.lastPacketTime) > 3:
print(f"last packet {(time.time() - self.lastPacketTime):.1f}s ago: got {self.testctr}/200 packets -> {(self.testctr/2):.2f}%\n")
self.testctr = 0
def parse(self, i, pn):
#converts binary data to radio packets, removing noise from either side
i = "".join([str(j) for j in i])
try:
j = i.index("0010110111010100")
except:
print("packet not found")
return 0
i = i[j+16:]
try:
length = int(i[:8], 2)
except Exception as e:
print(f"#1 - {i[:8]}")
#print(f"packet #{pn+1}")
#print(f"found packet #{pn+1} with length {length}", end ="\n")
i=i[24:]
#print("0x", end=" ")
out = []
for j in range(length):
try:
s = int(i[:8],2)
out.append(s)
except Exception as e:
print("discarded packet")
return 0
i=i[8:]
#print(out)
split(self, out)
return 1
class blk(gr.sync_block):
def __init__(self):
np.set_printoptions(threshold=np.inf)
gr.sync_block.__init__(
self,
name='yeet',
in_sig=[np.byte, np.float32],
out_sig=[np.byte]
)
self.set_min_output_buffer(8192)
self.cleanBuffer = ""
self.fullBuffer = ""
self.cumPackets = 0
self.lastProcessTime = time.time()
self.preval = 0
self.cumctr = 0
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.testctr = 1
self.lastPacketTime = 0
self.good_packets, self.bad_packets = 0, 0
self.lastSecondBytes = 0
self.prevTime = 0
self.rssiDeque = deque(maxlen = 100000)
self.rssi = 0
self.prevRssiTime = time.time()
def work(self, input_items, output_items):
# print(f"hi with {len(input_items[0])} samples")
checkErrorRate(self)
# if (testing_check): checkPacketTime(self)
# # t1 = (input_items[1][:] == 1)
# # t2 = (input_items[0])[t1]
t2 = input_items[0]
# for i in input_items[1]: #the avg received power (not necessarily signal strength)
# self.rssiDeque.append(i)
# fg = sorted(self.rssiDeque)
# self.rssi = sum(fg[-300:]) / sum(fg[:300])
# print(self.rssi)
# if (time.time() - self.prevRssiTime > 0.25):
# # sendRssiPacket(self, self.rssi)
# self.prevRssiTime = time.time()
# print(t2[:100])
g = str(t2)
bad = ['[', ']', '\n', ' ', ',']
for i in bad:
g = g.replace(i, "")
#g is good str.
self.fullBuffer += g
if len(self.fullBuffer) > 100:
try:
(shortened, self.cumctr, self.preval) = clean(self.fullBuffer, self.cumctr, self.preval)
except Exception as e:
print("clean error")
return len(output_items[0])
self.fullBuffer = ""
self.cleanBuffer += shortened
if ((time.time() - self.lastProcessTime > 0.1) or len(self.cleanBuffer) > 100):
#print(self.cleanBuffer)
self.lastProcessTime = time.time()
# print(f"processing {len(self.cleanBuffer)} bits")
s = self.cleanBuffer
seq = "1010101010100010110111010100"
res = [i for i in range(len(s)) if s.startswith(seq, i)]
if (res):
for i in range(len(res)-1):
packet = self.cleanBuffer[res[i]:res[i+1]]
numparsed = parse(self, packet, self.cumPackets)
#print(f"got {numparsed} packets, buffer has size {len(self.cleanBuffer)}")
if (numparsed == 0):
print(f"parse error - discarded buffer with size {len(self.cleanBuffer)}")
self.cleanBuffer = "0"
return len(output_items[0])
else:
self.cumPackets += numparsed
self.cleanBuffer = self.cleanBuffer[res[-1]:]
#print(self.cleanBuffer)
#print(len(output_items[0]))
#output_items[0][:] = (input_items[0])[temp]
#output_items[0][:] = input_items[0] * self.example_param
#return len(output_items[0])
return len(output_items[0])