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
Blueprint Bina, the module guide, in a scene from this chapter.
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.

  • The table should include source state, event, guard, action, target state, timeout, and the log fields needed for diagnosis.
  • 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.
  • The dispatch algorithm should prefer deterministic rules over clever branching.

Key terms

Concurrency
Concurrency is where informal state machines fail.

Why it matters

That pattern works in embedded C, Rust, Python services, TypeScript backends, and test harnesses because the reviewable artifact is the table, not the syntax.

IoT device lifecycle from manufacturing and provisioning through active operating, sleeping, updating, maintenance, and decommission states.
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)

A mature state machine makes normal behavior, rejected events, timeout paths, and recovery paths equally reviewable.

  • Tools: statecharts, SCXML, XState-style models, table-driven dispatch, and property-based tests can keep diagrams, code, and tests aligned.
  • The lifecycle makes clear why a record needs more than the current mode.
  • Concurrency is where informal state machines fail.
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.

  • 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.
  • 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.
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

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?

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

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

iotclass.org

Print reference

Answers

Answer key.

  1. C · A state machine is useful when a system has modes and only certain events are legal in each mode.
iotclass.org