phaxi 0.1.0__tar.gz
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-0.1.0/LICENSE.txt +21 -0
- phaxi-0.1.0/PKG-INFO +107 -0
- phaxi-0.1.0/README.md +77 -0
- phaxi-0.1.0/pyproject.toml +50 -0
- phaxi-0.1.0/setup.cfg +4 -0
- phaxi-0.1.0/src/phaxi/__init__.py +174 -0
- phaxi-0.1.0/src/phaxi/py.typed +0 -0
- phaxi-0.1.0/src/phaxi.egg-info/PKG-INFO +107 -0
- phaxi-0.1.0/src/phaxi.egg-info/SOURCES.txt +11 -0
- phaxi-0.1.0/src/phaxi.egg-info/dependency_links.txt +1 -0
- phaxi-0.1.0/src/phaxi.egg-info/requires.txt +4 -0
- phaxi-0.1.0/src/phaxi.egg-info/top_level.txt +1 -0
- phaxi-0.1.0/tests/test_phaxi.py +271 -0
phaxi-0.1.0/LICENSE.txt
ADDED
|
@@ -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.
|
phaxi-0.1.0/PKG-INFO
ADDED
|
@@ -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
|
phaxi-0.1.0/README.md
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# Phaxi
|
|
2
|
+
|
|
3
|
+
A Python library for a Raspberry Pi to talk to an Arduino over USB serial, using one JSON message per line.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install phaxi
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
import time
|
|
15
|
+
|
|
16
|
+
from phaxi import Phax, PhaxTimeout, open_serial
|
|
17
|
+
|
|
18
|
+
port = open_serial("/dev/ttyACM0", 9600)
|
|
19
|
+
time.sleep(2) # the Arduino resets when the port opens
|
|
20
|
+
pi = Phax(port)
|
|
21
|
+
|
|
22
|
+
@pi.on("uptime") # message from the Arduino
|
|
23
|
+
def on_uptime(data):
|
|
24
|
+
print("Arduino uptime:", data["ms"])
|
|
25
|
+
|
|
26
|
+
pi.start() # listen in the background
|
|
27
|
+
|
|
28
|
+
pi.send("led", {"on": True}) # send, no reply
|
|
29
|
+
try:
|
|
30
|
+
print(pi.request("ping", timeout=2)) # send and wait for the reply
|
|
31
|
+
except PhaxTimeout:
|
|
32
|
+
print("no reply")
|
|
33
|
+
|
|
34
|
+
pi.stop()
|
|
35
|
+
port.close()
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Do not call `request()` inside a handler.
|
|
39
|
+
|
|
40
|
+
To see every message sent and received:
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
import logging
|
|
44
|
+
logging.basicConfig(level=logging.DEBUG)
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Arduino
|
|
48
|
+
|
|
49
|
+
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.
|
|
50
|
+
|
|
51
|
+
To send a message from the Arduino:
|
|
52
|
+
|
|
53
|
+
```cpp
|
|
54
|
+
Serial.println("{\"topic\":\"temp\",\"data\":{\"c\":21.5}}");
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Message format
|
|
58
|
+
|
|
59
|
+
```json
|
|
60
|
+
{"topic": "led", "data": {"on": true}}
|
|
61
|
+
{"id": 7, "topic": "ping"}
|
|
62
|
+
{"reply_to": 7, "topic": "ping", "data": {"uptime": 12345}}
|
|
63
|
+
{"reply_to": 7, "topic": "ping", "error": "unknown topic"}
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
A message with an `id` expects a reply with the same number in `reply_to`.
|
|
67
|
+
|
|
68
|
+
## Development
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
make config # install tools
|
|
72
|
+
make ci # lint and test
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## License
|
|
76
|
+
|
|
77
|
+
MIT
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=84.2.1", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "phaxi"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Talk to an Arduino from a Raspberry Pi over serial, one JSON message per line."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE.txt"]
|
|
12
|
+
authors = [{ name = "Clivern", email = "hello@clivern.com" }]
|
|
13
|
+
keywords = ["arduino", "serial", "raspberry-pi", "json", "messaging"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 3 - Alpha",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"Operating System :: OS Independent",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
20
|
+
"Programming Language :: Python :: 3.10",
|
|
21
|
+
"Programming Language :: Python :: 3.11",
|
|
22
|
+
"Programming Language :: Python :: 3.12",
|
|
23
|
+
"Programming Language :: Python :: 3.13",
|
|
24
|
+
"Programming Language :: Python :: 3.14",
|
|
25
|
+
"Topic :: Home Automation",
|
|
26
|
+
"Topic :: System :: Hardware",
|
|
27
|
+
]
|
|
28
|
+
requires-python = ">=3.10"
|
|
29
|
+
dependencies = ["pyserial>=3.5"]
|
|
30
|
+
|
|
31
|
+
[project.optional-dependencies]
|
|
32
|
+
test = ["pytest>=9.2.0"]
|
|
33
|
+
|
|
34
|
+
[project.urls]
|
|
35
|
+
Source = "https://github.com/clivern/phax"
|
|
36
|
+
Tracker = "https://github.com/clivern/phax/issues"
|
|
37
|
+
Changelog = "https://github.com/clivern/phax/blob/main/CHANGELOG.rst"
|
|
38
|
+
|
|
39
|
+
[tool.setuptools.packages.find]
|
|
40
|
+
where = ["src"]
|
|
41
|
+
|
|
42
|
+
[tool.setuptools.dynamic]
|
|
43
|
+
version = { attr = "phaxi.__version__" }
|
|
44
|
+
|
|
45
|
+
[tool.setuptools.package-data]
|
|
46
|
+
phaxi = ["py.typed"]
|
|
47
|
+
|
|
48
|
+
[tool.pytest.ini_options]
|
|
49
|
+
addopts = "--verbose"
|
|
50
|
+
testpaths = ["tests"]
|
phaxi-0.1.0/setup.cfg
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())
|
|
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,11 @@
|
|
|
1
|
+
LICENSE.txt
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/phaxi/__init__.py
|
|
5
|
+
src/phaxi/py.typed
|
|
6
|
+
src/phaxi.egg-info/PKG-INFO
|
|
7
|
+
src/phaxi.egg-info/SOURCES.txt
|
|
8
|
+
src/phaxi.egg-info/dependency_links.txt
|
|
9
|
+
src/phaxi.egg-info/requires.txt
|
|
10
|
+
src/phaxi.egg-info/top_level.txt
|
|
11
|
+
tests/test_phaxi.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
phaxi
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
import queue
|
|
4
|
+
import time
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
from phaxi import Phax, PhaxError, PhaxTimeout
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Endpoint:
|
|
12
|
+
"""One end of a serial line. Lines written here are read by its peer."""
|
|
13
|
+
|
|
14
|
+
def __init__(self):
|
|
15
|
+
self.peer = None
|
|
16
|
+
self.inbox = queue.Queue()
|
|
17
|
+
self.written = []
|
|
18
|
+
|
|
19
|
+
def write(self, data):
|
|
20
|
+
self.written.append(data)
|
|
21
|
+
if self.peer is not None:
|
|
22
|
+
self.peer.inbox.put(data)
|
|
23
|
+
return len(data)
|
|
24
|
+
|
|
25
|
+
def readline(self):
|
|
26
|
+
try:
|
|
27
|
+
return self.inbox.get(timeout=0.01)
|
|
28
|
+
except queue.Empty:
|
|
29
|
+
time.sleep(0.001)
|
|
30
|
+
return b""
|
|
31
|
+
|
|
32
|
+
def frames(self):
|
|
33
|
+
return [json.loads(line) for line in self.written]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def link():
|
|
37
|
+
"""Two connected endpoints: what one writes, the other reads."""
|
|
38
|
+
a, b = Endpoint(), Endpoint()
|
|
39
|
+
a.peer, b.peer = b, a
|
|
40
|
+
return a, b
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def test_send_writes_one_json_line():
|
|
44
|
+
end = Endpoint()
|
|
45
|
+
Phax(end).send("led", {"on": True})
|
|
46
|
+
|
|
47
|
+
assert end.written == [b'{"topic":"led","data":{"on":true}}\n']
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def test_incoming_message_calls_handler():
|
|
51
|
+
end = Endpoint()
|
|
52
|
+
phax = Phax(end)
|
|
53
|
+
received = []
|
|
54
|
+
phax.on("temp", received.append)
|
|
55
|
+
|
|
56
|
+
phax.handle('{"topic": "temp", "data": {"c": 21.5}}\n')
|
|
57
|
+
|
|
58
|
+
assert received == [{"c": 21.5}]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def test_handler_decorator():
|
|
62
|
+
phax = Phax(Endpoint())
|
|
63
|
+
received = []
|
|
64
|
+
|
|
65
|
+
@phax.on("led")
|
|
66
|
+
def led(data):
|
|
67
|
+
received.append(data)
|
|
68
|
+
|
|
69
|
+
phax.handle('{"topic": "led", "data": {"on": false}}')
|
|
70
|
+
|
|
71
|
+
assert received == [{"on": False}]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def test_return_value_is_sent_as_reply():
|
|
75
|
+
end = Endpoint()
|
|
76
|
+
phax = Phax(end)
|
|
77
|
+
phax.on("ping", lambda data: {"pong": True})
|
|
78
|
+
|
|
79
|
+
phax.handle('{"id": 4, "topic": "ping"}')
|
|
80
|
+
|
|
81
|
+
assert end.frames() == [{"reply_to": 4, "topic": "ping", "data": {"pong": True}}]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def test_handler_exception_is_sent_as_error_reply():
|
|
85
|
+
end = Endpoint()
|
|
86
|
+
phax = Phax(end)
|
|
87
|
+
|
|
88
|
+
def broken(data):
|
|
89
|
+
raise ValueError("boom")
|
|
90
|
+
|
|
91
|
+
phax.on("ping", broken)
|
|
92
|
+
phax.handle('{"id": 4, "topic": "ping"}')
|
|
93
|
+
|
|
94
|
+
assert end.frames() == [{"reply_to": 4, "topic": "ping", "error": "boom"}]
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def test_unknown_topic_request_gets_error_reply():
|
|
98
|
+
end = Endpoint()
|
|
99
|
+
Phax(end).handle('{"id": 9, "topic": "nope"}')
|
|
100
|
+
|
|
101
|
+
assert end.frames()[0]["reply_to"] == 9
|
|
102
|
+
assert "unknown topic" in end.frames()[0]["error"]
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def test_send_without_id_gets_no_reply():
|
|
106
|
+
end = Endpoint()
|
|
107
|
+
phax = Phax(end)
|
|
108
|
+
phax.on("ping", lambda data: {"pong": True})
|
|
109
|
+
|
|
110
|
+
phax.handle('{"topic": "ping"}')
|
|
111
|
+
|
|
112
|
+
assert end.written == []
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@pytest.mark.parametrize(
|
|
116
|
+
"line",
|
|
117
|
+
[
|
|
118
|
+
"",
|
|
119
|
+
"garbage",
|
|
120
|
+
"[1, 2]",
|
|
121
|
+
'{"data": 1}',
|
|
122
|
+
'"just a string"',
|
|
123
|
+
'{"topic": 5}',
|
|
124
|
+
'{"reply_to": [1], "topic": "x"}',
|
|
125
|
+
'{"reply_to": "7", "topic": "x"}',
|
|
126
|
+
],
|
|
127
|
+
)
|
|
128
|
+
def test_bad_lines_are_ignored(line):
|
|
129
|
+
end = Endpoint()
|
|
130
|
+
Phax(end).handle(line)
|
|
131
|
+
|
|
132
|
+
assert end.written == []
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def test_two_way_request_and_reply():
|
|
136
|
+
"""Each side sends a request and the other side answers it."""
|
|
137
|
+
a, b = link()
|
|
138
|
+
arduino, pi = Phax(a), Phax(b)
|
|
139
|
+
led_state = {}
|
|
140
|
+
|
|
141
|
+
def set_led(data):
|
|
142
|
+
led_state.update(data)
|
|
143
|
+
return {"ok": True}
|
|
144
|
+
|
|
145
|
+
arduino.on("led", set_led)
|
|
146
|
+
pi.on("ping", lambda data: {"pong": True})
|
|
147
|
+
|
|
148
|
+
arduino.start()
|
|
149
|
+
pi.start()
|
|
150
|
+
try:
|
|
151
|
+
assert pi.request("led", {"on": True}) == {"ok": True}
|
|
152
|
+
assert led_state == {"on": True}
|
|
153
|
+
assert arduino.request("ping") == {"pong": True}
|
|
154
|
+
finally:
|
|
155
|
+
pi.stop()
|
|
156
|
+
arduino.stop()
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def test_send_from_arduino_reaches_pi_handler():
|
|
160
|
+
a, b = link()
|
|
161
|
+
arduino, pi = Phax(a), Phax(b)
|
|
162
|
+
temps = queue.Queue()
|
|
163
|
+
pi.on("temp", temps.put)
|
|
164
|
+
|
|
165
|
+
pi.start()
|
|
166
|
+
try:
|
|
167
|
+
arduino.send("temp", {"c": 21.5})
|
|
168
|
+
assert temps.get(timeout=1) == {"c": 21.5}
|
|
169
|
+
finally:
|
|
170
|
+
pi.stop()
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def test_request_raises_on_error_reply():
|
|
174
|
+
a, b = link()
|
|
175
|
+
arduino, pi = Phax(a), Phax(b)
|
|
176
|
+
|
|
177
|
+
def broken(data):
|
|
178
|
+
raise RuntimeError("sensor offline")
|
|
179
|
+
|
|
180
|
+
arduino.on("read", broken)
|
|
181
|
+
|
|
182
|
+
arduino.start()
|
|
183
|
+
pi.start()
|
|
184
|
+
try:
|
|
185
|
+
with pytest.raises(PhaxError, match="sensor offline"):
|
|
186
|
+
pi.request("read")
|
|
187
|
+
finally:
|
|
188
|
+
pi.stop()
|
|
189
|
+
arduino.stop()
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def test_request_times_out_without_a_peer():
|
|
193
|
+
phax = Phax(Endpoint())
|
|
194
|
+
phax.start()
|
|
195
|
+
try:
|
|
196
|
+
with pytest.raises(PhaxTimeout):
|
|
197
|
+
phax.request("ping", timeout=0.1)
|
|
198
|
+
finally:
|
|
199
|
+
phax.stop()
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def test_reply_with_unhashable_reply_to_is_ignored():
|
|
203
|
+
"""Regression: a list as reply_to crashed the reader thread."""
|
|
204
|
+
phax = Phax(Endpoint())
|
|
205
|
+
phax.handle('{"reply_to": [1], "topic": "ping"}')
|
|
206
|
+
phax.handle('{"reply_to": "7", "topic": "ping"}')
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def test_poll_reads_one_line_from_port():
|
|
210
|
+
end = Endpoint()
|
|
211
|
+
phax = Phax(end)
|
|
212
|
+
received = []
|
|
213
|
+
phax.on("temp", received.append)
|
|
214
|
+
end.inbox.put(b'{"topic": "temp", "data": 3}\n')
|
|
215
|
+
|
|
216
|
+
assert phax.poll() is True
|
|
217
|
+
assert phax.poll() is False
|
|
218
|
+
assert received == [3]
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def test_traffic_is_logged_at_debug(caplog):
|
|
222
|
+
end = Endpoint()
|
|
223
|
+
phax = Phax(end)
|
|
224
|
+
phax.on("ping", lambda data: {"pong": True})
|
|
225
|
+
|
|
226
|
+
with caplog.at_level(logging.DEBUG, logger="phaxi"):
|
|
227
|
+
phax.handle('{"id": 1, "topic": "ping"}\n')
|
|
228
|
+
|
|
229
|
+
assert caplog.messages == [
|
|
230
|
+
'<- {"id": 1, "topic": "ping"}',
|
|
231
|
+
'-> {"reply_to":1,"topic":"ping","data":{"pong":true}}',
|
|
232
|
+
]
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def test_handler_failure_is_logged_with_traceback(caplog):
|
|
236
|
+
phax = Phax(Endpoint())
|
|
237
|
+
|
|
238
|
+
def broken(data):
|
|
239
|
+
raise ValueError("boom")
|
|
240
|
+
|
|
241
|
+
phax.on("ping", broken)
|
|
242
|
+
phax.handle('{"id": 4, "topic": "ping"}')
|
|
243
|
+
|
|
244
|
+
record = caplog.records[-1]
|
|
245
|
+
assert record.levelno == logging.ERROR
|
|
246
|
+
assert record.exc_info[0] is ValueError
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def test_unknown_topic_and_late_reply_are_warned(caplog):
|
|
250
|
+
phax = Phax(Endpoint())
|
|
251
|
+
|
|
252
|
+
phax.handle('{"topic": "nope"}')
|
|
253
|
+
phax.handle('{"reply_to": 99, "topic": "ping"}')
|
|
254
|
+
|
|
255
|
+
assert "No handler for topic 'nope'" in caplog.messages[0]
|
|
256
|
+
assert "unknown request 99" in caplog.messages[1]
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def test_reader_logs_and_stops_when_port_fails(caplog):
|
|
260
|
+
class BrokenPort(Endpoint):
|
|
261
|
+
def readline(self):
|
|
262
|
+
raise OSError("device unplugged")
|
|
263
|
+
|
|
264
|
+
phax = Phax(BrokenPort())
|
|
265
|
+
phax.start()
|
|
266
|
+
phax._thread.join(timeout=1)
|
|
267
|
+
|
|
268
|
+
assert not phax._thread.is_alive()
|
|
269
|
+
assert "stopping the reader" in caplog.messages[-1]
|
|
270
|
+
assert caplog.records[-1].exc_info[0] is OSError
|
|
271
|
+
phax.stop()
|