Chapters

8 State Machines in IoT

reference-architectures
state
machines
iot

8.1 Start With the Device Mode

Prove Recovery Without Guessing the Hidden State

Picture a pump controller that restarts after a power cut and resumes an unsafe command. Recovery must use recorded rules, not an operator’s guess.

A gateway means the boundary system that joins local devices to another network or service. Treat its connection as an event, not as proof that the device state is correct.

Run startup, valid action, blocked action, lost link, power cut, and restart. Keep the initial state, event, guard, output, saved state, next state, and time so another person can replay the path.

This check covers named sequences on one build, not every race or hardware fault. The deeper sections add hierarchy, concurrency, persistence, timeouts, and distributed coordination.

A state machine starts when “the device is running” is no longer precise enough. A gateway might be idle, joining, connected, retrying, degraded, or locked out, and each mode allows different events.

For IoT, naming those modes turns vague behavior into a contract that developers, operators, and testers can inspect. Start with one device mode, one event, and one allowed transition; the rest of the state model grows from those visible promises.

In 60 Seconds

State machines make IoT behavior explicit. A device, gateway, or service is modeled as named states, receives events, evaluates guards, performs actions, and moves through checked transitions. This section shows where state machines fit in IoT systems, how the companion chapters build from concepts to implementation and reusable patterns, and how to check a design for fault handling, timing behavior, coordination, persistence, and test proof.

8.2 Learning Objectives

By the end of this section, you will be able to:

  • Explain why IoT systems use state machines to make device behavior checkable.
  • Route a learning path through fundamentals, implementation practice, and reusable design patterns.
  • Choose whether a behavior belongs in a device, gateway, service, or coordinated multi-machine design.
  • Compare Moore, Mealy, hierarchical, and parallel state-machine styles at a practical level.
  • Check IoT state-machine designs for fault paths, timeout behavior, guard/action separation, persistence, and transition coverage.
Quick Check: Gateway State Boundary

8.3 Minimum Viable Understanding

A state machine is useful when a system has named modes and clear events that move it between modes. In IoT, those events often come from timers, sensors, radio links, buttons, gateway messages, reset causes, or service acknowledgements.

Use this route:

Taken together, these checks make the section reviewable. That order makes timing, persistence, and recovery part of the behaviour contract, so the later implementation and test record can prove deterministic outcomes.

8.4 Section Map

This section has three companion chapters. Inspect Figure 8.1 to see how each one advances from vocabulary to implementation, reuse, and proof.

Section map linking the fundamentals, lab, and design-pattern chapters to the local concept, implementation, reuse, and proof checks for IoT state-machine work.
Figure 8.1: State machines section map

Read Figure 8.1 from fundamentals to the lab and then to reusable patterns. The sequence moves from naming a behaviour contract, through implementing and testing it, to selecting structures that remain understandable as device coordination grows.

State Machine Fundamentals

Use this chapter first when you need the vocabulary: state, event, transition, guard, action, output, fault path, and transition coverage.

Open the fundamentals chapter

Lab: ESP32 State Machines

Use this lab when you want to turn a transition table into a compact event-driven firmware loop and test record.

Open the implementation lab

State Machine Design Patterns

Use this chapter when you need reusable patterns for connection management, duty cycling, safety, and coordination.

Open the patterns chapter

8.5 Where State Machines Fit in IoT

State machines can appear at several layers. The key is to keep each machine responsible for one coherent behavior.

Choosing a state-machine boundary also chooses where events are interpreted and where recovery responsibility lives. Before assigning behaviour to firmware, a gateway, or a service, inspect Figure 8.2 to compare the jobs at each IoT layer and check that one machine is not being asked to span several ownership domains.

IoT layers showing device firmware, gateway coordination, edge service, cloud workflow, and operations-check state machines.
Figure 8.2: State machine placement across IoT layers

At the base of Figure 8.2, Device firmware owns immediate equipment behaviour such as sleep, sample, transmit, fault, reset, service. Move up to Gateway coordination and the vocabulary changes to registration, buffering, routing, back-pressure: these are fleet-facing concerns that require knowledge beyond one device. Edge service adds local analytics, offline mode, recovery, safety interlock, while Cloud workflow handles the longer-lived sequence ingest, validate, approve, acknowledge, close. The separate operations line—incident, maintenance, rollback, close—shows why organisational response should not be hidden inside a device transition table. This layering turns the chapter’s “one coherent behavior” rule into a placement test: keep fast local safety near the device, coordination at the gateway or edge, and human workflow in systems that can own its full lifecycle.

Common placements:

  • Device firmware: sleep, sample, transmit, fault, service, and reset behavior.
  • Gateway coordination: device registration, link health, local buffering, command routing, and back-pressure.
  • Edge service: local analytics, safety interlocks, offline mode, and recovery after network loss.
  • Cloud workflow: ingest status, approval workflow, alert lifecycle, and command acknowledgement.
  • Operations process: incident states, maintenance handoff, rollback decision, and closure check.

