-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserial_reader.py
More file actions
80 lines (59 loc) · 2.01 KB
/
Copy pathserial_reader.py
File metadata and controls
80 lines (59 loc) · 2.01 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
"""
Arduino Serial Reader.
Responsible for:
Arduino UNO → USB → Serial/COM Port → Python
"""
import json
import serial
from config import ARDUINO_PORT, BAUD_RATE, SERIAL_TIMEOUT
class ArduinoSerialReader:
"""Reads JSON sensor data from Arduino over Serial."""
def __init__(self):
self.port = ARDUINO_PORT
self.baud_rate = BAUD_RATE
self.timeout = SERIAL_TIMEOUT
self.connection = None
def connect(self):
"""Open the Arduino serial connection."""
try:
self.connection = serial.Serial(
port=self.port,
baudrate=self.baud_rate,
timeout=self.timeout,
)
print(
f"[SERIAL] Connected to Arduino "
f"on {self.port} @ {self.baud_rate} baud"
)
except serial.SerialException as error:
print(f"[SERIAL] Connection failed: {error}")
raise
def read_data(self):
"""
Read one line from Arduino and convert it to JSON.
Returns:
dict | None: Parsed sensor data or None if invalid.
"""
if self.connection is None:
raise RuntimeError("Serial connection is not open.")
try:
raw_data = self.connection.readline().decode(
"utf-8",
errors="ignore"
).strip()
if not raw_data:
return None
# Convert Arduino JSON string into Python dictionary
data = json.loads(raw_data)
return data
except json.JSONDecodeError:
print(f"[SERIAL] Invalid JSON received: {raw_data}")
return None
except serial.SerialException as error:
print(f"[SERIAL] Read error: {error}")
return None
def close(self):
"""Close the serial connection."""
if self.connection and self.connection.is_open:
self.connection.close()
print("[SERIAL] Connection closed.")