Code generation
archec gen writes source code from the model: C, Rust, C++ and more, and also
files for other tools (CAN databases, AUTOSAR, AADL, containers, model
checkers). You pick what to write with --target. When the model changes, you
run it again, and the code you wrote around the generated code is kept.
Every option of archec gen is in commands.md.
Generators of your own are in generators.md.
A first generation#
A part that counts the messages it receives:
message TICK "A tick" { n: uint32 }
component Counter "Counts the ticks" {
in tick: data receives TICK {
on-receive ```arche
count += 1
```
}
var count: uint32 = 0
}
system Demo {
part counter: Counter
}Generate C from it:
archec gen main.arche --target c -o generated
generated/c/arche_rt.h
generated/c/arche_rt_posix.c
generated/c/arche_rt_freertos.c
generated/c/arche_types.h
generated/c/arche_types.c
generated/c/counter.h
generated/c/counter.c
counter.c holds the part's code. The body of the handler is translated, and
the places for your own code are marked:
/* @arche Counter.init main.arche:3 init */
void counter_init(counter_t *self)
{
self->count = 0;
/* USER CODE BEGIN Counter.init */
/* USER CODE END Counter.init */
}
/* @arche Counter.tick.on-receive main.arche:4 on-receive */
void counter_on_receive_tick(counter_t *self)
{
self->count += 1;
}
Run the same command again and the files you own are not touched:
kept (yours): c/arche_rt_posix.c, c/arche_rt_freertos.c
Add --build to build what was written:
── cc -std=c99 -Wall -Wextra -Werror -pedantic -O2
✓ built clean
Generating again#
- Some files are yours: they are written once and never overwritten. Examples
are
app.rs,main.rsandCargo.toml. - Your code inside a
USER CODEregion is put back each time. See regenerating code. --checkfails when a generated file is out of date. Use it in CI.- In VS Code, the command is Arche: Generate code….
To check that the code builds clean, lint it, test it and trace it to the requirements, see the quality of the generated code.
The targets#
The "from" column says what the model must have for the target to write anything.
| Target | What it writes | From |
|---|---|---|
c |
C99 for a microcontroller: no heap | components; deployment |
cpp |
C++17 for a hosted target, see C++ | components; deployment |
embassy |
Rust for Embassy: one crate per binary | deployment |
dbc |
CAN DBC: one file per bus | deployment routes |
wire |
the codecs of the messages that say their wire format, in C, Rust, Go and Python | messages |
regmap |
register maps, see register maps | memory blocks |
vhdl |
VHDL-2008 for an FPGA, with a GHDL testbench per test case, see FPGA components | components with a clock |
aadl |
AADL v2, for OSATE | deployment |
arxml |
AUTOSAR Classic ARXML | deployment |
arxml-adaptive |
AUTOSAR Adaptive ARXML | deployment |
bom |
a bill of materials | root systems (no deployment needed) |
icd |
interface control documents in Markdown | root systems, deployment routes |
containerd |
container images and compose files for containerd | deployment containers |
k8s |
Kubernetes manifests | deployment containers |
ros2 |
ROS 2 interfaces and nodes | data; deployment |
gazebo |
the plant in Gazebo | system, deployment |
mujoco |
the plant in MuJoCo | system |
devicetree |
Zephyr devicetree overlays | deployment on boards |
renode |
the microcontrollers in Renode | deployment |
ui-web |
the product's screens as a web app | ui blocks |
freertos, zephyr, posix |
the Arche app's RTOS skeleton | threads / tasks |
uppaal |
UPPAAL timed automata and queries | state machines, links, contracts |
nusmv |
NuSMV / nuXmv models | state machines |
components |
the Arche app's component sources | components |
c-tests, trace-matrix |
C unit tests, a traceability matrix, see quality | test plans, requirements |
The integration targets are in integration targets. The sections below say what each of the others writes.
embassy#
Rust for Embassy, one crate per binary.
arche.rs is generated again each time. It holds:
- the model's types and messages;
- a
Channelper link, with itsdepthandoverflow, or aSignalforbuffer sample; - per part, an
Outhandle and a behaviour trait; - one task per thread: a
Tickerforperiod+step, and aselectover the inputs; - per routed message, encode and decode and a
BusFrame. The CAN id is the route'sid; spawn_all.
hal std|stm32|rp|nrf|esp32 and chip "…" on the processor pick the HAL.
With hal rp and threads on two cores, core 1 is started.
When the binary is on a board of the store and the platform has devices with a
Rust driver (a BME280, an LED, a servo…), the crate also gets src/hw/:
mod.rs (generated again each time: the board's I²C bus shared by its devices,
their pins, a Hardware with a field per device, the HW mutex and the
start! macro), peripherals.rs (std/peripherals as embedded-hal 1.0 traits)
and one file per device, copied from the store. main.rs calls
hw::start!(spawner, _p) and Cargo.toml gets the drivers' crates. Which
devices, which pins, and how to add one: drivers.md.
A part's state machine runs as the model writes it when its guards, actions,
on-enter and on-exit are in the action language. The guards read the
trigger's fields by name ([temperature > 28.0]), and on "after 10s"
timers are armed on entering their state. These are methods of the part in
arche.rs (arche_start, arche_on_<message>, arche_timeouts). A guard
written otherwise (Python, self.speed) leaves the machine to app.rs, as
before: a <Part>Guards trait to implement, and on_transition.
With --trace, on an STM32 board whose UART is the ST-LINK's virtual COM
port (the NUCLEO-F446RE's USART2), the trace lines go out on that UART as
text at 115200 baud. A terminal, examples/greenhouse/board.sh or Renode
records them. On other boards they are defmt over RTT.
dbc#
A CAN DBC file per bus. Each routed message is a frame, and each field is a signal. The layout is the same as the Embassy codec.
A message can give its wire format (at, bits, scale, byte-order…, see
the spec). Then each signal is on its bits, with its
start bit, byte order, sign, factor and offset.
wire#
The codecs of the messages that say their wire format, with their types:
wire/c/arche_wire.hand.c: C99, no heap, no libm;wire/rust/: ano_stdcrate;wire/go/: packagearchewire;wire/python/arche_wire.py: dataclasses.
Encode puts each field on its bits. Decode fails on a short frame, a wrong
checksum or an unknown enum value. The four write the same bytes. --target c, embassy and go use the same code for these messages.
aadl#
AADL v2, one package for OSATE, in aadl/<deployment>.aadl:
datawith Data_Model properties per message and type;- a
processorper processor, with avirtual processorper core and amemoryfor itsram; - a
bus, with Transmission_Time frombitrate; - a
virtual processorper container, bound to the cores of its cpuset. Its processes are bound to it; - a
processper process (or per binary when there is none); - a
threadper thread, with Dispatch_Protocol, Period, Deadline, Compute_Execution_Time, Priority and Stack_Size. Compute_Execution_Time is0 ms .. wcet, else the step's cost; - event data ports. A port with
buffer sampleis a data port. Queue_Size comes fromdepth; - a
deviceper linked part that is on no thread; - a port connection per link, with Latency from
latency; - Actual_Processor_Binding to the core, and Actual_Connection_Binding to the route's bus.
A port that carries several messages is typed by a union of them.
arxml#
AUTOSAR Classic ARXML (R4, AUTOSAR_00049), in arxml/<deployment>.arxml.
Types and interfaces:
- an IMPLEMENTATION-DATA-TYPE per type and message. An enum is uint8 with a TEXTTABLE COMPU-METHOD;
- a SENDER-RECEIVER-INTERFACE per message.
Software components:
- an APPLICATION-SW-COMPONENT-TYPE per part with behaviour. Sensors and hardware are SENSOR-ACTUATOR components;
- a P-PORT-PROTOTYPE or R-PORT-PROTOTYPE per port and message;
- RUNNABLE-ENTITYs, started by a TIMING-EVENT (thread
period+step), DATA-RECEIVED-EVENTs (handlers,receives) and an INIT-EVENT (fn main); - the system as a COMPOSITION-SW-COMPONENT-TYPE, with an ASSEMBLY-SW-CONNECTOR per link and message.
The CAN bus, for each message routed over one:
- I-SIGNALs in the DBC's layout, an I-SIGNAL-I-PDU, a CAN-FRAME, and a CAN-FRAME-TRIGGERING with the route's CAN id;
- its PDU and signal triggerings. A structure also has a signal group.
The ECUs and the system:
- an ECU-INSTANCE per processor a thread runs on. It has a CAN connector per bus, and a frame, PDU and signal port per frame it sends or receives;
- the SYSTEM, with its root composition and the SWC-TO-ECU-MAPPING of each part;
- each routed message's data element mapped on its signals, field by field for a structure.
The file validates against AUTOSAR's AUTOSAR_00049.xsd. The examples'
deployments are checked with xmllint when AUTOSAR_XSD names the schema.
arxml-adaptive#
AUTOSAR Adaptive ARXML (R20-11, AUTOSAR_00049): four files in
adaptive/<deployment>/.
Design.arxml:
- the data types, as
arxmlwrites them; - a SERVICE-INTERFACE per interface that a port provides or requires:
- what its provider sends is an EVENT;
- its operations are METHODs, with their ARGUMENTs. A result is an OUT argument. A method without a result is FIRE-AND-FORGET;
- a message the provider only receives is a fire-and-forget METHOD;
- a message it both sends and receives is a FIELD, with getter, setter and notifier;
- a SERVICE-INTERFACE of EVENTs per Ethernet
outport that sends without an interface; - per process, an ADAPTIVE-APPLICATION-SW-COMPONENT-TYPE, with a P-PORT- or R-PORT-PROTOTYPE per service its parts provide or require. For a binary without processes, this is per binary;
- an EXECUTABLE whose ROOT-SW-COMPONENT-PROTOTYPE that component is.
MachineManifest.arxml:
- a MACHINE-DESIGN (with an ETHERNET-COMMUNICATION-CONNECTOR) and a MACHINE (with its PROCESSOR and cores) per processor whose operating system is not an RTOS or bare metal;
- the machine function group
MachineFG(Startup, Running, Shutdown); - an ETHERNET-CLUSTER with a NETWORK-ENDPOINT per machine. The address is
attr ip = "10.0.0.2"on the processor or on a binary on it. Without it, addresses start at 192.168.0.10.
ExecutionManifest.arxml: a PROCESS per process of its EXECUTABLE. It is
started in MachineFG.Running with a STARTUP-CONFIG. The STARTUP-CONFIG has
the policy (fifo, rr, else other) and the priority of its
highest-priority thread.
ServiceInstanceManifest.arxml:
- a SOMEIP-SERVICE-INTERFACE-DEPLOYMENT per service, with the ids of
--target someip: service, version, methods, events, event group. A field's getter and setter are numbered after the methods. Its notifier is the message's event id; - a PROVIDED- or REQUIRED-SOMEIP-SERVICE-INSTANCE per port;
- its SERVICE-INSTANCE-TO-PORT-PROTOTYPE-MAPPING to the process;
- a SOMEIP-SERVICE-INSTANCE-TO-MACHINE-MAPPING per machine.
A binary on a microcontroller is a Classic ECU (arxml) and is left out. A
service it provides then has no provided instance; the notes say which.
The examples' deployments are checked with xmllint against
AUTOSAR_00049.xsd when AUTOSAR_XSD names it.
bom#
A bill of materials. No deployment is needed.
bom/bom.csvhas a row per definition, and per part that has none. A row gives its parts, its kind and its quantity (copies[n]are counted). It also gives each number a budget adds up:mass,power,cost,ram, and every name abudgetis written for. Totals follow, overall and per system.bom/bom.mdhas the same table, and the roll-up of each part with everything beneath it.
A number given in two units gets a column per unit. Nothing is converted.
icd#
Interface control documents in Markdown: icd/<port-type or interface>.md
and icd/<bus>.md. Each one gives:
- each message's fields: type, unit, range, default, description;
- its byte layout;
- the links that provide and consume it: latency, buffer, route, transport time;
- on a bus, the frames, with CAN id, period and frame time;
- the types used;
- the requirements traced to the parts, messages and interface, or that name them.
icd/index.md lists them.
containerd#
For containerd, through nerdctl:
containers/<container>/Containerfile: a multi-stage build per binary into a slim Debian image. C comes fromc/<binary>and Rust fromembassy/<binary>: generate those into the same directory, the build context. When the container runs several binaries, anentrypoint.shstarts them;containers/<processor>/compose.yaml, fornerdctl compose up. It sets the image, theplatform(from the processor'sisaorcore-type),cpuset,mem_limit,network_mode,devices,cap_add,privileged, anrtprioulimit at the highest real-time priority, andenvironment;containers/deploy.sh: it builds every image (PUSH=1pushes it) and says what to start on each processor.
k8s#
For Kubernetes or k3s, with the images containerd builds.
k8s/<container>.yaml is a Deployment of one replica:
- pinned to its processor's node:
nodeSelectorkubernetes.io/hostnameis the processor's name (with-for_), andkubernetes.io/archcomes from itsisa; resourceswith requests equal to limits, from its cpuset size andmemory-limit. This is the Guaranteed class: it gets exclusive cores with the kubelet's static CPU manager;hostNetworkfornetwork host;privilegedforcapabilities all, elsecapabilities.add;- each
devicemounted from the host (hostPath); - its props as
env.
A container with network none gets a deny-all NetworkPolicy.
k8s/kustomization.yaml is for kubectl apply -k k8s. What Kubernetes cannot
say, such as the exact cores or a bridge latency, is a note.
ros2#
- the messages as the ament interface package
ros2/(.msg,.srv); - with a deployment that says
packaging ros2:ros2_nodes/<binary>/, rclcpp nodes around the parts' C modules (see ROS 2), andros2_nodes/<deployment>_bringup/launch/<deployment>.launch.py.
colcon build builds them.
gazebo#
The plant of a packaging ros2 deployment in Gazebo
(gz sim Harmonic), see Gazebo:
gazebo/worlds/<system>.sdf: sensors, actuators, masses;gazebo/config/bridge.yaml, for ros_gz_bridge;gazebo/scripts/sim_adapter.py;gazebo/launch/<system>_sim.launch.py.
mujoco#
The plant in MuJoCo, see MuJoCo:
mujoco/<system>.xml: MJCF, with bodies from the parts'mass,shapeandjoint, and the sensors and actuators;mujoco/plant_bridge.py: it passes the model's messages to and from the plant.archec sim --plantruns the model against it.
devicetree#
A Zephyr devicetree overlay per binary on a
board's microcontroller: devicetree/<binary>/boards/<zephyr board>.overlay.
It enables each CAN, UART, I2C and SPI connector of the board that the platform links:
- on its pins, with pinctrl: hal_stm32's
usart2_tx_pa2nodes,NRF_PSEL, the RP2040 and ESP32 pinmux macros. A part's ownpinswin over the board's; - at the bitrate of the link or the bus (
bitrate,current-speed,clock-frequency); - an MCP2515 under the SPI, for a CAN on SPI;
- the I2C devices at their
address.
It also writes an alias per bus (arche-chassis-can) and zephyr,canbus.
prj.conf turns on the drivers; it is written once.
Under Zephyr, the C of --target c opens each CAN or UART bus by that alias:
DEVICE_DT_GET(DT_ALIAS(arche_chassis_can)) in drivers.c.
renode#
The deployment's microcontrollers in Renode, without the boards:
renode/<deployment>/<machine>.replper processor with a binary. It uses Renode's own platform for itschip(using "platforms/cpus/stm32h743.repl"). A chip Renode has no platform for is a note, see the boards;machines.rescloads each binary's ELF. The path is wherecargo build --releaseputs the Embassy crate's, in a variable you can change. It adds a CANHub per CAN bus and a UARTHub per UART link of the platform;<deployment>.rescstarts it;<deployment>.robot, forrenode-test. It checks that the firmware starts its CAN controllers. It runs the test cases' frames: put on the bus for a part Renode does not run, counted by CAN id for a part it runs.
Linux processors are left out (a SocketCAN bridge, commented out).
ui-web#
The product's screens as a web app: ui-web/index.html, ui.js (the UI
runtime, the web renderer, the browser simulator), ui.css and ui.json (the
UI models, sample values, the sim program).
It runs on its own from the folder. By default the model is simulated in the
page. With ?ws=ws://host:port it shows live values over a WebSocket. The
protocol is in ui.
freertos, zephyr, posix#
The Arche app's RTOS skeleton: objects, tasks, priorities, stacks.
uppaal#
UPPAAL timed automata (model.xml) and queries
(model.q).
- There is one template per part with a state machine. Its states are locations.
- Composite states and pseudo-states that move on at once are committed locations.
- A message that a link brings is a broadcast channel. It is
?on the transition it triggers, and!where an action sends it. A sender whose sends no transition places gets an emitter template. - Each
withinguarantee gets an observer with a clock. - Each periodic thread of the deployment ticks.
- A guard on the component's own variables becomes a UPPAAL guard, see guards in UPPAAL and NuSMV. The rest of a guard is a comment and is dropped.
- Of the transitions of one state on one trigger, the first that can fire wins.
The queries are A[] not deadlock, E<> P.S per state, and A[] not Obs.late per deadline.
nusmv#
NuSMV or nuXmv, untimed:
- one
MODULEper state machine, withstate, a free inputevent, and aTRANSrelation from the transitions. The first transition that can fire wins. One whose guard is not fully translated may fire or not; CTLSPEC EFper state.
components#
The Arche app's component sources in Rust, C or C++. Your code is kept
between generations (arche-cli gen).
Guards in UPPAAL and NuSMV#
A variable of the component, such as var mode: Mode = MANUAL, is followed
when two things hold:
- it starts at a value written in the model;
- only the machine's transitions change it, each time to a value written there
too (
/ self.mode = AUTO).
It then becomes a small integer: the index of its value in the list of values
it can take. The export prints that list as a comment. A guard on it is
translated exactly, such as [self.mode == MANUAL and not self.armed] or
[self.tries < LIMIT].
Some variables are not followed, and the export notes each one:
- one no transition sets: it is an input;
- one other code also changes, such as a handler or a function;
- one a transition sets to a computed value.
The same goes for the rest of a guard: a message field, a call or an or.
Those parts are dropped. So the checked model allows more than the real one,
never less. A value that a test step or the physics writes into a followed
variable is not seen.
Monitors in the firmware#
A monitor checks a requirement while the firmware runs. archec gen --target c --monitors compiles the requirements into each binary of the deployment. They
are the same checks archec replay makes on a log.
What each kind of requirement checks:
- An EARS requirement watches for its trigger: a message the part receives,
or a state it enters. Then it watches for its response within its
within. With nowithin, the response is due right after the trigger is handled. - A
formalnever,alwaysorimpliesmust hold at every check. eventually C within 30msmust hold by 30 ms after the binary starts.A leads to B within 20msmust hold each time A holds. ForX receives M, that is each time M arrives.
The earliest answer awaited is the one that counts. So each requirement takes
one flag and one deadline: constant memory, and constant time per check. With
no within, eventually and leads to cannot fail at run time, so they are
left out.
How it runs in the C:
- A binary checks the requirements whose parts it runs.
c/<binary>/monitors.hlists them. - The wiring arms a monitor when the trigger arrives, before the part handles it. It clears the monitor when the part sends the message or reaches the state. It checks after each message, and from a monitor thread.
- A violation calls
arche_monitor_violation(req, at_ns). That function is yours, inmonitor_hook.c. It is written once, and logs by default. - There is no heap: one small struct per requirement.
- When the binary's threads preempt each other, define
ARCHE_MONITOR_LOCKandARCHE_MONITOR_UNLOCKas a critical section. - With
--traceas well, each verdict is also a trace record:arche-trace <ns> monitor <REQ> <1|0>. A failure is always recorded. A pass is recorded when a response arrives in time.
--target embassy --monitors does the same in Rust. It writes a Requirement
enum, a Monitors struct behind a blocking mutex, and a monitor_task. The
struct holds a copy of each watched part's state, kept by that part's task.
The MonitorHook trait is implemented by Hook in src/monitor_hook.rs
(yours, written once).
One instant, deadlines and watchdogs#
What happens at one instant happens in the order the specification gives. As in Lingua Franca, the model says the order, not the machine:
- what is due first runs first;
- a part does one thing at a time;
- a message fires the innermost transition first, then the port's
on-receive, then its handlers.
The simulator (archec sim) and the C follow this order.
A deadline is on a port or a transition, with an on-deadline body. When
the part starts on a trigger too late, that body runs instead.
A watchdog runs out unless a body restarts it in time:
watchdog w { timeout 50ms; on-timeout … }
A body restarts it with kick w.
Both are simulated, and both are generated:
- In C:
arche_item_t.sent,<part>_kickand<part>_timeouts. The wiring's threads wait for the next timer. - In Rust (Embassy): a channel into a part with a deadline carries
(Instant, message). The task compareselapsed()with the deadline. When it is late, it callson_deadline_<port>oron_deadline(t)instead. - In Rust, a part's watchdogs are a
<Part>Watchdogsfield (self.wd.kick(…)). The task'sselectalso waits on anembassy_time::Timeruntil the next watchdog runs out, then callson_timeout(w).
With --trace, each is a line:
arche-trace <ns> deadline <part>.<port or From->To> <µs late>
arche-trace <ns> watchdog <part>.<name> 0
archec difftest main.arche --seed 3 checks the C against the simulator. It
puts the same random inputs into both. The C is built with a harness on a
virtual clock. The two traces are compared, and the first difference is
shown.
Calls to another part#
In the action language, port.op(…) calls an operation of an interface the
port requires (the specification).
- In C, it is
<part>_call_<port>_<op>(self, …). The wiring gives this function. It calls the part at the other end of the link, chosen by which part asks.difftestchecks it against the simulator. - In Rust, it is an
Outmethod. It sends a request to the provider's task (CALL_…, a channel) and awaits its reply (REPLY_…, a signal). When the other end is a device of the board (sampler.sensor -> sensor.temperature_sensor), the method runs the device's driver throughhw::with. A driver that does not answer gives the default value, and with--traceafaultline. - In Go it is
Call, and in C++ astd::functionmember. The binary's main sets both.
Thread priorities in Embassy#
Thread priorities are enforced with one executor per priority level. A more urgent level preempts the ones below it. So a slow handler on a low-priority thread cannot hold up the 1 ms loop.
On a chip (
hal stm32|nrf|rp|esp32), each level is anInterruptExecutoron a spare interrupt:- stm32:
UART4,UART5…; - nrf:
SWIn_EGUn; - rp:
SWI_IRQ_n; - esp32: software interrupts 1–3, esp-hal's.
The interrupt priorities are in the same order: the most urgent level has the lowest number.
P0is left to the HAL. If your firmware uses one of these interrupts, change it inmain.rs. When there are more levels than the chip has priority bits (rp: 3), the least urgent ones share the last executor, andgensays so.- stm32:
On a host (
hal std), each level is an executor on its own OS thread at that priority (thread-priority). On Linux, SCHED_FIFO needsCAP_SYS_NICE.Tasks with no priority run in thread mode, the lowest level. These are bus tasks and threads without
priority. When no task is without a priority, the least urgent level takes thread mode.An
isrwith no priority is above every thread.
Within one level, and on a bare cortex-m skeleton, tasks are cooperative. A
message handler runs to its end first. So archec check warns
(handler-blocking) when a handler on a periodic thread can hold its step
past the deadline.
main.rs is yours once written. A crate generated before priority levels
existed does not start them; gen notes it.
CAN in Embassy#
On a bus:
- an
optionalfield is a presence byte, then its value; - a
unionis a case byte, then its largest case. The DBC multiplexes on the case byte, or says in a comment when a signal counts.
src/can.rs moves the frames between the bus channels and the hardware. It is
yours once written.
- On a host: Linux SocketCAN, and CAN FD when the bus is CAN FD.
hal stm32: bxCAN on CAN1, classic frames, up to 1 Mbit/s.hal esp32: the TWAI controller (TWAI0), classic frames, at the nearest of 125k, 250k, 500k or 1M bit/s.
Check the pins in main.rs. nRF chips, the RP2040 and the ESP32-C2 have no CAN
controller. There the channels are left to your driver, for example for an
external MCP2515 on SPI.
Limits#
arxmlleaves out send and receive points, units and data constraints. It also leaves out arrays, optional fields and unions in the field-by-field mapping.arxml-adaptiveleaves out UDP/TCP ports and service discovery timings, E2E, security, persistency, platform health management and StdCppImplementationDataTypes.arxml-adaptiveleaves out a binary on a microcontroller: it is a Classic ECU, forarxml.uppaalandnusmvdrop the parts of a guard they cannot translate, so the checked model allows more than the real one.renodeleaves out Linux processors.k8scannot say the exact cores or a bridgelatency: they are notes.- On nRF chips, the RP2040 and the ESP32-C2, the Embassy CAN channels are left to your driver.