Skip to content

About

Standalone ESPHome HIL simulator for OpenQuatt: dual Modbus Quatt ODUs and OpenTherm boiler.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

OpenQuatt Modbus and OpenTherm Simulator

Standalone ESPHome firmware for an HCQ Q-edition revision 1.0 board. The board can simultaneously simulate:

  • one OpenTherm boiler/slave on OTT;
  • one OpenTherm thermostat/master on OTB;
  • two independent Quatt outdoor units on the M2 RS485 port, normally at Modbus addresses 1 and 2.

The combined firmware publishes compatibility contract openquatt-modbus-opentherm-v2 and simulator version v0.7.0. HIL clients must verify the contract before changing controller or simulator state.

The project has no runtime or source dependency on OpenQuatt. Its register, profile and numerical performance data are local snapshots with explicit provenance. ESPHome is pinned to 2026.8.0.

Two firmware entrypoints are retained:

Entrypoint Function
hcq_v1_boiler_simulator.yaml Existing OpenTherm boiler simulator only
hcq_v1_system_simulator.yaml OpenTherm boiler, thermostat and dual Quatt ODU simulator

For step-by-step operation and test scenarios, see the Dutch tester handleiding.

For the fixed desktop HIL setup, use the versioned lab guide, testcase catalogue and interface catalogue. The versioned $hcq-hil skill provides the repeatable Codex workflow, including verified simulator and controller REST inputs plus safe M2 UART fault injection.

Hardware and wiring

This firmware is only for HCQ revision 1.0. The pin map is based on the OpenQuatt Q-edition definitions before jeroen85/OpenQuatt#303.

Function Connector HCQ v1.0 GPIO
OpenTherm slave input OTT GPIO16
OpenTherm slave output OTT GPIO15
OpenTherm master input OTB GPIO17
OpenTherm master output OTB GPIO21
Yellow status LED front GPIO47
Red status LED front GPIO48
Modbus TX M2 GPIO40
Modbus RX M2 GPIO39
Modbus DE/RE M2 GPIO38

OTT is the OpenTherm thermostat/slave side and is used here to impersonate a boiler. OTB is the OpenTherm boiler/master side and is used here to impersonate a thermostat. The two HCQ interfaces are electrically separate. M1 and M2 are RS485/Modbus connections, not OpenTherm connections. In this test setup, the controller-under-test uses its primary ODU RS485 connection and the simulator uses its onboard M2 transceiver as server.

Controller/project under test                 HCQ v1.0 simulator

OTB / OpenTherm master ── two wires ───────── OTT / OpenTherm slave
OTT / OpenTherm slave  ── two wires ───────── OTB / OpenTherm master

Primary ODU RS485      ── A / B / GND ────── M2 / Modbus RTU server
                                                ├─ address 1: ODU 1
                                                └─ address 2: ODU 2

Connect A to A, B to B and GND to GND. OpenTherm polarity does not matter. Use RS485 termination only at both bus ends. Each OpenTherm connection must join exactly one master to one slave; never bridge the two simulator ports or connect two masters. Never put a real ODU with the same Modbus address on this bus. The simulator drives no relay, pump or other physical actuator.

The M2 bus is fixed at 19200 baud, 8 data bits, even parity and 1 stop bit (19200 8E1). No external MAX485 is needed.

Build and flash

Run from this repository root:

python3 -m pip install -r requirements.txt

esphome config hcq_v1_boiler_simulator.yaml
esphome compile hcq_v1_boiler_simulator.yaml

esphome config hcq_v1_system_simulator.yaml
esphome compile hcq_v1_system_simulator.yaml
esphome run hcq_v1_system_simulator.yaml

Without station Wi-Fi, the combined firmware starts the access point OpenQuatt Simulator with password openquatt. Use the native ESPHome web page to configure scenarios. Both ODU profiles default to Disabled, so the board does not answer as an ODU until profiles are explicitly selected.

To start a normal PR #534 test:

  1. Select V2 old for ODU 1 and V2 new for ODU 2.
  2. Keep their default Modbus addresses 1 and 2.
  3. Press Apply ODU profiles and addresses, then reboot.
  4. Let the controller-under-test rediscover both addresses after the real bus interruption caused by the reboot.

Equal addresses are rejected by the apply action. Profile and address changes only become active after that explicit reboot.

ODU profiles

Profile 2114 2122 2127 Customer model Levels
V1 0 0x0119 0x0037 empty F0–F10
V1.5 0 0x011E 0x0E37 empty F0–F10
V2 old 2825 0x0122 0x0E37 AMH6 F0–F10
V2 new 2825 0x0201 0x1037 AMH6 F0–F20

