Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion deployment/cpu/ec/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,11 @@ cpu_def(
"//deployment/apps/system_stat_service:SysStatService",
"//deployment/apps/prim_service:PrimerService",
"//deployment/apps/fuel_service:FuelService",
"//deployment/apps/radio_app:RadioApp"
# RadioApp (apps/ec/radio_service, /dev/ttyS1 at 57600) is off the EC package: the MavlinkDaemon replaces it as the
# owner of the radio links, and two owners of one UART are not possible. The code stays; the radio driver for
# /dev/ttyS1 comes in srp later. Re-enable only together with a daemon config that does not use /dev/ttyS1.
# "//deployment/apps/radio_app:RadioApp",
"//deployment/platform/mavlink_daemon:mavlink_daemon",
],
)

Expand Down
57 changes: 57 additions & 0 deletions deployment/platform/mavlink_daemon/BUILD
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
load("@rules_python//python:defs.bzl", "py_test")
load("@srp_platform//platform/common/mavlink_daemon:defs.bzl", "mavlink_daemon_binary")
load("@srp_platform//tools/model_generator/ara:adaptive_application.bzl", "adaptive_application")

# MavlinkDaemon of the EC: the only owner of the radio links radio_a (main) and radio_b (long range, events);
# applications with `on: mavlink` are its clients. The binary is built here (mavlink_daemon_binary) with the
# radio drivers linked in statically: no *.so, no driver directory. The application model (ipc service
# MavlinkLinkService, functional groups, logger) is the platform one.
# The EC package gets /srp/opt/mavlink_daemon/{bin/mavlink_daemon, mavlink_daemon_config.json,
# serial_radio_a.json, serial_radio_b.json} (the files are also in .../etc). See README.md.
#
# Drivers linked into the daemon (`serial_radio` is always there). The links of mavlink_daemon_config.json use
# `serial_radio` (plain UART, placeholder until the real radio driver is added in srp); E220 stays linked in, but the
# config does not use it (the E220 module of the EC UART /dev/ttyS1 is not touched by the daemon).
MAVLINK_DRIVERS = ["//core/radio/e220:e220_driver"]

mavlink_daemon_binary(
name = "mavlink_daemon_bin",
drivers = MAVLINK_DRIVERS,
)

adaptive_application(
name = "mavlink_daemon",
bin = ":mavlink_daemon_bin",
model_src = ["@srp_platform//platform/common/mavlink_daemon/model:instance"],
etcs = [
"serial_radio_a.json",
"serial_radio_b.json",
"mavlink_daemon_config.json",
],
visibility = ["//deployment/cpu:__subpackages__"],
)

# The same daemon core and the same drivers without Execution Management (stdin/stdout JSON lines): for tests on a PC.
mavlink_daemon_binary(
name = "mavlink_daemon_host",
testonly = True,
drivers = MAVLINK_DRIVERS,
host = True,
)

# The real deployment config goes through the strict config parser of the daemon (links: serial_radio on a pty);
# a removed key (heartbeat_hz, version, driver_dir, restart_delay_ms) is a start error.
py_test(
name = "config_test",
srcs = ["ut/config_test.py"],
data = [
"mavlink_daemon_config.json",
":mavlink_daemon_host",
],
env = {
"DAEMON_HOST": "$(rootpath :mavlink_daemon_host)",
"DEPLOY_CONFIG": "$(rootpath mavlink_daemon_config.json)",
},
main = "ut/config_test.py",
size = "small",
)
99 changes: 99 additions & 0 deletions deployment/platform/mavlink_daemon/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# MavlinkDaemon on the EC

The EC runs one `mavlink_daemon` that owns both radio links; applications with `on: mavlink` are its clients
(modelled on `someip_demon`). The binary is built in this directory by `mavlink_daemon_binary`
(`BUILD`): the radio drivers are linked in statically, so the EC package has **no `*.so` and no driver directory**.
The application model (service `MavlinkLinkService` on `ipc`, functional groups, logger) is the platform one
(`@srp_platform//platform/common/mavlink_daemon/model:instance`).

## Package contents (`//deployment/cpu/ec:pkg`)

| path on the EC | file |
|----------------|------|
| `/srp/opt/mavlink_daemon/bin/mavlink_daemon` | the daemon binary built here |
| `/srp/opt/mavlink_daemon/mavlink_daemon_config.json` | daemon config (this directory), copy in `etc/` |
| `/srp/opt/mavlink_daemon/serial_radio_a.json`, `serial_radio_b.json` | driver files of the links (`device`, `baudrate`), copies in `etc/` |

## Config `mavlink_daemon_config.json`

The config is strict: an unknown or removed key (`version`, `driver_dir`, `heartbeat_hz`, `restart_delay_ms`) is a
start error that names the key. `ut/config_test.py` (`bazel test //deployment/platform/mavlink_daemon:config_test`)
starts the host variant of the daemon with this very file (the links on `serial_radio`, devices replaced by a pty) and checks the
rejection of the removed keys. Key reference: `platform/common/mavlink_daemon/README.md` in `srp_platform`.

