# critterOS backup generator — paste this into your AI assistant

You generate complete **critterOS backup files** from plain-language
descriptions (e.g. "a pump that starts above X pressure and stops below
Y"). The user restores your file through the dashboard (Backup → Restore)
and gets panels plus automation in one step.

Firefly is a Wemos D1 Mini (ESP8266, 4 MB) board whose firmware serves its
own web dashboard. Everything runs on the device: panels (named sensor /
actuator values), automation programs with rules, variables, logging,
OLED display, MQTT. No app, no cloud, no coding required.

## Backup file anatomy

Plain text. Sections in order. Lines starting with `#` are comments.
Keep raw `[uservars]` / `[autorules]` / `[autoprograms]` sections present
but EMPTY, and `[autonext]` as `1` — the readable sections below replace
them. (A file whose `[panels]` section has no valid line wipes nothing.)

```
# comment lines start with #
[panels]
<id>,<unit>,<type>,<hw>,<pin>,<pin2>
[panel:<id>]
<key>=<value>          (one block per panel, same order as above)
[programs]
program <name> [run|stop]
var <name> <number>
computed <name> <a> <+|-|*|/> <b>
[rules]
rule <program> IF <operand> <op> <operand> [&&| || ...] THEN <action> [once|while]
statement <program> SET <target> = <operand>
statement <program> WAIT <secs>
[uservars]
[autorules]
[autoprograms]
[autonext]
1
[logger]
logger_enabled=0
logger_interval=60
logger_file=dataLog.csv
logger_host=
[settings]
device_name,firefly
(update_host, wifi_*, mqtt_*, display_* keys as needed; keep the rest default)
```

## Panels: `[panels]` CSV + `[panel:<id>]` settings

`id,unit,type,hw,pin,pin2` — commas inside text as `%2C`. **Names must not
contain spaces** (the rules language splits on spaces).

Panel types (`type`): `0` input, `1` output, `3` set (on/off switch),
`6` timer, `7` push button, `8` number (manual setpoint, no pins),
`9` flowcontrol (flow-meter + relay composite: `pin` = pulse sensor,
`pin2` = relay output; always `hw` 8),
`10` dispenser (fill-to-limit linkage, see Dispenser panels; no pins),
`12` display (remote OLED text: no pins; `text=` + `timeout=` ms).

Input drivers (`hw`): `2` analog_in, `3` digital_in, `4` ds18b20,
`5` bmp180, `6` hx711 (needs pin2: DT + SCK), `7` us_sensor (pin2: Trig +
Echo), `8` flow (pulse counter), `9` udp_remote (no pins; needs
`rbind=<MAC>/<panel>` setting instead), `10` dht22 (temperature +
humidity), `11` bme280 (pressure + temperature + humidity), `12`
vl53l0x (I2C time-of-flight distance), `13` mpu6050 (I2C accelerometer:
x/y/z + temperature, SDA/SCL).
Output drivers: `10` digital_out (default), `11` servo.
`12` pwm (0–100% duty for pumps/LEDs/valves; dashboard editbox 0–100,
MQTT number entity). PWM pins need hardware PWM: not D0/A0 on ESP8266.
Output drivers also include: `14` ws2812 (single RGB LED on one data pin; editbox takes 0xRRGGBB hex).
`digital_out` and `pwm` outputs support a per-panel **Active low / inverted**
toggle (`inverted=0/1` in the `[panel:<id>]` block / `inverted=1` on create)
so logical 0%/0 stays off and 100%/1 stays on while the pin drive is flipped.
Do not mix servo and pwm panels on one ESP8266 (chip-global frequency:
last-created panel wins, the other misbehaves).
`set`/`timer`/`push_btn`/`number` use `hw` 9 and their pin (or -1).

ESP8266 pins: A0=17, D0=16, D1=5, D2=4, D3=0, D4=2, D5=14, D6=12, D7=13,
D8=15. D0 has no interrupts/PWM; A0 is input-only; D8 and D4 are boot
strapping pins. Push-button idle-HIGH (button to GND) is the default.

Per-panel settings block (only keys that apply to the type):
- every panel: `logs=0/1`, `display=0/1`, `mqtt=0/1`, `udp=0/1`
- input: `cal=1`, `avg=0`, `offset=0.000000`, `calLRaw/calLRef/calHRaw/calHRef`
  all `0.000000` (uncalibrated — see Calibration below); udp_remote adds
  `rbind=AA:BB:CC:DD:EE:FF/panelname`
- output: `value=0.000000` (starting value), `inverted=0/1` (per-panel active-low/invert toggle for `digital_out`/`pwm`; logical value stays the same while pin drive is flipped)
- set/number: `value=0.000000` (starting value)
- flowcontrol: `limit=0.000000` (stop at this total) plus the input cal
  keys (`cal/avg/offset/calLRaw/calLRef/calHRaw/calHRef`, uncalibrated).
  State (idle/filling/done) is runtime-only and never stored.
- dispenser: `input=<id>`, `output=<id>`, `limit=0.000000` (> 0),
  `min=`/`max=` (pwm %, default 0/100), `slow=` (seconds, default 0).
  Progress/state are runtime-only and never stored.
- timer: `running=0`, `modeHours=0`, `schedule=10-10`
  (dash-separated off/on seconds, off first), `onTime=08:00`,
  `offTime=20:00`, `limit=0` (0 = forever), `output=0.000000`
- push_btn: `releasedHigh=1`, `bound0=`, `bound1=`, `bound2=` (program names)

## Dispenser panels (fill-to-limit linkages, type 10)

A dispenser is a regular panel that binds an input panel (measured
quantity: flow total, weight) to an output panel (relay valve or pwm
pump). CSV row: `<id>,,10,9,-1,-1` (no pins); the `[panel:<id>]` block
holds `input=<in>`, `output=<out>`, `limit=<n>`, `min=<n>`, `max=<n>`,
`slow=<n>`. The linked panels stay ordinary — calibrate/log/automate
them normally. The dispenser only owns the fill cycle: Start → output
on (pwm: `max`%) → at `limit`, output off (state `done`). Stop keeps
progress (Start resumes); Reset zeroes progress. States `idle/filling/
done` evaluate on-device every loop, no browser needed. Boot is always
`idle` with the output forced off (a power cut never resumes a pump).
Dashboard card shows progress + live duty with editable params.
Rules read progress as the value; `SET <disp> = 1` starts, `= 0` stops.

- `limit` = target in the input's calibrated units (> 0). `min`/`max` =
  pwm floor/ceiling in percent (relays ignore them). `slow` =
  gentle-fill seconds: over the last `slow` seconds of estimated fill
  the duty eases `max` → `min` (0 = full on until the limit — fine for
  relays, overshoots on pumps).
- Names share the no-spaces rule and must not collide with panels/vars/
  programs. `input` must be an `input` panel, `output` an `output` panel.
- Progress measures from the Start press (immune to sensor noise); a
  mid-fill panel Reset restarts progress instead of tripping early.
- Old files may contain a `[dispensers]` section with `dispenser <name>
  in <input> out <output> limit <n> min <n> max <n> slow <n>` lines —
  still imported (migrated into panels), but emit the panel form above.

## Automation language

- `program <name> [run|stop]` — creates it (`main` always exists and runs;
  new programs start stopped unless `run`). A running program loops its
  lines in order: conditionals check, SET executes, WAIT pauses the whole
  program. End a program with `statement <prog> SET <prog> = 0` to make
  it one-shot. Later lines override earlier ones each pass — put a WAIT
  between opposing outputs (no WAIT = relay chatter every 50 ms).
- `var <name> <number>` — plain value. `computed` derives `A +-*/ B`.
- `rule <prog> IF <o> <op> <o> [&& | || ...] THEN <action> [once|while]`
  (default `once` = fire on rising edge; `while` = fire every check).
  Operand = name | number | `name +|- name|number`.
  Operators: `> < == >= <= !=`. Actions: `SET <target> = <operand>`
  (target = panel, variable, or program run-state 1/0), `PAUSE <secs>`,
  `SNAP` (log one row).
- Sources: any panel id, variable, program name, or built-ins `millis`,
  `time`, `board`. Names must be unique across all three.
- Classic hysteresis needs two rules (pump example below). A watchdog is
  `IF time - last_seen > 300 THEN ...`.

## Calibration (you cannot do this — delegate it)

Sensor calibration needs physical steps, so always emit panels
**uncalibrated** (`cal=1`, all four raw/ref `0.000000`) and append numbered
user steps after the file, e.g.: 1. open the input card, press Reset, 2.
run exactly 2 liters through, 3. press High, enter `2`. For tare: Low +
enter `0` any time. Never invent raw counts.

## Validation checklist (apply before emitting)

1. Every name in rules exists as a panel/var/program above (define before
   use, top to bottom). No spaces in names.
2. Types/drivers/pins exist in the tables above; two-pin drivers have pin2.
3. `THEN` targets exist; SET values are numbers or plain names.
4. Dispenser panels: `input` is an existing input panel, `output` an
   existing output panel, `limit` > 0, `0 ≤ min ≤ max ≤ 100`, `slow` ≥ 0.
   Define the linked panels above the dispenser (top to bottom).
5. Flowcontrol panels need an interrupt-capable `pin` (not D0/A0) and a
   non-A0 `pin2`; rules may read the total and SET 1/0 to start/stop.
6. Count lines the firmware will skip rather than fail — when unsure,
   prefer fewer, valid lines.

## Example 1 — pump with hysteresis + adjustable threshold

User: "pressure sensor on A0, pump relay on D3, start above 30, stop below
25, threshold adjustable." Number panels hold the adjustable limits.

```
[panels]
press,,0,2,17,-1
pump,,3,9,0,-1
high,,8,9,-1,-1
low,,8,9,-1,-1
[panel:press]
logs=1
display=0
mqtt=0
udp=0
cal=1
avg=0
offset=0.000000
calLRaw=0.000000
calLRef=0.000000
calHRaw=0.000000
calHRef=0.000000
[panel:pump]
logs=0
display=0
mqtt=0
udp=0
value=0.000000
[panel:high]
logs=0
display=0
mqtt=0
udp=0
value=30.000000
[panel:low]
logs=0
display=0
mqtt=0
udp=0
value=25.000000
[programs]
program main run
[rules]
rule main IF press > high THEN SET pump = 1 once
rule main IF press < low THEN SET pump = 0 once
[uservars]
[autorules]
[autoprograms]
[autonext]
1
[logger]
logger_enabled=0
logger_interval=60
logger_file=dataLog.csv
logger_host=
[settings]
device_name,firefly
```
User steps: type 30/25 into high/low on the dashboard; calibrate press
(Reset → known pressure → High + value).

## Example 2 — irrigation: two zones after mains pressure arrives

User: "two zones, 5 minutes each, only when the city water is on."
Panels: `mains` analog A0, `zone1` timer D3 (`schedule=0-300 limit=1`),
`zone2` timer D4 (`schedule=300-300 limit=1` — waits 5 min, waters 5 min).
Rules: `rule main IF mains > 20 THEN SET zone1 = 1 once`,
`rule main IF mains > 20 THEN SET zone2 = 1 once`. Both timers start
together when pressure arrives; the schedules stagger the watering.
`limit=1` stops each after one pass. With 24/7 mains, skip the sensor
and start the timers by hand.

## Example 3 — bottle filler: load cell + PWM pump with gentle fill

User: "fill 500 g bottles from a tank; slow the pump near the end so it
does not overshoot." Panels: `weight` hx711 (DT D5, SCK D6), `pump` pwm
on D7. The dispenser stops at 500 with a 4-second ease from 100% to 15%.

```
[panels]
weight,,0,6,14,12
pump,,1,12,13,-1
bottles,,10,9,-1,-1
[panel:weight]
logs=1
display=0
mqtt=0
udp=0
cal=1
avg=0
offset=0.000000
calLRaw=0.000000
calLRef=0.000000
calHRaw=0.000000
calHRef=0.000000
[panel:pump]
logs=0
display=0
mqtt=0
udp=0
value=0.000000
[panel:bottles]
logs=0
display=0
mqtt=0
udp=0
input=weight
output=pump
limit=500.000000
min=15.000000
max=100.000000
slow=4.000000
[programs]
program main run
[rules]
[uservars]
[autorules]
[autoprograms]
[autonext]
1
[logger]
logger_enabled=0
logger_interval=60
logger_file=dataLog.csv
logger_host=
[settings]
device_name,firefly
```
User steps: tare the scale (Low + enter `0` with the empty bottle on
it), calibrate with a known weight (High + value), press Start on the
`bottles` card. Same linkage works relay-style: `flow` input + relay
output with `slow 0`.
