groveyard 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of groveyard might be problematic. Click here for more details.

groveyard/__init__.py ADDED
@@ -0,0 +1,115 @@
1
+ """groveyard — a modern async Python library for GrovePi+ sensors and actuators.
2
+
3
+ Everything is asynchronous and safe to share between concurrent tasks: one lock
4
+ serialises the I2C bus so transactions cannot interleave, and one lock per device
5
+ keeps multi-step operations on the same module atomic.
6
+
7
+ Example:
8
+ ```python
9
+ import asyncio
10
+
11
+ from groveyard import AnalogPort, Board, DigitalPort, Led, LightSensor
12
+
13
+
14
+ async def main() -> None:
15
+ async with Board.on_i2c() as board:
16
+ led = Led(board, DigitalPort.D4)
17
+ sensor = LightSensor(board, AnalogPort.A0)
18
+ if await sensor.read_raw() < 300:
19
+ await led.on()
20
+
21
+
22
+ asyncio.run(main())
23
+ ```
24
+
25
+ Off-device, swap the transport for the in-memory fake and the same code runs on a
26
+ laptop; see :mod:`groveyard.testing`.
27
+ """
28
+
29
+ from groveyard.board import Board
30
+ from groveyard.devices import (
31
+ AnalogInputDevice,
32
+ BacklightColor,
33
+ BridgedDevice,
34
+ Button,
35
+ Buzzer,
36
+ Device,
37
+ Dht,
38
+ DhtReading,
39
+ DigitalInputDevice,
40
+ DigitalOutputDevice,
41
+ DisplayRows,
42
+ I2CDevice,
43
+ Led,
44
+ LightSensor,
45
+ PortDevice,
46
+ Potentiometer,
47
+ Relay,
48
+ RgbLcd,
49
+ SoundSensor,
50
+ Ultrasonic,
51
+ )
52
+ from groveyard.errors import (
53
+ BoardError,
54
+ DeviceClosedError,
55
+ DeviceError,
56
+ DeviceNotReadyError,
57
+ GroveyardError,
58
+ NotConnectedError,
59
+ PortInUseError,
60
+ ProtocolError,
61
+ TransportError,
62
+ )
63
+ from groveyard.ports import AnalogPort, DigitalPort, PinMode, Port, PortKind
64
+ from groveyard.protocol.bridge import FirmwareVersion
65
+ from groveyard.protocol.commands import DhtVariant
66
+ from groveyard.transport.base import RetryPolicy, Transport
67
+ from groveyard.transport.fake import FakeTransport
68
+ from groveyard.transport.i2c import SMBusTransport
69
+
70
+ __version__ = "0.1.0"
71
+
72
+ __all__ = [
73
+ "AnalogInputDevice",
74
+ "AnalogPort",
75
+ "BacklightColor",
76
+ "Board",
77
+ "BoardError",
78
+ "BridgedDevice",
79
+ "Button",
80
+ "Buzzer",
81
+ "Device",
82
+ "DeviceClosedError",
83
+ "DeviceError",
84
+ "DeviceNotReadyError",
85
+ "Dht",
86
+ "DhtReading",
87
+ "DhtVariant",
88
+ "DigitalInputDevice",
89
+ "DigitalOutputDevice",
90
+ "DigitalPort",
91
+ "DisplayRows",
92
+ "FakeTransport",
93
+ "FirmwareVersion",
94
+ "GroveyardError",
95
+ "I2CDevice",
96
+ "Led",
97
+ "LightSensor",
98
+ "NotConnectedError",
99
+ "PinMode",
100
+ "Port",
101
+ "PortDevice",
102
+ "PortInUseError",
103
+ "PortKind",
104
+ "Potentiometer",
105
+ "ProtocolError",
106
+ "Relay",
107
+ "RetryPolicy",
108
+ "RgbLcd",
109
+ "SMBusTransport",
110
+ "SoundSensor",
111
+ "Transport",
112
+ "TransportError",
113
+ "Ultrasonic",
114
+ "__version__",
115
+ ]
groveyard/board.py ADDED
@@ -0,0 +1,477 @@
1
+ """The connection object: lifecycle, port ownership and pin-mode cache.
2
+
3
+ :class:`Board` sits between the protocol layer and the drivers. It is the single
4
+ collaborator a driver talks to, which keeps drivers free of bus and encoding
5
+ concerns (and keeps the call graph flat: a driver never reaches through the board
6
+ into the transport).
7
+
8
+ Responsibilities:
9
+
10
+ * open and close the connection, and run the firmware-version handshake;
11
+ * hand out and validate ports, refusing to let two drivers share one socket;
12
+ * remember which pin mode each port is already configured for, so repeated reads
13
+ do not re-send ``pin_mode``;
14
+ * expose the bridged operations in terms of :class:`~groveyard.ports.Port` values,
15
+ and lend the raw bus session to native-I2C drivers such as the RGB LCD.
16
+
17
+ The board holds exactly one lock, and it is the *outermost* one: a lifecycle lock
18
+ serialising :meth:`Board.connect` and :meth:`Board.disconnect`. The full order is
19
+ **lifecycle → device → bus**, and it is never taken in the other direction —
20
+ `disconnect` calls into devices, no device ever calls back into the lifecycle.
21
+ Ordinary traffic takes no board lock at all: bus atomicity belongs to the
22
+ transport and device-state atomicity belongs to each driver.
23
+
24
+ The pin-mode cache is deliberately unlocked. Every entry is owned by exactly one
25
+ device (see :meth:`Board.attach`), and is only read or written while that device
26
+ holds its own lock, so there is no second writer to race with. That invariant
27
+ holds for the drivers; it can be broken by calling the bridged operations below
28
+ directly on the board while a driver owns the same port — see the warning on
29
+ :meth:`Board.set_pin_mode`.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import asyncio
35
+ import logging
36
+ from typing import TYPE_CHECKING, Final, Self
37
+
38
+ from groveyard.errors import GroveyardError, NotConnectedError, PortInUseError
39
+ from groveyard.ports import AnalogPort, DigitalPort, PinMode, PortKind
40
+ from groveyard.protocol.bridge import BridgeProtocol
41
+ from groveyard.protocol.commands import DhtVariant
42
+ from groveyard.transport.i2c import DEFAULT_BUS_NUMBER, SMBusTransport
43
+
44
+ if TYPE_CHECKING:
45
+ from contextlib import AbstractAsyncContextManager
46
+ from types import TracebackType
47
+
48
+ from groveyard.devices.base import Device
49
+ from groveyard.ports import Port
50
+ from groveyard.protocol.bridge import FirmwareVersion
51
+ from groveyard.transport.base import BusSession, RetryPolicy, Transport
52
+
53
+ _LOGGER: Final = logging.getLogger(__name__)
54
+
55
+ type PortKey = tuple[PortKind, int]
56
+ """Identity of a socket: its family plus its number, so ``D2`` and ``A2`` differ."""
57
+
58
+
59
+ class Board:
60
+ """An open connection to a GrovePi+ HAT.
61
+
62
+ The board owns the connection, not the devices: drivers are constructed
63
+ against a board and register themselves with it. That keeps the board closed
64
+ for modification — adding a new module means adding a
65
+ :class:`~groveyard.devices.base.Device` subclass, never editing this class.
66
+
67
+ Example:
68
+ ```python
69
+ async with Board.on_i2c() as board:
70
+ led = Led(board, DigitalPort.D4)
71
+ await led.on()
72
+ ```
73
+ """
74
+
75
+ def __init__(self, transport: Transport, bridge: BridgeProtocol | None = None) -> None:
76
+ """Wire the board to its collaborators without opening the connection.
77
+
78
+ Args:
79
+ transport: Bus abstraction to use. Inject
80
+ :class:`~groveyard.transport.fake.FakeTransport` in tests and
81
+ :class:`~groveyard.transport.i2c.SMBusTransport` on a Pi.
82
+ bridge: Encoder for the firmware command set. Defaults to a
83
+ :class:`~groveyard.protocol.bridge.BridgeProtocol` bound to
84
+ ``transport``; inject one to change addressing or retry policy.
85
+ """
86
+ self._transport = transport
87
+ self._bridge = bridge or BridgeProtocol(transport)
88
+ self._devices: dict[PortKey, Device] = {}
89
+ self._pin_modes: dict[PortKey, PinMode] = {}
90
+ self._firmware_version: FirmwareVersion | None = None
91
+ self._connected = False
92
+ self._lifecycle_lock = asyncio.Lock()
93
+
94
+ @classmethod
95
+ def on_i2c(cls, bus_number: int = DEFAULT_BUS_NUMBER, retry_policy: RetryPolicy | None = None) -> Self:
96
+ """Build a board that talks to real hardware over ``/dev/i2c-<n>``.
97
+
98
+ Args:
99
+ bus_number: I2C bus number. Bus 1 on every modern Raspberry Pi.
100
+ retry_policy: How transient bus faults are retried.
101
+
102
+ Returns:
103
+ A board that is not connected yet.
104
+ """
105
+ return cls(SMBusTransport(bus_number=bus_number, retry_policy=retry_policy))
106
+
107
+ @property
108
+ def is_connected(self) -> bool:
109
+ """Whether :meth:`connect` has completed and :meth:`disconnect` has not run."""
110
+ return self._connected
111
+
112
+ @property
113
+ def firmware_version(self) -> FirmwareVersion:
114
+ """Version reported by the board during the connect handshake.
115
+
116
+ Raises:
117
+ NotConnectedError: If the handshake has not run yet.
118
+ """
119
+ if self._firmware_version is None:
120
+ msg = "firmware version is only known after connect()"
121
+ raise NotConnectedError(msg)
122
+ return self._firmware_version
123
+
124
+ async def connect(self) -> Self:
125
+ """Open the bus and perform the firmware-version handshake.
126
+
127
+ Idempotent, and safe to call from several tasks at once: the lifecycle
128
+ lock makes the check-and-open one step, so two callers cannot both open a
129
+ handle or both run the handshake.
130
+
131
+ Returns:
132
+ The board itself, so it can be used fluently.
133
+
134
+ Raises:
135
+ DeviceNotReadyError: If the board never answered the handshake.
136
+ ProtocolError: If the handshake reply was malformed.
137
+ TransportError: If the bus could not be opened or used.
138
+ """
139
+ async with self._lifecycle_lock:
140
+ if self._connected:
141
+ return self
142
+ await self._transport.open()
143
+ try:
144
+ self._firmware_version = await self._bridge.firmware_version()
145
+ except GroveyardError:
146
+ await self._transport.close()
147
+ raise
148
+ self._connected = True
149
+ _LOGGER.debug("connected to GrovePi+ firmware %s", self._firmware_version)
150
+ return self
151
+
152
+ async def disconnect(self) -> None:
153
+ """Shut every attached device down safely and close the bus.
154
+
155
+ Devices are closed first and while the connection is still usable, so
156
+ actuators can drive themselves back to *off*. A device that fails to shut
157
+ down is logged and skipped: one broken module must not keep the bus open.
158
+ Idempotent.
159
+
160
+ Shutting down is a cleanup path, so the whole sweep runs inside a shield:
161
+ a Ctrl-C or a collapsing :class:`asyncio.TaskGroup` cannot interrupt it
162
+ half-way and leave actuators energised with the bus descriptor still open.
163
+ The sweep is awaited to completion first, and only then is the
164
+ cancellation re-raised, so when this method returns — or raises — the
165
+ board really is shut down.
166
+
167
+ Raises:
168
+ asyncio.CancelledError: If the caller was cancelled during the sweep.
169
+ Every device has still been shut down and the bus is closed.
170
+ """
171
+ async with self._lifecycle_lock:
172
+ shutdown = asyncio.ensure_future(self._shut_everything_down())
173
+ try:
174
+ await asyncio.shield(shutdown)
175
+ except asyncio.CancelledError:
176
+ await shutdown
177
+ raise
178
+
179
+ async def _shut_everything_down(self) -> None:
180
+ """Close every device, then the bus. Runs under the lifecycle lock.
181
+
182
+ A device that fails to shut down is logged and skipped, because one broken
183
+ module must not keep the bus open or strand the modules after it.
184
+ """
185
+ try:
186
+ if self._connected:
187
+ for device in list(self._devices.values()):
188
+ try:
189
+ await device.close()
190
+ except GroveyardError:
191
+ _LOGGER.warning(
192
+ "device on %s failed to shut down cleanly",
193
+ device.describe(),
194
+ exc_info=True,
195
+ )
196
+ finally:
197
+ self._connected = False
198
+ self._pin_modes.clear()
199
+ await self._transport.close()
200
+
201
+ async def __aenter__(self) -> Self:
202
+ """Connect on entering an ``async with`` block.
203
+
204
+ Returns:
205
+ The connected board.
206
+ """
207
+ return await self.connect()
208
+
209
+ async def __aexit__(
210
+ self,
211
+ exc_type: type[BaseException] | None,
212
+ exc: BaseException | None,
213
+ traceback: TracebackType | None,
214
+ ) -> None:
215
+ """Disconnect on leaving an ``async with`` block, including on error.
216
+
217
+ Args:
218
+ exc_type: Type of the exception that is propagating, if any.
219
+ exc: The exception that is propagating, if any.
220
+ traceback: Traceback of that exception, if any.
221
+ """
222
+ await self.disconnect()
223
+
224
+ def attach(self, device: Device, port: Port | None = None) -> None:
225
+ """Claim a socket for a device.
226
+
227
+ Args:
228
+ device: The driver claiming the socket.
229
+ port: The socket being claimed, or ``None`` for the shared I2C port.
230
+
231
+ Raises:
232
+ PortInUseError: If another live device already holds that socket.
233
+ """
234
+ key = self._key(port)
235
+ owner = self._devices.get(key)
236
+ if owner is not None and owner is not device:
237
+ msg = f"{self._describe_key(key)} is already used by {type(owner).__name__}"
238
+ raise PortInUseError(msg)
239
+ self._devices[key] = device
240
+
241
+ def detach(self, device: Device, port: Port | None = None) -> None:
242
+ """Release a socket previously claimed by a device.
243
+
244
+ Releasing a socket the device does not own is a no-op, so closing twice is
245
+ harmless.
246
+
247
+ Args:
248
+ device: The driver releasing the socket.
249
+ port: The socket being released, or ``None`` for the shared I2C port.
250
+ """
251
+ key = self._key(port)
252
+ if self._devices.get(key) is device:
253
+ del self._devices[key]
254
+ self._pin_modes.pop(key, None)
255
+
256
+ async def ensure_pin_mode(self, port: Port, mode: PinMode) -> None:
257
+ """Configure a port's direction unless it is already configured that way.
258
+
259
+ Callers must hold their device lock, which is what makes the cache
260
+ race-free: a port belongs to exactly one device.
261
+
262
+ Args:
263
+ port: Socket to configure.
264
+ mode: Direction the driver needs.
265
+
266
+ Raises:
267
+ NotConnectedError: If the board is not connected.
268
+ TransportError: If the bus itself failed.
269
+ """
270
+ key = self._key(port)
271
+ if self._pin_modes.get(key) is mode:
272
+ return
273
+ await self.set_pin_mode(port, mode)
274
+
275
+ async def set_pin_mode(self, port: Port, mode: PinMode) -> None:
276
+ """Configure a port's direction unconditionally and remember it.
277
+
278
+ Warning:
279
+ This and the bridged operations below are the plumbing the drivers
280
+ are built on. They take **no device lock**, so calling them on a port
281
+ that a driver already owns races that driver's cached state — drive
282
+ the device through its own class instead. They are public because a
283
+ module this library does not ship yet still has to be reachable.
284
+
285
+ Args:
286
+ port: Socket to configure.
287
+ mode: Direction to configure.
288
+
289
+ Raises:
290
+ NotConnectedError: If the board is not connected.
291
+ TransportError: If the bus itself failed.
292
+ """
293
+ self._require_connected()
294
+ await self._bridge.set_pin_mode(int(port), mode)
295
+ self._pin_modes[self._key(port)] = mode
296
+
297
+ async def digital_read(self, port: DigitalPort) -> int:
298
+ """Read the logic level of a digital socket.
299
+
300
+ Args:
301
+ port: Digital socket to read.
302
+
303
+ Returns:
304
+ ``0`` for low, ``1`` for high.
305
+
306
+ Raises:
307
+ NotConnectedError: If the board is not connected.
308
+ DeviceNotReadyError: If the board never became ready.
309
+ ProtocolError: If the reply was malformed.
310
+ TransportError: If the bus itself failed.
311
+ """
312
+ self._require_connected()
313
+ return await self._bridge.digital_read(int(port))
314
+
315
+ async def digital_write(self, port: DigitalPort, value: int) -> None:
316
+ """Drive a digital socket high or low.
317
+
318
+ Args:
319
+ port: Digital socket to drive.
320
+ value: ``0`` for low, ``1`` for high.
321
+
322
+ Raises:
323
+ NotConnectedError: If the board is not connected.
324
+ TransportError: If the bus itself failed.
325
+ """
326
+ self._require_connected()
327
+ await self._bridge.digital_write(int(port), value)
328
+
329
+ async def analog_read(self, port: AnalogPort) -> int:
330
+ """Read the ADC value of an analog socket.
331
+
332
+ Args:
333
+ port: Analog socket to read.
334
+
335
+ Returns:
336
+ Raw counts in ``0..1023``.
337
+
338
+ Raises:
339
+ NotConnectedError: If the board is not connected.
340
+ DeviceNotReadyError: If the board never became ready.
341
+ ProtocolError: If the reply was malformed.
342
+ TransportError: If the bus itself failed.
343
+ """
344
+ self._require_connected()
345
+ return await self._bridge.analog_read(int(port))
346
+
347
+ async def analog_write(self, port: Port, value: int) -> None:
348
+ """Set the PWM duty cycle of a socket.
349
+
350
+ Args:
351
+ port: Socket to drive. Digital sockets that the firmware can PWM are
352
+ the usual target.
353
+ value: Duty cycle in ``0..255``.
354
+
355
+ Raises:
356
+ NotConnectedError: If the board is not connected.
357
+ TransportError: If the bus itself failed.
358
+ """
359
+ self._require_connected()
360
+ await self._bridge.analog_write(int(port), value)
361
+
362
+ async def ultrasonic_read(self, port: DigitalPort) -> int:
363
+ """Trigger an ultrasonic ping and read the distance it measured.
364
+
365
+ Args:
366
+ port: Digital socket the ranger is plugged into.
367
+
368
+ Returns:
369
+ Distance in centimetres, as reported by the firmware.
370
+
371
+ Raises:
372
+ NotConnectedError: If the board is not connected.
373
+ DeviceNotReadyError: If the board never became ready.
374
+ ProtocolError: If the reply was malformed.
375
+ TransportError: If the bus itself failed.
376
+ """
377
+ self._require_connected()
378
+ return await self._bridge.ultrasonic_read(int(port))
379
+
380
+ async def dht_read(self, port: DigitalPort, variant: DhtVariant = DhtVariant.DHT11) -> tuple[float, float]:
381
+ """Read temperature and humidity from a DHT sensor.
382
+
383
+ Args:
384
+ port: Digital socket the sensor is plugged into.
385
+ variant: Which DHT variant is connected.
386
+
387
+ Returns:
388
+ A ``(temperature_celsius, humidity_percent)`` pair.
389
+
390
+ Raises:
391
+ NotConnectedError: If the board is not connected.
392
+ DeviceNotReadyError: If every attempt produced an implausible reading.
393
+ ProtocolError: If the reply was malformed.
394
+ TransportError: If the bus itself failed.
395
+ """
396
+ self._require_connected()
397
+ return await self._bridge.dht_read(int(port), variant)
398
+
399
+ async def wait(self, seconds: float) -> None:
400
+ """Wait for a device that needs time but does not need the bus.
401
+
402
+ Used by drivers whose controller needs a settling period — the RGB LCD
403
+ after a clear, for instance. Keeping such a delay out of
404
+ :meth:`bus_session` is what stops one slow display from stalling every
405
+ other device for 50 ms.
406
+
407
+ Args:
408
+ seconds: How long to wait. Never blocks the event loop.
409
+ """
410
+ await self._transport.wait(seconds)
411
+
412
+ def bus_session(self) -> AbstractAsyncContextManager[BusSession]:
413
+ """Borrow the bus for one transaction, for native-I2C drivers.
414
+
415
+ Modules such as the RGB LCD do not go through the bridge, but they do
416
+ share the wires, so they must use the same lock. This hands out the
417
+ transport's session unchanged.
418
+
419
+ Warning:
420
+ The session **is** the bus lock. Never call a device method while one
421
+ is open: the device would take its own lock and then wait forever for
422
+ the bus lock this task is already holding. Keep the block to raw
423
+ ``session`` calls, and take the delays that do not need the bus with
424
+ :meth:`wait` instead.
425
+
426
+ Returns:
427
+ An async context manager yielding a
428
+ :class:`~groveyard.transport.base.BusSession`.
429
+
430
+ Raises:
431
+ NotConnectedError: If the board is not connected.
432
+ """
433
+ self._require_connected()
434
+ return self._transport.session()
435
+
436
+ def _require_connected(self) -> None:
437
+ """Guard operations that need an open connection.
438
+
439
+ Raises:
440
+ NotConnectedError: If the board is not connected.
441
+ """
442
+ if not self._connected:
443
+ msg = "board is not connected; call connect() or use it as an async context manager"
444
+ raise NotConnectedError(msg)
445
+
446
+ def _key(self, port: Port | None) -> PortKey:
447
+ """Build the registry key identifying a socket.
448
+
449
+ Args:
450
+ port: Socket to identify, or ``None`` for the shared I2C port.
451
+
452
+ Returns:
453
+ A ``(kind, number)`` pair, distinguishing ``D2`` from ``A2``.
454
+
455
+ Raises:
456
+ TypeError: If ``port`` is not a known port type.
457
+ """
458
+ if port is None:
459
+ return (PortKind.I2C, 0)
460
+ if isinstance(port, DigitalPort | AnalogPort):
461
+ return (port.kind, int(port))
462
+ msg = f"expected a DigitalPort or an AnalogPort, got {type(port).__name__}"
463
+ raise TypeError(msg)
464
+
465
+ def _describe_key(self, key: PortKey) -> str:
466
+ """Render a registry key for error messages.
467
+
468
+ Args:
469
+ key: The ``(kind, number)`` pair to describe.
470
+
471
+ Returns:
472
+ A human-readable socket name such as ``"digital port 4"``.
473
+ """
474
+ kind, number = key
475
+ if kind is PortKind.I2C:
476
+ return "the I2C port"
477
+ return f"{kind.value} port {number}"
@@ -0,0 +1,47 @@
1
+ """Device drivers: one class per Grove module, plus the bases they share.
2
+
3
+ Adding a module means adding a class here — no other layer changes.
4
+ """
5
+
6
+ from groveyard.devices.base import (
7
+ AnalogInputDevice,
8
+ BridgedDevice,
9
+ Device,
10
+ DigitalInputDevice,
11
+ DigitalOutputDevice,
12
+ I2CDevice,
13
+ PortDevice,
14
+ )
15
+ from groveyard.devices.button import Button
16
+ from groveyard.devices.buzzer import Buzzer
17
+ from groveyard.devices.dht import Dht, DhtReading
18
+ from groveyard.devices.led import Led
19
+ from groveyard.devices.light_sensor import LightSensor
20
+ from groveyard.devices.potentiometer import Potentiometer
21
+ from groveyard.devices.relay import Relay
22
+ from groveyard.devices.rgb_lcd import BacklightColor, DisplayRows, RgbLcd
23
+ from groveyard.devices.sound_sensor import SoundSensor
24
+ from groveyard.devices.ultrasonic import Ultrasonic
25
+
26
+ __all__ = [
27
+ "AnalogInputDevice",
28
+ "BacklightColor",
29
+ "BridgedDevice",
30
+ "Button",
31
+ "Buzzer",
32
+ "Device",
33
+ "Dht",
34
+ "DhtReading",
35
+ "DigitalInputDevice",
36
+ "DigitalOutputDevice",
37
+ "DisplayRows",
38
+ "I2CDevice",
39
+ "Led",
40
+ "LightSensor",
41
+ "PortDevice",
42
+ "Potentiometer",
43
+ "Relay",
44
+ "RgbLcd",
45
+ "SoundSensor",
46
+ "Ultrasonic",
47
+ ]