Factory frequency tables are loaded when a profile is activated. V1 and V1.5 also offer the known Runtime modified preset. The controller can write base tables at 3000..3021; only V2 new accepts the extension at 3050..3069. Writes live in RAM, set the table dirty flag and can be undone with the factory restore button. Legacy reads of the extension return recognizable poison values and increment Legacy extension read violation.

The model implements actuator writes at 1999, 2006, 2010, 2015 and 3999, the defrost method write at 3275, the defrost parameter blocks at 3270..3280, 3307..3315, 3336..3341 and 3414..3427, every runtime register at 2099..2138, core identity, customer/model text, synthetic serial metadata and the EEPROM read range used by OpenQuatt. The generated contract documents every supported address and its confidence: docs/quatt-odu-register-contract.md.

Dynamic model

Each ODU has independent mode, level, frequency tables, compressor timers, pump, flow, temperatures, pressures, fan/EEV state, power, faults and diagnostics. Heating and cooling select separate tables. Requested levels above the profile capability are recorded and capped before a frequency is chosen. Mode changes ramp the compressor to zero before restarting in the other mode.

Each enabled ODU now has a nominal normal-Modbus communication watchdog: 10 ms per count, limit 12000, compare before increment and saturate at the limit. A correctly addressed CRC-valid FC03/FC06/FC16 request resets its counter before register-range validation, regardless of response delay or loss. Reads keep the ODU alive. The next watchdog call clears its generated 2121.b0 fault after a reset; it never restores commands cleared by the normal safety update. That update clears 3999, 1999 and internal Hz demand, while measured frequency uses the existing stop ramp. Other fault bits and explicit fault injection are preserved. The wd field in each ODU diagnostics string exposes its counter.

This is a shared HIL preset based on static analysis of one ODU S19 backup, not physical validation of every profile or firmware. It models nominal scheduler ticks using an explicit monotonic clock; real ODU scheduler delays can lengthen the interval. It does not add the real firmware's pump-type-specific emergency pump path or service-mode behavior. The existing pump/flow model remains in use. See the watchdog test procedure for receipt-versus-response tests and limitations.

ODU 1/2 heating limits enabled opts each ODU into its profile's bounded normal-heating outside limits. V1, V1.5 and V2 old use six warm-weather zones; V2 new also retains its cold bands, inlet-temperature release of the highest levels, and quiet cap. The switches start off after boot. The preset limits physical levels before looking up the current RAM table; cooling and defrost retain the contract model. The enable register follows the switch even during standby/cooling/defrost, and the six warm-zone caps are read from the same profile data used by the model. These selected settings are read-only over Modbus; the remaining EEPROM fixture is synthetic. Diagnostics separate the requested table frequency, prepared demand, driver command and measured frequency and report all applicable heating-limit reasons. See the tester guide for examples and hysteresis/reset behavior. Compressor ramp rates remain lab settings; this preset does not model all start conditions or protections. Performance-table boundaries do not impose compressor stops. In particular, V1/V1.5 continue above 12 C using a lower physical-level cap. Cold shutdown and quiet behavior for the older profiles remain outside this preset.

Selected defrost readback defaults are profile-specific: method 0 for V1/V1.5, method 4 for V2 old/V2 new, and start interval raw 0 for V1 or 45 for the other profiles. They do not enable autonomous defrost. Bottom-plate mode 0 clears the model's heater status bit; modes 1..3 still use the existing synthetic outside-temperature/forced-defrost rule. Heater power and full heater timing are not modelled. Manual raw status overrides remain available.

Pump writes control a settling flow model and the flowswitch. 2138 uses the OpenQuatt conversion round(flow_lph / 0.618). Water-out temperature follows a finite water heat capacity and the heat carried away by the flow. The existing four-second response setting defines that capacity at 800 l/h; it is a simulator parameter, not a measured ODU water volume. At zero flow, remaining compressor power heats the trapped water at a finite rate instead of dividing by nearly zero flow. After the compressor stops, trapped water retains its heat until flow resumes; heat loss to the surroundings is not modelled. With steady flow, the final temperature difference still corresponds to thermal power divided by water mass flow and specific heat capacity. ODU external system pump flow applies the configured iPWM flow without requiring ODU pump-relay register 2010; use it when the controller drives a separate system pump. Water-in can be set from 0.0 to 60.0 °C in 0.1 °C steps. Refrigerant temperatures, pressures, fan speed, EEV position and electrical current are deliberately synthetic but internally related.

