swa.ml language tutorial
This tutorial builds a complete swa.ml 3.2 model in seven steps: the window-lifter ECU of a car door. The door switch panel sends commands over LIN, the ECU drives the window motor, tracks the glass with a Hall sensor and reverses the motor when the motor current shows a trapped hand. Position counts run from 0 (closed) to 400 (fully open), and the glass moves 4 counts every 10 ms.
Each step is a complete, valid model that adds one topic to the previous one. Every snippet below is copied from the step file named above it, so you can open the file and find it there. For the extension itself (views, editing, runs and export), follow the Extension tutorial. For the full rules of each construct, read the swa.ml language guide and the usage guide.
Get the files
The model and its steps are an MIT-licensed example in the swa.ml repository, under examples/tutorial/window-lifter. Read them there, clone the repository, or download the same files as window-lifter.zip and unzip it. The folder contains:
steps/step1-ports.swamltosteps/step7-views.swaml, the seven steps;window-lifter.swaml, the finished model (step 7 without the step note in its documentation);.swamlignore, which leavessteps/out of the project. Every step declares the same packageWindowLifter; without the ignore file, VS Code would load all eight copies as one project and report SW2001 on each. A step file you open is checked on its own. The folder in the swa.ml repository has the same.swamlignore, and the repository's example check validates each file on its own.
Each file can also be read on its own in the repository, for example step1-ports.swaml.
Validate and run each step
Open a step in VS Code with Aliot Software Architect installed; diagnostics appear as you type. To check a step from a terminal, use the extension's validator (run swa.ml: Copy Headless CLI Command for the full path):
node "<extension-folder>/out/validate.mjs" steps/step1-ports.swaml
Validated 1 swa.ml file(s), swa.ml 3.2 (language release 0.3.3).
The swa.ml language's own command-line tool also simulates a model and runs its use cases and tests. Clone the swa.ml repository, run npm ci and npm run build there, then run its CLI on the steps, which are already in the clone:
cd examples/tutorial/window-lifter
node ../../../out/src/cli/main.js steps/step1-ports.swaml
node ../../../out/src/cli/main.js simulate --until-ns 50000000 steps/step4-behaviour.swaml
node ../../../out/src/cli/main.js test steps/step6-requirements.swaml
The first command prints Checked 1 model(s), swa.ml 3.2: 0 error(s). for every step. simulate prints the run as JSON; test prints one line per case. Each step below says what to expect.
Step 1: enums and ports

A model starts with a package, the named context that owns every declaration. A /** … */ comment right after an opening brace is the documentation of its owner; the diagrams, Properties and Grid show it. This is the whole of step 1:
From steps/step1-ports.swaml:
package WindowLifter {
/** Step 1: value types and port definitions. Ports are typed contracts: provides marks what a side sends. A car window-lifter ECU: the switch panel sends commands over LIN, the ECU drives the window motor, tracks the glass with a Hall sensor and reverses when the motor current shows a trapped hand. */
enum Command {
none, up, down, autoUp, autoDown
}
enum Direction {
stop, up, down
}
port def SwitchLin {
/** LIN frame of the door switch panel: the pressed detent, none when released. */
provides event pressed(command: Command);
}
port def Request {
provides attribute command: Command = Command.none;
}
port def Drive {
provides attribute direction: Direction = Direction.stop;
}
port def MotorPwm {
/** H-bridge duty cycle in percent: positive closes, negative opens. */
provides attribute duty: int = 0;
}
port def HallSensor {
provides attribute counts: uint = 400;
}
port def MotorCurrent {
provides attribute milliamps: uint = 0;
}
port def PinchAlarm {
provides attribute active: bool = false;
}
port def Obstacle {
/** Position at which something blocks the glass; 0 means nothing is in the way. */
provides attribute at: uint = 0;
}
port def BodyCan {
/** CAN frame WindowStatus to the body controller. */
provides event windowStatus(position: uint, pinched: bool);
}
}
enumdeclares a value type with named literals. A literal is written with its enum,Command.none.port defdeclares a port type: a typed contract between two components. Each member has a direction.providesmarks what the owner of a plainportof this type sends; areversed portof the same type turns everyprovidesintorequires, so it receives.provides event pressed(command: Command);is an event: a message with typed parameters, sent withpublishand queued at the receiver. The LIN switch frame and the CAN status frame are events.provides attribute duty: int = 0;is an attribute member: a sampled value with an initial value, updated withsend. The receiver reads the latest value, like a signal on a wire. Motor duty, Hall counts and motor current are attributes.- The built-in types used here are
bool,intanduint; swa.ml also hasbyte,real,string, records (datatype) and fixed arrays.
Nothing uses the ports yet, and the step validates with no diagnostics. More in ports and communication.
Step 2: components and the ECU's wiring