Avoid one giant state machine that owns everything. Split behavior where ownership, timing, or failure domains differ.

8.6 State-Machine Styles

The style is a design choice. Pick the style that makes behavior easiest to prove.

To judge State-Machine Styles rather than merely name it, first establish how “State-machine style choice for IoT behavior” is explicit in the diagram. Figure 8.3 is the evidence map for that judgment.

Decision map comparing Moore, Mealy, hierarchical, and parallel state-machine styles by output stability, event response, shared behavior, coordination, and proof burden.
Figure 8.3: State-machine style choice for IoT behavior

Start Figure 8.3 at Moore, but do not stop there: share handling changes the interpretation, and coordinated concerns closes the account. This progression is the diagram’s proof that “State-machine style choice for IoT behavior” is explicit in the diagram. It is also the narrative bridge from State-Machine Styles to implementation.

Moore Style

Outputs are tied to state. This is useful when visible behavior should be stable and easy to inspect.

Mealy Style

Outputs may depend on state and event. This can be responsive, but event handling needs careful tests.

Hierarchical Style

Parent states share behavior across child states. This reduces duplicated transitions and common fault handling.

Parallel Machines

Independent concerns run as separate machines and coordinate through events instead of one flat combined state.

8.7 Pattern Families

Many IoT systems reuse a small set of state-machine patterns.

Reusable state shapes save design effort only when their proof obligations travel with them. Inspect Figure 8.4 before choosing a familiar pattern, because its labels expose the fault and timing questions that a copied state list can hide.

Five IoT state-machine pattern families showing connection, sampling, safety, update, and workflow states plus the proof checks needed before reuse.
Figure 8.4: IoT state-machine pattern families

In Figure 8.4, Connection must prove link loss and retry backoff, while Sampling must prove wake, validation, and reporting timing. Safety adds inhibited, faulted, and manual-reset paths; the Update family must distinguish verification, application, rollback, and confirmation. Those differences explain the footer warning Reusable does not mean copy blindly and connect the family choice to guards, faults, and tests for the actual device. The Workflow family adds acknowledgements and escalation, showing why an application transaction cannot inherit a radio reconnection machine unchanged.

Useful families:

  • Connection pattern: disconnected, connecting, connected, degraded, retry, and backoff behavior.
  • Sampling pattern: sleeping, waking, sampling, validating, reporting, and returning to idle.
  • Safety pattern: armed, active, inhibited, faulted, manual reset, and service override behavior.
  • Update pattern: ready, downloading, verifying, applying, rollback, and confirmed behavior.
  • Workflow pattern: received, validated, assigned, acknowledged, escalated, resolved, and closed behavior.

Patterns are starting points, not templates to paste blindly. Every pattern still needs guards, fault handling, and tests matched to the actual system boundary.

8.8 Coordination Without State Explosion

State explosion happens when independent concerns are forced into one flat model. A gateway that tracks device link state, local buffer state, and command state should usually model those as separate machines that exchange events.

Why look now? The surrounding argument assumes that “Parallel state machines coordinate through events” is explicit in the diagram. Figure 8.5 lets you verify that assumption inside Coordination Without State Explosion.

Separate radio, buffer, command, and power machines coordinating through explicit events.
Figure 8.5: Parallel state machines coordinate through events

The important evidence in Figure 8.5 is the relationship among offline, online, Service machine, and command_expired. The first frames the issue, the second changes or constrains it, and the third makes the result visible. In this way the visual demonstrates “Parallel state machines coordinate through events” is explicit in the diagram and advances Coordination Without State Explosion.

Use separate machines when:

  • The concerns can change independently.
  • Each concern has its own owner or test plan.
  • Combining them creates many artificial state names.
  • Coordination can be expressed as events such as link_lost, buffer_full, command_acked, or battery_low.

Use one combined machine when:

  • The states are inseparable in real behavior.
  • One transition must update all outputs atomically.
  • Separate machines would hide a safety-critical dependency.

8.9 Build Gateway State Machines

A building gateway receives sensor reports, buffers data during network outages, and forwards commands to local controllers. A flat design tries to combine link status, buffer status, command lifecycle, and maintenance mode into one diagram. The design check should split the concerns.

Recommended split

  1. Link machine: `offline`, `joining`, `online`, `degraded`, `recovering`.
  2. Buffer machine: `empty`, `collecting`, `near_limit`, `full`, `draining`.
  3. Command machine: `idle`, `received`, `validated`, `sent`, `acknowledged`, `expired`, `rejected`.
  4. Service machine: `normal`, `maintenance`, `locked_out`, `manual_check`.

Coordination events

Event: link_lost
From: Link machine
To: Buffer machine
Expected behavior: buffer enters collecting or near_limit based on capacity

