Design Patterns · Study deck

Device State Machines: Modes and Safety

A state diagram is useful only if the real controller rejects that impossible combination.

Blueprint Bina is your guide for this deck.

statemachine
iotclass.org

After studying this chapter

Learning objectives

You will be able to:

  • Choose when a state machine is a better design than scattered flags or nested conditionals.
  • Model IoT connection, sampling, actuator-safety, and cloud-shadow workflows as state machines.
  • Define transition contracts using states, events, guards, actions, targets, timeouts, and logs.
  • Explain why waiting states need timeout and error transitions.
iotclass.org

Major section

Start With the Behavior That Must Not Be Ambiguous

A state diagram is useful only if the real controller rejects that impossible combination.

  • A state-machine pattern earns its place when a device has behavior that prose cannot keep straight.
  • Sleep, wake, sample, transmit, retry, fault, and recover are simple words, but a deployed device needs exact rules for moving between them.
  • The practical story is to make modes visible before adding cleverness.
iotclass.org

Major section

Modes Become Safer When They Are Named

A device that is commissioning over BLE, reconnecting over LTE, applying a firmware update, or holding an actuator in lockout should not be interpreted through the same loose set of flags.

  • The mode is part of the product contract.
  • A gateway should not be both locked out and active.
  • That keeps the model reviewable.

Why it matters

That matters for IoT because connection, power, command, actuator, and cloud-shadow behavior all depend on what the device or service is allowed to do right now.

iotclass.org

Major section

Modes Become Safer When They Are Named (continued)

The design quality test is whether the model rejects impossible combinations before they escape into firmware and operations.

  • A sensor should not transmit forever after a missed acknowledgement.
  • A shadow should not report success for a command the device rejected locally.
  • Good state-machine work also separates independent concerns.
iotclass.org

Major section

Modes Become Safer When They Are Named (continued)

Guards prevent unsafe transitions unless conditions such as authorization valid, battery above threshold, door closed, retry budget remaining, or command sequence accepted are true.

  • A temperature node may accept a calibration command only after it has completed warmup.
  • The practical value is shared language.
  • QA can write tests for rejected events and timeout paths.
iotclass.org

Major section

Modes Become Safer When They Are Named (continued)

A lock may accept an unlock command only after it has verified authorization, door position, and local safety state.

  • A Matter or Bluetooth LE pairing flow may allow different events during advertising, credential exchange, verification, and operational modes.
  • Connection lifecycle, sampling cycle, actuator safety, and cloud synchronization often deserve separate machines or hierarchical regions rather than one giant list of combined states.
  • Firmware engineers can implement table-driven dispatch in C, Rust, or MicroPython.
iotclass.org

Major section

Build The Transition Table First

Connection: MQTT, WebSocket, BLE, cellular modem, or Matter commissioning states need bounded connect attempts and backoff with jitter.

  • A gateway that bridges Modbus, BLE, Zigbee, or LoRaWAN into MQTT should not report a cloud command as applied until the downstream device confirms it or the command enters a visible failed state.
  • If a row cannot be reviewed by firmware, cloud, QA, and support together, the model is probably still too informal.
  • Safety: actuator transitions should move toward SAFE_OFF, EMERGENCY_STOP, or LOCKOUT on watchdog, sensor fault, overcurrent, or invalid command events.
iotclass.org

Major section

Build The Transition Table First (continued)

A valve, pump, or door controller should treat local interlock state as stronger than a cloud command.

  • The transition table should say what happens when the sensor never becomes ready, the broker acknowledgement times out, flash storage is full, battery is below threshold, or the device receives an OTA update request mid-cycle.
  • Cloud shadow: AWS IoT Device Shadows, Azure Device Twins, or similar desired/reported models need rejected and stale states, not only synchronized success.
  • In Zephyr or FreeRTOS, keep transition logic separate from driver actions so the model can be unit tested without real radios and sensors.
iotclass.org

Major section

State Is Data With Time

The implementation must carry enough context to explain a transition later: previous state, event, guard result, target state, action result, timestamp, firmware version, boot reason, command id, sequence number, and correlation id.

  • Without that context, a field failure becomes a guess about which branch ran.
  • Tools: statecharts, SCXML, XState-style models, table-driven dispatch, and property-based tests can keep diagrams, code, and tests aligned.
  • The dispatch algorithm should prefer deterministic rules over clever branching.

Key terms

Concurrency
Concurrency is where informal state machines fail.
IoT device lifecycle showing manufacturing, provisioning, the active operating, sleeping, and updating states, maintenance after a fault, repair back to active operation, and end-of-life decommissioning.
IoT device lifecycle from manufacturing and provisioning through active operating, sleeping, updating, maintenance, and decommission states.
iotclass.org

Major section

State Is Data With Time (continued)

Synchronization: device-shadow version, MQTT retained state, OTA rollback slot, and local event log sequence need explicit rules when cloud and device reconnect.

  • The lifecycle makes clear why a record needs more than the current mode.
  • This ordering shows why state is data with time: a later reviewer needs the event, prior state, and recorded outcome to distinguish routine activity, recovery, and irreversible retirement.
  • Concurrency is where informal state machines fail.
