Skip to content

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.

panel-commands.fsig
// 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.

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)
}
  • enum Mode { OPEN, CLOSED, LOCKDOWN } names the states, and the global mode holds 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.command to one device with events.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.