-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathboot.py
More file actions
335 lines (238 loc) · 9.44 KB
/
boot.py
File metadata and controls
335 lines (238 loc) · 9.44 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
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# _____ _
# | __ \ (_)
# | |__) | ___ ___ ___ _ __ __ ___ _ __
# | _ / / _ \ / __|/ _ \| |\ \ / // _ \| '__|
# | | \ \| __/| (__| __/| | \ V /| __/| |
# |_| \_\\___| \___|\___||_| \_/ \___||_|
#
from machine import Pin, ADC
import time
import network
import _thread
import Webserver
import socket
print("Booting Reciver")
#=============Preamble=================
# Consts
ADC_CONV_FACTOR = 3.3/65536
SENSOR_THRESHOLD = 1
DATA_FILE_PATH = "data.csv"
# Transmit Options
is_reading = False
dtr = 64 # Data Transfer Rate in bit/s
END_SYMBOLE = int('00000100', 2) # 00000100
# Pins
indicator_led = Pin(14, Pin.OUT, value=0)
onboard_led = Pin("LED", Pin.OUT, value=0)
button = Pin(2, Pin.IN, Pin.PULL_DOWN)
adc_pin = Pin(26, mode=Pin.IN)
adc = ADC(adc_pin)
# Network
SSID = "Receiver"
PASSWORD = "receiverAP"
#=============Functions=================
# Funktion to set the Thershold acording to the Enviorment, Overwritable by the overwrite value
def autoSetThreshold(overwrite=-1):
global SENSOR_THRESHOLD, adc, indicator_led
if(overwrite >= 0):
SENSOR_THRESHOLD = overwrite
else:
reading_max = 0
reading_resolution = 100
print("Start reading threshold")
# Messure Enviorment many times and find the highest reading
for i in range(reading_resolution):
indicator_led.on()
reading = adc.read_u16()
print("{0}:\t{1}V".format(i, round(reading * ADC_CONV_FACTOR, 3)))
if(reading > reading_max):
reading_max = reading
indicator_led.off()
time.sleep(1/8)
print("Reading Stoped. Max reading of {0}V.".format(reading_max * ADC_CONV_FACTOR))
# Sets Sensor to 110% of the max
SENSOR_THRESHOLD = 1.1 * reading_max * ADC_CONV_FACTOR
print("Set Threshold to {0}V".format(SENSOR_THRESHOLD))
# Function that safes all recived Data as a .csv file
def save_data(byte_array):
file = open(DATA_FILE_PATH, 'a')
try:
encoded_msg = byte_array.decode('utf-8')
except:
encoded_msg = "[Error] No Encoding with ascii Possibile"
msg_len = len(byte_array)
# Escape msg
encoded_msg = encoded_msg.replace('"', '""')
encoded_msg = encoded_msg.replace('\n', '\\n')
encoded_msg = encoded_msg.replace('\r', '\\r')
out = '"' + encoded_msg + '",' + str(msg_len)
# Append Bytes
for b in byte_array:
byte = ''
for i in range(8):
bit = (b & 1<<(7 - i)) != 0
byte = byte + str(int(bit))
out = out + ',' + byte
file.write(out + '\r\n')
# Function that recives the Message and Listens to the End Byte
def reciveMessage(reciver_adc):
global END_SYMBOLE, dtr, ADC_CONV_FACTOR, SENSOR_THRESHOLD, onboard_led, button
print("Recording Message")
#onboard_led.on()
raw_message = bytearray()
recived_byte = 0
# Only executes if the last Byte was not the End Symbole
while recived_byte != END_SYMBOLE:
print("Wainting for Package Indicator")
# Wait for Package Indicator Bit
while True:
reading = reciver_adc.read_u16() * ADC_CONV_FACTOR
if( reading > SENSOR_THRESHOLD):
break
# Check for Brake Button
if button.value() == 1:
print('\r\nInterupted by Button, returning the until now recived Message')
return raw_message
time.sleep(1/(4*dtr))
print("New Package:")
# Waiting
time.sleep(1/dtr)
# Resetting recived Byte
recived_byte = 0
# Start reading Byte
for i in range(8):
# Check for Brake Button
if button.value() == 1:
print('\r\nInterupted by Button, returning the until now recived Message')
return raw_message
volt_read = reciver_adc.read_u16() * ADC_CONV_FACTOR
bit = volt_read > SENSOR_THRESHOLD
#Set current Position of byte to read bit, starting with highest
recived_byte += bit << (7 - i)
print(int(bit), end='')
# Wait for the next Bit acording to the Data Transfer Rate
time.sleep(1/dtr)
# End Reading Byte, pushing it to Byte Array
raw_message.append(recived_byte)
print("\nByte: '{1}' ({0})".format(recived_byte, chr(recived_byte)))
print('\n')
print("Finished Reading Message")
#onboard_led.off()
# Slice the end Symbole of the Message
raw_message = raw_message[:-1]
return raw_message
#
def start_reciving_message():
# Set Threshold according to sourunding Messurments
autoSetThreshold()
while True:
reading = adc.read_u16() * ADC_CONV_FACTOR
#Set LED to Value
indicator_led.value(reading >= SENSOR_THRESHOLD)
if reading >= SENSOR_THRESHOLD:
#==================Init Pin Recived=============
print("Threshold of {0}V overcome with {1}V. Start reading".format(SENSOR_THRESHOLD, reading))
is_reading = True
# Recive the Data Packadge wise
recived = reciveMessage(adc)
# Save to File
save_data(recived)
# Decode Message
try:
msg = recived.decode('utf-8')
print('Recived Message:\n "{0}"'.format(msg))
except:
print('Recived Message couldnt be decoded using ascii')
is_reading = False
time.sleep(1/(4*dtr))
#
def webResponseGenerator(header, path, properties):
global index_html, dtr, SENSOR_THRESHOLD
# Settings Page
if path == '/settings':
setSettings = properties.keys()
if('dtr' in setSettings and properties['dtr'] != ''): # Data Transfer Rate
value = float(properties['dtr'])
# Data Transfer Rate must be grater than 0
if value > 0:
dtr = value
print("Set Data Transfer Rate to {0}".format(dtr))
if('threshold' in setSettings): # Threshold
SENSOR_THRESHOLD = float(properties['threshold'])
print("Set Threshold to {0}".format(SENSOR_THRESHOLD))
# Read settings.html
settings_file = open('settings.html')
response = settings_file.read()
settings_file.close()
page_data = {
"dtr":str(dtr),
"threshold":str(SENSOR_THRESHOLD),
}
return Webserver.generateResponse(response, page_data)
# csv File
if path == '/history/csv':
# Reading csv File as Body
csv_file = open(DATA_FILE_PATH)
body = csv_file.read()
csv_file.close()
header = 'HTTP/1.1 200 OK \r\nContent-Length: {0}\n\rContent-Type: text/csv\r\nContent-Disposition: attachment;filename=data.csv\r\n'.format(str(len(body)))
# Empty Line
response = header + "\r\n" + body
return response
# History
if path == '/history':
history_file = open("history.html")
history_html = history_file.read()
history_file.close()
# Reading csv File
csv_file = open('data.csv')
data = csv_file.read()
csv_file.close()
# Generate History
lines = data.split("\r\n")[-6:]
histroy = ""
quoted = False
for l in lines[:5]:
collum = ""
# Read the First Collum
for c in l:
# Check for Quotes
if c == '"':
quoted = not quoted
#Add read Charakter to string
collum = collum + c
if not quoted and c == ',':
# Finished reading the first Collum, exiting the loop
break
histroy = histroy + '\r\n<hr>\r\n<p class="entry">{0}</p>'.format(collum)
page_data = {
"history":histroy
}
return Webserver.generateResponse(history_html, page_data)
# Default
page_data = {
"is_reading":str(is_reading),
"dtr":str(dtr),
}
index_html_file = open("index.html")
index_html = index_html_file.read()
index_html_file.close()
return Webserver.generateResponse(index_html, page_data)
#================Start================
try:
onboard_led.off()
# Setup
ap = network.WLAN(network.AP_IF)
ap.config(essid=SSID, password=PASSWORD)
ap.active(True)
# Start Listening to Messages on the Second Thread
_thread.start_new_thread(start_reciving_message, [])
# Waiting for AP to be ready
while ap.active() == False:
pass
print ('AP Mode Is Active, You can Now Connect')
print('IP Address To Connect to:: ' + ap.ifconfig () [0])
# Start Webserver on main Thread
Webserver.start(webResponseGenerator)
except KeyboardInterrupt:
ap.active(False)