GHIElectronics.Endpoint.Drivers.RaspberryPi 0.5.4__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.
@@ -0,0 +1,253 @@
1
+ """Raspberry Pi Zero 2 W board support for Endpoint (Python).
2
+
3
+ Registers Zero2WBoardSupport with Core's BoardSupport.Current on import,
4
+ so user code uses Core's chip-neutral verbs:
5
+
6
+ from GHIElectronics.Endpoint.Core import I2cController, SpiController, PwmController, SerialPortController
7
+ from GHIElectronics.Endpoint.Drivers.RaspberryPi import Zero2W
8
+
9
+ I2cController.Initialize(Zero2W.I2c.I2c1)
10
+ PwmController.Initialize(Zero2W.Pwm.Pin.Pin12)
11
+ SpiController.Initialize(Zero2W.Spi.Spi0, Zero2W.Spi.DefaultBufferSize)
12
+ SerialPortController.Initialize(Zero2W.SerialPort.Uart1, False)
13
+
14
+ Identical shape to Endpoint boards; swap `EPDomino24.*` for `Zero2W.*`.
15
+ Zero2WBoardSupport only overrides I2C/SPI/PWM/SerialPort (the peripherals
16
+ the Pi actually implements). Everything else (CAN, DAC, Watchdog, ADC,
17
+ STM32 pin primitives) inherits UnknownBoardSupport's "not supported on
18
+ this board" throw from Core.
19
+ """
20
+
21
+ # Import Core FIRST: this loads libendpoint-<arch>.so (with RTLD_GLOBAL, see
22
+ # Core/_native.py). Required BEFORE we dlopen libendpoint-zero2w-<arch>.so
23
+ # below, because that .so's __attribute__((constructor)) looks up
24
+ # endpoint_register_board_support via dlsym(RTLD_DEFAULT) and will find
25
+ # nothing if libendpoint has not been loaded globally first. On an Endpoint
26
+ # chip (EPM815/EPN256/EPN128) the libendpoint load also auto-registers that
27
+ # chip's BoardSupport, and the zero2w constructor then no-ops on the
28
+ # ChipDetect check so the Endpoint board stays active.
29
+ from GHIElectronics.Endpoint.Core import _native as _unused_core_native # noqa: F401
30
+
31
+ from GHIElectronics.Endpoint.Core._board_support import (
32
+ BoardSupport as _BoardSupport,
33
+ UnknownBoardSupport as _UnknownBoardSupport,
34
+ )
35
+ from GHIElectronics.Endpoint.Core._chip_detect import Chip as _Chip, Current as _ChipCurrent
36
+
37
+ from ._pinmux import Pinmux as _Pinmux
38
+
39
+ # Load the native board-support .so so libendpoint's C++ dispatch sees the
40
+ # Pi. Python GPIO goes through libendpoint directly (unlike I2C/SPI/PWM/UART
41
+ # which still use the Python-side Zero2WBoardSupport below), so without this
42
+ # load every gpio.OpenPin would throw "GPIO is not supported on this board
43
+ # ('Unknown')".
44
+ def _load_native_board_driver():
45
+ import ctypes, os, platform
46
+ machine = platform.machine().lower()
47
+ if machine in ("aarch64", "arm64"):
48
+ name = "libendpoint-zero2w-arm64.so"
49
+ elif machine.startswith("armv") or machine == "arm":
50
+ name = "libendpoint-zero2w-arm.so"
51
+ else:
52
+ # Dev PC (Linux x86_64, Windows, Mac); no board native lib to load.
53
+ # Python-side Zero2WBoardSupport below still registers for the
54
+ # Python-dispatched peripherals; GPIO on dev has no meaning anyway.
55
+ return
56
+ here = os.path.dirname(os.path.abspath(__file__))
57
+ path = os.path.join(here, name)
58
+ if not os.path.exists(path):
59
+ # Driver wheel was built without the per-arch .so (dev install from
60
+ # source skipped the C++ build step). Python peripherals still work;
61
+ # Python GPIO on a Pi will fall through to libendpoint's "Unknown
62
+ # board" throw.
63
+ return
64
+ # RTLD_GLOBAL is overkill here (the .so has no symbols other callers need
65
+ # to see), but matches Core's load mode so the dynamic linker behavior is
66
+ # uniform. Harmless either way.
67
+ ctypes.CDLL(path, mode=ctypes.RTLD_GLOBAL)
68
+
69
+ _load_native_board_driver()
70
+
71
+
72
+ class Zero2W:
73
+ """Raspberry Pi Zero 2 W (BCM2710 SoC). Pin constants + bus / port / channel
74
+ identifiers. The chip-neutral verbs live on Core's I2cController etc.;
75
+ this class is just the hardware tables.
76
+ """
77
+
78
+ class Gpio:
79
+ """BCM GPIO pin constants. All pin numbers are BCM GPIO numbers
80
+ (as labelled in every Pi pinout diagram, e.g. https://pinout.xyz),
81
+ NOT physical header pin numbers.
82
+ """
83
+ Led = 29 # on-board ACT LED, active-low
84
+ Pin0 = 0
85
+ Pin1 = 1
86
+ Pin2 = 2
87
+ Pin3 = 3
88
+ Pin4 = 4
89
+ Pin5 = 5
90
+ Pin6 = 6
91
+ Pin7 = 7
92
+ Pin8 = 8
93
+ Pin9 = 9
94
+ Pin10 = 10
95
+ Pin11 = 11
96
+ Pin12 = 12
97
+ Pin13 = 13
98
+ Pin14 = 14
99
+ Pin15 = 15
100
+ Pin16 = 16
101
+ Pin17 = 17
102
+ Pin18 = 18
103
+ Pin19 = 19
104
+ Pin20 = 20
105
+ Pin21 = 21
106
+ Pin22 = 22
107
+ Pin23 = 23
108
+ Pin24 = 24
109
+ Pin25 = 25
110
+ Pin26 = 26
111
+ Pin27 = 27
112
+ GpioChip = 0 # pass to python-gpiod's Chip() / libgpiod
113
+
114
+ class I2c:
115
+ """Pi user I2C: SDA on GPIO 2 (pin 3), SCL on GPIO 3 (pin 5), ALT0.
116
+ Maps to /dev/i2c-1.
117
+ """
118
+ I2c1 = 1
119
+ DefaultFrequency = 400_000 # fast mode
120
+
121
+ class Spi:
122
+ """Pi user SPI: MOSI=GPIO10, MISO=GPIO9, SCLK=GPIO11, CE0=GPIO8.
123
+ All ALT0. Maps to /dev/spidev0.0.
124
+ """
125
+ Spi0 = 0
126
+ DefaultBufferSize = 4096
127
+
128
+ class Pwm:
129
+ """BCM2837 has one PWM block (pwmchip0) with two channels, each
130
+ routable to one of two GPIOs.
131
+ """
132
+ class Pin:
133
+ Pin12 = 12 # PWM0 ch0 at ALT0 (header pin 32)
134
+ Pin13 = 13 # PWM0 ch1 at ALT0 (header pin 33)
135
+ Pin18 = 18 # PWM0 ch0 at ALT5 (header pin 12)
136
+ Pin19 = 19 # PWM0 ch1 at ALT5 (header pin 35)
137
+
138
+ class SerialPort:
139
+ """Mini-UART on GPIO 14 TX / GPIO 15 RX, ALT5. Maps to /dev/ttyS0.
140
+ PL011 stays on Bluetooth; mini-UART owns the header pins.
141
+ """
142
+ Uart1 = "/dev/ttyS0"
143
+
144
+
145
+ class Zero2WBoardSupport(_UnknownBoardSupport):
146
+ """Zero2W implementation of IBoardSupport. Overrides only the methods
147
+ Pi actually implements via endpoint-pinmux + modprobe; the rest keep
148
+ UnknownBoardSupport's throw.
149
+ """
150
+
151
+ Name = "Zero2W"
152
+
153
+ def __init__(self):
154
+ # Shared per-pin pre-Initialize state so UnInitialize restores
155
+ # exactly what was there before.
156
+ self._saved = {}
157
+
158
+ # ---------- GPIO introspection ----------
159
+ def GpioChipLabel(self, port): return "gpiochip0"
160
+ def GpioChipId(self, pin): return 0
161
+ def GpioLineId(self, pin): return pin
162
+ def GpioName(self, pin): return f"GPIO{pin}"
163
+
164
+ # ---------- I2C ----------
165
+ def I2cInitialize(self, bus, frequency):
166
+ if bus != Zero2W.I2c.I2c1:
167
+ raise ValueError(f"Pi Zero 2 W exposes only I2c1 (/dev/i2c-1), got bus={bus}")
168
+ # Snapshot BEFORE modprobe: the kernel i2c-bcm2835 bind may mux
169
+ # SDA/SCL on its own; capture user's real pre-Init state first.
170
+ self._saved[2] = _Pinmux.Get(2) # SDA
171
+ self._saved[3] = _Pinmux.Get(3) # SCL
172
+ _Pinmux.Modprobe("i2c-bcm2835")
173
+ _Pinmux.Modprobe("i2c-dev")
174
+ _Pinmux.Set(2, 4) # ALT0 = SDA1
175
+ _Pinmux.Set(3, 4) # ALT0 = SCL1
176
+
177
+ def I2cUnInitialize(self, bus):
178
+ sda = self._saved.pop(2, None)
179
+ scl = self._saved.pop(3, None)
180
+ if sda is not None: _Pinmux.Set(2, sda)
181
+ if scl is not None: _Pinmux.Set(3, scl)
182
+
183
+ def I2cGetFrequency(self, bus):
184
+ return Zero2W.I2c.DefaultFrequency
185
+
186
+ # ---------- SPI ----------
187
+ def SpiInitialize(self, bus, buffer_size):
188
+ if bus != Zero2W.Spi.Spi0:
189
+ raise ValueError(f"Pi Zero 2 W exposes only Spi0 (/dev/spidev0.0), got bus={bus}")
190
+ for p in (10, 9, 11, 8):
191
+ self._saved[p] = _Pinmux.Get(p)
192
+ _Pinmux.Modprobe("spi-bcm2835")
193
+ _Pinmux.Modprobe("spidev")
194
+ for p in (10, 9, 11, 8):
195
+ _Pinmux.Set(p, 4) # ALT0
196
+
197
+ def SpiUnInitialize(self, bus):
198
+ for p in (10, 9, 11, 8):
199
+ v = self._saved.pop(p, None)
200
+ if v is not None: _Pinmux.Set(p, v)
201
+
202
+ # ---------- PWM ----------
203
+ _PWM_TABLE = {
204
+ 12: (0, 0, 4), # chip 0 ch 0 at ALT0
205
+ 13: (0, 1, 4), # chip 0 ch 1 at ALT0
206
+ 18: (0, 0, 2), # chip 0 ch 0 at ALT5 (alt pin)
207
+ 19: (0, 1, 2), # chip 0 ch 1 at ALT5 (alt pin)
208
+ }
209
+
210
+ def _pwm_lookup(self, pin):
211
+ if pin not in self._PWM_TABLE:
212
+ raise ValueError(f"Pi Zero 2 W PWM pins are 12, 13, 18, 19 — got {pin}")
213
+ return self._PWM_TABLE[pin]
214
+
215
+ def PwmInitialize(self, pin):
216
+ _, _, alt = self._pwm_lookup(pin)
217
+ self._saved[pin] = _Pinmux.Get(pin)
218
+ _Pinmux.Modprobe("pwm-bcm2835")
219
+ _Pinmux.Set(pin, alt)
220
+
221
+ def PwmUnInitialize(self, pin):
222
+ self._pwm_lookup(pin) # validate
223
+ v = self._saved.pop(pin, None)
224
+ if v is not None: _Pinmux.Set(pin, v)
225
+
226
+ def PwmGetChipId(self, pin): return self._pwm_lookup(pin)[0]
227
+ def PwmGetChannelId(self, pin): return self._pwm_lookup(pin)[1]
228
+
229
+ # ---------- SerialPort ----------
230
+ def SerialPortInitialize(self, port_name, enable_hw_flow_control):
231
+ if port_name != Zero2W.SerialPort.Uart1:
232
+ raise ValueError(f"Pi Zero 2 W exposes only Uart1 (/dev/ttyS0), got {port_name!r}")
233
+ # GPIO 14 TXD1 / 15 RXD1, ALT5 (function code 2)
234
+ self._saved[14] = _Pinmux.Get(14)
235
+ self._saved[15] = _Pinmux.Get(15)
236
+ _Pinmux.Set(14, 2)
237
+ _Pinmux.Set(15, 2)
238
+
239
+ def SerialPortUnInitialize(self, port_name):
240
+ tx = self._saved.pop(14, None)
241
+ rx = self._saved.pop(15, None)
242
+ if tx is not None: _Pinmux.Set(14, tx)
243
+ if rx is not None: _Pinmux.Set(15, rx)
244
+
245
+
246
+ # Register at import time, but only if Core's ChipDetect doesn't already
247
+ # identify a specific Endpoint chip. On an Endpoint board, the matching
248
+ # Pins package registers its own BoardSupport first; we don't fight it.
249
+ if _ChipCurrent == _Chip.Unknown:
250
+ _BoardSupport.Register(Zero2WBoardSupport())
251
+
252
+
253
+ __all__ = ["Zero2W", "Zero2WBoardSupport"]
@@ -0,0 +1,79 @@
1
+ """Fork+exec wrapper around /usr/sbin/endpoint-pinmux, the C helper that
2
+ writes SoC pinmux registers via /dev/mem. One binary per chip ships in
3
+ the Buildroot image; this driver uses the bcm2837 build on Pi Zero 2 W.
4
+ Keeps chip-specific register knowledge in one place (the C binary) so
5
+ .NET, Python, and C/C++ don't each re-implement it. Same shape as
6
+ GHIElectronics.Endpoint.Core._board_support.Pinmux.
7
+
8
+ `function` is a chip-specific packed uint32 - see
9
+ Endpoint-Firmware/pinmux/src/pinmux.h for each chip's layout. For
10
+ BCM2837 (Pi): bits 0-2 = GPFSEL function (0=input, 1=output,
11
+ 2..7 = alt5/alt4/alt0/alt1/alt2/alt3).
12
+
13
+ Peripheral verb classes (Zero2W.I2c / Spi / Pwm) use Get before their
14
+ first Set to snapshot the user's pre-Initialize state, then Set again
15
+ in UnInitialize to put it back. The in-process state lives in the
16
+ peripheral class; nothing persists across processes.
17
+ """
18
+
19
+ import subprocess
20
+
21
+ _PINMUX_PATH = "/usr/sbin/endpoint-pinmux"
22
+ _MODPROBE_PATH = "/sbin/modprobe"
23
+
24
+
25
+ class Pinmux:
26
+ """Internal fork+exec wrapper. Not part of the public API."""
27
+
28
+ @staticmethod
29
+ def Set(pin, function):
30
+ """Set the pin's function. Throws if the binary exits non-zero."""
31
+ Pinmux._run(_PINMUX_PATH, "set", str(int(pin)), f"0x{int(function):X}")
32
+
33
+ @staticmethod
34
+ def Get(pin):
35
+ """Read the pin's current function (packed uint32, chip-specific layout)."""
36
+ out = Pinmux._run_capture(_PINMUX_PATH, "get", str(int(pin)))
37
+ # Output: "pin=<n> function=0x<hex> level=<0|1>\n"
38
+ for token in out.split():
39
+ if token.startswith("function="):
40
+ return int(token[len("function="):], 0) # auto-detects 0x prefix
41
+ raise RuntimeError(
42
+ f"endpoint-pinmux get {pin}: unexpected output '{out.rstrip()}'"
43
+ )
44
+
45
+ @staticmethod
46
+ def Modprobe(module):
47
+ """Load a kernel module via /sbin/modprobe (idempotent)."""
48
+ Pinmux._run(_MODPROBE_PATH, module)
49
+
50
+ @staticmethod
51
+ def _run(path, *args):
52
+ try:
53
+ subprocess.run(
54
+ [path, *args],
55
+ check=True,
56
+ capture_output=True,
57
+ text=True,
58
+ )
59
+ except subprocess.CalledProcessError as e:
60
+ raise RuntimeError(
61
+ f"{path} {' '.join(args)} failed "
62
+ f"(exit {e.returncode}): {e.stderr.rstrip()}"
63
+ ) from None
64
+
65
+ @staticmethod
66
+ def _run_capture(path, *args):
67
+ try:
68
+ result = subprocess.run(
69
+ [path, *args],
70
+ check=True,
71
+ capture_output=True,
72
+ text=True,
73
+ )
74
+ return result.stdout
75
+ except subprocess.CalledProcessError as e:
76
+ raise RuntimeError(
77
+ f"{path} {' '.join(args)} failed "
78
+ f"(exit {e.returncode}): {e.stderr.rstrip()}"
79
+ ) from None
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.4
2
+ Name: GHIElectronics.Endpoint.Drivers.RaspberryPi
3
+ Version: 0.5.4
4
+ Summary: Raspberry Pi board support for Endpoint. One package covers every Pi model this library knows (Zero 2 W today; more added in later versions). Mirrors the .NET driver API.
5
+ Author-email: "GHI Electronics, LLC" <support@ghielectronics.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://www.ghielectronics.com/
8
+ Project-URL: Repository, https://github.com/ghi-electronics/endpoint-drivers
9
+ Project-URL: Issues, https://github.com/ghi-electronics/endpoint-drivers/issues
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Operating System :: POSIX :: Linux
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ Requires-Dist: GHIElectronics.Endpoint.Core<0.6,>=0.5.4
15
+
16
+ # GHIElectronics.Endpoint.Drivers.RaspberryPi
17
+
18
+ Raspberry Pi board support for Endpoint (Python). Mirrors the .NET driver API.
19
+
20
+ One package covers every Pi model this library knows (Zero 2 W today; more
21
+ added in later versions). Thin layer over the Linux kernel: each
22
+ peripheral's `Initialize(bus_or_channel)` muxes the pins by shelling out
23
+ to `/usr/sbin/endpoint-pinmux` (the C helper shipped in the Pi firmware
24
+ image) and loads the matching kernel module. `UnInitialize` restores the
25
+ pins to their pre-Initialize state.
26
+
27
+ ```python
28
+ from GHIElectronics.Endpoint.Drivers.RaspberryPi import Zero2W
29
+
30
+ Zero2W.I2c.Initialize(Zero2W.I2c.I2c1)
31
+ # ... open /dev/i2c-1 with smbus2 / python-periphery / anything ...
32
+ Zero2W.I2c.UnInitialize(Zero2W.I2c.I2c1)
33
+ ```
34
+
35
+ Users bring their own GPIO / I2C / SPI library (python-gpiod, smbus2,
36
+ spidev, ...). This package only handles pin muxing and kernel module
37
+ loading.
38
+
39
+ Part of the [GHI Electronics Endpoint drivers](https://github.com/ghi-electronics/endpoint-drivers).
40
+ See the repository README for the full driver list.
@@ -0,0 +1,8 @@
1
+ GHIElectronics/Endpoint/Drivers/RaspberryPi/__init__.py,sha256=Dney5lkSpSKKgZV1WWl94s-ayPGc5qtu0o8ywZoJOKw,9557
2
+ GHIElectronics/Endpoint/Drivers/RaspberryPi/_pinmux.py,sha256=V4kZrC9vpHjJqZJTzaLbzYTF8yezbtklGMxux2XNynE,2889
3
+ GHIElectronics/Endpoint/Drivers/RaspberryPi/libendpoint-zero2w-arm.so,sha256=pCyqy0RZUgCPqBLLOW-JLP8Tcsdea0LD3BBH9Gfzm30,5623460
4
+ GHIElectronics/Endpoint/Drivers/RaspberryPi/libendpoint-zero2w-arm64.so,sha256=9JLJdWDWDpjjeU4XADOH4_9aNibPdhspzF_NhdTZYKo,5533664
5
+ ghielectronics_endpoint_drivers_raspberrypi-0.5.4.dist-info/METADATA,sha256=XtyANMpmzjynQxkqQL9GbUNiFqH4VtoEu5jjv2xgY3k,1875
6
+ ghielectronics_endpoint_drivers_raspberrypi-0.5.4.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ ghielectronics_endpoint_drivers_raspberrypi-0.5.4.dist-info/top_level.txt,sha256=NpOZNgd0iquwrRPrTOhUDxc2V9TtNFLv5Z_Dx3YZtIU,15
8
+ ghielectronics_endpoint_drivers_raspberrypi-0.5.4.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+