The numerical thermal-power/COP snapshot comes from the OpenQuatt source revision recorded in data/odu/performance.yaml; no OpenQuatt header is linked at runtime. Performance is interpolated by actual frequency. Above 90 Hz the reported frequency remains correct, while power and COP are capped at the 90 Hz point and High-frequency performance synthetic is set.

The V2 snapshot uses the complete CiC 4.2.0 10 Hz × 17 ambient × 8 supply surface. Masked cells and inputs outside the V2 ambient/supply domain yield no synthetic performance output. For deterministic HIL fixtures, each ODU has an off-by-default manual telemetry override. It supplies only the documented raw readbacks for 2099, 2100, 2101, 2103, 2105, 2108, 2133, 2134, 2137 and 2138; it does not alter dynamic state or the independent defrost register 2118.

The installed ODU Defrost Contract=manual-defrost-v1 marker identifies the accelerated manual-cycle fixture. A 3999=4 write requires actual simulated heating, nonzero compressor feedback, flow switch and at least 250 l/h, no fault words, no injected defrost and no manual telemetry override. Duplicate commands acknowledge the same cycle without resetting its timer or increasing started. The default duration is 30 seconds (configurable 1..600 seconds), independent of synthetic P279. During the cycle, 2099=4, 2118=1, and 2108 defrost, four-way cooling and bottom-plate heater bits are asserted. Completion returns to heating; ambient heater control can keep the heater on below 2 °C.

ODU 1 defrost diagnostics and ODU 2 defrost diagnostics publish started=N completed=N aborted=N. These counters survive the generic diagnostic reset and reset only on boot or model/profile reconfiguration. Normal-mode writes, 1999=0, or loss of heating/flow/fault-free prerequisites abort the manual cycle; compressor stop still follows the ordinary ramp/runtime model. Defrost method and parameter blocks remain synthetic controller fixtures. This does not validate real ODU automatic defrost thresholds or physical cycle timing.

Defrost can be injected per ODU. The defrost register and status bit are set, water-out temporarily falls, and Hold physical level during defrost controls whether a new requested F-level is deferred until defrost ends.

Fault words 2119, 2120 and 2121 accept raw 16-bit values, including multiple simultaneous and unknown bits. Named bit definitions live in the register catalog. Pump/no-flow and measured-frequency freeze are separate web controls.

Protocol fault injection

The custom server dispatch uses ESPHome's UART, frame timing and Modbus CRC, but keeps request, pending-response and response buffers fixed-size. It supports:

  • all ODU responses off, or either address independently offline;
  • non-blocking response delay;
  • every Nth response dropped;
  • timeout for one selected start address;
  • an injected Modbus exception at one selected start address;
  • wrong byte count or an incomplete read response;
  • one-shot reboot on a selected request start address.

For controller UART-error handling, M2 also has deliberately disabled one-shot physical UART fault injection. Enable M2 UART fault injection enabled and then use one of the parity or framing buttons. A parity fault transmits one byte with odd parity on the otherwise 19200 8E1 bus. A framing fault transmits one byte followed by a BREAK condition. The simulator waits for an idle bus, exclusively drives the RS485 transceiver during the fault, and restores even parity and receive mode afterwards. The diagnostics provide the injection, rejected-request and restore-error counters. This is M2-only: M1 requires a second physically connected RS485 path.

For controller-side receive-filter diagnostics, the simulator can instead mark the next FC3/FC4 ODU reply. Inject M2 UART response sentinel replaces the first two data bytes with A5 5A and recalculates the Modbus CRC. Inject M2 UART response parity error marks that same reply but transmits it with odd parity before restoring 8E1. Both actions are one-shot, require the existing fault-injection switch, are mutually exclusive and never alter a write reply. Use controller counters or the log stream as independent evidence; a simulator injection count alone does not prove that the controller filtered it.

The diagnostics show request/read/write/drop/exception counts, invalid address and write counts, capability violations, highest F-level, last request/write and request age. Reset them before each measurement.

Malformed protocol injection intentionally produces frames a normal Modbus client should reject. Disable all injections before interpreting normal timing or functional results.

HTTP and runtime diagnostics

The combined simulator publishes internal free heap, minimum-since-boot heap, largest internal free block and the loop/HTTPD task stack high-watermarks in bytes. An unavailable HTTPD task reports an unknown value rather than a zero margin. Free PSRAM and its largest block are separate measurements; spare PSRAM does not establish that Wi-Fi/TCP allocations have enough internal memory.