Step 2 declares the software parts, the plant and the actors as component definitions. A definition is a type: it describes ports, state and parts, and every occurrence of it gets its own state.
From steps/step2-components.swaml:
component def AntiPinch {
/** Flags a pinch when the closing motor draws more than the force limit allows. */
reversed port current: MotorCurrent;
port alarm: PinchAlarm;
const attribute limitMa: uint = 6000;
}
component def Controller {
/** The window state machine: manual and one-touch travel, and reversal on a pinch. */
reversed port request: Request;
reversed port position: HallSensor;
reversed port pinch: PinchAlarm;
port drive: Drive;
port bus: BodyCan;
attribute reversals: uint = 0;
}
port alarm: PinchAlarm;gives the component a port of that type;AntiPinchprovidesactive.reversed port current: MotorCurrent;receives the motor current that the window provides.attribute reversals: uint = 0;is mutable state of each occurrence, private to the component.const attribute limitMais a fixed configuration value per occurrence.
The ECU itself is a definition made of parts and connections:
From steps/step2-components.swaml:
component def WindowLifterEcu {
/** The door ECU software: five parts behind the LIN, motor, sensor and CAN ports. */
reversed port switch: SwitchLin;
port pwm: MotorPwm;
reversed port hall: HallSensor;
reversed port current: MotorCurrent;
port bus: BodyCan;
component input: InputHandler;
component tracker: PositionTracker;
component antiPinch: AntiPinch;
component controller: Controller;
component driver: MotorDriver;
connect (switch, input.switch);
connect (hall, tracker.hall);
connect (current, antiPinch.current);
connect (input.request, controller.request);
connect (tracker.position, controller.position);
connect (antiPinch.alarm, controller.pinch);
connect (controller.drive, driver.drive);
connect (driver.pwm, pwm);
connect (controller.bus, bus);
}
component input: InputHandler;declares a part: an occurrence ofInputHandlerowned by everyWindowLifterEcu.connect (a, b);joins an owned port or a port of an immediate part.connect (input.request, controller.request);joins two parts: whatinputprovides,controllerreceives.connect (switch, input.switch);joins the ECU's own boundary port to a part's port with the same direction, which forwards the boundary to the part. The endpoints are unordered.
The actors are interface-only components: they have ports and nothing else, and later steps drive them from use cases and tests.
From steps/step2-components.swaml:
component def SwitchPanel {
/** Actor: the driver's door switch panel. */
port switch: SwitchLin;
}
Step 3: occurrences and connections

Definitions alone do not run. Step 3 places top-level occurrences in the package and connects them. A package is a closed context: its connections join ports of its own top-level occurrences.
From steps/step3-connections.swaml:
component driver: SwitchPanel;
component passenger: Passenger;
component ecu: WindowLifterEcu;
component window: Window;
component body: BodyController;
connect lin (driver.switch, ecu.switch);
connect motor (ecu.pwm, window.pwm);
connect sensor (window.hall, ecu.hall);
connect shunt (window.current, ecu.current);
connect can (ecu.bus, body.bus);
connect (passenger.hand, window.obstacle);
component ecu: WindowLifterEcu;at package level is an occurrence: the ECU that exists in this system, with its own five parts.connect lin (driver.switch, ecu.switch);is a named connection; the name shows on the diagrams. A bareconnectuses the default policySwaml::Qos::Default(at most once, in order, a queue of 16).connect name: Reliable (a.p, b.q);chooses another policy.- Every port that is not
optionalmust be connected. Leave outconnect can (...)and validation reports SW2004, "Unconnected required port ecu.bus in package WindowLifter.", and the same forbody.busand the forwardedecu.controller.bus.
The window is the plant, the physical part the software controls; the passenger's hand provides an obstacle position to it.
Step 4: behaviour

