Your AI runs on your PC. The robot's body runs on the Jetson. The robot API is the one door between them. It's a small web server inside a ROS 2 node, buddy_link/robot_api.py, run on the robot by a service called rosorin-api. Through it a program on your PC reads the robot's state, sees through its camera and hears through its microphone. The API also has calls for speaking through the robot's speaker and for stopping its wheel tasks. I describe those from the code, because I haven't confirmed either of them on a robot built from these chapters.
Connections go one way only. Your PC connects to the robot, and the API never connects out. That way your PC opens no ports for it, and the robot doesn't need to know where your PC is. Every request carries a secret token that only the robot and your PC hold.
This chapter takes about two hours. Nothing in it drives the wheels or moves the arm.
HTTP is the protocol your browser uses. A client opens a connection to a server and sends a request. The request has a method, GET to read something or POST to send something or ask for an action. It has a path such as /status, and headers, name and value lines such as X-Robot-Token: .... A POST also has a body. The server answers with a status code and a body of its own. The codes this API uses are 200 for OK, 400 for a bad request, 401 for a missing or wrong token, 404 for an unknown path, 409 for busy or refused, 500 for an error inside the server, and 503 when a device is missing. An API is the list of paths a program answers and what each one does.
robot_api.py is two things in one process. A ROS node subscribes to topics and keeps only the latest message of each in memory, with one background thread keeping those callbacks running. A web server answers each request in its own thread and reads the stored messages. Nothing is fetched from ROS when a request arrives. /state returns whatever the board driver last published.
Every request needs the header X-Robot-Token. Without it, or with a wrong value, every path answers 401 with {"error": "missing or wrong X-Robot-Token"}.
For reading, GET /state returns the board driver's last state message: wheels, e-stop, arm and gamepad mode. GET /status is a one-glance summary with the battery voltage, whether the charger is plugged in, the wheels, the e-stop, the arm, the mind's mode and why, whether a wheel task is running, and the last line of the newest exploration log. GET /seen returns the newest detections of the robot's own loop, rosorin-mind, and {"dets": [], "t": null} before there are any. Chapter 13 describes that loop, but no chapter installs it with a tested step, so on a robot built from this guide that's what you'll get.
A few more read paths aren't used in this guide. GET /say returns the next sentence the robot wants spoken, and POST /say/ack with {"id": ...} marks it as said. GET /selfcare returns a summary of the robot's latest self-check. GET /task returns {"active": ..., "last": ...}, whether a wheel task is running and the last exploration log line. GET /roomscan and GET /roomscan.jpg return the mind's newest look around the room, as JSON or as a mosaic of its pictures, and 404 with no room scan yet before the first one.
For seeing, GET /frame.jpg returns the newest camera frame as a JPEG, and GET /stream.mjpg streams the camera live for as long as you stay connected. Without a frame yet, /frame.jpg answers 500.
For hearing and speaking, GET /audio streams raw sound from the robot's microphone array for as long as you stay connected, to one listener at a time. It needs a USB microphone array on the robot. Mine is a reSpeaker XVF3800. Without one, /audio answers 503. POST /play takes a WAV file and plays it on the array's speaker, and also on any other USB speaker plugged into the robot, then returns when playback has ended. A clip of 1.2 seconds or longer is treated as speech and made as loud as the small speaker allows without clipping. A shorter clip, such as a chime, is scaled to a quiet fixed level, its loudest sample a tenth of full scale. With no USB speaker at all, /play answers 503.
For telling the mind something, POST /heard takes {"event": ..., "text": ...} and publishes it on the ROS topic /buddy/heard. The event must be wake, speech, inspect, learn or scan_room. Any other event gets 400, with the out-of-date text event must be wake or speech. The API itself never moves anything for /heard.
For motion, POST /stop asks systemd to stop the robot's wheel task services. POST /task/come, /task/home and /task/sethome ask it to start one, and POST /look aims the camera with the arm. GET /objects lists objects from an older scanning program. None of these is run in this chapter, and the section "Doesn't work yet" says why.
The token is permission to move the robot. The API is plain HTTP on your home network, with no encryption, so anything that can read traffic on your network can read the token. Keep the token file at mode 0600, never paste its contents into a chat, a commit or a log, and never echo the variable that holds it.
def token():
if not os.path.exists(TOKEN_FILE):
os.makedirs(os.path.dirname(TOKEN_FILE), exist_ok=True)
fd = os.open(TOKEN_FILE, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
os.write(fd, secrets.token_urlsafe(24).encode()); os.close(fd)
return open(TOKEN_FILE).read().strip()
On its first start the API makes 24 random bytes, encodes them as 32 characters, and writes them to ~/.config/rosorin/api_token. os.open(..., O_CREAT | O_EXCL, 0o600) creates the file already at mode 0600, so it's never readable by others, not even for a moment. Later starts read the same file, so the token survives restarts and reboots. To make a new token, stop the service, delete the file, start the service, and copy the new file to your PC again.
Every request is checked like this:
def authed(self):
if secrets.compare_digest(self.headers.get('X-Robot-Token', ''), tok):
return True
self.send(401, {'error': 'missing or wrong X-Robot-Token'}); return False
secrets.compare_digest takes the same time whether the first or the last character is wrong, so timing the answers gives nothing away.
The API doesn't drive anything itself. Wheel tasks are separate systemd services, and the API asks systemd to start or stop them. This is the part of the handler for /task/... and /stop:
if self.path.split('?')[0].startswith('/task/'):
mode = self.path.split('?')[0].split('/')[-1]
if mode not in TASKS:
return self.send(404, {'started': False, 'error': f'unknown task {mode}'})
if task_active() or unit_active('rosorin-explore'):
return self.send(409, {'started': False, 'error': 'already driving'})
r = subprocess.run(['sudo', 'systemctl', 'start', '--no-block', f'rosorin-task@{mode}'], capture_output=True, text=True)
return self.send(200 if r.returncode == 0 else 500, {'started': r.returncode == 0, 'error': r.stderr.strip()[:200]})
if self.path.split('?')[0] == '/stop':
r = subprocess.run(['sudo', 'systemctl', 'stop', '--no-block', 'rosorin-task@come', 'rosorin-task@home',
'rosorin-task@sethome', 'rosorin-explore'],
capture_output=True, text=True)
return self.send(200, {'ok': r.returncode == 0, 'error': r.stderr.strip()[:200]})
/stop stops four units at once: rosorin-task@come, rosorin-task@home, rosorin-task@sethome and rosorin-explore. The repo's unit files for them each have an ExecStopPost line that disables the wheels when the unit exits, so stopping the unit is meant to stop the wheels. /stop always answers HTTP 200, even when systemctl failed. You have to read the ok field in the answer, not the status code. Both calls need the passwordless sudo for burgerbarn from chapter 4.
The API needs these already working: rosorin-base from chapter 6, rosorin-camera from chapter 7, the vision venv and ~/vision/mind_pause.py from chapter 8, and passwordless sudo and linger for burgerbarn from chapter 4. Linger matters because the service runs as burgerbarn without a login, and it reaches the microphone and speaker through burgerbarn's PulseAudio. That PulseAudio only runs without a login when linger is on.
The unit file, systemd/rosorin-api.service:
[Unit]
Description=ROSOrin robot API for Buddy (state, objects, frame, look - arm only) on :8296
After=network-online.target rosorin-base.service rosorin-camera.service
Wants=network-online.target
[Service]
User=burgerbarn
Environment=ROS_DOMAIN_ID=0
ExecStart=/bin/bash -c 'source /opt/ros/humble/setup.bash && source /home/burgerbarn/ros2_ws/install/setup.bash && source /home/burgerbarn/vision/venv/bin/activate && exec python /home/burgerbarn/buddy_link/robot_api.py'
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
It sources ROS for the message types, the robot's workspace, and the vision venv for numpy and OpenCV. Then it execs Python, so systemd's signals reach the Python process directly.
The install script, scripts/install_api_service.sh:
#!/bin/bash
# Install + enable rosorin-api.service (robot API for Buddy, :8296, token in ~/.config/rosorin/api_token).
# Rollback: sudo bash ~/setup/rollback_api_service.sh
set -euo pipefail
[ "$(id -u)" = 0 ] || { echo "run with sudo"; exit 1; }
install -m 0644 /home/burgerbarn/setup/rosorin-api.service /etc/systemd/system/rosorin-api.service
systemctl daemon-reload
systemctl enable --now rosorin-api.service
sleep 8; systemctl --no-pager --lines=4 status rosorin-api.service | head -6
The API imports two of the robot's own folders at start: ~/vision/mind_pause.py, which you copied in chapter 8, and ~/selfcare/say.py, the speech queue behind /say. Copy the code, the self-care folder, the unit and its scripts from your laptop:
cd ~/CCode/rosorin-pro
python3 -m py_compile buddy_link/robot_api.py
ssh rosorin 'mkdir -p ~/buddy_link ~/setup ~/selfcare'
scp -q buddy_link/robot_api.py rosorin:buddy_link/
rsync -a --exclude __pycache__ selfcare/ rosorin:selfcare/
scp -q systemd/rosorin-api.service scripts/install_api_service.sh scripts/rollback_api_service.sh rosorin:setup/
Then, on the robot, install and start it:
sudo bash ~/setup/install_api_service.sh
journalctl -u rosorin-api -b --no-pager -o cat | grep "robot API on" | tail -1
ls -la ~/.config/rosorin/api_token | cut -c1-10
The status lines should say enabled and active (running), the log line should end in robot API on :8296, and the last line should print -rw-------, the token file at mode 0600. If the journal shows ModuleNotFoundError: No module named 'say' or 'mind_pause', one of the two folders above is missing on the robot.
A program that holds /audio open keeps a connection to the API all the time. When I restarted the API with such a listener connected, the restart sat in deactivating and didn't finish. systemd waits 90 seconds by default before it kills a service that doesn't stop. A drop-in file cuts that wait to 5 seconds. A drop-in is a file in /etc/systemd/system/<unit>.service.d/ that adds to or overrides lines of a unit without editing the unit file. This one is not in the repo, so create it by hand on the robot:
sudo mkdir -p /etc/systemd/system/rosorin-api.service.d
printf "[Service]\n# the ears stream (/audio) keeps a connection open; do not wait 90 s on stop\nTimeoutStopSec=5\n" | sudo tee /etc/systemd/system/rosorin-api.service.d/10-fast-stop.conf >/dev/null
sudo systemctl daemon-reload
sudo systemctl restart rosorin-api
cat /etc/systemd/system/rosorin-api.service.d/10-fast-stop.conf
systemctl show rosorin-api -p TimeoutStopUSec -p KillMode | tr "\n" " "; echo
You should see the file's three lines, then TimeoutStopUSec=5s KillMode=control-group. systemctl cat rosorin-api shows the unit together with all its drop-ins.
If you later update the API with the repo's deploy script, scripts/ops/deploy.sh api, know that it copies a second file, buddy_link/body_endpoints.py, as well. That file switches on the /body/ endpoints of chapter 13. The wheels and the arm joints beyond the head stay refused until the robot's ROBOT_BODY_ALLOW setting allows them, but head looks through /body/look are not held back by that setting. If you don't want them yet, delete ~/buddy_link/body_endpoints.py on the robot and restart the service.
Your PC keeps two copies of the same token. Programs that only listen to the robot's microphone read ~/voice/robot_api_token, and the AI's robot tools read ~/.config/rosorin/api_token. Both must be mode 0600. Copy them from your laptop, so the value never appears on a screen:
ssh yourpc 'mkdir -p ~/voice ~/.config/rosorin'
scp -3 -q rosorin:.config/rosorin/api_token yourpc:voice/robot_api_token
ssh yourpc 'chmod 600 ~/voice/robot_api_token'
ssh rosorin 'cat ~/.config/rosorin/api_token' | ssh yourpc 'bash -c "mkdir -p ~/.config/rosorin && umask 077 && cat > ~/.config/rosorin/api_token && chmod 600 ~/.config/rosorin/api_token && echo token installed"'
scp -3 copies between two remote machines through your laptop. The last line pipes the file through SSH. It should print token installed. If it doesn't, one of the SSH connections failed; check ssh rosorin hostname and ssh yourpc hostname. Then check both copies on your PC. All the PC commands in this chapter are bash, so if your login shell is something else, type bash first:
stat -c '%a %s %n' ~/voice/robot_api_token ~/.config/rosorin/api_token
cmp ~/voice/robot_api_token ~/.config/rosorin/api_token && echo same
600 32 /home/burgerbarn/voice/robot_api_token
600 32 /home/burgerbarn/.config/rosorin/api_token
same
Run these on your PC. The first line reads the token into a shell variable without printing it, and sets the robot's address. Mine is on Wi-Fi at ROBOT_WIFI_IP; put in your robot's own address.
T=$(cat ~/.config/rosorin/api_token); R=http://ROBOT_WIFI_IP:8296
echo "no key -> $(curl -s -o /dev/null -w '%{http_code}' $R/state)"
curl -s -m 10 -H "X-Robot-Token: $T" $R/state | python3 -c "import json,sys; s=json.load(sys.stdin); print('state: wheels', s.get('enabled'), 'estop', s.get('estop'), 'arm_holding', s.get('arm_holding'), 'pad', s.get('pad_mode'))"
curl -s -m 10 -H "X-Robot-Token: $T" -o /tmp/robot_frame.jpg -w "frame.jpg -> HTTP %{http_code}, %{size_download} bytes\n" $R/frame.jpg
No token gives 401. With the token you get the driver state and a camera frame. On my robot:
no key -> 401
state: wheels False estop None arm_holding True pad locked
frame.jpg -> HTTP 200, 74958 bytes
Open /tmp/robot_frame.jpg to see what the camera sees. If /frame.jpg answers no camera frame (is rosorin-camera running?), the API hasn't received an image yet; check systemctl is-active rosorin-camera on the robot. While curl runs, -H "X-Robot-Token: $T" shows the token in the process list. For a test on your own PC that's fine. A program that runs all the time should pass -H @file with a 0600 file instead.
Now the summary and the other read-only paths:
curl -s -m 5 -H "X-Robot-Token: $T" $R/status; echo
curl -s -m 5 -H "X-Robot-Token: $T" $R/seen | head -c 300; echo
curl -s -m 5 -H "X-Robot-Token: $T" $R/say; echo
curl -s -m 5 -H "X-Robot-Token: $T" $R/selfcare | head -c 300; echo
Each answers with one line of JSON. /status starts with the battery voltage; mine began {"battery_v": 12.62, "plugged": false,. My robot already had its mind running, so /status showed "mind": "track" and /seen listed detections. Without the mind, the code returns "mind": null and {"dets": [], "t": null}. /say gave {"say": null} and /selfcare gave {"time": null}.
The API has a stop call, POST /stop, but I haven't tested it on a robot built from these chapters, so there's no command for it here. Going by the code, it answers {"ok": true, "error": ""} when systemd accepted the stop, and {"ok": false, "error": "..."} with the first 200 characters of systemd's complaint when it didn't. The HTTP code is 200 either way, so a program that calls /stop must check ok. As the code above shows, it stops rosorin-task@come, rosorin-task@home, rosorin-task@sethome and rosorin-explore, and nothing else. In particular it does not stop rosorin-practice.
When your AI drives the robot through the /body/ endpoints of chapter 13, the matching stop is POST /body/stop. Its code cancels the navigation goal and disables the wheels, but it hasn't been tried during a goal either. Chapter 13 describes it.
Neither of these is a stop to count on. The gamepad's e-stop from chapter 10 is meant to latch in the board driver with no network in between, and the robot's own loop never clears it, but it wasn't tested on this build. The power switch is the stop that works. Keep it within reach whenever a program might drive the robot.
/audio serves one listener. If you already run a program on your PC that holds it open, such as a robot-mic service, stop it for the test. The systemctl --user lines do that and do nothing if there's no such service. The test measures 4 seconds of sound:
systemctl --user stop robot-mic 2>/dev/null
n=$(timeout 4 curl -sN -H "X-Robot-Token: $T" $R/audio | wc -c); echo "bytes from /audio in ~4 s: $n (expect ~128000 = 32 kB/s)"
systemctl --user start robot-mic 2>/dev/null
On my robot:
bytes from /audio in ~4 s: 111360 (expect ~128000 = 32 kB/s)
Here's where that number comes from. A microphone signal in a computer is a list of numbers, one per sample. The API sends 16,000 samples a second, each a 16-bit number of 2 bytes, on one channel, so one second is 32,000 bytes. The array actually records two channels. The API reads them through burgerbarn's PulseAudio with parec, keeps every second sample, which is the right channel, and sends only that. The right channel is the array's own cleaned-up speech signal for the direction it picked. A little under 128,000 bytes is normal, because curl takes a moment to connect.
A count under about 100 means the API sent a short JSON error, and wc -c counted that. A 503 with reSpeaker array not found means the array isn't plugged in, or burgerbarn's PulseAudio isn't running or can't see it. Check with lsusb | grep -c Seeed on the robot. A 409 with another client has the audio stream means some other program still holds the stream. A count of 43 is a 401: $T is empty or wrong. A count of 0 means you didn't run the line that sets T and R in this shell.
curl -s -m 3 -X POST -H "X-Robot-Token: $T" -H 'Content-Type: application/json' -d '{"event":"speech","text":"link test from yourpc"}' $R/heard; echo
The API answers {"ok": true}. That only means the API published the message on /buddy/heard. If the robot's own loop is running (chapter 13 describes it; no chapter installs it with a tested step), it logs the event too, and on my robot it did. The API never moves anything for /heard, but the mind does: wake, inspect and scan_room move the arm, and the words stop, stay, halt or freeze hold its wheel skills for 30 minutes. Don't test with those.
timeout 5 curl -s -N -H "X-Robot-Token: $T" $R/stream.mjpg | grep -a -c -- "--frame" | awk '{printf "frames in 5 s: %s (%.1f fps)\n", $1, $1/5}'
You should get roughly the camera's rate of 14 frames a second. Mine printed:
frames in 5 s: 73 (14.6 fps)
I haven't tested POST /stop on a robot built from these chapters, neither alone nor with a wheel task running. Everything I've said about it above is read from the code. The wheel task units it stops, rosorin-task@... and rosorin-explore, are not installed anywhere in this guide, so on such a robot /stop has nothing to stop. I expect it then answers "ok": false with systemd's "not loaded" message, but I haven't checked that. Until /stop has been tested against a running task, the power switch is your stop.
POST /task/... starts those same wheel units, so going by the code, on a robot built from this guide it answers 500 with systemd's error that the unit doesn't exist. I haven't run it. Even with the units installed, the API's "already driving" check only looks at the task units and rosorin-explore, not at rosorin-practice, so a task could start underneath a practice run.
POST /look has never answered successfully on my robot. Its aiming maths for a bearing or a label was refitted to the arm's current rest pose, but no look through it has been checked, so whether it points the camera where you asked is unknown. GET /objects reads results from an old scanning program that is no longer used, so its data may be days old. Its age_s field tells you how old.
POST /play played test tones on an earlier install of the same robot, but on a robot built from these chapters I haven't confirmed it, because only a person standing next to the robot can tell whether the speaker made a sound. On that earlier install, after one reboot, the array's playback stalled while its microphone kept working. The call hung and paplay logged Failed to drain stream: Timeout. A software USB unbind and bind made it worse, and only unplugging the array and plugging it back in fixed it.
The token check has a gap. A request whose X-Robot-Token header contains a non-ASCII character makes compare_digest raise an error before the handler's error catching starts, so the connection drops with no answer at all. The request is still refused, but the client gets no 401.
/status reported "plugged": false the whole time my robot sat on its charger. I haven't found out whether the contact or the reading is at fault.
The repo's scripts/rollback_api_service.sh disables and removes the service, but I haven't run it on a robot built from these chapters.
You're ready for the next chapter when systemctl is-active rosorin-api prints active on the robot and still does after a reboot, curl without a token gets 401 and with the token /status answers with the battery voltage, both token files on your PC are mode 600, 32 bytes and identical and you've never seen the token's value, systemctl show rosorin-api -p TimeoutStopUSec prints TimeoutStopUSec=5s, and with the array plugged in, 4 seconds of /audio deliver a little over 100,000 bytes.