Simulator internal heap fragmentation is 100 * (1 - largest / free) for internal 8-bit memory. Simulator maximum loop time is the maximum loop gap in each 10-second window, excluding the first window that includes setup. Uptime and reset reason distinguish a reboot from a temporary HTTP outage; WiFi signal and a disconnect counter help distinguish link loss. Disconnects reset at boot and count ESPHome disconnect notifications, not failed HTTP requests. Added diagnostics publish every 10 seconds.

The combined image uses INFO logging and disables web log streaming to reduce duplicate log/state SSE traffic. State events, REST, serial and native API logging remain available. Model and protocol update intervals are unchanged. The 37 ODU sensor/text readouts publish every five seconds to reduce steady SSE traffic; model updates remain at 250 ms and configuration sync at 500 ms. The boiler-only image keeps its existing logging settings. The USB-powered combined image disables WiFi power saving for sustained HTTP/SSE traffic on the weak lab link; the standalone boiler keeps its WiFi settings. This does not increase signal strength or guarantee RF coverage.

The combined image reserves at least 8192 bytes for the native HTTPD task, using a linker wrapper around httpd_start. Its original 4352-byte stack had only 128 bytes left during entity-detail GETs alongside SSE in HIL. This costs 3840 additional bytes of internal RAM with ESPHome 2026.8.0. Larger upstream stacks, native allocation capabilities and start-failure behavior are preserved. This addresses the measured stack margin; a stack overflow has not yet been proven as the cause of the earlier intermittent panic.

The combined image also selects a local ESPHome 2026.8.0 SSE lifecycle backport of ESPHome #17800. Stalled streams close through their owning HTTPD task; queued close work keeps the response alive and checks session identity before shutdown. The standalone boiler image uses the unmodified upstream component. See the physical HIL and crash investigation for measured results and remaining limits.

For a bounded, read-only comparison with one SSE client and one HTTP GET every two seconds (plus response time), use:

python3 scripts/probe_http.py --url http://SIMULATOR-IP --duration 120 --output build/http-probe.json

Use repeated --path arguments to replay specific GETs, for example --path '/number/ODU%201%20outside%20temperature?detail=all'. Paths are relative to the explicit lab URL; the probe sends no POST requests.

Run identical baseline/candidate loads with the same ODU profiles and controller polling. Record HTTP errors/latencies, SSE traffic and memory trends. An early SSE disconnect is an error, even if root HTTP requests still succeed. A clean short run does not prove the intermittent outage fixed or establish a memory safety budget. Capture serial logs during an outage to retain evidence when HTTP and SSE both become unavailable.

OpenTherm start-sequence diagnostics

The boiler simulator records every valid CH-enable rising edge and whether it was immediately preceded by a valid ID1/TSet write. The diagnostic entities retain the preceding request ID, TSet and frame-end-to-frame-end interval after normal polling has moved on. Resetting diagnostics deliberately drops that request history, so a reset between ID1 and ID0 cannot create a false match.

For a prioritized-start test, reset the OpenTherm diagnostics with CH Enable off, trigger one normal start, and require one rising edge with a finite TSet-to-CH-enable interval and previous request ID 1. These diagnostics describe the simulated OpenTherm exchange; they are not proof of a real boiler startup sequence.

Register data and generation

These files are the editable sources of truth:

data/odu/registers.yaml
data/odu/profiles.yaml
data/odu/performance.yaml
data/odu/scenarios.yaml

Regenerate C++ tables and documentation with:

python3 scripts/generate_odu_contract.py
python3 scripts/generate_odu_contract.py --check

Confidence values mean:

  • observed: confirmed in hardware data or a known dump;
  • documented: from known ODU documentation;
  • controller_contract: required or decoded by OpenQuatt;
  • synthetic: chosen for an internally consistent simulation;
  • unknown: meaning or generation-specific behavior is not established.

Synthetic behavior is never evidence of real ODU behavior.

Host tests

The pure model and generated contract can be tested without ESPHome or hardware. On macOS, select the installed Command Line Tools SDK if the default compiler does not find libc++ headers.

c++ -std=c++17 -Wall -Wextra -Werror tests/boiler_simulator_model_test.cpp -o /tmp/boiler_model_test
/tmp/boiler_model_test
c++ -std=c++17 -Wall -Wextra -Werror tests/opentherm_response_scheduler_test.cpp -o /tmp/ot_scheduler_test
/tmp/ot_scheduler_test
c++ -std=c++17 -Wall -Wextra -Werror tests/opentherm_start_sequence_diagnostics_test.cpp -o /tmp/ot_start_sequence_test
/tmp/ot_start_sequence_test
c++ -std=c++17 -Wall -Wextra -Werror tests/quatt_odu_register_contract_test.cpp -o /tmp/odu_contract_test
/tmp/odu_contract_test
c++ -std=c++17 -Wall -Wextra -Werror tests/quatt_odu_fingerprint_test.cpp -o /tmp/odu_fingerprint_test
/tmp/odu_fingerprint_test
c++ -std=c++17 -Wall -Wextra -Werror tests/quatt_odu_simulator_model_test.cpp -o /tmp/odu_model_test
/tmp/odu_model_test
c++ -std=c++17 -Wall -Wextra -Werror tests/quatt_odu_performance_model_test.cpp -o /tmp/odu_performance_test
/tmp/odu_performance_test