Step 4 adds operations (what each component does) and schedules (when it does it). The input handler turns each LIN frame into the current request:
From steps/step4-behaviour.swaml:
component def InputHandler {
/** Turns LIN switch frames into the current request. */
reversed port switch: SwitchLin;
port request: Request;
operation handle(command: Command) {
send request.command(command);
}
schedule {
on receive switch.pressed(command) handle(command);
}
}
operation handle(command: Command) { … }declares behaviour with typed parameters. Withoutreturns, it returns nothing.send request.command(command);updates the provided attributecommandof the portrequest. Usesendfor an attribute member andpublishfor an event.schedule { … }says when operations run.on receive switch.pressed(command) handle(command);runshandlefor eachpressedevent and binds the event'scommandparameter to the argument.on every 10ms track();runs an operation periodically. An operation without a schedule entry is a helper that runs only when called.
The controller's control is a state machine, written as states in the operation's flow:
From steps/step4-behaviour.swaml:
operation control() {
while (true) {
state idle {
on entry {
send drive.direction(Direction.stop);
}
if (request.command == Command.up and position.counts > 0) to closing;
if (request.command == Command.down and position.counts < 400) to opening;
if (request.command == Command.autoUp and position.counts > 0) to autoClosing;
if (request.command == Command.autoDown and position.counts < 400) to autoOpening;
}
state closing {
on entry {
send drive.direction(Direction.up);
}
if (pinch.active) to reversing;
if (request.command != Command.up or position.counts == 0) to idle;
}
and further down in the same operation:
state autoClosing {
on entry {
send drive.direction(Direction.up);
}
if (pinch.active) to reversing;
if (position.counts == 0 or request.command == Command.down) to idle;
after 3s to idle;
}
state reversing {
on entry {
reversals = reversals + 1;
send drive.direction(Direction.down);
}
after 200ms to idle;
}
}
}
operation report() {
publish bus.windowStatus(position.counts, reversals > 0);
}
schedule {
on every 10ms control();
on every 100ms report();
}
state idle { … }is a step of the flow. When the flow reaches it,on entryruns once, and the state stays, waiting.- Each time something happens to a waiting state (here, each 10 ms release of
on every 10ms control();, becausecontrolis a periodic machine), it looks at its lines again from the top.if (pinch.active) to reversing;checks now and goes to the statereversingwhen the condition holds. Readingrequest.commandorpinch.activereads the latest value received on thatreversedport. The guards out ofidlealso check the end positions (position.counts > 0to close,< 400to open), so a command held at an end leaves the motor stopped. after 3s to idle;leaves after 3 s in the state, the safety stop of one-touch travel.after 200ms to idle;ends the reversal.while (true) { … }keeps the machine running;to idlejumps back to the first state.report()publishes the CAN status every 100 ms.reversals > 0is aboolexpression passed as thepinchedvalue.
The plant moves the glass and models the stall current with var, if / else if and arithmetic:
From steps/step4-behaviour.swaml:
operation move() {
var blocked: bool = pwm.duty > 0 and obstacle.at > 0 and position <= obstacle.at;
if (blocked) {
send current.milliamps(9000);
} else if (pwm.duty > 0 and position > 0) {
position = position - 4;
send current.milliamps(2500);
} else if (pwm.duty < 0 and position < 400) {
position = position + 4;
send current.milliamps(2500);
} else {
send current.milliamps(0);
}
send hall.counts(position);
}
The motor driver chooses its duty with a conditional expression, if (c) a else b, written as a value:
From steps/step4-behaviour.swaml:
send pwm.duty(if (drive.direction == Direction.up) 100 else if (drive.direction == Direction.down) -100 else 0);
Run the model for 50 ms of logical time with the language CLI: simulate --until-ns 50000000 steps/step4-behaviour.swaml ends with "outcome": "no-failure-observed" and "status": "horizon", and its stores show the window still at "position": 400, since nobody has pressed the switch yet. More on states and schedules.
Step 5: deadlines and execution time

