-
Notifications
You must be signed in to change notification settings - Fork 0
/
serialdata.py
94 lines (73 loc) · 2.17 KB
/
serialdata.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
import serial
import json
import hashlib
def read(port, file):
retrieved = False
send = f'get\n{file}\n'.encode()
checksum = createHash(send)
send = send + checksum + b'\r\n'
print(send)
ser = serial.Serial(port)
ser.write(send)
while retrieved == False:
if ser.inWaiting():
message = retreiveAll(ser)
print(message)
# handle checksum error
if message.splitlines()[0] == b'AGAIN':
ser.write(send)
if message.splitlines()[0] == b'OK':
print('All OK')
print('recieved')
ser.close()
return data
def write(port, data, endLocation):
# checks if endLocation is a json file
if endLocation.split('.')[1] == 'json':
try:
print(endLocation.split('.')[1])
ser = serial.Serial(port)
ser.write(f'set\n{endLocation}\n{json.dumps(data)}\r\n'.encode())
ser.close()
except ValueError:
pass
elif data.split('.')[1] == 'bmp' and endLocation.split('.')[1] == 'bmp':
f = open(data, 'rb')
image = f.read()
f.close()
ser = serial.Serial(port)
ser.write(f'set\n{endLocation}\n'.encode() + image + b'\r\n')
ser.close()
def remove(port, file):
retrieved = False
ser = serial.Serial(port)
ser.write(f'delete\n{file}\r\n'.encode())
while retrieved == False:
if ser.inWaiting():
data = ser.readline()
retrieved = True
print(data)
ser.close()
def createHash(data):
sha = hashlib.sha1()
sha.update(data)
print(sha.digest())
return sha.digest()
def retreiveAll(ser):
end = False
byte_array = bytearray()
while end == False:
line = ser.readline()
if line[-2:-1] == b'\r':
print('End')
end = True
line = line[:-2]
byte_array.extend(line)
return bytes(byte_array)
# remove('COM9', 'test.json')
data = read('COM9', 'pages.json')
print(data)
# write('COM9', data, 'test.json')
# write('COM9', 'acc-cycle-wipers.bmp', '/images/test.bmp')
# delete('COM9', '/images/test.bmp')
# delete('COM9', 'pages.json')