Skip to main content

Building a state machine

In this example we build a finite state machine that controls a temperature sensor: the sensor initialises, measures, and can be halted and resumed.

The state machine below follows the pattern described in the OPC UA reference manual.

State Machine

Declaring the state machine

A FiniteStateMachineType is defined by two things, and both are required: the states it can be in, and the transitions between them. Exactly one state carries isInitialState: true.

Temperature control state machine
stateMachines:
- browseName: TemperatureControlStateMachineType
subtypeOf: ua:FiniteStateMachineType
description: |
Controls a temperature sensor: it initialises, measures, and can be halted
and resumed.
# Promoting an inherited optional makes it mandatory on every instance, so a
# client can always read the current state by name.
promotedToMandatory:
- ua:CurrentState.ua:Name
- ua:LastTransition.ua:TransitionTime
states:
- name: Initializing
isInitialState: true
value: 0
description: |
**Initializing** — the sensor is powering up and self-checking.
- name: Measuring
value: 1
description: |
**Measuring** — the sensor is acquiring temperature values.
- name: Halted
value: 2
description: |
**Halted** — acquisition has been stopped and can be resumed.
transitions:
- from: Initializing
to: Measuring
value: 0
- from: Measuring
to: Halted
value: 1
- from: Halted
to: Measuring
value: 2

Each transition names the state it comes from and the state it goes to. The value is the transition's number in the address space — clients use it to tell transitions apart.

Promote what clients need to read

ua:CurrentState and ua:LastTransition are inherited as optionals. Listing them under promotedToMandatory makes them mandatory on every instance, so a client can always read the current state by name without checking whether the node exists.

Using it on an object type

A state machine becomes useful once an object type owns one. Declare it as a component whose typeDefinition is the state machine type:

A sensor driven by the state machine
objectTypes:
- browseName: TemperatureSensorType
subtypeOf: di:ComponentType
description: A temperature sensor driven by a state machine.
components:
- browseName: ControlState
typeDefinition: TemperatureControlStateMachineType
description: The state machine controlling this sensor.

instances:
- browseName: MyTemperatureSensor
typeDefinition: TemperatureSensorType
organizedBy: /ua:Objects

Generating this model produces MyTemperatureSensor with a ControlState component, its three states, and the three transitions between them.

Going further