-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathComArduino.py
86 lines (71 loc) · 2.52 KB
/
ComArduino.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
##################################### Arduino ##################################
import serial
import serial.tools.list_ports
import time
import datetime
from utils import *
class ComArduino:
def __init__(self, coonfig):
self.ser = serial.Serial()
self.baudrate = config['ino_boudrate']
#dati prrovenienti da arduino
self.lettura = {}
self.connect()
#TODO controllare connessione attraverso pyserial
print("[SERIALE] arduino connesso")
#ritorna la lettura completa di tutti i valori
def get_all_data(self):
return self.lettura
#ritorna la il valore del campo di lettura
def get_by_name(self, name):
return self.lettura[name]
#chiude la connessione con arduino
def close(self):
self.ser.close()
#scrive sulla seriale
def write(self, text):
self.ser.write(str.encode(text))
#leggo i valori provenienti da arduino
def read(self, raw=False):
out = b""
try:
while(self.ser.inWaiting() > 0):
out += self.ser.read(1)
except:
print("[SERIALE] errore nella connessione con arduino")
#pulisco i dati
self.lettura = {}
#tento riconnessione
self.close()
self.connect()
raise Exception('Reading error')
if not raw:
try:
if out.decode() != "":
self.lettura = dataParser(out.decode())
self.lettura['date'] = '{:%d-%b-%Y %H:%M:%S}'.format(datetime.datetime.now())
except Exception as ex:
print(ex)
return self.lettura
else:
return out.decode()
"""
####### connessione tramite handshake #######
# python----connect---->Arduino #
# python<---"handshake"----Arduino #
# connection DONE! #
#############################################
"""
def connect(self):
ports = list(serial.tools.list_ports.comports())
for p in ports:
try:
self.ser = serial.Serial(p.device, self.baudrate)
time.sleep(1) #evito che arduino vada in reset
if self.read(raw=True).strip() == "handshake":
break
else:
self.close()
except serial.SerialException as ex:
print(ex)
#return self.ser.state()