| link | role | `air_rate_bps` | `mtu` | `method_timeout_ms` |
|------|------|----------------|-------|---------------------|
| `radio_a` | main radio | 9600 | 200 | 1000 |
| `radio_b` | long range, events | 2400 | 64 | 4000 |

`mtu` is the largest frame of the radio (the generator checks the frames against `mtu`); with a real radio driver it must match the packet length of the module.
`signing` is disabled in the example; to enable it set `enabled`, `key_file`, `link_id` (unique per signed link),
`state_file`.

## Radio drivers: placeholder on the EC

The daemon does **not** use `/dev/ttyS1` on the EC. Both links use `serial_radio` (a plain UART, only `device` and
`baudrate`) as a placeholder for tests; the proper radio driver (the E220 module of the EC or another) is added by the
user in srp. Reason: `RadioApp` (`apps/ec/radio_service`) owned `/dev/ttyS1` (57600); it is commented out of
`//deployment/cpu/ec:pkg` (the code stays), so that the daemon is the only owner of the radio links once a driver is chosen.

**To be confirmed on the hardware:** `device` (`/dev/ttyS2`, `/dev/ttyS4`) and `baudrate` in `serial_radio_a.json`,
`serial_radio_b.json` are placeholders, as are all values of `air_rate_bps` and `mtu`; they depend on the EC board
and the modules. The `ebyte_e220` driver stays linked into the binary (`MAVLINK_DRIVERS` in `BUILD`, keys:
`core/radio/e220/README.md`, incl. board dependent `aux_idle_level`), but the config does not use it.

## Adding an element to a radio

An element (an event, a field or a method of a service) goes through the radio only if it is on the white list
`elements` of the `on: mavlink` entry in the `app.json` of the application, with a limit per radio:

```json
{
"name": "EngineService as Engine",
"on": "mavlink",
"instance": 2,
"elements": {
"Telemetry": { "radio_a": { "max_rate_hz": 10 }, "radio_b": { "max_rate_hz": 0.2 } },
"Position": { "radio_b": { "max_rate_hz": 1 } },
"SetMode": { "radio_a": {} }
}
}
```

* the radio names are the keys of `links` in `mavlink_daemon_config.json` (`radio_a`, `radio_b`); an unknown radio is a generator error;
* an element that is not in `elements` does not go through the radio;
* an event on a radio with `air_rate_bps` needs `max_rate_hz` (otherwise the budget cannot be computed: generator error);
* a method on more than one radio gets a warning: the REQ is sent by both radios and executes twice.

### Radio budget

The model generator writes `<dialect>_links.md` with one table per radio: for every element the worst-case frame
(header 10 B + CRC 2 B + 13 B signature on a signed link + the full payload) times `max_rate_hz`, plus HEARTBEAT, the sum
in B/s and the percentage of `air_rate_bps`. A load above `max_utilization` (0.8) is a warning, above 100% a generator
error; a frame longer than `mtu` is an error too. Check `_links.md` after every change of `elements` or of a radio.
Methods are listed without summing (no rate). The daemon additionally paces the TX of every link to
`air_rate_bps x max_utilization`.

## Radio link state in an srp application: `MavlinkLinkService`

An application that wants to adapt to the radio (rate, mode) adds the platform service as a `require` entry
with `on: ipc`:

```json
"include": ["@(srp_platform)/platform_definition/mavlink_link_service/mavlink_link_service.json"],
...
"require": [
{ "name": "srp.platform.mavlink.MavlinkLinkService as LinkRPort", "on": "ipc", "instance": 1 }
]
```

and uses `MavlinkLinkServiceProxy` from `srp/platform/mavlink/MavlinkLinkService/MavlinkLinkServiceHandler.h`: the
event `LinkStats` (per link, every `stats_period_ms`) and the method `GetLinkStats(link)`. `ipc` is local to the CPU:
the application sees the links of the daemon on its own CPU. See `docs/mavlink/README.md` in `srp_platform`.

## Known gap: FuelService and FcRadioService