Step 5 changes only schedules and adds execution times. Every schedule entry gets a deadline, and the sampling operations model how long they take with wait.
From steps/step5-timing.swaml:
component def PositionTracker {
reversed port hall: HallSensor;
port position: HallSensor;
operation track() {
wait 200us;
send position.counts(hall.counts);
}
schedule {
on every 10ms track() deadline 1ms;
}
}
From steps/step5-timing.swaml:
schedule {
on every 10ms control() deadline 2ms;
on every 100ms report() deadline 5ms;
}
deadline 1msbounds each activation, from its release to its end, including any waiting. Without it, a periodic entry's deadline is its period. A periodic deadline cannot exceed its period:deadline 20mson a 10 ms entry is error SW2007.wait 200us;suspends the activation for 200 µs of logical time, standing in for the time the work takes. A wait releases the component, so another activation may change its attributes in the meantime.- Durations are written with a unit:
us,msors(andns). on receive switch.pressed(command) handle(command) deadline 2ms;gives an event handler a deadline too.
Timing View draws one row per schedule entry with its activations and deadline flags. A simulation of step 5 for the same 50 ms takes 530 steps instead of 480, because each wait adds a resume. Deadlines in the model are requirements on the schedule; the run is evidence of one bounded run, not a guarantee for the real ECU.
Step 6: requirements, use cases and tests

Step 6 records what the ECU must do and checks it. A requirement has documentation and typed attributes:
From steps/step6-requirements.swaml:
requirement 'Anti-pinch reversal' {
/** When the closing glass meets an obstacle, the motor reverses within 100 ms. */
attribute reactionMs: uint = 100;
}
A name with spaces or other special characters is written in single quotes, 'Anti-pinch reversal'.
A use case describes an interaction with the system and can run as a script. It acts through the ports of the actors associated with it:
From steps/step6-requirements.swaml:
use case 'Close with one touch' of ecu {
/** The driver taps auto-up and lets go; the body controller sees the glass moving without a pinch. */
publish driver.switch.pressed(Command.autoUp);
wait 50ms;
publish driver.switch.pressed(Command.none);
on receive body.bus.windowStatus(position, pinched) {
assert position < 400 and not pinched;
} or after 200ms {
fail "no window status";
}
}
of ecunames the subject, a top-level occurrence of the same package: the system under consideration.publish driver.switch.pressed(Command.autoUp);acts as the driver: it publishes an event on the switch panel's port, which thelinconnection delivers to the ECU. Script endpoints are writtenoccurrence.port.member.wait 50ms;lets logical time pass.on receive body.bus.windowStatus(position, pinched) { … } or after 200ms { … }waits for the CAN frame at the body controller and binds its values; if none arrives within 200 ms, the other branch runs.assertchecks a condition, andfail "…"fails the case with a reason.
A test may also read the state of its subject and of the occurrences associated with it:
From steps/step6-requirements.swaml:
test 'Pinch reverses within 100 ms' of ecu {
/** A hand at 200 counts stalls the glass; the PWM turns negative within 100 ms of the stall. */
send passenger.hand.at(200);
publish driver.switch.pressed(Command.autoUp);
wait 30ms;
publish driver.switch.pressed(Command.none);
wait 485ms;
assert window.position == 200 and ecu.controller.reversals == 0;
wait 100ms;
assert window.position > 200 and ecu.controller.reversals == 1;
}
send passenger.hand.at(200);sets the passenger's obstacle attribute: a hand at 200 counts.ecu.controller.reversalsreads a private attribute of a part of the subject, andwindow.positionone of an associated occurrence. Only tests may do this; a use case stays a black box and works through actor ports.- Another test keeps a value in a local:
var stopped: uint = window.position;.
The package then links the cases, actors and requirements:
From steps/step6-requirements.swaml:
associate passenger to 'Pinch reverses within 100 ms';
associate driver,
window
to 'Close with one touch',
'Close manually',
'Auto-up closes fully',
'Pinch reverses within 100 ms',
'Manual closing stops on release';
associate body to 'Close with one touch', 'Close manually';
satisfy 'Anti-pinch reversal' by AntiPinch;
satisfy 'One-touch closing' by Controller;
satisfy 'Closing force limit' by AntiPinch;
verify 'Anti-pinch reversal' by 'Pinch reverses within 100 ms';
verify 'Closing force limit' by 'Pinch reverses within 100 ms';
verify 'One-touch closing' by 'Auto-up closes fully';
associate driver, window to 'A', 'B';records that each listed occurrence takes part in each listed case; a script may act through an associated actor's ports, and a test may read an associated occurrence.satisfy Requirement by Design;claims that a component definition or occurrence path is meant to meet the requirement.verify Requirement by Test;links a test that checks it. A use case never verifies.
Run the cases with the language CLI's test command:
pass WindowLifter::Close with one touch
pass WindowLifter::Close manually
pass WindowLifter::Auto-up closes fully
pass WindowLifter::Pinch reverses within 100 ms
pass WindowLifter::Manual closing stops on release
5 case(s): 5 pass, 0 fail, 0 inconclusive, 0 no checks.
In VS Code, the same cases run from the Testing view, their code lenses or Run on the diagram toolbar. Each case runs in its own fresh, deterministic run of the package. A requirement claim records intent, and a passed test is evidence of one run, not a proof. More on cases.
Step 7: deployment and views

The last step imports two standard libraries, places the ECU on a hardware node and declares named views.
From steps/step7-views.swaml:
import Swaml::Views;
import Swaml::Platform;
From steps/step7-views.swaml:
component def DoorModule specializes Node {
const attribute cores: uint = 1;
}
component Vehicle: Platform {
component frontLeftDoor: DoorModule;
}
deployment InDoor of ecu on Vehicle {
deploy on frontLeftDoor;
}
view overview: General of WindowLifter;
view wiring: Interconnect of ecu;
view states: Flow of ecu.controller.control;
view oneTouch: Sequence of 'Close with one touch';
view cases: Case of WindowLifter;
view timing: Timing of ecu.controller.control;
view inventory: Grid of WindowLifter;
import Swaml::Platform;makesNodeandPlatformusable by their short names;import Swaml::Views;does the same for the view kinds.component def DoorModule specializes Nodedeclares a hardware node type.specializesinherits from another definition; General View draws it as a line with a hollow triangle.component Vehicle: Platform { … }is the platform root, with the door module as a part.deployment InDoor of ecu on Vehicle { deploy on frontLeftDoor; }places theecuoccurrence and all its parts on the front-left door module. A target must be a node occurrence of the platform root.view wiring: Interconnect of ecu;declares a named view: a kind (General, Interconnect, Flow, Sequence, Case, Timing or Grid) and what it shows. Named views select existing elements; their layout is saved beside the model, never in it.
The finished window-lifter.swaml is step 7 with the package's own documentation. It validates without diagnostics and all five cases pass.
What you used
| Construct | Step |
|---|---|
package, /** … */ documentation, enum |
1 |
port def, provides event, provides attribute with an initial value |
1 |
component def, port, reversed port, attribute, const attribute |
2 |
parts (component x: Def; inside a definition) and connect |
2 |
| top-level occurrences and named package connections | 3 |
operation, send, publish, var, if / else if, conditional expression |
4 |
state, on entry, if (…) to s;, after D to s;, while (true) |
4 |
schedule, on receive … handle(x), on every D |
4 |
deadline, wait |
5 |
requirement, quoted names, use case … of, test … of |
6 |
case scripts: publish, send, wait, on receive … or after, assert, fail |
6 |
associate, satisfy, verify |
6 |
import, specializes, deployment, deploy on, view |
7 |
Go further
- The swa.ml language guide, with the usage guide, the keyword reference and the complete 3.2 reference.
- The language's official examples, from a first counter to services, parallel parts and deployment.
- The Extension tutorial, which opens this model in every view, edits it from the diagrams and runs its cases.