Smart-Home Automation Rules Engine — Part B: Build
Definitions
Registry
- In plain English
- A registry maps names to constructor functions, letting new types register without editing the code that uses them.
- Think of it like
- It is like a phone directory of who handles which service.
The brief
Build smart-home with fake vendor lights, JSON rules, composable checks and undoable scenes. A fixed clock makes the evening motion demo repeatable.
What it must do
- Register devices from different vendors and receive their events.
- Match one trigger, combine conditions with AND, OR and NOT, then run actions.
- Load rules from JSON and evaluate them when matching events arrive.
- Run scenes with several actions and undo successful actions in reverse order.
How well it must do it
- Protect device control while events are processed concurrently.
- Add vendor, condition and action types without changing the engine loop.
- Log failed actions and continue with other actions and rules.
Out of scope
- Mobile apps and cloud sync.
- Real device protocols and persistent rule storage.
Design walkthrough
Events and time
package main
import "time"
type Event struct{ DeviceID, Kind string }
type Clock interface{ Now() time.Time }
type FixedClock struct{ At time.Time }
func (c FixedClock) Now() time.Time { return c.At }
type Context struct {
Clock Clock
Occupied func() bool
}
type Rule struct {
DeviceID, Trigger string
When Condition
Actions []func() Action
}
The engine receives an immutable rule list. One goroutine owns its evaluations; an injected clock supplies 22:30 without sleeping.
Conditions are small checks
package main
type Condition interface{ Match(Context) bool }
type TimeAfter struct{ Hour, Minute int }
func (t TimeAfter) Match(c Context) bool {
now := c.Clock.Now()
return now.Hour()*60+now.Minute() >= t.Hour*60+t.Minute
}
type DeviceIs struct {
Light Light
Level int
}
func (d DeviceIs) Match(Context) bool { return d.Light.Level() == d.Level }
type And []Condition
func (a And) Match(c Context) bool {
for _, part := range a {
if !part.Match(c) {
return false
}
}
return true
}
type Or []Condition
func (o Or) Match(c Context) bool {
for _, part := range o {
if part.Match(c) {
return true
}
}
return false
}
type Not struct{ Inner Condition }
func (n Not) Match(c Context) bool { return !n.Inner.Match(c) }
TimeAfter means at or after the configured minute, in the injected clock’s location. Empty And is true; empty Or is false.
Adapters protect vendor devices
package main
import (
"errors"
"sync"
)
type Light interface {
Level() int
SetLevel(int) (int, error)
}
type SafeLight struct {
mu sync.Mutex
read func() int
write func(int)
}
func (s *SafeLight) Level() int {
s.mu.Lock()
defer s.mu.Unlock()
return s.read()
}
func (s *SafeLight) SetLevel(n int) (int, error) {
s.mu.Lock()
defer s.mu.Unlock()
old := s.read()
if n < 0 || n > 100 {
return old, errors.New("level outside 0..100")
}
s.write(n)
return old, nil
}
The vendor pointers stay inside adapters. SetLevel reads and writes under one lock, so commands capture an accurate previous value.
package main
type VendorA struct{ brightness int }
func (v *VendorA) Brightness() int { return v.brightness }
func (v *VendorA) Dim(n int) { v.brightness = n }
type VendorB struct{ power int }
func (v *VendorB) Read() int { return v.power }
func (v *VendorB) Write(n int) { v.power = n }
func adaptA() Light {
v := &VendorA{}
return &SafeLight{read: v.Brightness, write: v.Dim}
}
func adaptB() Light {
v := &VendorB{}
return &SafeLight{read: v.Read, write: v.Write}
}
Commands remember their changes
package main
import "errors"
type Action interface {
Execute() error
Undo() error
}
type SetLevel struct {
Light Light
Target, previous int
done bool
}
func (s *SetLevel) Execute() error {
if s.done {
return errors.New("command already executed")
}
old, err := s.Light.SetLevel(s.Target)
if err != nil {
return err
}
s.previous, s.done = old, true
return nil
}
func (s *SetLevel) Undo() error {
if !s.done {
return errors.New("command not executed")
}
if _, err := s.Light.SetLevel(s.previous); err != nil {
return err
}
s.done = false
return nil
}
Undo restores a captured value; it does not merge concurrent edits. Run and undo scenes through the same owner when ordering matters.
package main
import "errors"
type Scene struct {
Actions []Action
history []Action
}
func (s *Scene) Execute() error {
if len(s.history) != 0 {
return errors.New("undo scene before replay")
}
var failures []error
for _, action := range s.Actions {
if err := action.Execute(); err != nil {
failures = append(failures, err)
continue
}
s.history = append(s.history, action)
}
return errors.Join(failures...)
}
func (s *Scene) Undo() error {
for len(s.history) > 0 {
i := len(s.history) - 1
if err := s.history[i].Undo(); err != nil {
return err
}
s.history = s.history[:i]
}
return nil
}
A failed Execute is not added to history. A failed Undo stays there for a retry; already undone commands are removed.
Decode through registries
package main
import (
"encoding/json"
"errors"
"io"
"strings"
)
type Spec struct {
Type string
Device string
Hour, Minute, Level int
Children []Spec
}
type Config struct {
Device, Trigger string
When Spec
Actions []Spec
}
type Decoder struct {
Conditions map[string]func(Spec) (Condition, error)
Actions map[string]func(Spec) (func() Action, error)
Lights map[string]Light
}
func (d *Decoder) Load(text string) (Rule, error) {
var cfg Config
decoder := json.NewDecoder(strings.NewReader(text))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&cfg); err != nil {
return Rule{}, err
}
if err := decoder.Decode(new(any)); err != io.EOF {
return Rule{}, errors.New("expected exactly one JSON value")
}
return d.rule(cfg)
}
func (d *Decoder) condition(s Spec) (Condition, error) {
constructor, ok := d.Conditions[s.Type]
if !ok {
return nil, errors.New("unknown condition: " + s.Type)
}
return constructor(s)
}
A registry rejects unknown type names. Constructors validate values before any event can use the rule.
package main
import "errors"
func (d *Decoder) rule(c Config) (Rule, error) {
if c.Device == "" || c.Trigger != "motion" || len(c.Actions) == 0 {
return Rule{}, errors.New("invalid trigger or empty actions")
}
condition, err := d.condition(c.When)
if err != nil {
return Rule{}, err
}
rule := Rule{DeviceID: c.Device, Trigger: c.Trigger, When: condition}
for _, spec := range c.Actions {
makeAction, ok := d.Actions[spec.Type]
if !ok {
return Rule{}, errors.New("unknown action: " + spec.Type)
}
factory, err := makeAction(spec)
if err != nil {
return Rule{}, err
}
rule.Actions = append(rule.Actions, factory)
}
return rule, nil
}
func (d *Decoder) parts(s Spec) ([]Condition, error) {
var children []Condition
for _, child := range s.Children {
condition, err := d.condition(child)
if err != nil {
return nil, err
}
children = append(children, condition)
}
return children, nil
}
Register condition and action factories
package main
import "errors"
func newDecoder(lights map[string]Light) *Decoder {
d := &Decoder{Lights: lights,
Conditions: map[string]func(Spec) (Condition, error){},
Actions: map[string]func(Spec) (func() Action, error){}}
d.Conditions["time-after"] = func(s Spec) (Condition, error) {
if s.Hour < 0 || s.Hour > 23 || s.Minute < 0 || s.Minute > 59 {
return nil, errors.New("invalid time")
}
return TimeAfter{s.Hour, s.Minute}, nil
}
d.Conditions["device-is"] = func(s Spec) (Condition, error) {
light := d.Lights[s.Device]
if light == nil || s.Level < 0 || s.Level > 100 {
return nil, errors.New("invalid device condition")
}
return DeviceIs{light, s.Level}, nil
}
d.Actions["set-level"] = func(s Spec) (func() Action, error) {
light := d.Lights[s.Device]
if light == nil || s.Level < 0 || s.Level > 100 {
return nil, errors.New("invalid light action")
}
return func() Action { return &SetLevel{Light: light, Target: s.Level} }, nil
}
d.combinations()
d.Conditions["nobody-home"] = nobodyHomeFactory
return d
}
Each action factory creates a fresh command. A second motion event cannot overwrite the first command’s Undo record.
package main
import "errors"
func (d *Decoder) combinations() {
d.Conditions["and"] = func(s Spec) (Condition, error) {
parts, err := d.parts(s)
return And(parts), err
}
d.Conditions["or"] = func(s Spec) (Condition, error) {
parts, err := d.parts(s)
return Or(parts), err
}
d.Conditions["not"] = func(s Spec) (Condition, error) {
if len(s.Children) != 1 {
return nil, errors.New("not needs one child")
}
parts, err := d.parts(s)
if err != nil {
return nil, err
}
return Not{parts[0]}, nil
}
}
Register factories before starting the engine. Treat maps as immutable afterward. A production loader also needs limits on input size and nesting.
The engine owns execution
package main
import "fmt"
type Engine struct {
Events <-chan Event
Rules []Rule
Context Context
}
func (e Engine) Run() {
for event := range e.Events {
for _, rule := range e.Rules {
if rule.DeviceID != event.DeviceID || rule.Trigger != event.Kind {
continue
}
if !rule.When.Match(e.Context) {
continue
}
for _, factory := range rule.Actions {
if err := factory().Execute(); err != nil {
fmt.Println("action error:", err)
}
}
}
}
}
Closing the channel after the last send drains accepted events. Wait for Run to return before reading results or running a scene.
Main waits for event processing to finish before it reads the light and performs scene changes.
Run a motion rule and undo a scene
package main
const motionRule = `{
"Device": "hall-sensor", "Trigger": "motion",
"When": {"Type": "and", "Children": [
{"Type": "time-after", "Hour": 22},
{"Type": "nobody-home"},
{"Type": "not", "Children": [
{"Type": "device-is", "Device": "hall", "Level": 100}
]}
]},
"Actions": [{"Type": "set-level", "Device": "hall", "Level": 30}]
}`
func must(err error) {
if err != nil {
panic(err)
}
}
The fixed occupancy callback says nobody is home. A real callback must provide a safe snapshot rather than read an unprotected shared variable.
package main
import (
"fmt"
"time"
)
func main() {
hall, desk := adaptA(), adaptB()
decoder := newDecoder(map[string]Light{"hall": hall, "desk": desk})
rule, err := decoder.Load(motionRule)
must(err)
now := time.Date(2026, 1, 1, 22, 30, 0, 0, time.UTC)
events := make(chan Event, 4)
engine := Engine{events, []Rule{rule}, Context{FixedClock{now}, func() bool { return false }}}
done := make(chan struct{})
go func() { engine.Run(); close(done) }()
events <- Event{"hall-sensor", "motion"}
close(events)
<-done
fmt.Println("motion level:", hall.Level())
scene := &Scene{Actions: []Action{
&SetLevel{Light: hall, Target: 80}, &SetLevel{Light: desk, Target: 60},
}}
must(scene.Execute())
fmt.Println("scene:", hall.Level(), desk.Level())
must(scene.Undo())
fmt.Println("undo:", hall.Level(), desk.Level())
checkFailureIsolation(hall)
}
motion level: 30
scene: 80 60
undo: 30 0
action error: device offline
continued level: 40Check action failure isolation
package main
import (
"errors"
"fmt"
"time"
)
type Offline struct{}
func (Offline) Execute() error { return errors.New("device offline") }
func (Offline) Undo() error { return nil }
func checkFailureIsolation(light Light) {
events := make(chan Event, 1)
first := Rule{"sensor", "motion", And{}, []func() Action{
func() Action { return Offline{} },
func() Action { return &SetLevel{Light: light, Target: 35} },
}}
second := Rule{"sensor", "motion", And{}, []func() Action{
func() Action {
if light.Level() != 35 {
panic("next action did not run")
}
return &SetLevel{Light: light, Target: 40}
},
}}
events <- Event{"sensor", "motion"}
close(events)
Engine{events, []Rule{first, second}, Context{FixedClock{time.Time{}}, nil}}.Run()
if light.Level() != 40 {
panic("next rule did not run")
}
fmt.Println("continued level:", light.Level())
}
Extend it: only when nobody is home
package main
type NobodyHome struct{}
func (NobodyHome) Match(c Context) bool { return !c.Occupied() }
func nobodyHomeFactory(Spec) (Condition, error) { return NobodyHome{}, nil }
The final program includes NobodyHome and one registry assignment in registry.go. The engine and decoder loops stay unchanged; existing JSON uses the same type field.
The occupancy callback is a dependency supplied at startup. Undo commands and Scene histories remain single-owner values, even though device operations are mutex-protected.
Design decisions
Why inject a Clock?
Our choice
Make time conditions repeatable without waiting until evening.
Why not the alternatives
- Read wall-clock time inside each conditionTests would depend on the time of day and local environment.
What happens when one action fails?
Our choice
Log that failure and continue with other actions and rules.
Why not the alternatives
- Return from the whole event loopOne offline device would disable unrelated automation.
Why a constructor registry?
Our choice
Decode names through registered factories and validate before execution.
Why not the alternatives
- Add a switch branch in the engineNew condition types would change the execution core.
Trade-offs
Pros
- The demo needs no real devices or sleeps.
- Vendor reads and writes are protected.
- Failure isolation is executable.
Cons
- Rules execute sequentially.
- Undo can overwrite intervening external edits.
- Real devices need retry and conflict policies.
Use when
- Configurable in-memory automation.
- Small, composable device behaviours.
Avoid when
- Transactional changes across physical devices.
- Unbounded or untrusted JSON without resource limits.
Quick check
Takeaways
- Decode through validated constructor registries.
- Keep command histories owned by one goroutine and protect device access inside adapters.
- Log action failures and continue; undo successful scene actions in reverse order.