โ† Back to the chapter

Technical detail ยท Device State Machines: Transition Contracts

Table-driven dispatch

This implementation selects transitions for the current state or ANY, then evaluates their guards. A missing guard defaults to false. The first passing candidate runs its action, records the target, and logs the transition. If no guard passes, the handler logs a rejected event and keeps the current state. Candidate order therefore matters when local and global transitions both match; the reviewed safety priority must be reflected in that order.

from dataclasses import dataclass

@dataclass(frozen=True)
class Transition:
    source: str
    event: str
    guard: str
    target: str
    action: str

class DeviceStateMachine:
    def __init__(self, initial_state, transitions, actions, guards):
        self.state = initial_state
        self.transitions = transitions
        self.actions = actions
        self.guards = guards

    def dispatch(self, event, context):
        candidates = [
            t for t in self.transitions
            if t.event == event and t.source in (self.state, "ANY")
        ]
        for transition in candidates:
            guard = self.guards.get(transition.guard, lambda _: False)
            if guard(context):
                previous = self.state
                self.actions[transition.action](context)
                self.state = transition.target
                context.log_transition(previous, event, self.state)
                return self.state
        context.log_rejected_event(self.state, event)
        return self.state

โ† Back to the chapter