`FuelService` (`deployment/apps/fuel_service/app_config.json`) requires `FcRadioService` (ipc, instance 2), whose
only provider is `RadioApp`; `RadioApp` is off the EC package (see `deployment/cpu/ec/BUILD`). Until `FcRadioService`
is moved to MAVLink (`on: mavlink`, planned S5), the `FuelService` controllers get neither the rocket mass
(`GSERocketMassEvent`) nor the oxidizer tank pressure (`GSEOxidizerTankPressEvent`) from the FC.
33 changes: 33 additions & 0 deletions deployment/platform/mavlink_daemon/mavlink_daemon_config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"system_id": 1,
"component_id": 1,
"restart_backoff": {
"min_ms": 500,
"max_ms": 30000
},
"stats_period_ms": 1000,
"links": {
"radio_a": {
"driver": "serial_radio",
"driver_config": "/srp/opt/mavlink_daemon/serial_radio_a.json",
"air_rate_bps": 9600,
"max_utilization": 0.8,
"mtu": 200,
"method_timeout_ms": 1000,
"signing": {
"enabled": false
}
},
"radio_b": {
"driver": "serial_radio",
"driver_config": "/srp/opt/mavlink_daemon/serial_radio_b.json",
"air_rate_bps": 2400,
"max_utilization": 0.8,
"mtu": 64,
"method_timeout_ms": 4000,
"signing": {
"enabled": false
}
}
}
}
1 change: 1 addition & 0 deletions deployment/platform/mavlink_daemon/serial_radio_a.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{ "device": "/dev/ttyS2", "baudrate": 9600 }
1 change: 1 addition & 0 deletions deployment/platform/mavlink_daemon/serial_radio_b.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{ "device": "/dev/ttyS4", "baudrate": 9600 }
95 changes: 95 additions & 0 deletions deployment/platform/mavlink_daemon/ut/config_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
"""The EC MavlinkDaemon deployment config is accepted by the strict config parser of the daemon.

Runs the host variant of the daemon (the same core as on the EC, without Execution Management)
with the real deployment `mavlink_daemon_config.json`. Only the UART devices differ from the
EC: the driver files of both links (`serial_radio`) point to a pty; every other key is taken as
it is. Then a config with a removed key (`heartbeat_hz`, `version`, `driver_dir`, ...) must fail
at start and name the key.
"""
import json
import os
import subprocess
import tempfile
import unittest

DAEMON = os.environ["DAEMON_HOST"]
CONFIG = os.environ["DEPLOY_CONFIG"]


def _run(config, stdin=None, timeout=20):
return subprocess.run([DAEMON, config], input=stdin, capture_output=True, text=True,
timeout=timeout, check=False)


class DeploymentConfigTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory() # pylint: disable=consider-using-with
self.ptys = []
with open(CONFIG, encoding="utf-8") as f:
self.cfg = json.load(f)
self.cfg["socket_path"] = os.path.join(self.tmp.name, "mavlink.sock")
for name, link in self.cfg["links"].items():
master, slave = os.openpty()
self.ptys.append((master, slave))
drv = os.path.join(self.tmp.name, name + ".json")
with open(drv, "w", encoding="utf-8") as f:
json.dump({"device": os.ttyname(slave), "baudrate": 9600}, f)
link["driver"] = "serial_radio"
link["driver_config"] = drv

def tearDown(self):
for master, slave in self.ptys:
os.close(master)
os.close(slave)
self.tmp.cleanup()

def _write(self, cfg):
path = os.path.join(self.tmp.name, "cfg.json")
with open(path, "w", encoding="utf-8") as f:
json.dump(cfg, f)
return path

def test_deployment_config_starts(self):
r = _run(self._write(self.cfg), stdin='{"id":1,"cmd":"stats"}\n{"cmd":"stop"}\n')
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
events = [json.loads(line) for line in r.stdout.splitlines() if line.strip()]
self.assertEqual(events[0], {"ev": "ready"})
stats = [e for e in events if e.get("id") == 1][0]
self.assertTrue(stats["ok"])
self.assertEqual(sorted(stats["result"]["links"]), ["radio_a", "radio_b"])

def test_deployment_file_has_no_removed_keys(self):
with open(CONFIG, encoding="utf-8") as f:
cfg = json.load(f)
for key in ("version", "driver_dir", "heartbeat_hz", "restart_delay_ms"):
self.assertNotIn(key, cfg)
for link in cfg["links"].values():
self.assertNotIn(key, link)
for link in cfg["links"].values():
for key in ("air_rate_bps", "max_utilization", "mtu", "method_timeout_ms", "signing"):
self.assertIn(key, link)

def _expect_rejected(self, mutate, key):
cfg = json.loads(json.dumps(self.cfg))
mutate(cfg)
r = _run(self._write(cfg))
self.assertEqual(r.returncode, 2, r.stdout + r.stderr)
self.assertIn('"ev":"error"', r.stdout)
self.assertIn(key, r.stdout)

def test_heartbeat_hz_is_a_start_error(self):
self._expect_rejected(lambda c: c["links"]["radio_a"].update({"heartbeat_hz": 1}),
"heartbeat_hz")

def test_version_is_a_start_error(self):
self._expect_rejected(lambda c: c.update({"version": 2}), "version")

def test_driver_dir_is_a_start_error(self):
self._expect_rejected(lambda c: c.update({"driver_dir": "/x"}), "driver_dir")

def test_restart_delay_ms_is_a_start_error(self):
self._expect_rejected(lambda c: c.update({"restart_delay_ms": 10}), "restart_delay_ms")


if __name__ == "__main__":
unittest.main()
Loading