-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimpleSerialMaster.py
executable file
·59 lines (48 loc) · 1.58 KB
/
SimpleSerialMaster.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
import time
import serial
import pyinputplus as pyip
def checkCommand(c):
if bool(re.match(r'(R|W|r|w)', c)) == False:
raise Exception('Invalid command [R,r,W,w]')
return c
def calcCheckSum(b):
checksum = b[0]
for i in range(1,len(b)):
checksum ^= b[i]
return checksum
def convertToMessage(command, number, value):
byteCommand = bytes(command, "ascii")
byteNumber = number.to_bytes(1, 'big')
byteValue = value.to_bytes(1, 'big')
message = bytearray(byteCommand)
message.append(byteNumber[0])
message.append(byteValue[0])
message.append(calcCheckSum(message))
return message
def sendAndReceve(ser, message):
ser.write(message)
time.sleep(0.2)
byteread = ser.read(3)
if(len(byteread)!=3):
return "None"
calcCheck = calcCheckSum(byteread[:-1])
byteCheckSum = byteread[2]
retmes = str(byteread[0]) + "," + str(byteread[1])
if(calcCheck != byteCheckSum):
retmes += "(!)"
return retmes
def main():
ser = serial.Serial('/dev/ttyACM0', 9600, timeout=5)
while True:
command = pyip.inputCustom(checkCommand, prompt="Command: ")
number = int(pyip.inputNum(prompt="PinNumber: ", min=0, lessThan=20))
value = int(pyip.inputNum(prompt="PinValue: ", min=0, lessThan=256))
print('invio: "'+command+','+str(number)+','+str(value)+'"')
m = convertToMessage(command,number,value)
r = sendAndReceve(ser,m)
print('ricevo: "'+r+'"')
if __name__ == "__main__":
main()