ROS is excellent middleware for high-level robotics components, but it's the wrong tool at the hardware boundary. Solutions like microROS pull a full ROS dependency onto the microcontroller, which bloats firmware, complicates debugging, and tightly couples low-level drivers to application-specific code.
xBot Framework solves this with a small, independent protocol for talking to sensors and actuators — no ROS dependency required on the device. It's the hardware layer powering OpenMower, running in production on real mowers today.
- Service-Based Architecture: Low-level features (sensors, actuators) are implemented as services, described by a JSON interface and implemented as C++ classes. Services run identically on a microcontroller or on Linux — the same code, the same protocol, no porting layer.
- Hardware Communication Simplified: Define a service in JSON and the code generator produces the C++ boilerplate for talking to ESCs, IMUs, GPIOs, and other hardware.
- Lightweight and Portable: Minimal dependencies, zero dynamic memory allocation. Built for microcontrollers, runs just as well on Linux.
- Service Discovery: Services advertise themselves automatically over UDP multicast — no manual wiring to connect low-level services to high-level application code.
- Runtime:
- REST API: Discover services programmatically. Stable. Port 18080, optional — pass
start_rest_api=truetoStart(). - Firmware Update: Flash firmware directly through the built-in Ethernet bootloader. Stable, used in production.
- Web UI: Visually explore devices, monitor data, and test actuators. Planned.
- REST API: Discover services programmatically. Stable. Port 18080, optional — pass
- Performant Serialization: Data is transmitted schemaless and binary-packed for low traffic and fast serialization.
This repository contains all parts of the xbot_framework.
Use this library to provide a service to the system. An example would be publishing IMU data or providing motor control services. The library will take care of advertising your service and connecting to the runtime.
Use libxbot-service-interface to connect to a specific service. For example if there is an IMU service on your network, and you want to receive its data (or bridge to ROS), include libxbot-service-interface in your project to use your services.
Files in this directory are needed on both sides (service and service interface). E.g. message header definitions.
This folder contains the code generation part of the xbot_framework. Code generation is done from service.json
files which describe inputs, outputs, registers and enums of services.
The code generator will generate callbacks for inputs and sending methods for the outputs. It will also generate all code necessary for service discovery and configuration.
All dependencies are included here as submodules. Not every dependency is needed by every part of the software.
Python service interface — connect to xBot services from Python without any code generation. See Python Interface below for a summary, or the package README for full details.
Go service interface — discovery, claim, RPC calls and DATA messages from Go, without any code generation. See Go Interface below for a summary, or the package README for full details.
All communication uses UDP. Every packet begins with a fixed 24-byte header (XbotHeader), followed by a
message-specific payload.
| Offset | Size | Field | Notes |
|---|---|---|---|
| 0 | 1 | protocol_version | Currently 1 |
| 1 | 1 | message_type | See message type table below |
| 2 | 1 | flags | Bit 0: reboot flag (set on boot, cleared on seq rollover) |
| 3 | 1 | reserved1 | |
| 4 | 2 | service_id | Identifies the service |
| 6 | 1 | arg1 | Message-specific (see table below) |
| 7 | 1 | reserved2 | |
| 8 | 2 | arg2 | Message-specific (see table below) |
| 10 | 2 | sequence_no | Increments per message; rollover clears reboot flag |
| 12 | 8 | timestamp | Unix timestamp in microseconds |
| 20 | 4 | payload_size | Byte length of payload following the header |
| Value | Name | arg1 | arg2 | Payload |
|---|---|---|---|---|
0x00 |
UNKNOWN | — | — | — |
0x01 |
DATA | — | target_id |
Raw value bytes |
0x02 |
CONFIGURATION_REQUEST | — | — | Empty |
0x03 |
CLAIM | 0=request, 1=ack |
— | ClaimPayload (request) or empty (ack) |
0x04 |
HEARTBEAT | — | — | Empty |
0x05 |
TRANSACTION | 0=data, 1=configuration |
— | Sequence of DataDescriptor+payload |
0x7F |
LOG | log level (1–7) | — | UTF-8 string (max 255 bytes) |
0x80 |
SERVICE_ADVERTISEMENT | — | — | CBOR-encoded service JSON |
0x81 |
SERVICE_QUERY | — | — | — |
0x82 |
DESCRIPTION_REQUEST | offset into the omitted desc | max_size |
DescriptionRequestPayload (ip:port) |
0x83 |
DESCRIPTION_PART | offset into the omitted desc | total_size |
Window of the omitted description |
DESCRIPTION_REQUEST is sent unicast by a host that needs the part of the schema the
advertisement could not carry (see Service description below); the service answers with one
DESCRIPTION_PART window and the host repeats until offset + payload_size >= total. A
service whose whole schema fits into one advertisement reports size 0 and ignores the
request.
A TRANSACTION payload is a sequence of chunks, each preceded by a DataDescriptor:
DataDescriptor (8 bytes, packed):
| Offset | Size | Field |
|---|---|---|
| 0 | 2 | target_id |
| 2 | 2 | reserved |
| 4 | 4 | payload_size |
Chunks are read sequentially until payload_size bytes of the transaction are consumed.
Sent by the interface as the payload of a CLAIM message:
| Offset | Size | Field | Notes |
|---|---|---|---|
| 0 | 4 | target_ip | Interface IP (network byte order) |
| 4 | 2 | target_port | Interface UDP port |
| 6 | 4 | heartbeat_micros | Requested heartbeat interval |
Service discovery uses UDP multicast.
| Parameter | Value |
|---|---|
| Multicast address | 233.255.255.0 |
| Port | 4242 |
| Message type | SERVICE_ADVERTISEMENT (0x80) |
Advertisement payload: CBOR-encoded JSON with the following structure:
{
"sid": 1,
"endpoint": { "ip": "192.168.1.10", "port": 12345 },
"desc": {
"type": "EchoService",
"version": 1,
"inputs": [{ "id": 0, "name": "InputText", "type": "char[100]" }],
"outputs": [{ "id": 0, "name": "Echo", "type": "char[100]" }]
}
}Advertisement rate:
- Fast: every 1 second while unclaimed
- Slow: every 10 seconds after being claimed
Discovery flow:
- Service broadcasts
SERVICE_ADVERTISEMENTon233.255.255.0:4242. - Interface listens on that multicast group and fires
OnServiceDiscovered. - Interface sends unicast
CLAIM(withClaimPayload) to the service's reported endpoint. - Service stops, loads defaults, sends
CLAIMack (arg1=1, empty payload). - If the service has registers, it sends
CONFIGURATION_REQUESTevery second until it receives configuration. - Interface responds with a
TRANSACTION(arg1=1) containing register values asDataDescriptor-framed chunks. - Service validates all required registers and calls
OnStart(). - Service sends
HEARTBEATat half the requested heartbeat interval. Interface drops the service afterheartbeat_micros + 100mswithout a heartbeat.
Remote logging uses UDP multicast.
| Parameter | Value |
|---|---|
| Multicast address | 233.255.255.1 |
| Port | 4242 |
| Message type | LOG (0x7F) |
Payload: UTF-8 string, max 255 bytes. When a service_id context is available the message is prefixed as [ID=X] message.
Log levels (arg1):
| arg1 | Level |
|---|---|
| 1 | TRACE |
| 2 | DEBUG |
| 3 | INFO |
| 4 | WARNING |
| 5 | ERROR |
| 6 | CRITICAL |
| 7 | ALWAYS |
Enable on the service side by calling xbot::service::startRemoteLogging(level). The interface-side RemoteLoggingReceiverImpl joins the multicast group automatically when Start() is called.
Services are defined in a JSON file. The code generator (codegen/) reads this file and generates a {ServiceName}Base C++ class.
{
"type": "EchoService",
"version": 1,
"inputs": [
{ "id": 0, "name": "InputText", "type": "char[100]" }
],
"outputs": [
{ "id": 0, "name": "Echo", "type": "char[100]" },
{ "id": 1, "name": "MessageCount", "type": "uint32_t" }
],
"registers": [
{ "id": 0, "name": "Prefix", "type": "char[42]", "default": "hello", "default_length": 5 },
{ "id": 1, "name": "EchoCount", "type": "uint32_t", "default": 0 },
{ "id": 2, "name": "BlobData", "type": "blob" },
{ "id": 3, "name": "Optional", "type": "uint32_t", "optional": true }
],
"enums": [
{
"id": "MyEnum", "base_type": "uint8_t",
"values": { "A": 0, "B": 1 }
},
{
"id": "MyFlags", "base_type": "uint8_t", "bitmask": true,
"values": { "FLAG_A": 0, "FLAG_B": 1 }
}
]
}Valid types: char, uint8_t, uint16_t, uint32_t, uint64_t, int8_t, int16_t, int32_t, int64_t, float, double, blob (registers, inputs, outputs, RPC parameters and RPC return values), string (RPC parameters and RPC return values), or fixed-length arrays of any scalar type as type[N].
blob is variable length: as a parameter it is passed as (pointer, length) into the received packet and is
not copied, as an input or output it is passed/sent as (pointer, length) with the length in bytes, as a
register it is the configuration blob, and as a return value it uses the shared buffer pool
(see Shared Buffer Pool). A type[N] return above 128 bytes is pooled the same way, so a
service never reserves stack for a payload it rarely sends. A blob output is bounded by one packet as well:
Send{Name}() returns false for more than 1448 bytes instead of sending a packet without its body.
string carries text and keeps the C string handling out of the service: the schema declares a max_length,
the wire carries the UTF-8 bytes without a terminator (the same layout as blob), and the generated server
decodes it into a checked, always terminated char[max_length + 1] before it calls the handler - a longer
payload is answered with RpcStatus::ERROR instead of being shortened. The handler gets const char* plus the
byte count and can hand it to LittleFS, printf or a parser without copying or truncating. A return gets a
zero-filled buffer of max_length + 1 bytes: the handler writes its text and sends it with
SendRpcResponse(call_id, RpcStatus::SUCCESS, data, strlen(data)) - like every return value it is sent by the
handler, never by the dispatcher, and the terminator stays local. Clients get std::string (C++), string (Go)
and str (Python), and refuse a value above max_length before sending.
The dispatcher reserves max_length + 1 bytes of stack for the call, so max_length is capped at one packet body
minus a descriptor (1440 bytes) and the working area of the service has to be sized for it - the thread watermark
shows what a service really uses. The parameters of one function also have to fit into one packet together: the
generators add up a descriptor (8 bytes) plus the largest payload of every fixed size, array and string
parameter and reject a function that needs more than 1448 bytes. Two 1440 byte strings could never be sent in
one call, but would reserve 2882 bytes of stack. A blob parameter only counts with its descriptor.
A string may contain U+0000: the terminator is a convenience for C APIs, so a handler that can pass the value on to printf, LittleFS or a parser and wants the whole value has to use the byte count (<Name>Len) instead of assuming the text ends at the first NUL.
{ "id": 3, "name": "PlayMp3", "return_type": "uint8_t",
"parameters": [ { "id": 0, "name": "Path", "type": "string", "max_length": 128 } ] }A char[N] parameter with the same limit costs one byte less stack, but it is only terminated when the payload
is shorter than N - a value that fills all N bytes arrives without a terminator.
Switching a parameter or return from a fixed type[N] to blob changes its wire layout, so the service needs a
version bump ("version": 2). Generated clients refuse a mismatch instead of sending a call with the wrong
layout: the C++ and Python clients always compare against the schema they were given, the Go client compares
only when ExpectVersion is set (generated clients set it, a hand-written one has to do the same). Service and
clients have to be updated together.
Moving a blob text parameter to string keeps the wire layout, so it needs no bump - as long as the new max_length accepts every value the old blob accepted. A limit that rejects values which used to work is a behavioural change (the client gets an error where it used to send a call), so that one needs the version bump.
IDs must be unique within each section (inputs, outputs, registers).
Generated API (service side):
void On{Name}Changed(const T* value, uint32_t length)— called when an input arrives (array types)void On{Name}Changed(const T& value)— called when an input arrives (scalar types)void On{Name}Changed(const uint8_t* value, uint32_t length)— called when a blob input arrives,lengthin bytesbool Send{Name}(const T* data, uint32_t length)— send an output (array types)bool Send{Name}(const T& data)— send an output (scalar types)bool Send{Name}(const uint8_t* data, uint32_t length)— send a blob output,lengthin bytesbool OnRegister{Name}Changed(const void* data, size_t length)— called when a register is set (blob registers)- Struct
{Name}withvalue,length(arrays), andvalidfields — for non-blob registers void RPC{Name}(uint16_t call_id, ...)— one pure virtual per function; ablobparameter arrives asconst uint8_t* <Name>, uint32_t <Name>Lenand is only valid until the handler returns (copy it if you need it longer)- A
type[N],stringorblobreturn appendsT* data, uint16_t* response_length: a zero-filled buffer and its capacity. Ablobreturn is alwaysuint8_t, astringreturnchar, atype[N]return uses its element type;*response_lengthis a byte count forblobandstring(without the terminator) and an element count fortype[N] - The handler answers every call itself with
SendRpcResponse(call_id, status, data, size_in_bytes). The dispatcher never sends a return value and does not read*response_lengthback, so a handler that returns without answering leaves the call pending and the service answers BUSY from then on
Generated API (interface side — same JSON, different template):
- Inputs and outputs swap roles: outputs become callbacks, inputs become send methods.
- Every
blobparameter gets a frame budget helper, e.g.MaxFileWriteData(PathLen)in C++ andMaxFileWriteData(Path []byte)in Go: how many bytes the parameter can carry in one call, with the other blob parameters as arguments. Chunking a value needs exactly that number, and the framing that limits it belongs to the generator, not to every client. The helpers saturate: a call whose other parameters already use up the packet reports 0, so a chunker has to stop instead of sending. Every chunk ismin(bytes left, budget)long - the budget is an upper bound, only the last chunk is shorter. Astringparameter gets the same helper, capped at itsmax_length: the call refuses a longer value even when the packet has room for it. - A call, an input or a transaction that does not fit into one packet is refused before it is sent
(
Call{Name}()/Send{Name}()returnfalsein C++, an error in Go,ValueErrorin Python). The services drop an oversized datagram without an answer, which would look like a timeout or a lost value. - The C++
Call{Name}()methods returnbool.GetLastRpcResult()tells the reasons apart:RPC_BUSY: the service refused the call for now (another call in progress, or no free block in its buffer pool). It did not run the call, so the call can be sent again.RPC_TIMEOUT: no answer came. The outcome is unknown: the request may have been lost, or the service ran the call and the answer was lost. Sending it again is only safe for a call that does no harm when it runs twice.RPC_ERROR: everything else, such as a service that is not discovered (yet), an error answer, or a call the method refuses itself (an argument over its limit, an answer of the wrong size).
CMake integration:
# Service side
include(${XBOT_CODEGEN_PATH}/cmake/AddService.cmake)
target_add_service(MyTarget MyServiceName path/to/service.json)
# Interface side
include(${XBOT_CODEGEN_PATH}/cmake/AddServiceInterface.cmake)
target_add_service_interface(MyTarget MyInterfaceName path/to/service.json)Then inherit from the generated MyServiceNameBase or MyInterfaceNameBase class.
An RPC return value is limited by max_packet_size - sizeof(XbotHeader) = 1448 bytes, but a service
thread stack is much smaller. Array return values above a small threshold therefore do not live on
the stack (that is what used to force the fixed size of a transfer type); the generated dispatcher
borrows a block from a pool that all services share:
#include <xbot-service/Buffer.hpp>
auto lease = xbot::service::buffer::acquire(required_bytes);
if (!lease) {
SendRpcResponse(call_id, xbot::datatypes::RpcStatus::BUSY, nullptr, 0);
return;
}
fill(lease.data(), lease.size()); // lease.size() is the capacity, not the request
SendRpcResponse(call_id, xbot::datatypes::RpcStatus::SUCCESS, lease.data(), used_bytes);A block is handed out as the previous owner left it. The generated dispatcher clears the bytes it passes
to a handler, so a pooled return buffer is zero-filled like one on the stack; code that calls acquire()
itself has to clear what it does not overwrite before it sends it.
Rules that keep the pool usable:
- A lease is move-only and returns its block in the destructor. Do not keep it beyond the call that borrowed it: the pool is shared by all services, and a lease held across a flash operation or across RPCs starves the next caller.
- A return value that the framework took from the pool (a
blob, a large array, a largestring) is only valid until the handler returns.SendRpcResponse()has to be called from inside the handler; a deferred response would point at a block that is already released and may have been handed to another service by then. acquire()is non-blocking on purpose. It returns an empty lease when every block is out, when no storage has been configured yet, and when the request is larger than a block; a handler that follows the pattern above answers BUSY in all three cases - an RPC handler must never wait for another service's transfer. With the default of two blocks, one outstanding return does not exhaust the pool.- The generated dispatcher borrows the block before it calls the handler and returns it after the handler
returned (
SendRpcResponse()copies the payload into a packet). A block is therefore out for as long as the handler runs: a handler that does slow work before it answers keeps it for that time, andbuffer_block_counthas to cover the pooled calls that can be in their handlers at once. - A caller sees an exhausted pool as
RpcStatus::BUSYand can repeat the call (RpcBusyErrorin Python,*xbot.RPCErrorin Go,GetLastRpcResult() == RPC_BUSYin C++). - No heap is involved: the storage is static.
An existing schema is affected as well: a type[N] return above 128 bytes used to live on the stack of
its service and now comes from the pool. Its wire format is unchanged, but such a call can answer BUSY
where it could not before, and it needs a pool - check the block count when updating a firmware with
several of them.
Sizing is a platform decision. xbot::config::buffer_block_size (1536 by default, must hold one
packet payload - asserted at build time) and buffer_block_count (2) only size the framework
internal default storage. A platform that brings its own storage - e.g. a section in a RAM region
that is otherwise unused - calls
alignas(xbot::service::buffer::block_alignment) uint8_t storage[2 * 1536]
__attribute__((section(".sram4")));
xbot::service::buffer::initialize(storage, 1536, 2);once, before the services start, and sets XBOT_BUFFER_DEFAULT_POOL=0 so the default array is not
linked in at all. initialize() is not thread safe and refuses to run while a lease is out. It also
refuses blocks below xbot::service::buffer::min_block_size (one packet payload, 1448 bytes): the
generated dispatchers borrow up to that much, and a pool that cannot serve it would answer BUSY forever.
XBOT_BUFFER_DEFAULT_POOL, XBOT_BUFFER_BLOCK_SIZE and XBOT_BUFFER_BLOCK_COUNT are compiled into the
xbot-service library, so set them as CMake variables (-DXBOT_BUFFER_DEFAULT_POOL=0, or set() before
add_subdirectory): they are then defined for the library and for everything that links it. A definition
on the application target alone does not reach the library, and the default array stays. Without a pool -
the default one disabled and initialize() not called - every pooled call is answered with BUSY and the
first one logs a warning.
Parameters hit the same stack limit from the other direction: a fixed type[N] parameter is copied into a
stack array by the generated dispatcher, which is why a variable length payload had to be declared as
e.g. uint8_t[256]. A blob parameter is passed as (pointer, length) into the received packet instead -
the contract handleData() and setRegister() already use - so it costs no stack and no copy, and its
length is only bounded by one packet. The generated dispatcher takes returns above 128 bytes and blob
returns from the pool; small returns stay on the stack, so the pool is not touched in the hot path.
xbot_service_interface_py is a pure-Python client for xBot services — no codegen step required. It talks directly
to the wire protocol described above, so it's a good fit for scripting, quick prototyping, ROS bridges, or driving
services from Jupyter/IPython.
Two ways to use a service:
- Schema provided: pass a
service.jsonfile (or dict) toServiceInterface. The schema is validated against the service's advertisement on connect, and anIncompatibleServiceErroraborts the connection on a mismatch. - Schema-free: omit the schema entirely. The advertisement carries as much of the schema as fits
into one UDP packet; a service whose schema is bigger lists the blocks it had to leave out under
omitted- any ofenums,functions,registers,outputs,inputs, whatever did not fit. The client fetches those blocks withDESCRIPTION_REQUEST/DESCRIPTION_PARTright after discovery (unicast, one round trip per window) and caches them per(service id, version). Hosts with generated classes never fetch: they know the types.
from xbot_service_interface import XbotServiceIo, ServiceInterface
xbot = XbotServiceIo(bind_ip='0.0.0.0')
echo = ServiceInterface(service_id=1, schema='echo_service.json')
xbot.register(echo)
@echo.on_connected
def connected():
echo.registers['Prefix'] = "py: "
@echo.on_echo_changed
def got_echo(value: str, timestamp: int):
print(f"echo: {value!r}")
xbot.start()Beyond the core send/receive/register API, the package includes:
- RPC calls — synchronous
call_{name}(*args, timeout_ms=...)with typed exceptions (RpcTimeoutError,RpcBusyError,RpcError). - Atomic transactions — bundle multiple sends into one UDP packet via
with iface.transaction(): .... xbot-shell— an IPython-based interactive shell (pip install "xbot-service-interface-py[shell]") with tab-completable service proxies, aservices()discovery table, live output streaming (svc.watch_all()), and an interactive register configuration wizard.xbot-logs— a CLI remote log viewer for theLOGmulticast stream, filterable by level.
Install from a tagged release:
pip install "xbot-service-interface-py @ git+https://github.com/xtech/xbot_framework.git@v1.0.0#subdirectory=xbot_service_interface_py"Requires Python 3.10+. Full API reference, type mapping table, and shell walkthrough in the package README.
xbot_service_interface_go is a Go client for the same protocol — no code generation, no cgo, one dependency
(fxamacker/cbor for the discovery payloads). It covers what a small tool or bridge needs: discovery, claim,
RPC calls and DATA messages.
# in your module
go get github.com/xtech/xbot_framework/xbot_service_interface_go@v0.1.0import "github.com/xtech/xbot_framework/xbot_service_interface_go/xbot"
// Discover (a service that is claimed advertises every 10 s, so allow a window)
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
services, err := xbot.Discover(ctx, "")
// Or connect straight away; RPC against the EchoService example
conn, err := xbot.Dial(ctx, xbot.Options{ServiceID: 1})
defer conn.Close()
reply, err := conn.Call(ctx, 2, xbot.Bytes(0, text), xbot.Uint32(1, 3))
if errors.Is(err, xbot.ErrBusy) { /* the service is still executing another call */ }Services are addressed as in the C++/Python side: a service.json names the function, input and register ids, and
the Go client sends those ids with typed helpers (xbot.String, xbot.Uint32, xbot.Bool, xbot.Bytes) or raw
payloads. Heatshrink-compressed blob registers use xbot.HeatshrinkEncode.
Install a specific version by tag (xbot_service_interface_go/v0.1.0) or the latest commit with @main. Full API
reference and examples in the package README.
Typed clients for a concrete service are generated from its service.json with xbot-codegen — see
Service clients.
What each client implements of the wire protocol above (o = only with an optional dependency, – = not
implemented). A missing feature is not a protocol limitation: the services accept it, the client just cannot send
or receive it yet.
| Feature | C++ interface | Python | Go |
|---|---|---|---|
| Discovery (multicast) | ✓ | ✓ | ✓ |
| Claim / release | ✓ | ✓ | ✓ |
| Heartbeat + disconnect detection | ✓ | ✓ | ✓ |
| RPC call (synchronous, status → error) | ✓ | ✓ | ✓ |
| RPC fire-and-forget (without waiting) | ✓ | ✓ | ✓ |
Inputs / outputs (DATA) |
✓ | ✓ | send |
| Registers (typed) | via codegen | ✓ | raw DATA |
| Transactions (atomic bundles) | ✓ | ✓ | send |
Schema from service.json (validated) |
via codegen | ✓ | – |
| Schema-free from the advertisement | ✓ | ✓ | – |
| Heatshrink encode / decode | encode | o | encode |
Remote log stream (LOG) |
service side | ✓ | – |
| Direct endpoint, no discovery | ✓ | ✓ | ✓ |
| Reconnect handling | ✓ | ✓ | – |
| Interactive shell / CLI tools | – | ✓ | – |
| Code generation needed | yes | no | no |
xBot Framework is stable and running in production as the hardware layer for OpenMower. The wire protocol, service discovery, and codegen are solid; the Web UI is the one piece still on the roadmap.
Contributions and feedback are welcome — check the issue tracker to get started.