-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhardware.py
More file actions
196 lines (168 loc) · 6.15 KB
/
hardware.py
File metadata and controls
196 lines (168 loc) · 6.15 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
"""Thread-safe HardwareController wrapper around Freenove modules."""
import json
import subprocess
import threading
import logging
from pathlib import Path
from server.freenove_bridge import load_hardware_modules
from server.config import settings
log = logging.getLogger(__name__)
STATE_PATH = Path("user_data/hardware_state.json")
class HardwareController:
"""Control motors, servos, LEDs, and sensors."""
VALID_MODES = {"manual", "ultrasonic", "infrared", "ai"}
def __init__(self):
saved_state = self._load_state()
modules = load_hardware_modules()
self._motor = modules["motor"]()
self._servo = modules["servo"]()
self._led = modules["led"]()
self._ultrasonic = modules["ultrasonic"]()
self._infrared = modules["infrared"]()
self._lock = threading.Lock()
self._mode = "manual"
self._estop = False
self._claw_servos_enabled = saved_state.get("claw_servos_enabled", True)
self._motor_left = 0
self._motor_right = 0
# Force both motor channels low as soon as the driver is initialized.
self._motor.setMotorModel(0, 0)
if not self._claw_servos_enabled:
self._servo.setServoEnabled(0, False)
self._servo.setServoEnabled(1, False)
log.info("HardwareController initialized")
def _load_state(self) -> dict:
"""Load persisted runtime state."""
try:
if STATE_PATH.exists():
return json.loads(STATE_PATH.read_text(encoding="utf-8"))
except Exception as exc:
log.warning("Failed to load hardware state: %s", exc)
return {}
def _save_state(self):
"""Persist runtime state to disk."""
payload = {
"claw_servos_enabled": self._claw_servos_enabled,
}
try:
STATE_PATH.parent.mkdir(parents=True, exist_ok=True)
STATE_PATH.write_text(json.dumps(payload, indent=2), encoding="utf-8")
except Exception as exc:
log.warning("Failed to save hardware state: %s", exc)
@property
def mode(self) -> str:
return self._mode
@mode.setter
def mode(self, value: str):
mode = (value or "manual").lower()
if mode not in self.VALID_MODES:
raise ValueError(f"Invalid mode: {value}")
if mode != self._mode:
self.stop_motors()
self._mode = mode
@property
def motor_left(self) -> int:
return self._motor_left
@property
def motor_right(self) -> int:
return self._motor_right
@property
def estop(self) -> bool:
return self._estop
@property
def claw_servos_enabled(self) -> bool:
return self._claw_servos_enabled
@property
def led_supported(self) -> bool:
return getattr(self._led, "supported", True)
def set_motor(self, left: int, right: int):
"""Set motor speed. Valid range: -4095..4095."""
left = max(-4095, min(4095, int(left)))
right = max(-4095, min(4095, int(right)))
with self._lock:
if self._estop:
left = 0
right = 0
self._motor_left = left
self._motor_right = right
self._motor.setMotorModel(left, right)
def stop_motors(self):
"""Stop both motors immediately."""
self.set_motor(0, 0)
def set_servo(self, channel: int, angle: int):
"""Set the servo angle."""
channel = max(0, min(2, channel))
angle = max(0, min(180, angle))
with self._lock:
if channel in (0, 1) and not self._claw_servos_enabled:
return
self._servo.setServoAngle(channel, angle)
def set_claw_servos_enabled(self, enabled: bool):
"""Enable or disable the grip/lift servos."""
with self._lock:
self._claw_servos_enabled = bool(enabled)
if not self._claw_servos_enabled:
self._servo.setServoEnabled(0, False)
self._servo.setServoEnabled(1, False)
self._save_state()
def set_led(self, r: int, g: int, b: int):
"""Set the color of all LEDs."""
with self._lock:
self._led.colorWipe([r, g, b])
def led_effect(self, effect: str):
"""Run a predefined LED effect."""
with self._lock:
if effect == "rainbow":
self._led.rainbow()
elif effect == "breathing":
self._led.Breathing([0, 100, 255])
elif effect == "off":
self._led.colorWipe([0, 0, 0])
def get_distance(self) -> float:
"""Get the ultrasonic sensor distance in centimeters."""
with self._lock:
return self._ultrasonic.get_distance()
def get_infrared(self) -> list[int]:
"""Get infrared sensor states as [IR1, IR2, IR3]."""
with self._lock:
val = self._infrared.read_all_infrared()
return [(val >> 2) & 1, (val >> 1) & 1, val & 1]
def get_cpu_temp(self) -> float:
"""Return the Raspberry Pi CPU temperature in Celsius."""
if settings.mock:
return 42.0
try:
out = subprocess.check_output(["vcgencmd", "measure_temp"], text=True)
# "temp=48.3'C\n"
return float(out.split("=")[1].split("'")[0])
except Exception:
return 0.0
def stop_all(self):
"""Latch the emergency stop and stop all controllable subsystems."""
self._estop = True
self.stop_motors()
self.set_led(0, 0, 0)
log.info("Emergency stop latched")
def release_stop(self):
"""Release the emergency stop latch."""
if not self._estop:
return
self._estop = False
self.stop_motors()
log.info("Emergency stop released")
def close(self):
"""Release hardware resources."""
self.stop_all()
try:
self._motor.close()
except Exception:
pass
try:
self._ultrasonic.close()
except Exception:
pass
try:
self._infrared.close()
except Exception:
pass
log.info("HardwareController closed")