Skip to content

About

No description, website, or topics provided.

Resources

Stars

6 stars

Watchers

2 watching

Forks

Latest commit

 

History

291 Commits

Folders and files

Repository files navigation

xBot Framework

A Lightweight Alternative to ROS at the Hardware Boundary

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.

Features

  • 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=true to Start().
    • 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.
  • Performant Serialization: Data is transmitted schemaless and binary-packed for low traffic and fast serialization.

Repository Structure

This repository contains all parts of the xbot_framework.

/libxbot-service

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.

/libxbot-service-interface

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.

/include

Files in this directory are needed on both sides (service and service interface). E.g. message header definitions.

/codegen

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.

/ext

All dependencies are included here as submodules. Not every dependency is needed by every part of the software.

/xbot_service_interface_py

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.

/xbot_service_interface_go

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.


Wire Protocol

All communication uses UDP. Every packet begins with a fixed 24-byte header (XbotHeader), followed by a message-specific payload.

XbotHeader (24 bytes, packed)

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

Message Types

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.

TRANSACTION payload format

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.

ClaimPayload (10 bytes, packed)

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

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:

  1. Service broadcasts SERVICE_ADVERTISEMENT on 233.255.255.0:4242.
  2. Interface listens on that multicast group and fires OnServiceDiscovered.
  3. Interface sends unicast CLAIM (with ClaimPayload) to the service's reported endpoint.
  4. Service stops, loads defaults, sends CLAIM ack (arg1=1, empty payload).
  5. If the service has registers, it sends CONFIGURATION_REQUEST every second until it receives configuration.
  6. Interface responds with a TRANSACTION (arg1=1) containing register values as DataDescriptor-framed chunks.
  7. Service validates all required registers and calls OnStart().
  8. Service sends HEARTBEAT at half the requested heartbeat interval. Interface drops the service after heartbeat_micros + 100ms without a heartbeat.

Remote Logging

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.


Service Definition (service.json)

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, length in bytes
  • bool 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, length in bytes
  • bool OnRegister{Name}Changed(const void* data, size_t length) — called when a register is set (blob registers)
  • Struct {Name} with value, length (arrays), and valid fields — for non-blob registers
  • void RPC{Name}(uint16_t call_id, ...) — one pure virtual per function; a blob parameter arrives as const uint8_t* <Name>, uint32_t <Name>Len and is only valid until the handler returns (copy it if you need it longer)
  • A type[N], string or blob return appends T* data, uint16_t* response_length: a zero-filled buffer and its capacity. A blob return is always uint8_t, a string return char, a type[N] return uses its element type; *response_length is a byte count for blob and string (without the terminator) and an element count for type[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_length back, 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 blob parameter gets a frame budget helper, e.g. MaxFileWriteData(PathLen) in C++ and MaxFileWriteData(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 is min(bytes left, budget) long - the budget is an upper bound, only the last chunk is shorter. A string parameter gets the same helper, capped at its max_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}() return false in C++, an error in Go, ValueError in 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 return bool. 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.


Shared Buffer Pool

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 large string) 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, and buffer_block_count has to cover the pooled calls that can be in their handlers at once.
  • A caller sees an exhausted pool as RpcStatus::BUSY and can repeat the call (RpcBusyError in Python, *xbot.RPCError in Go, GetLastRpcResult() == RPC_BUSY in 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.


Python Interface

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.json file (or dict) to ServiceInterface. The schema is validated against the service's advertisement on connect, and an IncompatibleServiceError aborts 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 of enums, functions, registers, outputs, inputs, whatever did not fit. The client fetches those blocks with DESCRIPTION_REQUEST/DESCRIPTION_PART right 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, a services() discovery table, live output streaming (svc.watch_all()), and an interactive register configuration wizard.
  • xbot-logs — a CLI remote log viewer for the LOG multicast 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.


Go Interface

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.0
import "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.


Client Support Matrix

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

Status and Contributions

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.

About

No description, website, or topics provided.

Resources

Stars

6 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages