ALITSoftware Architect Get the extension

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:

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

Step 1 open in VS Code: the port definitions in General View

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);
  }
}

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 open in VS Code: the ECU's five parts wired in Interconnect View

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;
  }

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);
  }

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

Step 3 open in VS Code: the package's occurrences connected over LIN, motor, sensor and CAN in Interconnect View

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);

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 open in VS Code: the controller's state machine in Flow View

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);
    }
  }

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();
    }

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 open in VS Code: the schedule with deadlines in Timing View

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;
    }

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 open in VS Code: use cases, tests, actors and requirements in Case View

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";
    }
  }

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;
  }

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';

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

Step 7 open in VS Code: the deployment and named views in the source; the Interconnect View of the package draws the system beside the platform Vehicle and its door module frontLeftDoor

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;

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