iotclass.org

Major section

State Is Data With Time (continued)

Many production systems use a transition table keyed by state and event, with guard functions and action functions attached to each row.

  • The dispatch step finds candidate rows, evaluates guards in a documented order, executes one idempotent action, records the transition, and rejects everything else with a structured log.
  • A device may receive a cloud command while it is reconnecting, wake because of a local interrupt while an OTA update is pending, or reboot after writing the action but before writing the final state.
  • A mature state machine makes normal behavior, rejected events, timeout paths, and recovery paths equally reviewable.
iotclass.org

Major section

State Is Data With Time (continued)

The implementation needs atomic update rules for persisted state, sequence checks for command messages, idempotent actions for retry, and a startup policy that decides whether to resume, roll back, or enter a safe state.

  • For cloud shadows and twins, desired and reported versions should be compared explicitly so an old desired property cannot overwrite a newer local decision.
  • The deeper engineering habit is to treat every missing transition as a product decision waiting to be made.
  • A device may receive a cloud command while it is reconnecting, wake because of a local interrupt while an OTA update is pending, or reboot after writing the action but before writing the final state.
iotclass.org

Major section

State Machine Pattern Map

Each ends at requires reviewed recovery rules, so the map's message is practical: selecting a pattern identifies which failures and recovery events the implementation must make explicit before the chapter examines individual examples.

  • Models safe off, armed, active, limited, emergency stop, and lockout behavior.
State machine pattern map for reviewing IoT device behavior
State machine pattern map for reviewing IoT device behavior
iotclass.org

Deck summary

Key takeaways

A state diagram is useful only if the real controller rejects that impossible combination.

  • A device that is commissioning over BLE, reconnecting over LTE, applying a firmware update, or holding an actuator in lockout should not be interpreted through the same loose set of flags.
  • The design quality test is whether the model rejects impossible combinations before they escape into firmware and operations.
  • Guards prevent unsafe transitions unless conditions such as authorization valid, battery above threshold, door closed, retry budget remaining, or command sequence accepted are true.
  • A lock may accept an unlock command only after it has verified authorization, door position, and local safety state.
iotclass.org

Retrieval practice

Recall check 1 of 4

Blueprint Bina says: answer from memory, then check your reasoning.

Q1A gateway has Boolean flags named connected, reconnecting, pendingConfig, commandInFlight, and emergencyStop. Different combinations are becoming hard to reason about. Which sign most strongly suggests a state machine would improve the design?

ASome flag combinations represent impossible or unsafe modes
BThe device publishes telemetry on a regular interval
CThe team wants a larger architecture diagram
DThe codebase has functions split across several files
Show answer

Answer: A A state machine is useful when a system has modes and only certain events are legal in each mode.

iotclass.org

Retrieval practice

Recall check 2 of 4

Blueprint Bina says: answer from memory, then check your reasoning.

Q2A valve controller gets an OPEN event while its safety guard fails. Which transition row is reviewable?

ARecord the OPEN event and desired target alone, keeping guard and timeout behavior outside the row.
BOpen the valve before testing the failed guard, then record the resulting action in the log.
CKeep the guard only in code, leaving the transition table without a reviewable safety condition.
DRecord source, event, failed guard, no-open action, safe target, timeout path and log fields.
Show answer

Answer: D A transition row must show the condition, action, target, timeout, and evidence for both accepted and rejected events.

iotclass.org

Retrieval practice

Recall check 3 of 4

Blueprint Bina says: answer from memory, then check your reasoning.

Q3A pump waits for an acknowledgement that may never arrive. What belongs in its state model?

AAn endless wait because the acknowledgement usually arrives.
BA timeout that enters a safe error path and leaves a transition record.
CA success transition whenever the network disconnects.
DA hidden retry loop with no state or log change.
Show answer

Answer: B Waiting states need bounded failure paths as well as success paths.

iotclass.org

Retrieval practice

Recall check 4 of 4

Blueprint Bina says: answer from memory, then check your reasoning.

Q4A team tests only the normal sample and send path of a battery device. Which added review best covers its state model?

ARepeat the normal sample-and-send path on faster hardware as proof that fault paths also work in field tests.
BReplay sleep, offline buffering, unsafe commands, stale updates and faults; inspect transition logs.
CRemove lockout so unsafe commands yield visible actions during the state-model test.
DReview the diagram alone, leaving transition tests and logs outside the state-model review.
Show answer

Answer: B A state-machine review needs normal, power, safety, failure, and trace evidence.

iotclass.org

Print reference

Answers

Answer key.

  1. A · A state machine is useful when a system has modes and only certain events are legal in each mode.
  2. D · A transition row must show the condition, action, target, timeout, and evidence for both accepted and rejected events.
  3. B · Waiting states need bounded failure paths as well as success paths.
  4. B · A state-machine review needs normal, power, safety, failure, and trace evidence.
iotclass.org