The SSE lifecycle failure-injection test compiles actual production method bodies against deterministic HTTPD/clock stubs, including delayed callbacks, socket reuse, partial sends, queue failures and HTTPD stack allocation failures:

python3 tests/web_server_idf_lifecycle_test.py

Set CXX when a different C++17 compiler is required. This test does not replace real scheduler, networking or HIL validation.

CI also validates the generated register contract and compiles the combined ESPHome firmware. Release tags use the simulator version published by OpenQuatt Simulator Version; contract changes require a new contract value, not only a patch-version bump.

HIL sequence

Host tests and a successful compile do not prove electrical or timing behavior. Use this hardware-in-the-loop sequence after flashing:

  1. Cold boot with ODU 1 V2 old, ODU 2 V2 new, normal responses and no protocol injection.
  2. Reset OT and ODU diagnostics. Confirm both addresses come online with the expected fingerprints.
  3. Confirm the old profile reads only 3000..3021; any read at 3050..3069 must increment the legacy violation counter. Confirm V2 new reads both.
  4. Exercise F0, F10 and F20. ODU 1 must cap F20 to F10; ODU 2 heating F20 must report a 110 Hz demand.
  5. Exercise heating/cooling, table writes/readback, equal-frequency selection, pump/flow, defrost hold and every fault word.
  6. Change a profile through Apply/reboot and verify the controller discards its old identity/table snapshot and reloads it.
  7. Test response loss, reconnect, extension timeout, exception, malformed response and reboot between base and extension reads.
  8. Run OpenTherm demand in parallel. OT RX overflow, overlap and TX error counters must stay zero and queued/completed responses must remain aligned.
  9. Repeat cold boot, Wi-Fi reconnect and OTA recovery.
  10. Finish with a one-hour soak: active OT polling, both ODU addresses, normal OpenQuatt runtime polling, periodic level changes, web UI open and at least one reconnect. Record minimum internal heap, largest free internal block, fragmentation and task-stack high-watermarks as well as protocol counters.

Existing OpenTherm behavior

The boiler simulator remains the same component and pin route as the existing boiler-only firmware. Automatic mode consumes master Status and TSet, models ignition/flame/temperature/modulation and stops on stale demand or fault. Manual telemetry, DHW, fault/status flags, response loss and a 20–700 ms OpenTherm response delay remain available. The yellow LED follows fresh master status; the red LED follows simulated fault/diagnostic state.

Known unknowns and limitations

  • Actual V2 hardware behavior for a level above its capability is unknown.
  • Real start/stop/ramp behavior and runtime telemetry may differ by generation.
  • V2 thermal/electrical behavior at F18–F20 is not validated; power/COP above 90 Hz are synthetic and capped.
  • Reserved registers/bits and most EEPROM metadata have no assigned meaning.
  • Real ODU response timing and exception behavior still require captures.
  • EEPROM fixtures are synthetic and do not implement a vendor CRC.
  • Runtime frequency writes are RAM-only; explicit flash persistence is not implemented, avoiding uncontrolled flash wear.
  • ODU faults are injected through three raw words; separate named switches, timed auto-clear and reboot-latched fault state are not yet implemented.
  • Unknown-fingerprint and arbitrary custom-fixture profiles are not yet exposed in the web UI; new redacted captures can be added to the catalogs without changing the model architecture.
  • A one-shot stale pre-profile response is not synthesized. The real reboot and configurable loss/malformed modes cover reconnect invalidation tests, but do not reproduce every possible stale-frame interleaving.
  • A simulator cannot validate combustion, hydraulics, physical heat output or undiscovered vendor behavior, and does not replace final testing with a real ODU.

License and provenance

The project is licensed under GPL-3.0. The vendored OpenTherm driver originates from Ihor Melnyk's MIT-licensed OpenTherm library and includes ESP32-S3 ESP-IDF/RMT adaptations. See THIRD_PARTY_NOTICES.md.

About

Standalone ESPHome HIL simulator for OpenQuatt: dual Modbus Quatt ODUs and OpenTherm boiler.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages