-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhardware.py
More file actions
297 lines (257 loc) · 8.93 KB
/
hardware.py
File metadata and controls
297 lines (257 loc) · 8.93 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
import importlib
import importlib.util
import time
try:
import serial # for Arduino serial communication
except Exception: # pragma: no cover - optional dependency
serial = None
class Arduino:
def __init__(self, port="COM3", baudrate=9600, timeout=1, handshake=True, handshake_timeout=2.0):
if serial is None:
print("[Arduino] pyserial not installed; Arduino unavailable.")
self.conn = None
else:
try:
self.conn = serial.Serial(port, baudrate, timeout=timeout)
time.sleep(2) # wait for Arduino to reset
print(f"[Arduino] Connected to {port} at {baudrate} baud.")
except Exception as e:
print("[Arduino] Connection failed:", e)
self.conn = None
self.capabilities = {"features": set(), "proto": None, "device": None, "model": None, "fw": None}
self.capabilities_known = False
if self.conn and handshake:
self.handshake(timeout=handshake_timeout)
def write(self, message):
"""Send a message to Arduino."""
if self.conn:
self.conn.write(str(message).encode())
print(f"[Arduino] Sent: {message}")
def read(self):
"""Read a line from Arduino if available."""
return self._read_line(timeout=0)
def _read_line(self, timeout=1.0):
if not self.conn:
return None
end = time.time() + max(0.0, timeout)
while True:
if self.conn.in_waiting > 0:
data = self.conn.readline().decode().strip()
print(f"[Arduino] Received: {data}")
return data
if time.time() >= end:
return None
time.sleep(0.05)
def _parse_caps_response(self, response):
if not response or not response.startswith("CAPS:"):
return None
payload = response[len("CAPS:"):]
fields = {}
for part in payload.split(";"):
if "=" not in part:
continue
key, value = part.split("=", 1)
fields[key.strip()] = value.strip()
if "proto" not in fields or "features" not in fields:
return None
try:
proto = int(fields["proto"])
except ValueError:
return None
features = {f.strip() for f in fields["features"].split(",") if f.strip()}
return {
"proto": proto,
"features": features,
"device": fields.get("device"),
"model": fields.get("model"),
"fw": fields.get("fw"),
}
def handshake(self, timeout=2.0):
"""Query device capabilities using the CAPS command."""
if not self.conn:
return None
self.write("CAPS\n")
response = self._read_line(timeout=timeout)
parsed = self._parse_caps_response(response)
if parsed:
self.capabilities = parsed
self.capabilities_known = True
return parsed
self.capabilities_known = False
return None
def get_capabilities(self):
"""Return last known capabilities, if any."""
return dict(self.capabilities)
def supports(self, feature):
"""Check if a feature is supported."""
if not self.capabilities_known:
return False
return feature in self.capabilities["features"]
def _require_feature(self, feature):
if self.capabilities_known and not self.supports(feature):
raise RuntimeError(f"[Arduino] Feature not supported: {feature}")
def led_on(self, pin=13):
"""Turn ON LED at given pin (default 13)."""
self._require_feature("led_on")
self.write(f"LED_ON:{pin}")
def led_off(self, pin=13):
"""Turn OFF LED at given pin (default 13)."""
self._require_feature("led_off")
self.write(f"LED_OFF:{pin}")
def motor_start(self, pin=9, speed=255):
"""Start motor at pin with speed (0-255)."""
self._require_feature("motor_start")
self.write(f"MOTOR_START:{pin}:{speed}")
def motor_stop(self, pin=9):
"""Stop motor at pin."""
self._require_feature("motor_stop")
self.write(f"MOTOR_STOP:{pin}")
def close(self):
"""Close Arduino connection."""
if self.conn:
self.conn.close()
print("[Arduino] Connection closed.")
class RaspberryPi:
def __init__(self, mode="BCM"):
self.mode = mode.upper()
self.gpio = None
self.available = False
spec = importlib.util.find_spec("RPi.GPIO")
if spec is not None:
self.gpio = importlib.import_module("RPi.GPIO")
if self.mode == "BOARD":
self.gpio.setmode(self.gpio.BOARD)
else:
self.gpio.setmode(self.gpio.BCM)
self.available = True
def setup_output(self, pin):
if not self.available:
return False
self.gpio.setup(pin, self.gpio.OUT)
return True
def setup_input(self, pin, pull="down"):
if not self.available:
return False
pull = pull.lower()
pud = self.gpio.PUD_DOWN if pull == "down" else self.gpio.PUD_UP
self.gpio.setup(pin, self.gpio.IN, pull_up_down=pud)
return True
def write(self, pin, value):
if not self.available:
return False
self.gpio.output(pin, self.gpio.HIGH if value else self.gpio.LOW)
return True
def read(self, pin):
if not self.available:
return None
return bool(self.gpio.input(pin))
def cleanup(self, pin=None):
if not self.available:
return False
if pin is None:
self.gpio.cleanup()
else:
self.gpio.cleanup(pin)
return True
class HardwareAdapter:
def __init__(self, port="COM3", baudrate=9600, timeout=1):
self.arduino = Arduino(port=port, baudrate=baudrate, timeout=timeout)
self.raspberry_pi = RaspberryPi()
def _no_device_error(self):
return {
"ok": False,
"error": {
"code": "no_device",
"message": "No hardware device connected.",
},
}
def _ok(self, **payload):
response = {"ok": True}
response.update(payload)
return response
def _ensure_connected(self):
if not getattr(self.arduino, "conn", None):
return self._no_device_error()
return None
def _ensure_pi(self):
if not getattr(self.raspberry_pi, "available", False):
return {
"ok": False,
"error": {
"code": "pi_unavailable",
"message": "Raspberry Pi GPIO not available.",
},
}
return None
def write(self, message):
error = self._ensure_connected()
if error:
return error
self.arduino.write(message)
return self._ok()
def read(self):
error = self._ensure_connected()
if error:
return error
data = self.arduino.read()
return self._ok(data=data)
def led_on(self, pin=13):
error = self._ensure_connected()
if error:
return error
self.arduino.led_on(pin=pin)
return self._ok()
def led_off(self, pin=13):
error = self._ensure_connected()
if error:
return error
self.arduino.led_off(pin=pin)
return self._ok()
def motor_start(self, pin=9, speed=255):
error = self._ensure_connected()
if error:
return error
self.arduino.motor_start(pin=pin, speed=speed)
return self._ok()
def motor_stop(self, pin=9):
error = self._ensure_connected()
if error:
return error
self.arduino.motor_stop(pin=pin)
return self._ok()
def close(self):
error = self._ensure_connected()
if error:
return error
self.arduino.close()
return self._ok()
def pi_setup_output(self, pin):
error = self._ensure_pi()
if error:
return error
self.raspberry_pi.setup_output(pin)
return self._ok()
def pi_setup_input(self, pin, pull="down"):
error = self._ensure_pi()
if error:
return error
self.raspberry_pi.setup_input(pin, pull=pull)
return self._ok()
def pi_write(self, pin, value):
error = self._ensure_pi()
if error:
return error
self.raspberry_pi.write(pin, value)
return self._ok()
def pi_read(self, pin):
error = self._ensure_pi()
if error:
return error
value = self.raspberry_pi.read(pin)
return self._ok(value=value)
def pi_cleanup(self, pin=None):
error = self._ensure_pi()
if error:
return error
self.raspberry_pi.cleanup(pin=pin)
return self._ok()