Event: buffer_full
From: Buffer machine
To: Command machine and Service machine
Expected behavior: new noncritical commands are rejected and service check is opened

Event: command_expired
From: Command machine
To: Service machine
Expected behavior: unresolved command is visible for operator check

This structure keeps each machine small while making coordination visible.

8.10 State-Machine Proof Checklist

Before accepting an IoT state-machine design, check the proof.

The distinction introduced here affects the later engineering decision. Figure 8.6 deserves attention because it demonstrates how “State-machine proof checklist” is explicit in the diagram.

Proof checklist for checking the behavior boundary, stable states, named events, guards, actions, faults, timing, coordination, tests, and decision evidence.
Figure 8.6: State-machine proof checklist

In the labeled structure of Figure 8.6, 1. Boundary frames the case, Timeout, retry, rejection supplies the critical condition, and Decision record records what follows. That structure shows “State-machine proof checklist” is explicit in the diagram. It is the evidence-bearing connection from State-Machine Proof Checklist to the next part of the chapter.

Ask:

  • Boundary: does the machine own one coherent behavior?
  • States: does each state represent a stable mode rather than a temporary flag?
  • Events: are timer, sensor, message, reset, and fault events named clearly?
  • Guards: are guards side-effect free and testable?
  • Actions: are hardware, message, logging, and persistence actions explicit?
  • Faults: are timeout, retry, rejection, reset, and service paths covered?
  • Coordination: are interactions between machines represented as events?
  • Tests: does the test matrix include invalid and wrong-state events, not only the happy path?

8.11 Knowledge Check

Check the IoT State-Machine Boundary
Match State-Machine Pattern to Use
Order an IoT State-Machine Check

8.12 Common Pitfalls

Taken together, these checks make the section reviewable. That order makes timing, persistence, and recovery part of the behaviour contract, so the later implementation and test record can prove deterministic outcomes.

8.13 Overview: A State Machine Owns Behavior

A state machine is not just a diagram of possible modes. It is an ownership boundary: this machine accepts these events, keeps this context, performs these actions, and refuses or escalates everything outside that contract. Inspect Figure 8.7 to follow how that boundary becomes a proofable design.

IoT state-machine route from behavior boundary through states and events, transition table, structure choice, fault paths, and proof record.
Figure 8.7: Build IoT state machines as proofable behavior contracts: name the behavior boundary, define states and events, write the transition table, choose the smallest structure, verify fault and reset paths, and keep the proof record.

Small-screen read: Follow Figure 8.7 from behavior boundary through states and events, transition table, structure, fault paths, and proof. If any step is missing, hidden flags and untested fault paths usually appear.

That ownership is valuable in IoT because behavior crosses unreliable boundaries. A sensor can report late, a gateway can lose backhaul, a command can expire, and a device can reboot in the middle of work. The state machine makes those cases visible instead of leaving them as scattered flags.

8.14 Practitioner: Write The Event Contract

Before implementing the transition table, write the event contract. It prevents each layer from inventing its own meaning for a message, timeout, retry, reset, or operator action.

Event Source

Name whether the event came from a sensor, timer, radio stack, gateway, cloud service, operator, or stored recovery record.

Allowed State

Name which source states may accept the event, which states must reject it, and what evidence is logged for wrong-state events.

Action And Proof

Name the action, emitted event, persisted field, acknowledgement, timeout, and test that proves the transition happened as intended.

For a gateway command, the event contract might say: `command_received` is valid only in `online` or `degraded`, requires a freshness check, emits `command_sent` or `command_rejected`, and must expire locally if no acknowledgement arrives inside the command lifetime.

8.15 Under the Hood: Reset Is A Transition

Reset and persistence are where many IoT state machines become unsafe. If firmware simply restores the previous state after power loss, it may resume a command, service mode, or safety state whose assumptions are no longer true.

Treat reset as an explicit transition. Decide which states can be restored, which must enter recovery, which outputs must be inhibited, which pending events must expire, and which proof must be rebuilt before normal operation resumes.

8.16 Summary

State machines help IoT teams make behavior explicit across devices, gateways, services, and operations workflows. Use fundamentals to name the model, use the lab to practice implementation and verification, and use design patterns to reuse proven structures without hiding system-specific proof. The acceptance standard is simple: every important state, event, guard, action, fault path, coordination event, and test expectation should be visible.

8.17 Key Takeaway

State machines make IoT firmware and workflows easier to reason about when every transition has a trigger, guard, action, and test.

8.18 See Also

Taken together, these checks make the section reviewable. That order makes timing, persistence, and recovery part of the behaviour contract, so the later implementation and test record can prove deterministic outcomes.

8.19 What’s Next

Start with State Machine Fundamentals for IoT if you need the core concepts, use Lab: ESP32 State Machines for implementation practice, or continue to State Machine Design Patterns when you are ready to choose reusable patterns.