axonio-ros2 0.5.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.
- axonio_ros2-0.5.0/LICENSE +21 -0
- axonio_ros2-0.5.0/PKG-INFO +135 -0
- axonio_ros2-0.5.0/README.md +108 -0
- axonio_ros2-0.5.0/axonio_ros2/__init__.py +20 -0
- axonio_ros2-0.5.0/axonio_ros2/client.py +367 -0
- axonio_ros2-0.5.0/axonio_ros2/fleet_sync.py +44 -0
- axonio_ros2-0.5.0/axonio_ros2/node.py +186 -0
- axonio_ros2-0.5.0/axonio_ros2/obstacle_subscriber.py +38 -0
- axonio_ros2-0.5.0/axonio_ros2/spatial_index.py +93 -0
- axonio_ros2-0.5.0/axonio_ros2/tf_listener.py +29 -0
- axonio_ros2-0.5.0/axonio_ros2.egg-info/PKG-INFO +135 -0
- axonio_ros2-0.5.0/axonio_ros2.egg-info/SOURCES.txt +25 -0
- axonio_ros2-0.5.0/axonio_ros2.egg-info/dependency_links.txt +1 -0
- axonio_ros2-0.5.0/axonio_ros2.egg-info/entry_points.txt +3 -0
- axonio_ros2-0.5.0/axonio_ros2.egg-info/requires.txt +5 -0
- axonio_ros2-0.5.0/axonio_ros2.egg-info/top_level.txt +1 -0
- axonio_ros2-0.5.0/config/bridge_params.yaml +13 -0
- axonio_ros2-0.5.0/launch/memory_bridge.launch.py +37 -0
- axonio_ros2-0.5.0/package.xml +24 -0
- axonio_ros2-0.5.0/pyproject.toml +43 -0
- axonio_ros2-0.5.0/resource/axonio_ros2 +0 -0
- axonio_ros2-0.5.0/setup.cfg +10 -0
- axonio_ros2-0.5.0/setup.py +18 -0
- axonio_ros2-0.5.0/tests/test_client.py +171 -0
- axonio_ros2-0.5.0/tests/test_node.py +59 -0
- axonio_ros2-0.5.0/tests/test_spatial_index.py +79 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Axonio
|
|
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,135 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: axonio-ros2
|
|
3
|
+
Version: 0.5.0
|
|
4
|
+
Summary: ROS2 SDK for Axonio: persistent, fleet-wide spatial memory for robots
|
|
5
|
+
Author-email: Axonio <team@axonio.xyz>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://axonio.xyz
|
|
8
|
+
Project-URL: Repository, https://github.com/hackcat29/axonio-sdk
|
|
9
|
+
Project-URL: Documentation, https://docs.axonio.xyz
|
|
10
|
+
Keywords: ros2,robotics,axonio,memory,amr,navigation,nav2,spatial-ai
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: axonio>=0.2.1
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: pytest>=7.0.0; extra == "dev"
|
|
25
|
+
Requires-Dist: ruff>=0.1.0; extra == "dev"
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# axonio-ros2
|
|
29
|
+
|
|
30
|
+
ROS2 package and Python SDK that give robots a shared, durable spatial memory in [Axonio](https://axonio.xyz). One robot reports an obstacle; every robot in the fleet can plan around it, and it is still there after a restart.
|
|
31
|
+
|
|
32
|
+
It is built on the [`axonio`](https://pypi.org/project/axonio/) Python SDK. Spatial events are stored as ordinary Axonio memories, so they also appear in the dashboard, in search, and to any AI agent connected through the Axonio MCP server.
|
|
33
|
+
|
|
34
|
+
Formerly `clawdb-ros2`.
|
|
35
|
+
|
|
36
|
+
## Install
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install axonio-ros2 # Python 3.10 or newer (ROS 2 Humble and later)
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Or inside a colcon workspace:
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
cd ~/ros2_ws/src
|
|
46
|
+
git clone https://github.com/hackcat29/axonio-sdk.git
|
|
47
|
+
ln -s axonio-sdk/sdks/ros2 axonio_ros2
|
|
48
|
+
pip install axonio
|
|
49
|
+
cd ~/ros2_ws && colcon build --packages-select axonio_ros2 && source install/setup.bash
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Create an API key in the Axonio dashboard (Robots → Register Robot Node) and export it. The key is never put on the command line or in a ROS parameter, where any node on the DDS domain could read it.
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
export AXONIO_API_KEY="ck_live_..." # or use api_key_file:=/run/secrets/axonio
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Run the bridge node
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
ros2 launch axonio_ros2 memory_bridge.launch.py robot_id:=amr_01
|
|
62
|
+
# or
|
|
63
|
+
ros2 run axonio_ros2 memory_node --ros-args -p robot_id:=amr_01
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
The node writes every obstacle it sees to Axonio, pulls what other robots recorded into a local index at `sync_rate_hz`, and publishes those new records on `~/fleet_updates`.
|
|
67
|
+
|
|
68
|
+
| Topic | Type | |
|
|
69
|
+
|---|---|---|
|
|
70
|
+
| `~/detected_obstacle` (sub) | `geometry_msgs/Point` | A point detection to remember |
|
|
71
|
+
| `~/fleet_updates` (pub) | `std_msgs/String` | JSON list of records new from other robots |
|
|
72
|
+
|
|
73
|
+
| Parameter | Default | |
|
|
74
|
+
|---|---|---|
|
|
75
|
+
| `endpoint` | `""` | Empty for the Axonio cloud, or a self-hosted server URL (`https://`, or `http://localhost`) |
|
|
76
|
+
| `api_key_file` | `""` | File holding the key, used when `AXONIO_API_KEY` is unset |
|
|
77
|
+
| `robot_id` | `amr-01` | This machine's id; its own records are not pulled back |
|
|
78
|
+
| `store_name` | `robot-fleet-memory` | Robots sharing a store share memory |
|
|
79
|
+
| `frame_id` | `map` | Coordinate frame of the records |
|
|
80
|
+
| `sync_rate_hz` | `1.0` | Fleet sync frequency (0 turns it off) |
|
|
81
|
+
| `local_ttl_seconds` | `7200.0` | How long a record stays in the local index |
|
|
82
|
+
|
|
83
|
+
## Use it from Python
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
from axonio_ros2 import AxonioClient, SpatialMemoryIndex, SpatialMemoryRecord
|
|
87
|
+
|
|
88
|
+
client = AxonioClient(store_name="warehouse", robot_id="amr_01") # key from AXONIO_API_KEY
|
|
89
|
+
|
|
90
|
+
client.record_spatial_event(
|
|
91
|
+
SpatialMemoryRecord(x=14.5, y=8.2, obstacle_type="pallet_spill", confidence=0.98, tags=["aisle_4"])
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
# Plan against a local index: no network call per query.
|
|
95
|
+
index = SpatialMemoryIndex(memory_ttl_seconds=3600)
|
|
96
|
+
for record in client.pull_fleet_deltas(since_timestamp=0.0):
|
|
97
|
+
index.insert(record)
|
|
98
|
+
|
|
99
|
+
for record, distance in index.query_radius(x=14.0, y=7.5, radius=5.0):
|
|
100
|
+
print(record.obstacle_type, f"{distance:.2f} m")
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
`record_spatial_event` never raises. If Axonio is unreachable the record is queued (up to 1000) and sent before the next call, and `{"status": "offline_cached"}` is returned.
|
|
104
|
+
|
|
105
|
+
### What is stored
|
|
106
|
+
|
|
107
|
+
Each record is one Axonio memory:
|
|
108
|
+
|
|
109
|
+
```
|
|
110
|
+
content pallet spill at (14.50, 8.20, 0.00) in frame map, confidence 0.98, reported by amr_01
|
|
111
|
+
tags axonio-ros2, store:warehouse, obstacle:pallet_spill, robot:amr_01, aisle_4
|
|
112
|
+
metadata x, y, z, frame_id, confidence, recorded_at, robot_id, ...
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Because the content is a sentence, an agent can answer "which aisles were blocked today?" from the same data.
|
|
116
|
+
|
|
117
|
+
`pull_fleet_deltas` and `load_recent` read memories back with Axonio's list call, which returns content and tags but not metadata. They rebuild position, frame, class, confidence, robot id, tags and `notes` from those. Other `metadata` keys you attach are stored and returned by search (`search_nearby`), but not by the list-based sync.
|
|
118
|
+
|
|
119
|
+
### Searching the cloud
|
|
120
|
+
|
|
121
|
+
`client.search_nearby(x, y, radius_meters)` asks Axonio for the memories that best match the place and keeps those inside the radius. Search ranks by meaning, not geometry, so treat it as a lookup for cold starts and dashboards. For a planner loop, fill a `SpatialMemoryIndex` from `pull_fleet_deltas` and query that: about 0.07 ms per radius query with 100,000 records (grid-hashed, measured on a laptop).
|
|
122
|
+
|
|
123
|
+
## Examples
|
|
124
|
+
|
|
125
|
+
`examples/` has a warehouse AMR, a multi-robot fleet and a Nav2 costmap sketch.
|
|
126
|
+
|
|
127
|
+
## Test
|
|
128
|
+
|
|
129
|
+
```bash
|
|
130
|
+
pip install -e ".[dev]" && pytest
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
## License
|
|
134
|
+
|
|
135
|
+
MIT
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# axonio-ros2
|
|
2
|
+
|
|
3
|
+
ROS2 package and Python SDK that give robots a shared, durable spatial memory in [Axonio](https://axonio.xyz). One robot reports an obstacle; every robot in the fleet can plan around it, and it is still there after a restart.
|
|
4
|
+
|
|
5
|
+
It is built on the [`axonio`](https://pypi.org/project/axonio/) Python SDK. Spatial events are stored as ordinary Axonio memories, so they also appear in the dashboard, in search, and to any AI agent connected through the Axonio MCP server.
|
|
6
|
+
|
|
7
|
+
Formerly `clawdb-ros2`.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pip install axonio-ros2 # Python 3.10 or newer (ROS 2 Humble and later)
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Or inside a colcon workspace:
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
cd ~/ros2_ws/src
|
|
19
|
+
git clone https://github.com/hackcat29/axonio-sdk.git
|
|
20
|
+
ln -s axonio-sdk/sdks/ros2 axonio_ros2
|
|
21
|
+
pip install axonio
|
|
22
|
+
cd ~/ros2_ws && colcon build --packages-select axonio_ros2 && source install/setup.bash
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Create an API key in the Axonio dashboard (Robots → Register Robot Node) and export it. The key is never put on the command line or in a ROS parameter, where any node on the DDS domain could read it.
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
export AXONIO_API_KEY="ck_live_..." # or use api_key_file:=/run/secrets/axonio
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Run the bridge node
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
ros2 launch axonio_ros2 memory_bridge.launch.py robot_id:=amr_01
|
|
35
|
+
# or
|
|
36
|
+
ros2 run axonio_ros2 memory_node --ros-args -p robot_id:=amr_01
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
The node writes every obstacle it sees to Axonio, pulls what other robots recorded into a local index at `sync_rate_hz`, and publishes those new records on `~/fleet_updates`.
|
|
40
|
+
|
|
41
|
+
| Topic | Type | |
|
|
42
|
+
|---|---|---|
|
|
43
|
+
| `~/detected_obstacle` (sub) | `geometry_msgs/Point` | A point detection to remember |
|
|
44
|
+
| `~/fleet_updates` (pub) | `std_msgs/String` | JSON list of records new from other robots |
|
|
45
|
+
|
|
46
|
+
| Parameter | Default | |
|
|
47
|
+
|---|---|---|
|
|
48
|
+
| `endpoint` | `""` | Empty for the Axonio cloud, or a self-hosted server URL (`https://`, or `http://localhost`) |
|
|
49
|
+
| `api_key_file` | `""` | File holding the key, used when `AXONIO_API_KEY` is unset |
|
|
50
|
+
| `robot_id` | `amr-01` | This machine's id; its own records are not pulled back |
|
|
51
|
+
| `store_name` | `robot-fleet-memory` | Robots sharing a store share memory |
|
|
52
|
+
| `frame_id` | `map` | Coordinate frame of the records |
|
|
53
|
+
| `sync_rate_hz` | `1.0` | Fleet sync frequency (0 turns it off) |
|
|
54
|
+
| `local_ttl_seconds` | `7200.0` | How long a record stays in the local index |
|
|
55
|
+
|
|
56
|
+
## Use it from Python
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
from axonio_ros2 import AxonioClient, SpatialMemoryIndex, SpatialMemoryRecord
|
|
60
|
+
|
|
61
|
+
client = AxonioClient(store_name="warehouse", robot_id="amr_01") # key from AXONIO_API_KEY
|
|
62
|
+
|
|
63
|
+
client.record_spatial_event(
|
|
64
|
+
SpatialMemoryRecord(x=14.5, y=8.2, obstacle_type="pallet_spill", confidence=0.98, tags=["aisle_4"])
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
# Plan against a local index: no network call per query.
|
|
68
|
+
index = SpatialMemoryIndex(memory_ttl_seconds=3600)
|
|
69
|
+
for record in client.pull_fleet_deltas(since_timestamp=0.0):
|
|
70
|
+
index.insert(record)
|
|
71
|
+
|
|
72
|
+
for record, distance in index.query_radius(x=14.0, y=7.5, radius=5.0):
|
|
73
|
+
print(record.obstacle_type, f"{distance:.2f} m")
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
`record_spatial_event` never raises. If Axonio is unreachable the record is queued (up to 1000) and sent before the next call, and `{"status": "offline_cached"}` is returned.
|
|
77
|
+
|
|
78
|
+
### What is stored
|
|
79
|
+
|
|
80
|
+
Each record is one Axonio memory:
|
|
81
|
+
|
|
82
|
+
```
|
|
83
|
+
content pallet spill at (14.50, 8.20, 0.00) in frame map, confidence 0.98, reported by amr_01
|
|
84
|
+
tags axonio-ros2, store:warehouse, obstacle:pallet_spill, robot:amr_01, aisle_4
|
|
85
|
+
metadata x, y, z, frame_id, confidence, recorded_at, robot_id, ...
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Because the content is a sentence, an agent can answer "which aisles were blocked today?" from the same data.
|
|
89
|
+
|
|
90
|
+
`pull_fleet_deltas` and `load_recent` read memories back with Axonio's list call, which returns content and tags but not metadata. They rebuild position, frame, class, confidence, robot id, tags and `notes` from those. Other `metadata` keys you attach are stored and returned by search (`search_nearby`), but not by the list-based sync.
|
|
91
|
+
|
|
92
|
+
### Searching the cloud
|
|
93
|
+
|
|
94
|
+
`client.search_nearby(x, y, radius_meters)` asks Axonio for the memories that best match the place and keeps those inside the radius. Search ranks by meaning, not geometry, so treat it as a lookup for cold starts and dashboards. For a planner loop, fill a `SpatialMemoryIndex` from `pull_fleet_deltas` and query that: about 0.07 ms per radius query with 100,000 records (grid-hashed, measured on a laptop).
|
|
95
|
+
|
|
96
|
+
## Examples
|
|
97
|
+
|
|
98
|
+
`examples/` has a warehouse AMR, a multi-robot fleet and a Nav2 costmap sketch.
|
|
99
|
+
|
|
100
|
+
## Test
|
|
101
|
+
|
|
102
|
+
```bash
|
|
103
|
+
pip install -e ".[dev]" && pytest
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## License
|
|
107
|
+
|
|
108
|
+
MIT
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Axonio ROS2 SDK: persistent, fleet-wide spatial memory for robots.
|
|
2
|
+
|
|
3
|
+
:license: MIT, see LICENSE for more details.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from .client import AxonioClient, ClawClient, QueryResult, SpatialMemoryRecord
|
|
7
|
+
from .node import AxonioSpatialMemoryNode, ClawSpatialMemoryNode
|
|
8
|
+
from .spatial_index import SpatialMemoryIndex
|
|
9
|
+
|
|
10
|
+
__version__ = "0.5.0"
|
|
11
|
+
__all__ = [
|
|
12
|
+
"AxonioClient",
|
|
13
|
+
"AxonioSpatialMemoryNode",
|
|
14
|
+
"QueryResult",
|
|
15
|
+
"SpatialMemoryIndex",
|
|
16
|
+
"SpatialMemoryRecord",
|
|
17
|
+
# Names used before the rename to Axonio.
|
|
18
|
+
"ClawClient",
|
|
19
|
+
"ClawSpatialMemoryNode",
|
|
20
|
+
]
|
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
"""Axonio client for robots: spatial memories stored in Axonio, with an offline queue.
|
|
2
|
+
|
|
3
|
+
A spatial event (an obstacle, a blocked aisle, a landmark) is stored as an
|
|
4
|
+
ordinary Axonio memory, so it also shows up in the dashboard, in search and for
|
|
5
|
+
any agent connected through the MCP server:
|
|
6
|
+
|
|
7
|
+
* the content is one readable sentence, e.g.
|
|
8
|
+
``pallet spill at (14.50, 8.20, 0.00) in frame map, confidence 0.98, reported by amr_01``
|
|
9
|
+
* the tags carry the store, robot and obstacle class (``store:robot-fleet-memory``,
|
|
10
|
+
``robot:amr_01``, ``obstacle:pallet_spill``)
|
|
11
|
+
* the metadata carries the exact numbers, which search results return
|
|
12
|
+
|
|
13
|
+
``list`` results carry no metadata, so records are also decoded from the
|
|
14
|
+
sentence and tags. Either way a record round-trips.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import logging
|
|
20
|
+
import math
|
|
21
|
+
import re
|
|
22
|
+
import threading
|
|
23
|
+
import time
|
|
24
|
+
from collections import deque
|
|
25
|
+
from dataclasses import asdict, dataclass, field
|
|
26
|
+
from datetime import datetime, timezone
|
|
27
|
+
from typing import Any, Deque, Dict, List, Optional
|
|
28
|
+
from urllib.parse import urlparse
|
|
29
|
+
|
|
30
|
+
logger = logging.getLogger("axonio_ros2.client")
|
|
31
|
+
|
|
32
|
+
BASE_TAG = "axonio-ros2"
|
|
33
|
+
STORE_TAG = "store:"
|
|
34
|
+
ROBOT_TAG = "robot:"
|
|
35
|
+
OBSTACLE_TAG = "obstacle:"
|
|
36
|
+
|
|
37
|
+
_NUM = r"(-?\d+(?:\.\d+)?)"
|
|
38
|
+
_SENTENCE = re.compile(rf"at \({_NUM}, {_NUM}, {_NUM}\) in frame ([^\s,]+), confidence {_NUM}")
|
|
39
|
+
_TAIL = re.compile(r"(?:, reported by \S+?)?(?:\. (.*))?$", re.S)
|
|
40
|
+
_FRACTION = re.compile(r"(\.\d{6})\d+")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class SpatialMemoryRecord:
|
|
45
|
+
"""A spatial memory: an obstacle, landmark or navigation failure at a point."""
|
|
46
|
+
|
|
47
|
+
id: Optional[str] = None
|
|
48
|
+
frame_id: str = "map"
|
|
49
|
+
x: float = 0.0
|
|
50
|
+
y: float = 0.0
|
|
51
|
+
z: float = 0.0
|
|
52
|
+
obstacle_type: str = "general_obstacle"
|
|
53
|
+
confidence: float = 1.0
|
|
54
|
+
tags: List[str] = field(default_factory=list)
|
|
55
|
+
metadata: Dict[str, Any] = field(default_factory=dict)
|
|
56
|
+
timestamp: float = field(default_factory=time.time)
|
|
57
|
+
|
|
58
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
59
|
+
return asdict(self)
|
|
60
|
+
|
|
61
|
+
@classmethod
|
|
62
|
+
def from_dict(cls, data: Dict[str, Any]) -> "SpatialMemoryRecord":
|
|
63
|
+
return cls(
|
|
64
|
+
id=data.get("id"),
|
|
65
|
+
frame_id=data.get("frame_id", "map"),
|
|
66
|
+
x=float(data.get("x", 0.0)),
|
|
67
|
+
y=float(data.get("y", 0.0)),
|
|
68
|
+
z=float(data.get("z", 0.0)),
|
|
69
|
+
obstacle_type=data.get("obstacle_type", "general_obstacle"),
|
|
70
|
+
confidence=float(data.get("confidence", 1.0)),
|
|
71
|
+
tags=list(data.get("tags", [])),
|
|
72
|
+
metadata=dict(data.get("metadata", {})),
|
|
73
|
+
timestamp=float(data.get("timestamp", time.time())),
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
def distance_to(self, x: float, y: float) -> float:
|
|
77
|
+
return math.hypot(self.x - x, self.y - y)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass
|
|
81
|
+
class QueryResult:
|
|
82
|
+
"""Records from a search, with how long the round trip took."""
|
|
83
|
+
|
|
84
|
+
records: List[SpatialMemoryRecord]
|
|
85
|
+
latency_ms: float
|
|
86
|
+
total_count: int
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def describe(record: SpatialMemoryRecord, robot_id: str = "") -> str:
|
|
90
|
+
"""The sentence stored as the memory's content."""
|
|
91
|
+
text = (
|
|
92
|
+
f"{record.obstacle_type.replace('_', ' ')} at ({record.x:.2f}, {record.y:.2f}, {record.z:.2f}) "
|
|
93
|
+
f"in frame {record.frame_id}, confidence {record.confidence:.2f}"
|
|
94
|
+
)
|
|
95
|
+
if robot_id:
|
|
96
|
+
text += f", reported by {robot_id}"
|
|
97
|
+
notes = str(record.metadata.get("notes", "")).strip()
|
|
98
|
+
if notes:
|
|
99
|
+
text += f". {notes}"
|
|
100
|
+
return text
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def build_tags(record: SpatialMemoryRecord, store_name: str, robot_id: str = "") -> List[str]:
|
|
104
|
+
tags = [BASE_TAG, STORE_TAG + store_name, OBSTACLE_TAG + record.obstacle_type]
|
|
105
|
+
if robot_id:
|
|
106
|
+
tags.append(ROBOT_TAG + robot_id)
|
|
107
|
+
for tag in record.tags:
|
|
108
|
+
if tag not in tags:
|
|
109
|
+
tags.append(tag)
|
|
110
|
+
return tags
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _tag_value(tags: List[str], prefix: str) -> Optional[str]:
|
|
114
|
+
for tag in tags:
|
|
115
|
+
if tag.startswith(prefix):
|
|
116
|
+
return tag[len(prefix):]
|
|
117
|
+
return None
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _parse_time(value: str) -> Optional[float]:
|
|
121
|
+
if not value:
|
|
122
|
+
return None
|
|
123
|
+
try:
|
|
124
|
+
return datetime.fromisoformat(_FRACTION.sub(r"\1", value).replace("Z", "+00:00")).astimezone(timezone.utc).timestamp()
|
|
125
|
+
except ValueError:
|
|
126
|
+
return None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def decode_memory(
|
|
130
|
+
memory_id: str,
|
|
131
|
+
content: str,
|
|
132
|
+
tags: List[str],
|
|
133
|
+
store_name: str,
|
|
134
|
+
metadata: Optional[Dict[str, Any]] = None,
|
|
135
|
+
created_at: str = "",
|
|
136
|
+
) -> Optional[SpatialMemoryRecord]:
|
|
137
|
+
"""Turn an Axonio memory back into a spatial record, or None if it is not one
|
|
138
|
+
of ours (a different store, or an ordinary memory)."""
|
|
139
|
+
if BASE_TAG not in tags or (STORE_TAG + store_name) not in tags:
|
|
140
|
+
return None
|
|
141
|
+
|
|
142
|
+
# Search results nest the stored metadata one level down.
|
|
143
|
+
meta: Dict[str, Any] = dict(metadata or {})
|
|
144
|
+
if isinstance(meta.get("metadata"), dict):
|
|
145
|
+
meta = dict(meta["metadata"])
|
|
146
|
+
|
|
147
|
+
obstacle = meta.get("obstacle_type") or _tag_value(tags, OBSTACLE_TAG) or "general_obstacle"
|
|
148
|
+
try:
|
|
149
|
+
if all(k in meta for k in ("x", "y")):
|
|
150
|
+
x, y, z = float(meta["x"]), float(meta["y"]), float(meta.get("z", 0.0))
|
|
151
|
+
frame = str(meta.get("frame_id", "map"))
|
|
152
|
+
confidence = float(meta.get("confidence", 1.0))
|
|
153
|
+
else:
|
|
154
|
+
found = _SENTENCE.search(content)
|
|
155
|
+
if not found:
|
|
156
|
+
return None
|
|
157
|
+
x, y, z = float(found.group(1)), float(found.group(2)), float(found.group(3))
|
|
158
|
+
frame = found.group(4)
|
|
159
|
+
confidence = float(found.group(5))
|
|
160
|
+
tail = _TAIL.match(content[found.end():])
|
|
161
|
+
if tail and tail.group(1):
|
|
162
|
+
meta["notes"] = tail.group(1)
|
|
163
|
+
except (TypeError, ValueError):
|
|
164
|
+
return None
|
|
165
|
+
|
|
166
|
+
recorded = meta.get("recorded_at")
|
|
167
|
+
timestamp = float(recorded) if isinstance(recorded, (int, float)) else (_parse_time(created_at) or time.time())
|
|
168
|
+
extra = {k: v for k, v in meta.items() if k not in {"x", "y", "z", "frame_id", "obstacle_type", "confidence", "recorded_at"}}
|
|
169
|
+
robot = _tag_value(tags, ROBOT_TAG)
|
|
170
|
+
if robot and "robot_id" not in extra:
|
|
171
|
+
extra["robot_id"] = robot
|
|
172
|
+
user_tags = [t for t in tags if t != BASE_TAG and not t.startswith((STORE_TAG, ROBOT_TAG, OBSTACLE_TAG))]
|
|
173
|
+
return SpatialMemoryRecord(
|
|
174
|
+
id=memory_id or None,
|
|
175
|
+
frame_id=frame,
|
|
176
|
+
x=x,
|
|
177
|
+
y=y,
|
|
178
|
+
z=z,
|
|
179
|
+
obstacle_type=str(obstacle),
|
|
180
|
+
confidence=confidence,
|
|
181
|
+
tags=user_tags,
|
|
182
|
+
metadata=extra,
|
|
183
|
+
timestamp=timestamp,
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
class AxonioClient:
|
|
188
|
+
"""Reads and writes a robot fleet's spatial memory in Axonio.
|
|
189
|
+
|
|
190
|
+
Authentication: ``api_key``, else ``AXONIO_API_KEY`` (``CLAWDB_API_KEY`` still
|
|
191
|
+
works). With only a key the client talks to the hosted Axonio cloud; pass
|
|
192
|
+
``endpoint`` for a self-hosted server. Writes that fail (no network) are
|
|
193
|
+
queued, up to ``max_pending``, and retried before the next call.
|
|
194
|
+
"""
|
|
195
|
+
|
|
196
|
+
def __init__(
|
|
197
|
+
self,
|
|
198
|
+
api_key: Optional[str] = None,
|
|
199
|
+
endpoint: Optional[str] = None,
|
|
200
|
+
store_name: str = "robot-fleet-memory",
|
|
201
|
+
robot_id: str = "",
|
|
202
|
+
timeout_seconds: float = 2.0,
|
|
203
|
+
max_pending: int = 1000,
|
|
204
|
+
workspace_id: Optional[str] = None,
|
|
205
|
+
db: Any = None,
|
|
206
|
+
) -> None:
|
|
207
|
+
if endpoint:
|
|
208
|
+
parsed = urlparse(endpoint)
|
|
209
|
+
# The API key is a bearer credential: never send it over plain HTTP,
|
|
210
|
+
# except to a development server on this machine.
|
|
211
|
+
if parsed.scheme != "https" and parsed.hostname not in ("localhost", "127.0.0.1", "::1"):
|
|
212
|
+
raise ValueError("Axonio endpoint must use https:// (plain http is only allowed for localhost)")
|
|
213
|
+
self.api_key = api_key or ""
|
|
214
|
+
self.endpoint = endpoint.rstrip("/") if endpoint else None
|
|
215
|
+
self.store_name = store_name
|
|
216
|
+
self.robot_id = robot_id
|
|
217
|
+
self.timeout = timeout_seconds
|
|
218
|
+
# Informational only: the API key already identifies the workspace.
|
|
219
|
+
self.workspace_id = workspace_id
|
|
220
|
+
self._db = db
|
|
221
|
+
self._lock = threading.RLock()
|
|
222
|
+
self._pending: Deque[SpatialMemoryRecord] = deque(maxlen=max_pending)
|
|
223
|
+
|
|
224
|
+
# -- connection ---------------------------------------------------------
|
|
225
|
+
|
|
226
|
+
def _client(self) -> Any:
|
|
227
|
+
with self._lock:
|
|
228
|
+
if self._db is None:
|
|
229
|
+
from axonio import ClawDB
|
|
230
|
+
|
|
231
|
+
options: Dict[str, Any] = {"timeout_ms": int(self.timeout * 1000)}
|
|
232
|
+
if self.api_key:
|
|
233
|
+
options["api_key"] = self.api_key
|
|
234
|
+
if self.endpoint:
|
|
235
|
+
options["endpoint"] = self.endpoint
|
|
236
|
+
if self.robot_id:
|
|
237
|
+
options["agent_id"] = self.robot_id
|
|
238
|
+
self._db = ClawDB(**options)
|
|
239
|
+
return self._db
|
|
240
|
+
|
|
241
|
+
def close(self) -> None:
|
|
242
|
+
with self._lock:
|
|
243
|
+
if self._db is not None:
|
|
244
|
+
try:
|
|
245
|
+
self._db.disconnect()
|
|
246
|
+
except Exception: # noqa: BLE001 - shutting down
|
|
247
|
+
pass
|
|
248
|
+
self._db = None
|
|
249
|
+
|
|
250
|
+
@property
|
|
251
|
+
def pending_count(self) -> int:
|
|
252
|
+
return len(self._pending)
|
|
253
|
+
|
|
254
|
+
# -- writes -------------------------------------------------------------
|
|
255
|
+
|
|
256
|
+
def _store(self, record: SpatialMemoryRecord) -> str:
|
|
257
|
+
meta: Dict[str, Any] = {
|
|
258
|
+
**record.metadata,
|
|
259
|
+
"x": record.x,
|
|
260
|
+
"y": record.y,
|
|
261
|
+
"z": record.z,
|
|
262
|
+
"frame_id": record.frame_id,
|
|
263
|
+
"obstacle_type": record.obstacle_type,
|
|
264
|
+
"confidence": record.confidence,
|
|
265
|
+
"recorded_at": record.timestamp,
|
|
266
|
+
}
|
|
267
|
+
if self.robot_id:
|
|
268
|
+
meta.setdefault("robot_id", self.robot_id)
|
|
269
|
+
return self._client().memory.remember(
|
|
270
|
+
describe(record, self.robot_id),
|
|
271
|
+
memory_type="spatial",
|
|
272
|
+
tags=build_tags(record, self.store_name, self.robot_id),
|
|
273
|
+
metadata=meta,
|
|
274
|
+
)
|
|
275
|
+
|
|
276
|
+
def flush_pending(self) -> int:
|
|
277
|
+
"""Retry queued writes, oldest first. Returns how many were stored."""
|
|
278
|
+
stored = 0
|
|
279
|
+
with self._lock:
|
|
280
|
+
while self._pending:
|
|
281
|
+
record = self._pending[0]
|
|
282
|
+
try:
|
|
283
|
+
record.id = self._store(record)
|
|
284
|
+
except Exception as exc: # noqa: BLE001 - still offline
|
|
285
|
+
logger.debug("flush stopped, still offline: %s", exc)
|
|
286
|
+
break
|
|
287
|
+
self._pending.popleft()
|
|
288
|
+
stored += 1
|
|
289
|
+
return stored
|
|
290
|
+
|
|
291
|
+
def record_spatial_event(self, record: SpatialMemoryRecord) -> Dict[str, Any]:
|
|
292
|
+
"""Store a spatial memory. Never raises: on a network failure the record is
|
|
293
|
+
queued and ``{"status": "offline_cached"}`` is returned."""
|
|
294
|
+
started = time.perf_counter()
|
|
295
|
+
try:
|
|
296
|
+
self.flush_pending()
|
|
297
|
+
record.id = self._store(record)
|
|
298
|
+
except Exception as exc: # noqa: BLE001 - robots keep running offline
|
|
299
|
+
logger.warning("Could not store spatial memory in Axonio, queued for retry: %s", exc)
|
|
300
|
+
with self._lock:
|
|
301
|
+
self._pending.append(record)
|
|
302
|
+
return {"status": "offline_cached", "error": str(exc), "pending": self.pending_count}
|
|
303
|
+
return {"status": "stored", "id": record.id, "latency_ms": (time.perf_counter() - started) * 1000.0}
|
|
304
|
+
|
|
305
|
+
# -- reads --------------------------------------------------------------
|
|
306
|
+
|
|
307
|
+
def search_nearby(
|
|
308
|
+
self,
|
|
309
|
+
x: float,
|
|
310
|
+
y: float,
|
|
311
|
+
radius_meters: float = 5.0,
|
|
312
|
+
frame_id: str = "map",
|
|
313
|
+
limit: int = 10,
|
|
314
|
+
) -> QueryResult:
|
|
315
|
+
"""Spatial memories within ``radius_meters`` of (x, y), nearest first.
|
|
316
|
+
|
|
317
|
+
Search is by meaning, not by geometry: the server returns the closest
|
|
318
|
+
matches to a description of the place and this method keeps the ones
|
|
319
|
+
actually inside the radius. For exact radius queries on a hot path, keep a
|
|
320
|
+
:class:`~axonio_ros2.SpatialMemoryIndex` filled with
|
|
321
|
+
:meth:`load_recent` and :meth:`pull_fleet_deltas`.
|
|
322
|
+
"""
|
|
323
|
+
started = time.perf_counter()
|
|
324
|
+
try:
|
|
325
|
+
hits = self._client().memory.search(
|
|
326
|
+
f"obstacle near ({x:.2f}, {y:.2f}) in frame {frame_id}", top_k=min(100, max(limit * 5, 20))
|
|
327
|
+
)
|
|
328
|
+
except Exception as exc: # noqa: BLE001
|
|
329
|
+
logger.warning("Could not query Axonio: %s", exc)
|
|
330
|
+
return QueryResult([], (time.perf_counter() - started) * 1000.0, 0)
|
|
331
|
+
|
|
332
|
+
found: List[SpatialMemoryRecord] = []
|
|
333
|
+
for hit in hits:
|
|
334
|
+
rec = decode_memory(hit.id, hit.content, hit.tags, self.store_name, hit.metadata)
|
|
335
|
+
if rec and rec.frame_id == frame_id and rec.distance_to(x, y) <= radius_meters:
|
|
336
|
+
found.append(rec)
|
|
337
|
+
found.sort(key=lambda r: r.distance_to(x, y))
|
|
338
|
+
found = found[:limit]
|
|
339
|
+
return QueryResult(found, (time.perf_counter() - started) * 1000.0, len(found))
|
|
340
|
+
|
|
341
|
+
def load_recent(self, limit: int = 100, since_timestamp: float = 0.0) -> List[SpatialMemoryRecord]:
|
|
342
|
+
"""The newest spatial memories of this store, optionally only those created
|
|
343
|
+
after ``since_timestamp`` (seconds since the epoch)."""
|
|
344
|
+
try:
|
|
345
|
+
memories = self._client().memory.list(limit=limit)
|
|
346
|
+
except Exception as exc: # noqa: BLE001
|
|
347
|
+
logger.warning("Could not list Axonio memories: %s", exc)
|
|
348
|
+
return []
|
|
349
|
+
records: List[SpatialMemoryRecord] = []
|
|
350
|
+
for mem in memories:
|
|
351
|
+
rec = decode_memory(mem.id, mem.content, mem.tags, self.store_name, created_at=mem.created_at)
|
|
352
|
+
if rec and rec.timestamp > since_timestamp:
|
|
353
|
+
records.append(rec)
|
|
354
|
+
return records
|
|
355
|
+
|
|
356
|
+
def pull_fleet_deltas(self, since_timestamp: float, limit: int = 100) -> List[SpatialMemoryRecord]:
|
|
357
|
+
"""Memories written by the other robots in the fleet since ``since_timestamp``.
|
|
358
|
+
This robot's own records are left out."""
|
|
359
|
+
return [
|
|
360
|
+
rec
|
|
361
|
+
for rec in self.load_recent(limit=limit, since_timestamp=since_timestamp)
|
|
362
|
+
if not (self.robot_id and rec.metadata.get("robot_id") == self.robot_id)
|
|
363
|
+
]
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
#: Name used before the rename to Axonio.
|
|
367
|
+
ClawClient = AxonioClient
|