fjagepy 2.2.0__tar.gz → 3.0.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.
- {fjagepy-2.2.0 → fjagepy-3.0.0}/PKG-INFO +27 -4
- {fjagepy-2.2.0 → fjagepy-3.0.0}/README.md +24 -2
- {fjagepy-2.2.0 → fjagepy-3.0.0}/fjagepy/Gateway.py +19 -12
- {fjagepy-2.2.0 → fjagepy-3.0.0}/fjagepy/JSONMessage.py +2 -0
- {fjagepy-2.2.0 → fjagepy-3.0.0}/fjagepy/Message.py +2 -0
- fjagepy-3.0.0/fjagepy/SerialConnector.py +189 -0
- {fjagepy-2.2.0 → fjagepy-3.0.0}/fjagepy/TCPConnector.py +28 -15
- {fjagepy-2.2.0 → fjagepy-3.0.0}/fjagepy/__init__.py +4 -0
- {fjagepy-2.2.0 → fjagepy-3.0.0}/fjagepy.egg-info/PKG-INFO +27 -4
- {fjagepy-2.2.0 → fjagepy-3.0.0}/fjagepy.egg-info/SOURCES.txt +4 -1
- {fjagepy-2.2.0 → fjagepy-3.0.0}/fjagepy.egg-info/requires.txt +2 -1
- {fjagepy-2.2.0 → fjagepy-3.0.0}/pyproject.toml +2 -2
- fjagepy-3.0.0/test/test_serialconnector.py +83 -0
- fjagepy-3.0.0/test/test_tcpconnector.py +19 -0
- {fjagepy-2.2.0 → fjagepy-3.0.0}/LICENSE +0 -0
- {fjagepy-2.2.0 → fjagepy-3.0.0}/fjagepy/AgentID.py +0 -0
- {fjagepy-2.2.0 → fjagepy-3.0.0}/fjagepy/Connector.py +0 -0
- {fjagepy-2.2.0 → fjagepy-3.0.0}/fjagepy/Performative.py +0 -0
- {fjagepy-2.2.0 → fjagepy-3.0.0}/fjagepy/Services.py +0 -0
- {fjagepy-2.2.0 → fjagepy-3.0.0}/fjagepy/Utils.py +0 -0
- {fjagepy-2.2.0 → fjagepy-3.0.0}/fjagepy/py.typed +0 -0
- {fjagepy-2.2.0 → fjagepy-3.0.0}/fjagepy.egg-info/dependency_links.txt +0 -0
- {fjagepy-2.2.0 → fjagepy-3.0.0}/fjagepy.egg-info/top_level.txt +0 -0
- {fjagepy-2.2.0 → fjagepy-3.0.0}/setup.cfg +0 -0
- {fjagepy-2.2.0 → fjagepy-3.0.0}/test/test_agentid.py +0 -0
- {fjagepy-2.2.0 → fjagepy-3.0.0}/test/test_gateway.py +0 -0
- {fjagepy-2.2.0 → fjagepy-3.0.0}/test/test_jsonmessage.py +0 -0
- {fjagepy-2.2.0 → fjagepy-3.0.0}/test/test_message.py +0 -0
- {fjagepy-2.2.0 → fjagepy-3.0.0}/test/test_shellreqs.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: fjagepy
|
|
3
|
-
Version:
|
|
3
|
+
Version: 3.0.0
|
|
4
4
|
Summary: fjage Gateway in Python
|
|
5
5
|
Author-email: Chinmay Pendharkar <chinmay@subnero.com>
|
|
6
6
|
License: BSD-3-Clause
|
|
@@ -13,8 +13,9 @@ Description-Content-Type: text/markdown
|
|
|
13
13
|
License-File: LICENSE
|
|
14
14
|
Provides-Extra: dev
|
|
15
15
|
Requires-Dist: pytest==8.3.5; extra == "dev"
|
|
16
|
-
Requires-Dist: numpy==2.
|
|
16
|
+
Requires-Dist: numpy==2.0.2; extra == "dev"
|
|
17
17
|
Requires-Dist: mypy==1.19.0; extra == "dev"
|
|
18
|
+
Requires-Dist: pyserial>=3.5; extra == "dev"
|
|
18
19
|
Provides-Extra: docs
|
|
19
20
|
Requires-Dist: sphinx==8.2.3; extra == "docs"
|
|
20
21
|
Requires-Dist: sphinx-rtd-theme==3.0.2; extra == "docs"
|
|
@@ -85,6 +86,18 @@ shell << msg
|
|
|
85
86
|
gw.close()
|
|
86
87
|
```
|
|
87
88
|
|
|
89
|
+
### Serial Connection
|
|
90
|
+
|
|
91
|
+
To connect to a fjåge container over a serial port, pass a `SerialConnector`
|
|
92
|
+
instead of a hostname and port. This needs the optional `pyserial` dependency
|
|
93
|
+
(`pip install "fjagepy[serial]"`):
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
from fjagepy import Gateway, SerialConnector
|
|
97
|
+
|
|
98
|
+
gw = Gateway(connector=SerialConnector('/dev/ttyUSB0', 115200))
|
|
99
|
+
```
|
|
100
|
+
|
|
88
101
|
### Request-Response Pattern
|
|
89
102
|
|
|
90
103
|
```python
|
|
@@ -164,6 +177,9 @@ Implement custom connectors by extending the `Connector` base class:
|
|
|
164
177
|
from fjagepy import Connector
|
|
165
178
|
|
|
166
179
|
class MyCustomConnector(Connector):
|
|
180
|
+
def __init__(self, url: str):
|
|
181
|
+
self.url = url
|
|
182
|
+
|
|
167
183
|
def connect(self):
|
|
168
184
|
# Implementation
|
|
169
185
|
pass
|
|
@@ -176,10 +192,17 @@ class MyCustomConnector(Connector):
|
|
|
176
192
|
# Implementation
|
|
177
193
|
pass
|
|
178
194
|
|
|
179
|
-
#
|
|
180
|
-
gw = Gateway(connector=MyCustomConnector)
|
|
195
|
+
# Construct the connector yourself and hand it to the Gateway
|
|
196
|
+
gw = Gateway(connector=MyCustomConnector('ws://localhost:8080/ws'))
|
|
181
197
|
```
|
|
182
198
|
|
|
199
|
+
A connector defines its own constructor arguments; the Gateway simply uses the
|
|
200
|
+
instance it is given. `TCPConnector(hostname, port, reconnect_delay)` may also be
|
|
201
|
+
constructed explicitly, which is the only way to set a custom `reconnect_delay`.
|
|
202
|
+
|
|
203
|
+
> **Note:** up to fjagepy 2.2.0, `connector` took a Connector *class*
|
|
204
|
+
> (`Gateway(connector=TCPConnector)`). It now takes an instance.
|
|
205
|
+
|
|
183
206
|
### Logging and Debugging
|
|
184
207
|
|
|
185
208
|
This library uses the standard [Python logging](https://docs.python.org/3/library/logging.html) system.
|
|
@@ -62,6 +62,18 @@ shell << msg
|
|
|
62
62
|
gw.close()
|
|
63
63
|
```
|
|
64
64
|
|
|
65
|
+
### Serial Connection
|
|
66
|
+
|
|
67
|
+
To connect to a fjåge container over a serial port, pass a `SerialConnector`
|
|
68
|
+
instead of a hostname and port. This needs the optional `pyserial` dependency
|
|
69
|
+
(`pip install "fjagepy[serial]"`):
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
from fjagepy import Gateway, SerialConnector
|
|
73
|
+
|
|
74
|
+
gw = Gateway(connector=SerialConnector('/dev/ttyUSB0', 115200))
|
|
75
|
+
```
|
|
76
|
+
|
|
65
77
|
### Request-Response Pattern
|
|
66
78
|
|
|
67
79
|
```python
|
|
@@ -141,6 +153,9 @@ Implement custom connectors by extending the `Connector` base class:
|
|
|
141
153
|
from fjagepy import Connector
|
|
142
154
|
|
|
143
155
|
class MyCustomConnector(Connector):
|
|
156
|
+
def __init__(self, url: str):
|
|
157
|
+
self.url = url
|
|
158
|
+
|
|
144
159
|
def connect(self):
|
|
145
160
|
# Implementation
|
|
146
161
|
pass
|
|
@@ -153,10 +168,17 @@ class MyCustomConnector(Connector):
|
|
|
153
168
|
# Implementation
|
|
154
169
|
pass
|
|
155
170
|
|
|
156
|
-
#
|
|
157
|
-
gw = Gateway(connector=MyCustomConnector)
|
|
171
|
+
# Construct the connector yourself and hand it to the Gateway
|
|
172
|
+
gw = Gateway(connector=MyCustomConnector('ws://localhost:8080/ws'))
|
|
158
173
|
```
|
|
159
174
|
|
|
175
|
+
A connector defines its own constructor arguments; the Gateway simply uses the
|
|
176
|
+
instance it is given. `TCPConnector(hostname, port, reconnect_delay)` may also be
|
|
177
|
+
constructed explicitly, which is the only way to set a custom `reconnect_delay`.
|
|
178
|
+
|
|
179
|
+
> **Note:** up to fjagepy 2.2.0, `connector` took a Connector *class*
|
|
180
|
+
> (`Gateway(connector=TCPConnector)`). It now takes an instance.
|
|
181
|
+
|
|
160
182
|
### Logging and Debugging
|
|
161
183
|
|
|
162
184
|
This library uses the standard [Python logging](https://docs.python.org/3/library/logging.html) system.
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
1
2
|
|
|
2
3
|
import uuid
|
|
3
4
|
import queue
|
|
@@ -43,23 +44,29 @@ class Gateway:
|
|
|
43
44
|
NON_BLOCKING = 0
|
|
44
45
|
BLOCKING = -1
|
|
45
46
|
|
|
46
|
-
def __init__(self, hostname: str = 'localhost', port: int = 1100, connector:
|
|
47
|
+
def __init__(self, hostname: str = 'localhost', port: int = 1100, connector: Optional[Connector] = None, reconnect: bool = True, timeout: int = DEFAULT_REQUEST_TIMEOUT, directory_timeout: int = DEFAULT_DIRECTORY_TIMEOUT) -> None:
|
|
47
48
|
"""Creates a new Gateway instance.
|
|
48
49
|
|
|
50
|
+
Connects over TCP by default. To use any other transport, construct its
|
|
51
|
+
Connector and pass it as `connector`, e.g. `SerialConnector` for a serial
|
|
52
|
+
port; `hostname`, `port` and `reconnect` are then ignored.
|
|
53
|
+
|
|
49
54
|
Args:
|
|
50
55
|
hostname : hostname of the fjage container. Defaults to 'localhost'.
|
|
51
56
|
port : port of the fjage container. Defaults to 1100.
|
|
52
|
-
connector : Connector
|
|
57
|
+
connector : a Connector instance to use, instead of connecting over TCP.
|
|
53
58
|
reconnect : whether to keep the connection alive. Defaults to True.
|
|
54
59
|
timeout : default timeout in milliseconds for request(). Defaults to 1000.
|
|
55
60
|
directory_timeout : default timeout in milliseconds for directory queries. Defaults to 6000.
|
|
56
61
|
"""
|
|
57
|
-
if
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
62
|
+
if connector is not None:
|
|
63
|
+
if not isinstance(connector, Connector):
|
|
64
|
+
raise ValueError("connector must be a Connector instance")
|
|
65
|
+
else:
|
|
66
|
+
if not isinstance(hostname, str) or not hostname:
|
|
67
|
+
raise ValueError("hostname must be a non-empty string")
|
|
68
|
+
if not isinstance(port, int) or not (0 < port < 65536):
|
|
69
|
+
raise ValueError("port must be an integer 1-65535")
|
|
63
70
|
if not isinstance(reconnect, bool):
|
|
64
71
|
raise ValueError("reconnect must be a boolean")
|
|
65
72
|
if not isinstance(timeout, int) or timeout <= 0:
|
|
@@ -74,12 +81,12 @@ class Gateway:
|
|
|
74
81
|
self._timeout = timeout
|
|
75
82
|
self._directory_timeout = directory_timeout
|
|
76
83
|
self.aid = AgentID("gateway-" + str(uuid.uuid4()), owner=self)
|
|
77
|
-
self.connector = connector(
|
|
84
|
+
self.connector = connector or TCPConnector(hostname, port, 5 if reconnect else -1)
|
|
78
85
|
self.connector.set_receive_callback(self._msg_rx)
|
|
79
86
|
try :
|
|
80
87
|
self.connector.connect()
|
|
81
88
|
except Exception as e:
|
|
82
|
-
logger.error(f"Failed to connect to {
|
|
89
|
+
logger.error(f"Failed to connect to {self.connector.__details__()}: {e}")
|
|
83
90
|
raise e
|
|
84
91
|
self._update_watch()
|
|
85
92
|
|
|
@@ -426,10 +433,10 @@ class Gateway:
|
|
|
426
433
|
self.close()
|
|
427
434
|
|
|
428
435
|
def __details__(self):
|
|
429
|
-
return f"(
|
|
436
|
+
return f"({self.connector.__details__()} connected={self.is_connected()})"
|
|
430
437
|
|
|
431
438
|
def __str__(self) -> str:
|
|
432
|
-
return f"Gateway
|
|
439
|
+
return f"Gateway{self.__details__()}"
|
|
433
440
|
|
|
434
441
|
def _repr_pretty_(self, p, cycle):
|
|
435
442
|
p.text(str(self) if not cycle else '...')
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import math
|
|
3
|
+
import threading
|
|
4
|
+
import time
|
|
5
|
+
from typing import Any, Callable, List, Optional
|
|
6
|
+
|
|
7
|
+
from .Connector import Connector
|
|
8
|
+
|
|
9
|
+
logger = logging.getLogger(__name__)
|
|
10
|
+
logger.addHandler(logging.NullHandler())
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class SerialConnector(Connector):
|
|
14
|
+
"""Simple serial port connector using pyserial.
|
|
15
|
+
|
|
16
|
+
Requires the optional `pyserial` dependency (`pip install fjagepy[serial]`).
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def __init__(self, devname: str, baud: int = 9600, reconnect_delay: float = 5) -> None:
|
|
20
|
+
"""
|
|
21
|
+
Args:
|
|
22
|
+
devname : serial device name (e.g. '/dev/ttyUSB0'), or a pyserial URL (e.g. 'loop://').
|
|
23
|
+
baud : baud rate. Defaults to 9600.
|
|
24
|
+
reconnect_delay : seconds to wait before reconnecting, or -1 to disable reconnection. Defaults to 5.
|
|
25
|
+
"""
|
|
26
|
+
if not isinstance(devname, str) or not devname.strip():
|
|
27
|
+
raise ValueError("devname must be a non-empty string")
|
|
28
|
+
if isinstance(baud, bool) or not isinstance(baud, int) or baud <= 0:
|
|
29
|
+
raise ValueError("baud must be a positive integer")
|
|
30
|
+
if (
|
|
31
|
+
isinstance(reconnect_delay, bool)
|
|
32
|
+
or not isinstance(reconnect_delay, (int, float))
|
|
33
|
+
or not math.isfinite(reconnect_delay)
|
|
34
|
+
or reconnect_delay < -1
|
|
35
|
+
):
|
|
36
|
+
raise ValueError("reconnect_delay must be a finite non-negative number or -1")
|
|
37
|
+
|
|
38
|
+
self.devname = devname
|
|
39
|
+
self.baud = baud
|
|
40
|
+
self.reconnect_delay = reconnect_delay
|
|
41
|
+
|
|
42
|
+
try:
|
|
43
|
+
import serial # type: ignore[import-untyped] # local import, so that pyserial stays an optional dependency
|
|
44
|
+
except ImportError as e:
|
|
45
|
+
raise ImportError("SerialConnector requires pyserial: pip install pyserial") from e
|
|
46
|
+
self._serial = serial
|
|
47
|
+
|
|
48
|
+
# Port and connection state
|
|
49
|
+
self._port: Optional[Any] = None
|
|
50
|
+
self._connected = False
|
|
51
|
+
self._callback: Optional[Callable[[List[str]], None]] = None
|
|
52
|
+
|
|
53
|
+
# Threading for receive loop
|
|
54
|
+
self._read_thread: Optional[threading.Thread] = None
|
|
55
|
+
self._stop_event = threading.Event()
|
|
56
|
+
self._lock = threading.Lock()
|
|
57
|
+
|
|
58
|
+
def set_receive_callback(self, callback: Callable[[List[str]], None]) -> None:
|
|
59
|
+
"""Set the callback function to handle incoming messages."""
|
|
60
|
+
if not callable(callback):
|
|
61
|
+
raise ValueError("callback must be callable")
|
|
62
|
+
self._callback = callback
|
|
63
|
+
|
|
64
|
+
def connect(self) -> None:
|
|
65
|
+
"""Open the serial port."""
|
|
66
|
+
with self._lock:
|
|
67
|
+
if self._connected:
|
|
68
|
+
return
|
|
69
|
+
|
|
70
|
+
try:
|
|
71
|
+
# serial_for_url() accepts device names as well as URLs (eg. loop://)
|
|
72
|
+
self._port = self._serial.serial_for_url(self.devname, baudrate=self.baud, timeout=0.1)
|
|
73
|
+
self._connected = True
|
|
74
|
+
logger.debug(f"Connected to {self.devname}@{self.baud}")
|
|
75
|
+
|
|
76
|
+
# Start read thread if callback is set
|
|
77
|
+
if self._callback:
|
|
78
|
+
self._stop_event.clear()
|
|
79
|
+
self._read_thread = threading.Thread(target=self._read_loop, daemon=True)
|
|
80
|
+
self._read_thread.start()
|
|
81
|
+
|
|
82
|
+
except Exception as e:
|
|
83
|
+
self._connected = False
|
|
84
|
+
self._cleanup_port()
|
|
85
|
+
raise ConnectionError(f"Failed to connect to {self.devname}@{self.baud}: {e}")
|
|
86
|
+
|
|
87
|
+
def disconnect(self) -> None:
|
|
88
|
+
"""Close the serial port."""
|
|
89
|
+
with self._lock:
|
|
90
|
+
if not self._connected:
|
|
91
|
+
return
|
|
92
|
+
|
|
93
|
+
self._stop_event.set()
|
|
94
|
+
self._connected = False
|
|
95
|
+
self._cleanup_port()
|
|
96
|
+
|
|
97
|
+
# Wait for read thread to finish
|
|
98
|
+
if self._read_thread and self._read_thread.is_alive():
|
|
99
|
+
self._read_thread.join(timeout=2.0)
|
|
100
|
+
|
|
101
|
+
logger.debug("Disconnected")
|
|
102
|
+
|
|
103
|
+
def is_connected(self) -> bool:
|
|
104
|
+
"""Check if connected."""
|
|
105
|
+
return self._connected
|
|
106
|
+
|
|
107
|
+
def send(self, msg: str) -> None:
|
|
108
|
+
"""Send a message."""
|
|
109
|
+
with self._lock:
|
|
110
|
+
if not self._connected or not self._port:
|
|
111
|
+
raise ConnectionError("Not connected")
|
|
112
|
+
try:
|
|
113
|
+
self._port.write((msg + "\n").encode())
|
|
114
|
+
except Exception as e:
|
|
115
|
+
self._connected = False
|
|
116
|
+
self._cleanup_port()
|
|
117
|
+
raise ConnectionError(f"Failed to send message: {e}")
|
|
118
|
+
|
|
119
|
+
def __details__(self):
|
|
120
|
+
return f"dev:{self.devname}@{self.baud}"
|
|
121
|
+
|
|
122
|
+
def __repr__(self):
|
|
123
|
+
return f"SerialConnector(devname={self.devname}, baud={self.baud}, connected={self.is_connected()})"
|
|
124
|
+
|
|
125
|
+
# Internal methods
|
|
126
|
+
|
|
127
|
+
def _cleanup_port(self) -> None:
|
|
128
|
+
"""Clean up serial port resources."""
|
|
129
|
+
if self._port:
|
|
130
|
+
try:
|
|
131
|
+
self._port.close()
|
|
132
|
+
except Exception:
|
|
133
|
+
pass
|
|
134
|
+
self._port = None
|
|
135
|
+
|
|
136
|
+
def _read_loop(self) -> None:
|
|
137
|
+
"""Background thread that reads data and calls the callback."""
|
|
138
|
+
buffer: str = ""
|
|
139
|
+
|
|
140
|
+
try:
|
|
141
|
+
while not self._stop_event.is_set() and self._connected:
|
|
142
|
+
port = self._port
|
|
143
|
+
if not port:
|
|
144
|
+
break
|
|
145
|
+
try:
|
|
146
|
+
# read() blocks for at most the port timeout (0.1s), allowing periodic stop checks
|
|
147
|
+
data = port.read(port.in_waiting or 1)
|
|
148
|
+
if not data:
|
|
149
|
+
continue
|
|
150
|
+
|
|
151
|
+
buffer += data.decode(errors="replace")
|
|
152
|
+
lines = buffer.split("\n")
|
|
153
|
+
buffer = lines.pop() # Keep incomplete line
|
|
154
|
+
|
|
155
|
+
if lines and self._callback:
|
|
156
|
+
try:
|
|
157
|
+
self._callback(lines)
|
|
158
|
+
except Exception as e:
|
|
159
|
+
logger.warning(f"Callback error: {e}")
|
|
160
|
+
|
|
161
|
+
except Exception as e:
|
|
162
|
+
if self._connected: # Only log if we expect to be connected
|
|
163
|
+
logger.warning(f"Read error: {e}")
|
|
164
|
+
with self._lock:
|
|
165
|
+
self._connected = False
|
|
166
|
+
self._cleanup_port()
|
|
167
|
+
break
|
|
168
|
+
|
|
169
|
+
except Exception as e:
|
|
170
|
+
logger.warning(f"Read loop error: {e}")
|
|
171
|
+
finally:
|
|
172
|
+
# Auto-reconnect if configured and not stopping
|
|
173
|
+
if not self._stop_event.is_set() and self.reconnect_delay >= 0:
|
|
174
|
+
self._attempt_reconnect()
|
|
175
|
+
|
|
176
|
+
def _attempt_reconnect(self) -> None:
|
|
177
|
+
"""Attempt to reopen the port with delay."""
|
|
178
|
+
while not self._stop_event.is_set() and self.reconnect_delay >= 0:
|
|
179
|
+
try:
|
|
180
|
+
logger.debug(f"Attempting to reconnect in {self.reconnect_delay}s...")
|
|
181
|
+
if self._stop_event.wait(timeout=self.reconnect_delay):
|
|
182
|
+
break
|
|
183
|
+
|
|
184
|
+
self.connect()
|
|
185
|
+
return # Successfully reconnected
|
|
186
|
+
|
|
187
|
+
except Exception as e:
|
|
188
|
+
logger.warning(f"Reconnection failed: {e}")
|
|
189
|
+
continue
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import socket
|
|
2
2
|
import logging
|
|
3
|
+
import math
|
|
3
4
|
import threading
|
|
4
5
|
import time
|
|
5
6
|
from typing import Any, Callable, List, Optional
|
|
@@ -14,16 +15,28 @@ logger.addHandler(logging.NullHandler())
|
|
|
14
15
|
class TCPConnector(Connector):
|
|
15
16
|
"""Simple TCP connector using synchronous sockets."""
|
|
16
17
|
|
|
17
|
-
def __init__(self,
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
18
|
+
def __init__(self, hostname: str = 'localhost', port: int = 1100, reconnect_delay: float = 5):
|
|
19
|
+
"""
|
|
20
|
+
Args:
|
|
21
|
+
hostname : hostname or IP address of the fjåge container. Defaults to 'localhost'.
|
|
22
|
+
port : port of the fjåge container. Defaults to 1100.
|
|
23
|
+
reconnect_delay : seconds to wait before reconnecting, or -1 to disable reconnection. Defaults to 5.
|
|
24
|
+
"""
|
|
25
|
+
if not isinstance(hostname, str) or not hostname.strip():
|
|
26
|
+
raise ValueError("hostname must be a non-empty string")
|
|
27
|
+
if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:
|
|
28
|
+
raise ValueError("port must be an integer between 1 and 65535")
|
|
29
|
+
if (
|
|
30
|
+
isinstance(reconnect_delay, bool)
|
|
31
|
+
or not isinstance(reconnect_delay, (int, float))
|
|
32
|
+
or not math.isfinite(reconnect_delay)
|
|
33
|
+
or reconnect_delay < -1
|
|
34
|
+
):
|
|
35
|
+
raise ValueError("reconnect_delay must be a finite non-negative number or -1")
|
|
36
|
+
|
|
37
|
+
self.hostname = hostname
|
|
38
|
+
self.port = port
|
|
39
|
+
self.reconnect_delay = reconnect_delay
|
|
27
40
|
|
|
28
41
|
# Socket and connection state
|
|
29
42
|
self._socket: Optional[socket.socket] = None
|
|
@@ -50,9 +63,9 @@ class TCPConnector(Connector):
|
|
|
50
63
|
try:
|
|
51
64
|
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
52
65
|
self._socket.settimeout(10.0) # 10 second connection timeout
|
|
53
|
-
self._socket.connect((self.
|
|
66
|
+
self._socket.connect((self.hostname, self.port))
|
|
54
67
|
self._connected = True
|
|
55
|
-
logger.debug(f"Connected to {self.
|
|
68
|
+
logger.debug(f"Connected to {self.hostname}:{self.port}")
|
|
56
69
|
|
|
57
70
|
# Start read thread if callback is set
|
|
58
71
|
if self._callback:
|
|
@@ -62,7 +75,7 @@ class TCPConnector(Connector):
|
|
|
62
75
|
|
|
63
76
|
except Exception as e:
|
|
64
77
|
self._cleanup_socket()
|
|
65
|
-
raise ConnectionError(f"Failed to connect to {self.
|
|
78
|
+
raise ConnectionError(f"Failed to connect to {self.hostname}:{self.port}: {e}")
|
|
66
79
|
|
|
67
80
|
def disconnect(self) -> None:
|
|
68
81
|
"""Close the connection."""
|
|
@@ -98,10 +111,10 @@ class TCPConnector(Connector):
|
|
|
98
111
|
raise ConnectionError(f"Failed to send message: {e}")
|
|
99
112
|
|
|
100
113
|
def __details__(self):
|
|
101
|
-
return f"{self.
|
|
114
|
+
return f"host:{self.hostname}:{self.port}"
|
|
102
115
|
|
|
103
116
|
def __repr__(self):
|
|
104
|
-
return f"TCPConnector(host={self.
|
|
117
|
+
return f"TCPConnector(host={self.hostname}, port={self.port}, connected={self.is_connected()})"
|
|
105
118
|
|
|
106
119
|
# Internal methods
|
|
107
120
|
|
|
@@ -6,7 +6,9 @@ from .Performative import Performative
|
|
|
6
6
|
from .AgentID import AgentID
|
|
7
7
|
from .Services import Services
|
|
8
8
|
|
|
9
|
+
from .Connector import Connector
|
|
9
10
|
from .TCPConnector import TCPConnector
|
|
11
|
+
from .SerialConnector import SerialConnector
|
|
10
12
|
from .JSONMessage import JSONMessage
|
|
11
13
|
|
|
12
14
|
|
|
@@ -22,7 +24,9 @@ __all__ = [
|
|
|
22
24
|
"Performative",
|
|
23
25
|
"AgentID",
|
|
24
26
|
"Services",
|
|
27
|
+
"Connector",
|
|
25
28
|
"TCPConnector",
|
|
29
|
+
"SerialConnector",
|
|
26
30
|
"JSONMessage",
|
|
27
31
|
"ParameterReq",
|
|
28
32
|
"ParameterRsp",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: fjagepy
|
|
3
|
-
Version:
|
|
3
|
+
Version: 3.0.0
|
|
4
4
|
Summary: fjage Gateway in Python
|
|
5
5
|
Author-email: Chinmay Pendharkar <chinmay@subnero.com>
|
|
6
6
|
License: BSD-3-Clause
|
|
@@ -13,8 +13,9 @@ Description-Content-Type: text/markdown
|
|
|
13
13
|
License-File: LICENSE
|
|
14
14
|
Provides-Extra: dev
|
|
15
15
|
Requires-Dist: pytest==8.3.5; extra == "dev"
|
|
16
|
-
Requires-Dist: numpy==2.
|
|
16
|
+
Requires-Dist: numpy==2.0.2; extra == "dev"
|
|
17
17
|
Requires-Dist: mypy==1.19.0; extra == "dev"
|
|
18
|
+
Requires-Dist: pyserial>=3.5; extra == "dev"
|
|
18
19
|
Provides-Extra: docs
|
|
19
20
|
Requires-Dist: sphinx==8.2.3; extra == "docs"
|
|
20
21
|
Requires-Dist: sphinx-rtd-theme==3.0.2; extra == "docs"
|
|
@@ -85,6 +86,18 @@ shell << msg
|
|
|
85
86
|
gw.close()
|
|
86
87
|
```
|
|
87
88
|
|
|
89
|
+
### Serial Connection
|
|
90
|
+
|
|
91
|
+
To connect to a fjåge container over a serial port, pass a `SerialConnector`
|
|
92
|
+
instead of a hostname and port. This needs the optional `pyserial` dependency
|
|
93
|
+
(`pip install "fjagepy[serial]"`):
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
from fjagepy import Gateway, SerialConnector
|
|
97
|
+
|
|
98
|
+
gw = Gateway(connector=SerialConnector('/dev/ttyUSB0', 115200))
|
|
99
|
+
```
|
|
100
|
+
|
|
88
101
|
### Request-Response Pattern
|
|
89
102
|
|
|
90
103
|
```python
|
|
@@ -164,6 +177,9 @@ Implement custom connectors by extending the `Connector` base class:
|
|
|
164
177
|
from fjagepy import Connector
|
|
165
178
|
|
|
166
179
|
class MyCustomConnector(Connector):
|
|
180
|
+
def __init__(self, url: str):
|
|
181
|
+
self.url = url
|
|
182
|
+
|
|
167
183
|
def connect(self):
|
|
168
184
|
# Implementation
|
|
169
185
|
pass
|
|
@@ -176,10 +192,17 @@ class MyCustomConnector(Connector):
|
|
|
176
192
|
# Implementation
|
|
177
193
|
pass
|
|
178
194
|
|
|
179
|
-
#
|
|
180
|
-
gw = Gateway(connector=MyCustomConnector)
|
|
195
|
+
# Construct the connector yourself and hand it to the Gateway
|
|
196
|
+
gw = Gateway(connector=MyCustomConnector('ws://localhost:8080/ws'))
|
|
181
197
|
```
|
|
182
198
|
|
|
199
|
+
A connector defines its own constructor arguments; the Gateway simply uses the
|
|
200
|
+
instance it is given. `TCPConnector(hostname, port, reconnect_delay)` may also be
|
|
201
|
+
constructed explicitly, which is the only way to set a custom `reconnect_delay`.
|
|
202
|
+
|
|
203
|
+
> **Note:** up to fjagepy 2.2.0, `connector` took a Connector *class*
|
|
204
|
+
> (`Gateway(connector=TCPConnector)`). It now takes an instance.
|
|
205
|
+
|
|
183
206
|
### Logging and Debugging
|
|
184
207
|
|
|
185
208
|
This library uses the standard [Python logging](https://docs.python.org/3/library/logging.html) system.
|
|
@@ -7,6 +7,7 @@ fjagepy/Gateway.py
|
|
|
7
7
|
fjagepy/JSONMessage.py
|
|
8
8
|
fjagepy/Message.py
|
|
9
9
|
fjagepy/Performative.py
|
|
10
|
+
fjagepy/SerialConnector.py
|
|
10
11
|
fjagepy/Services.py
|
|
11
12
|
fjagepy/TCPConnector.py
|
|
12
13
|
fjagepy/Utils.py
|
|
@@ -21,4 +22,6 @@ test/test_agentid.py
|
|
|
21
22
|
test/test_gateway.py
|
|
22
23
|
test/test_jsonmessage.py
|
|
23
24
|
test/test_message.py
|
|
24
|
-
test/
|
|
25
|
+
test/test_serialconnector.py
|
|
26
|
+
test/test_shellreqs.py
|
|
27
|
+
test/test_tcpconnector.py
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "fjagepy"
|
|
7
|
-
version = "
|
|
7
|
+
version = "3.0.0"
|
|
8
8
|
description = "fjage Gateway in Python"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = {text = "BSD-3-Clause"}
|
|
@@ -23,7 +23,7 @@ testpaths = ["test"]
|
|
|
23
23
|
addopts = "-ra -q"
|
|
24
24
|
|
|
25
25
|
[project.optional-dependencies]
|
|
26
|
-
dev = ["pytest==8.3.5", "numpy==2.
|
|
26
|
+
dev = ["pytest==8.3.5", "numpy==2.0.2", "mypy==1.19.0", "pyserial>=3.5"]
|
|
27
27
|
docs = ["sphinx==8.2.3", "sphinx-rtd-theme==3.0.2", "myst-parser==4.0.1"]
|
|
28
28
|
|
|
29
29
|
[tool.mypy]
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import time
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
pytest.importorskip("serial")
|
|
6
|
+
|
|
7
|
+
from fjagepy import SerialConnector
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@pytest.fixture
|
|
11
|
+
def connector():
|
|
12
|
+
"""SerialConnector on a pyserial loopback port, so writes come back as reads."""
|
|
13
|
+
conn = SerialConnector('loop://', reconnect_delay=-1)
|
|
14
|
+
yield conn
|
|
15
|
+
conn.disconnect()
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def collect(conn):
|
|
19
|
+
"""Attach a receive callback, returning the list it appends lines to."""
|
|
20
|
+
lines = []
|
|
21
|
+
conn.set_receive_callback(lines.extend)
|
|
22
|
+
return lines
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def wait_for(lines, n, timeout=2.0):
|
|
26
|
+
deadline = time.time() + timeout
|
|
27
|
+
while len(lines) < n and time.time() < deadline:
|
|
28
|
+
time.sleep(0.01)
|
|
29
|
+
return lines
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def test_serialconnector_requires_devname():
|
|
33
|
+
"""SerialConnector should require a device name."""
|
|
34
|
+
with pytest.raises(TypeError):
|
|
35
|
+
SerialConnector() # type: ignore[call-arg]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@pytest.mark.parametrize(
|
|
39
|
+
("devname", "baud", "reconnect_delay"),
|
|
40
|
+
[
|
|
41
|
+
("", 9600, 5),
|
|
42
|
+
("loop://", 0, 5),
|
|
43
|
+
("loop://", True, 5),
|
|
44
|
+
("loop://", 9600, -2),
|
|
45
|
+
("loop://", 9600, float("inf")),
|
|
46
|
+
],
|
|
47
|
+
)
|
|
48
|
+
def test_serialconnector_validates_constructor_arguments(devname, baud, reconnect_delay):
|
|
49
|
+
with pytest.raises(ValueError):
|
|
50
|
+
SerialConnector(devname, baud, reconnect_delay)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def test_serialconnector_send_receive(connector):
|
|
54
|
+
"""A line sent on a loopback port should come back to the receive callback."""
|
|
55
|
+
lines = collect(connector)
|
|
56
|
+
connector.connect()
|
|
57
|
+
assert connector.is_connected()
|
|
58
|
+
connector.send('{"alive": true}')
|
|
59
|
+
assert wait_for(lines, 1) == ['{"alive": true}']
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def test_serialconnector_reassembles_split_lines(connector):
|
|
63
|
+
"""Partial writes should be buffered until a complete line arrives."""
|
|
64
|
+
lines = collect(connector)
|
|
65
|
+
connector.connect()
|
|
66
|
+
connector._port.write(b'{"ali')
|
|
67
|
+
time.sleep(0.2)
|
|
68
|
+
assert lines == []
|
|
69
|
+
connector._port.write(b've": true}\n{"partial"')
|
|
70
|
+
assert wait_for(lines, 1) == ['{"alive": true}']
|
|
71
|
+
time.sleep(0.2)
|
|
72
|
+
assert len(lines) == 1 # incomplete line not delivered
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def test_serialconnector_disconnect(connector):
|
|
76
|
+
"""Disconnect should close the port and stop the read thread."""
|
|
77
|
+
collect(connector)
|
|
78
|
+
connector.connect()
|
|
79
|
+
connector.disconnect()
|
|
80
|
+
assert not connector.is_connected()
|
|
81
|
+
assert not connector._read_thread.is_alive()
|
|
82
|
+
with pytest.raises(ConnectionError):
|
|
83
|
+
connector.send('nope')
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
|
|
3
|
+
from fjagepy import TCPConnector
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@pytest.mark.parametrize(
|
|
7
|
+
("hostname", "port", "reconnect_delay"),
|
|
8
|
+
[
|
|
9
|
+
("", 1100, 5),
|
|
10
|
+
("localhost", 0, 5),
|
|
11
|
+
("localhost", 65536, 5),
|
|
12
|
+
("localhost", True, 5),
|
|
13
|
+
("localhost", 1100, -2),
|
|
14
|
+
("localhost", 1100, float("nan")),
|
|
15
|
+
],
|
|
16
|
+
)
|
|
17
|
+
def test_tcpconnector_validates_constructor_arguments(hostname, port, reconnect_delay):
|
|
18
|
+
with pytest.raises(ValueError):
|
|
19
|
+
TCPConnector(hostname, port, reconnect_delay)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|