Distributed state machine
A state machine is a program that is always in one of a few modes and changes mode in response to events. Here a Control Panel holds the state of a gate (open, closed or lockdown), and a separate door program carries out its commands.
You need: a Control Panel and a Redstone Controller named gate_door with a door on its south side, both with
drives, on one network with a repeater.
The panel (drive type control_panel)
Section titled “The panel (drive type control_panel)”// Advanced: a command panel (Control Panel drive). Each button sends a structured command to a named device// program with events.send, and the panel keeps a small state machine in its globals.enum Mode { OPEN, CLOSED, LOCKDOWN }global mode = Mode.CLOSED
fn command(target, action) { delivered, err = events.send(target, "gate.command", {action: action, mode: str(mode)}) if err is not nil { print("Could not reach " + target + ": " + err.message) } else if delivered is 0 { print(target + " is not listening for gate.command") }}
on device.buttonPressed(button) { if mode is Mode.LOCKDOWN and button.id is not Button.FOUR { return } if button.id is Button.ONE { mode = Mode.OPEN command("gate_door", "open") } else if button.id is Button.TWO { mode = Mode.CLOSED command("gate_door", "close") } else if button.id is Button.THREE { mode = Mode.LOCKDOWN events.emit("security.alert", {who: button.player, hostile: false, count: 0}) } else { mode = Mode.CLOSED events.emit("security.clear", {by: button.player}) }}Label the buttons in the panel’s form: Open, Close, Lockdown, Clear.
The door (drive type redstone_controller)
Section titled “The door (drive type redstone_controller)”on startup { device.setMode(Direction.SOUTH, PortMode.OUTPUT)}
on events.custom("gate.command", command, sender) { if sender.kind is not "control_panel" { return } if command.action is "open" { device.set(Direction.SOUTH, 15) } else if command.action is "close" { device.set(Direction.SOUTH, 0) } print("Gate " + command.action + " (" + command.mode + ")")}
on events.custom("security.alert", alert, sender) { // Lockdown always closes the gate. device.set(Direction.SOUTH, 0)}How it works
Section titled “How it works”enum Mode { OPEN, CLOSED, LOCKDOWN }names the states, and the globalmodeholds the current one. Because it is a global on the drive, the state survives restarts and moving the drive.- In
LOCKDOWN, every button except four is ignored. That one rule is the heart of the state machine: the same button does different things in different states. - The panel sends
gate.commandto one device withevents.send("gate_door", ...)and warns when nobody listens. - The door only accepts commands from a Control Panel, checked with the server-filled
sender.kind. - The enum value travels as text,
str(mode), because constants cannot be sent in events.