phaxi 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.
- phaxi/__init__.py +174 -0
- phaxi/py.typed +0 -0
- phaxi-0.1.0.dist-info/METADATA +107 -0
- phaxi-0.1.0.dist-info/RECORD +7 -0
- phaxi-0.1.0.dist-info/WHEEL +5 -0
- phaxi-0.1.0.dist-info/licenses/LICENSE.txt +21 -0
- phaxi-0.1.0.dist-info/top_level.txt +1 -0
phaxi/__init__.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""Talk to an Arduino from a Raspberry Pi over serial, one JSON message per line.
|
|
2
|
+
|
|
3
|
+
Each message is one JSON object on its own line:
|
|
4
|
+
|
|
5
|
+
{"topic": "led", "data": {"on": true}} event, no reply
|
|
6
|
+
{"id": 7, "topic": "ping"} request
|
|
7
|
+
{"reply_to": 7, "topic": "ping", "data": {...}} reply
|
|
8
|
+
{"reply_to": 7, "topic": "ping", "error": "..."} failed reply
|
|
9
|
+
|
|
10
|
+
Logs go to the "phaxi" logger. Every message sent and received is logged at
|
|
11
|
+
DEBUG; problems are logged at WARNING or ERROR.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import itertools
|
|
15
|
+
import json
|
|
16
|
+
import logging
|
|
17
|
+
import queue
|
|
18
|
+
import threading
|
|
19
|
+
|
|
20
|
+
import serial
|
|
21
|
+
|
|
22
|
+
__version__ = "0.1.0"
|
|
23
|
+
__all__ = ["Phax", "PhaxError", "PhaxTimeout", "open_serial"]
|
|
24
|
+
|
|
25
|
+
log = logging.getLogger(__name__)
|
|
26
|
+
# A library must not print on its own: the application decides where logs go.
|
|
27
|
+
log.addHandler(logging.NullHandler())
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class PhaxError(Exception):
|
|
31
|
+
"""The peer replied with an error."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class PhaxTimeout(PhaxError):
|
|
35
|
+
"""The peer did not reply in time."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def open_serial(device, baud=9600, timeout=1):
|
|
39
|
+
"""Open a serial port. The read timeout is what lets ``stop()`` return."""
|
|
40
|
+
log.info("Opening %s at %d baud", device, baud)
|
|
41
|
+
return serial.Serial(device, baud, timeout=timeout)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Phax:
|
|
45
|
+
"""The Pi's side of the link to the Arduino.
|
|
46
|
+
|
|
47
|
+
``port`` needs ``readline()`` (returning b"" on timeout) and
|
|
48
|
+
``write(bytes)``, as a pyserial port has. Handlers run on the reader
|
|
49
|
+
thread, so do not call ``request()`` from inside one.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
def __init__(self, port):
|
|
53
|
+
self._port = port
|
|
54
|
+
self._handlers = {}
|
|
55
|
+
self._pending = {}
|
|
56
|
+
self._ids = itertools.count(1)
|
|
57
|
+
self._write_lock = threading.Lock()
|
|
58
|
+
self._stop = threading.Event()
|
|
59
|
+
self._thread = None
|
|
60
|
+
|
|
61
|
+
def on(self, topic, handler=None):
|
|
62
|
+
"""Register ``handler(data)`` for ``topic``. Also works as a decorator.
|
|
63
|
+
|
|
64
|
+
For a request, the return value is sent back as the reply, and an
|
|
65
|
+
exception is sent back as an error.
|
|
66
|
+
"""
|
|
67
|
+
if handler is None:
|
|
68
|
+
return lambda fn: self.on(topic, fn)
|
|
69
|
+
self._handlers[topic] = handler
|
|
70
|
+
return handler
|
|
71
|
+
|
|
72
|
+
def send(self, topic, data=None):
|
|
73
|
+
"""Send a message without waiting for a reply."""
|
|
74
|
+
self._write({"topic": topic, "data": data})
|
|
75
|
+
|
|
76
|
+
def request(self, topic, data=None, timeout=2.0):
|
|
77
|
+
"""Send a request and return the reply's data. Needs ``start()``."""
|
|
78
|
+
msg_id = next(self._ids)
|
|
79
|
+
box = self._pending[msg_id] = queue.Queue(maxsize=1)
|
|
80
|
+
try:
|
|
81
|
+
self._write({"id": msg_id, "topic": topic, "data": data})
|
|
82
|
+
reply = box.get(timeout=timeout)
|
|
83
|
+
except queue.Empty:
|
|
84
|
+
log.warning("Request %d %r got no reply within %ss", msg_id, topic, timeout)
|
|
85
|
+
raise PhaxTimeout(f"no reply to {topic!r} within {timeout}s") from None
|
|
86
|
+
finally:
|
|
87
|
+
self._pending.pop(msg_id, None)
|
|
88
|
+
if "error" in reply:
|
|
89
|
+
log.warning("Request %d %r failed: %s", msg_id, topic, reply["error"])
|
|
90
|
+
raise PhaxError(reply["error"])
|
|
91
|
+
return reply.get("data")
|
|
92
|
+
|
|
93
|
+
def handle(self, line):
|
|
94
|
+
"""Process one incoming line. Malformed lines are logged and skipped."""
|
|
95
|
+
line = line.strip()
|
|
96
|
+
if not line:
|
|
97
|
+
return
|
|
98
|
+
log.debug("<- %s", line)
|
|
99
|
+
try:
|
|
100
|
+
msg = json.loads(line)
|
|
101
|
+
except ValueError as e:
|
|
102
|
+
log.warning("Ignoring line that is not JSON (%s): %r", e, line)
|
|
103
|
+
return
|
|
104
|
+
if not isinstance(msg, dict):
|
|
105
|
+
log.warning("Ignoring line that is not a JSON object: %r", line)
|
|
106
|
+
return
|
|
107
|
+
|
|
108
|
+
if "reply_to" in msg:
|
|
109
|
+
self._deliver_reply(msg)
|
|
110
|
+
return
|
|
111
|
+
|
|
112
|
+
topic, msg_id = msg.get("topic"), msg.get("id")
|
|
113
|
+
reply = {"reply_to": msg_id, "topic": topic}
|
|
114
|
+
handler = self._handlers.get(topic) if isinstance(topic, str) else None
|
|
115
|
+
if handler is None:
|
|
116
|
+
log.warning("No handler for topic %r: %r", topic, line)
|
|
117
|
+
reply["error"] = f"unknown topic {topic!r}"
|
|
118
|
+
else:
|
|
119
|
+
try:
|
|
120
|
+
reply["data"] = handler(msg.get("data"))
|
|
121
|
+
except Exception as e: # noqa: BLE001 - report any failure to the peer
|
|
122
|
+
log.exception("Handler for %r failed", topic)
|
|
123
|
+
reply["error"] = str(e)
|
|
124
|
+
if msg_id is not None:
|
|
125
|
+
self._write(reply)
|
|
126
|
+
|
|
127
|
+
def poll(self):
|
|
128
|
+
"""Read and handle one line. Returns False if nothing arrived."""
|
|
129
|
+
line = self._port.readline()
|
|
130
|
+
if line:
|
|
131
|
+
self.handle(line.decode("utf-8", errors="replace"))
|
|
132
|
+
return bool(line)
|
|
133
|
+
|
|
134
|
+
def start(self):
|
|
135
|
+
"""Read and handle incoming lines on a background thread."""
|
|
136
|
+
if self._thread is None:
|
|
137
|
+
self._stop.clear()
|
|
138
|
+
self._thread = threading.Thread(
|
|
139
|
+
target=self._run, name="phaxi-reader", daemon=True
|
|
140
|
+
)
|
|
141
|
+
self._thread.start()
|
|
142
|
+
log.debug("Reader started")
|
|
143
|
+
|
|
144
|
+
def stop(self):
|
|
145
|
+
"""Stop the reader. Returns within about one port timeout."""
|
|
146
|
+
self._stop.set()
|
|
147
|
+
if self._thread is not None:
|
|
148
|
+
self._thread.join(timeout=5)
|
|
149
|
+
self._thread = None
|
|
150
|
+
log.debug("Reader stopped")
|
|
151
|
+
|
|
152
|
+
def _run(self):
|
|
153
|
+
while not self._stop.is_set():
|
|
154
|
+
try:
|
|
155
|
+
self.poll()
|
|
156
|
+
except Exception: # noqa: BLE001 - e.g. the board was unplugged
|
|
157
|
+
log.exception("Reading from the port failed, stopping the reader")
|
|
158
|
+
return
|
|
159
|
+
|
|
160
|
+
def _deliver_reply(self, msg):
|
|
161
|
+
reply_to = msg["reply_to"]
|
|
162
|
+
box = self._pending.get(reply_to) if type(reply_to) is int else None
|
|
163
|
+
if box is None:
|
|
164
|
+
log.warning("Ignoring reply to unknown request %r (late?)", reply_to)
|
|
165
|
+
elif not box.empty():
|
|
166
|
+
log.warning("Ignoring duplicate reply to request %r", reply_to)
|
|
167
|
+
else:
|
|
168
|
+
box.put(msg)
|
|
169
|
+
|
|
170
|
+
def _write(self, msg):
|
|
171
|
+
line = json.dumps(msg, separators=(",", ":"))
|
|
172
|
+
log.debug("-> %s", line)
|
|
173
|
+
with self._write_lock:
|
|
174
|
+
self._port.write((line + "\n").encode())
|
phaxi/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: phaxi
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Talk to an Arduino from a Raspberry Pi over serial, one JSON message per line.
|
|
5
|
+
Author-email: Clivern <hello@clivern.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Source, https://github.com/clivern/phax
|
|
8
|
+
Project-URL: Tracker, https://github.com/clivern/phax/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/clivern/phax/blob/main/CHANGELOG.rst
|
|
10
|
+
Keywords: arduino,serial,raspberry-pi,json,messaging
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
21
|
+
Classifier: Topic :: Home Automation
|
|
22
|
+
Classifier: Topic :: System :: Hardware
|
|
23
|
+
Requires-Python: >=3.10
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
License-File: LICENSE.txt
|
|
26
|
+
Requires-Dist: pyserial>=3.5
|
|
27
|
+
Provides-Extra: test
|
|
28
|
+
Requires-Dist: pytest>=9.2.0; extra == "test"
|
|
29
|
+
Dynamic: license-file
|
|
30
|
+
|
|
31
|
+
# Phaxi
|
|
32
|
+
|
|
33
|
+
A Python library for a Raspberry Pi to talk to an Arduino over USB serial, using one JSON message per line.
|
|
34
|
+
|
|
35
|
+
## Install
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install phaxi
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Usage
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
import time
|
|
45
|
+
|
|
46
|
+
from phaxi import Phax, PhaxTimeout, open_serial
|
|
47
|
+
|
|
48
|
+
port = open_serial("/dev/ttyACM0", 9600)
|
|
49
|
+
time.sleep(2) # the Arduino resets when the port opens
|
|
50
|
+
pi = Phax(port)
|
|
51
|
+
|
|
52
|
+
@pi.on("uptime") # message from the Arduino
|
|
53
|
+
def on_uptime(data):
|
|
54
|
+
print("Arduino uptime:", data["ms"])
|
|
55
|
+
|
|
56
|
+
pi.start() # listen in the background
|
|
57
|
+
|
|
58
|
+
pi.send("led", {"on": True}) # send, no reply
|
|
59
|
+
try:
|
|
60
|
+
print(pi.request("ping", timeout=2)) # send and wait for the reply
|
|
61
|
+
except PhaxTimeout:
|
|
62
|
+
print("no reply")
|
|
63
|
+
|
|
64
|
+
pi.stop()
|
|
65
|
+
port.close()
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Do not call `request()` inside a handler.
|
|
69
|
+
|
|
70
|
+
To see every message sent and received:
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
import logging
|
|
74
|
+
logging.basicConfig(level=logging.DEBUG)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Arduino
|
|
78
|
+
|
|
79
|
+
Upload `examples/arduino/phaxi_led/phaxi_led.ino`. It needs the [ArduinoJson](https://arduinojson.org/) v7 library. It turns the LED on pin 13 on or off on `led`, answers `ping`, and sends `uptime` every 5 seconds.
|
|
80
|
+
|
|
81
|
+
To send a message from the Arduino:
|
|
82
|
+
|
|
83
|
+
```cpp
|
|
84
|
+
Serial.println("{\"topic\":\"temp\",\"data\":{\"c\":21.5}}");
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## Message format
|
|
88
|
+
|
|
89
|
+
```json
|
|
90
|
+
{"topic": "led", "data": {"on": true}}
|
|
91
|
+
{"id": 7, "topic": "ping"}
|
|
92
|
+
{"reply_to": 7, "topic": "ping", "data": {"uptime": 12345}}
|
|
93
|
+
{"reply_to": 7, "topic": "ping", "error": "unknown topic"}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
A message with an `id` expects a reply with the same number in `reply_to`.
|
|
97
|
+
|
|
98
|
+
## Development
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
make config # install tools
|
|
102
|
+
make ci # lint and test
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## License
|
|
106
|
+
|
|
107
|
+
MIT
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
phaxi/__init__.py,sha256=n97YdPBoUVB1nOgyRUMAta77-0p6FHbDiuJxU6RXwRs,6137
|
|
2
|
+
phaxi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
phaxi-0.1.0.dist-info/licenses/LICENSE.txt,sha256=YelzfzuRQMWsbsuV0uyf0BuiX62WZD2DAylgldNBI5A,1074
|
|
4
|
+
phaxi-0.1.0.dist-info/METADATA,sha256=p2L8w0ga8nNz0U5u2jfm98UzgSV8-tRAQNuoEkMKZBk,2871
|
|
5
|
+
phaxi-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
6
|
+
phaxi-0.1.0.dist-info/top_level.txt,sha256=5MgIgBDP8Yh4kzlr-HquTw-pCIAyqAv_E6teXylrTg4,6
|
|
7
|
+
phaxi-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Clivern
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
phaxi
|