Custom driver for Sonoff SNZB-02DR2 Temperature and Humidity Sensor (BETA 2)

Below is a custom driver for the Sonoff SNZB-02DR2 (see image below). This device has native min/max temp and humidity data; the driver also computes min/max values with a timestamp.

EDIT 2026-11-06: V1.12.2 fixes a few issues with saving Preferences. You can also now change the LCD display temperature units to F or C (the device must be woken up for the changes to take place).

EDIT 2026-11-17: See here for the latest code and README. Version 1.2.1 is a unified driver for Sonoff SNZB-02P, SNZB-02D, SNZB-02DR2 and SNZB-02M Zigbee sensors.

For the 02DR2 sensor, v. 1.2.1 allows programmatic setting of numeric data to at least one field (EXT1) on all FW versions, and two fields (EXT1, EXT2) for some FW versions (1.05 onwards). Example usage: monitoring the temp of a different sensor (does not have to be Sonoff) and mirroring that value to an 02DR2 display (taking into account that the 02DR2 likely will have lag as a "sleepy" device).

EDIT 2026-11-17: For the SNZB-02DR2 only: new attributes Device Temp Avg and Device Humidity Avg (FC11 0x200A / 0x200D, previously logged as unexplained reference values). Believed to show the values averaged over 24 hours.

2026-11-17 EDIT: This section is no longer up to date, but is mostly correct. Check the README.md file here for more accurate information:

https://github.com/JohnFLand/Sonoff_SNZB-02_Series-Zigbee-driver-for-Hubitat

==================================================

==================================================

Below is a REVISED (as of 2026-11-06) README regarding the discovered characteristics of the Sonoff SNZB-02DR2 sensor, for those interested in exploring its capabilities and quirks:

=========================================================

Sonoff SNZB-02DR2 AirGuard TH β€” Hubitat Driver

Driver version: 1.12.2
Device: Sonoff SNZB-02DR2 ("AirGuard TH") Zigbee temperature and humidity sensor
Manufacturer/Model strings: SONOFF / SNZB-02DR2 or eWeLink / SNZB-02DR2
Firmware: Software Build ID 1.0.2, Date Code 20251020, ZCL version 3, HW version 16
Manufacturer code: 0x1286 = SHENZHEN COOLKIT (Sonoff/eWeLink)


Overview

The SNZB-02DR2 is a Zigbee sleepy end-device with a 3.6" LCD display showing current temperature, current humidity, 24-hour min/max extremes, comfort zone icons, and battery level. It uses a mix of standard Zigbee clusters and Sonoff's private FC11 and FC57 clusters for extended features.

This driver was developed through iterative Zigbee sniffing using the Knockturn Alley diagnostic driver. Several of the FC11 attributes described below were not previously documented for this specific device, and some behaviours remain under investigation.


Installation

  1. In Hubitat, go to Drivers Code β†’ New Driver
  2. Paste the full driver code and click Save
  3. The driver's fingerprints will auto-match on pairing, or manually select Sonoff SNZB-02DR2 Temperature and Humidity Sensor from the device's Type dropdown

Upgrading

Paste the new code over the existing driver in Drivers Code and click Save. Then:

From v1.10.0 or earlier

  1. For each device: press the button on the back of the sensor, then immediately click Save Preferences. This sends your reporting settings to the device β€” earlier versions only did so at pairing or on Initialize, so changes made in the preferences page may never have reached the device.
  2. If a decimal preference was stuck (for example Temperature reporting threshold showing 0.0 and refusing other values, or an offset that would only accept negative numbers), it can now be edited normally. An out-of-range saved value is corrected automatically on the next Save and noted in the log.

From v1.11.0 or v1.12.x

No action is needed unless you use LCD temperature unit: v1.12.0 and v1.12.1 sent it with a data type the device rejects, so wake the device and click Save Preferences once to apply it. Re-publish on Save (see Preferences) starts working once the device has sent its first temperature and humidity readings after the upgrade.

Comfort humidity limits are now 5–95 %. A saved value outside that range is sent to the device as the nearest limit.


Device Characteristics

Property Value
Logical type Zigbee End Device (ZED) β€” not a router
Sleepy device Receiver off when idle; wakes to report then sleeps
Check-in interval 29 minutes (0x00001B30 = 1740 seconds)
Long poll interval 1740 seconds (same as check-in)
Short poll interval 1 second (while awake / fast polling)
Fast poll timeout 10 seconds after wake
Max buffer size 74 bytes
Physical sensor range βˆ’40Β°C to 115Β°C / battery reports 27–29 min cycle

Check-in vs. reporting: The 29-minute check-in / long-poll interval controls how often the device listens for messages from the hub β€” which is why writes must be sent while the device is awake. It does not limit how often the device sends readings: temperature and humidity reports are pushed whenever the change exceeds the reporting threshold (subject to the minimum interval), plus a heartbeat at the maximum interval. See FAQ below.

Health check note: With a 29-minute check-in interval, the driver's health check (which fires every 3 hours and marks offline after 4 missed cycles) gives the device approximately 2 hours of grace before being flagged offline. This is appropriate for normal operation but means the device will not be marked offline quickly after a battery failure or signal loss.


Supported Capabilities

Capability Notes
TemperatureMeasurement Standard ZCL cluster 0x0402
RelativeHumidityMeasurement Standard ZCL cluster 0x0405
Battery Percentage from cluster 0x0001 attr 0x0021; voltage from attr 0x0020
Refresh Reads all current values and FC11 attributes on demand
Health Check Marks device offline after 4 missed health-check cycles
Sensor Base capability

Current States

All temperature values are displayed in the hub's configured scale (Β°F or Β°C).

Standard readings

Attribute Description
temperature Current temperature (standard capability attribute)
humidity Current relative humidity % (standard capability attribute)
battery Battery level %

Hubitat-tracked min/max

Calculated by the driver from the stream of incoming readings. Accumulate from driver install or last reset, independent of the device's own 24-hour window.

Each min/max value includes the timestamp of the occurrence embedded directly in the attribute string, in the format <value> @ <MM-dd HH:mm> (e.g. 21.4Β°C @ 06-03 14:22 or 58% @ 06-03 09:47). The timestamp reflects when that record was set, not when the attribute was last read.

Attribute Description
Temperature Min Lowest temperature reading since last reset, with occurrence timestamp
Temperature Max Highest temperature reading since last reset, with occurrence timestamp
Humidity Min Lowest humidity reading since last reset, with occurrence timestamp
Humidity Max Highest humidity reading since last reset, with occurrence timestamp
Min/Max Reset Timestamp of the last reset (manual or automatic)
Readings Since Reset Count of temperature+humidity reading pairs since last reset

Device-native 24-hour min/max (confirmed via Zigbee sniff)

These come directly from the device firmware via FC11 cluster attributes 0x2008–0x200D. They are the same values shown on the LCD display. The device pushes these unsolicited roughly once per hour; Refresh while awake also reads them explicitly.

Attribute FC11 Attr Type Notes
Device Temp Max 0x2008 INT16 Γ—100 Β°C
Device Temp Min 0x2009 INT16 Γ—100 Β°C
Device Humidity Max 0x200B UINT16 Γ—100 %
Device Humidity Min 0x200C UINT16 Γ—100 %

Note: Attributes 0x200A (reference temp) and 0x200D (reference humidity) also arrive in the hourly burst. Their meaning is unconfirmed β€” logged at info level but not exposed as Current States.

Note: Two additional FC11 attributes β€” 0x200E and 0x600E (both UINT8, both currently 0x00) β€” were discovered via sniffing. Their meaning is unknown. See the FC11 attribute map and Known Limitations below.

Comfort zone thresholds and LCD unit

Reflect what is currently programmed in the device firmware. Read from FC11 on every Refresh and on Configure/Initialize.

Attribute FC11 Attr Notes
comfortTempMin 0x0004 :snowflake: icon threshold
comfortTempMax 0x0003 :fire: icon threshold
comfortHumiMin 0x0005 Lower humidity comfort bound
comfortHumiMax 0x0006 Upper humidity comfort bound
lcdTempUnit 0x0007 Celsius or Fahrenheit β€” unit the device's LCD is actually using (read back after every Save), not the preference (new in 1.11.0)

Note: FC11 comfort threshold attributes (0x0003–0x0006) and device min/max attributes (0x2008–0x200D) do not appear in FC11's attribute discovery response. They are only accessible via direct read with manufacturer code 0x1286, or received as unsolicited reports. This is why standard Zigbee tools cannot see them without the manufacturer code.

Other

Attribute Description
Last Reading Timestamp of the most recent temperature+humidity report received from the device
healthStatus online / offline / unknown
rtt Round-trip time in ms (from Ping), or -1 if the ping timed out

Preferences

Preference Default Valid range Notes
Debug logging enabled Auto-disables after 24 hours
Description text logging enabled Logs readings to Events tab
Min time between temperature reports 10 s 1–3600 Sent to device on Save
Max time between temperature reports 3600 s 10–43200 Heartbeat interval; sent to device on Save
Temperature reporting threshold 0.2 Β°C 0.1–5.0 Minimum change to trigger a report; sent to device on Save
Min time between humidity reports 10 s 1–3600 Sent to device on Save
Max time between humidity reports 3600 s 10–43200 Sent to device on Save
Humidity reporting threshold 1 % 1–10 Sent to device on Save
Temperature offset 0.0 Β°C βˆ’20.0–20.0 Applied in Hubitat only; does not write to device. Takes effect immediately on Save
Humidity offset 0.0 % βˆ’20.0–20.0 Applied in Hubitat only; does not write to device. Takes effect immediately on Save
LCD temperature unit Leave unchanged Leave unchanged / Β°C / Β°F Unit shown on the device screen. Hubitat's own values always follow the hub's scale.
Comfort temperature minimum (Β°C) 18.0 βˆ’10–60 Always enter in Β°C regardless of hub scale
Comfort temperature maximum (Β°C) 26.0 βˆ’10–60 Always enter in Β°C regardless of hub scale
Comfort humidity minimum (%) 40 5–95 :sun: icon shown below this value
Comfort humidity maximum (%) 60 5–95 :droplet: icon shown above this value
Auto-reset min/max daily disabled When enabled, driver-tracked min/max resets automatically each day at the time below
Auto-reset time 00:00 Time of day for the daily reset; only active when auto-reset is enabled

Decimal preferences are range-checked by the driver rather than by the preferences page. A value outside the valid range is replaced with the nearest valid value on Save, and a warning is written to the log.

Offsets take effect immediately. When you click Save Preferences, the driver re-publishes the current temperature and humidity from the last readings it received, with the new offsets applied, so you don't have to wait for the next report. This part works whether or not the device is awake. Re-published events are marked digital and logged with "(re-published)". The Hubitat-tracked min/max, Last Reading and Readings Since Reset are not changed; use Reset Min/Max if you want the min/max recalculated on the new offset. The device's screen and its own 24-hour min/max are never affected by Hubitat offsets.

Important β€” sleepy device: The SNZB-02DR2 listens for messages from the hub only about every 29 minutes. Saving preferences sends the reporting configuration and the FC11 settings (comfort thresholds, LCD unit) to the device, and these are dropped if the device is asleep. Press the button on the back to wake it immediately before clicking Save Preferences.

With description text logging enabled, the log confirms the result of each request:

  • Temperature reporting configuration accepted by device (likewise Humidity, Battery)
  • FC11 attribute write accepted by device
  • A warning such as FC11 write of attribute 0x0007 rejected (status 0x8D) if the device refuses a change
  • The comfort thresholds and LCD unit read back from the device (FC11 comfort temp min = …, FC11 LCD temperature unit: …), so comfort* and lcdTempUnit show what the device now holds

If none of these lines appear after a Save, the device was asleep β€” wake it and save again. (Re-publishing the current readings with new offsets does not need the device awake.)


Commands

Command Description
Refresh Reads all current values, comfort thresholds, LCD unit, and device-native 24-hr min/max. Use this to force an immediate read of Device Temp/Humidity Min/Max without waiting for the next unsolicited ~hourly report from the device. Wake the device first.
Reset Min/Max Clears the Hubitat-tracked min/max and resets the readings counter. Does not affect device's own 24-hr values. Also triggered automatically when auto-reset fires.
Initialize Re-initializes all driver state and re-runs configure(). Clears all Current State values, including the Hubitat-tracked min/max. Not needed just to apply preference changes β€” Save Preferences does that.
Ping Sends a basic cluster read and reports round-trip time

FAQ

Can I get temperature updates more often than every ~29 minutes?

Usually, yes. Reports are triggered by change: the device sends a temperature report whenever the reading moves by at least the Temperature reporting threshold, no more often than the Min time interval, and sends a heartbeat at the Max time interval even if nothing has changed. For use as a remote sensor for a thermostat, a threshold of 0.1–0.2 Β°C and a max interval of 300–600 s are reasonable starting points. Wake the device before saving and check the log for "reporting configuration accepted".

The 29-minute check-in interval (Poll Control cluster) is separate. It governs how often the device listens for commands from the hub, not how often it reports, and this driver does not change it. More frequent reporting will shorten battery life.

Can the temperature units be changed?

Hubitat's displayed values always follow the hub's temperature scale (Settings β†’ Location). The unit on the device's own LCD is controlled separately by the LCD temperature unit preference (wake the device, then click Save Preferences).

Can the device receive firmware updates through Hubitat?

Not as far as is known. Hubitat only performs Zigbee OTA updates for firmware images it hosts itself, and Sonoff images are not among them. To update, temporarily pair the sensor to a platform that carries Sonoff firmware (a Sonoff/eWeLink hub, Zigbee2MQTT, or ZHA), update it there, then reset and re-pair it to Hubitat.


Known Limitations and Open Questions

Decimal preferences could not be edited β€” Fixed in v1.11.0

In v1.10.0 and earlier, decimal preferences declared a range: (for example '0.1..5.0' or '-20.0..20.0'). Hubitat's preferences page does not handle ranges with fractional bounds reliably, which caused symptoms such as:

  • Temperature reporting threshold stuck at 0.0 β€” any other value reverted on leaving the field or saving, and values like 0.3 or 0.4 were never accepted
  • Temperature offset and Humidity offset accepting only negative numbers

A threshold of 0.0 also makes the device report every tiny fluctuation, which shows up as oscillation in graphs. v1.11.0 removes range: from all decimal inputs and enforces the ranges in the driver instead.

Reporting preferences were not sent on Save β€” Fixed in v1.11.0

In v1.10.0 and earlier, the reporting interval and threshold preferences were sent to the device only at pairing or on Initialize (which also clears all tracked min/max). Save Preferences now sends them every time.

LCD temperature unit could not be set β€” Fixed in v1.12.2

The device declares FC11 0x0007 as UINT16 (data type 0x21 in its read responses) and rejects UINT8 writes with status 0x8D (invalid data type). v1.11.0 wrote UINT16, which was correct; v1.12.0 and v1.12.1 switched to UINT8 based on an earlier, incorrect entry in the attribute map below, so the LCD unit could not be changed with those versions.

v1.12.2 writes UINT16, confirmed working in both directions on firmware 1.0.2. If other firmware answers 0x8D, the driver retries at once with ENUM8, BOOLEAN and UINT8 while the device is still awake, and keeps whichever type is accepted for later Saves.

Comfort Temp Min does not populate β€” Fixed in v1.9.0

The FC11 attribute map used in v1.8.0 and earlier had an off-by-one error inherited from an older version of the zigbee-herdsman-converters source. The correct attribute IDs, verified against the current converter source and confirmed by the symptom (a value that looked like a temperature minimum appearing under Comfort Humi Min), are:

Attribute Correct ID Old (wrong) ID
comfortTempMax 0x0003 0x0003 (was correct)
comfortTempMin 0x0004 0x0002 ← was wrong
comfortHumiMin 0x0005 0x0004
comfortHumiMax 0x0006 0x0005
tempUnit 0x0007 0x0001
tempCalibration 0x2003 0x0006
humiCalibration 0x2004 0x0007

All seven attributes now read and decode correctly.

Device-native 24-hr min/max is not remotely resettable

Writing 0 to FC11 attributes 0x2008–0x200C is silently ignored by the device. Those attributes are read-only from the Zigbee side; the device firmware owns them entirely. The Reset Device Min/Max command introduced in v1.6.0 was removed in v1.9.0. To re-read the current values on demand, use Refresh while the device is awake.

The Zigbee2MQTT SNZB-02DR2 page does not expose a reset function for these values. SONOFF's product page describes them as "24-hour extremes," consistent with a firmware-maintained rolling window rather than a Hubitat-resettable state.

The only confirmed way to reset the device's 24-hour min/max is a ~10-second hold of the physical button. This is a local firmware action with no Zigbee equivalent.

Device-native min/max reset timing

Not yet confirmed: does the device reset its 24-hour window at midnight, on a rolling 24-hour cycle, or only on button hold? Observation across midnight is needed.

FC11 0x200E β€” newly discovered, meaning unknown

UINT8, reported value 0x00. Sent in the wake-up burst after humidity calibration. Numerically follows the 0x2008–0x200D min/max group. Candidates: a reset-occurred flag (would become 1 after the 10-second button hold?), a period counter, or an alarm state. Worth monitoring after a button-hold reset to see if it changes.

FC11 0x600E β€” newly discovered, meaning unknown

UINT8, reported value 0x00. Sent ~2 seconds before 0x200E in the same wake burst. The 0x60xx address space is well outside the 0x20xx group. May be related to the FC57 cluster (note that FC57 also has an 0x000E attribute, also UINT8, also 0x00).

FC11 0x200A and 0x200D β€” reference values, meaning unknown

Arrive with the hourly 0x2008–0x200D min/max report. Plausibly previous-period or rolling-average values. Meaning not yet confirmed.


Zigbee Cluster Summary

Cluster ID Usage
Basic 0x0000 Device info, ping/RTT
Power Configuration 0x0001 Battery % (attr 0x0021) and voltage (attr 0x0020)
Identify 0x0003 Standard
Poll Control 0x0020 Sleepy device check-in; 29-min interval confirmed
Temperature Measurement 0x0402 Current temp; sensor range βˆ’40Β°C to 115Β°C
Relative Humidity 0x0405 Current humidity
Time 0x000A Out-cluster (device receives time from coordinator)
OTA Upgrade 0x0019 Out-cluster (device receives OTA firmware updates)
Sonoff Private (FC11) 0xFC11 Comfort thresholds, LCD unit, calibration, device min/max
Sonoff Private (FC57) 0xFC57 OTA/device management β€” see below

FC57 Cluster β€” Decoded

FC57 is Sonoff/eWeLink's private device management cluster, used across their Zigbee product range. Based on cross-referencing with other Sonoff devices in zigbee2mqtt, combined with the attribute types and values observed, FC57 is most likely the Sonoff OTA / firmware management cluster. Evidence:

  • The device declares 0x0019 (standard OTA Upgrade cluster) as an out-cluster, meaning it expects to receive OTA images from the coordinator. FC57 likely coordinates that process on the Sonoff side.
  • 0x0011 = 0xFF and 0x0012 = 0xFFFF are classic "not set / no limit" sentinel values.
  • 0x0013 = 0 could be a downloaded-bytes counter or OTA sequence number.
  • The bool flags fit a state machine (checking/available/downloading/complete).
  • Cluster Revision = 1 indicates an early internal cluster definition.

All FC57 attributes are read-only (r--). No received commands are defined, meaning this cluster cannot be commanded from Hubitat. It is informational only.

Attribute Type Value Likely meaning
0x0002 bool True OTA check enabled / feature available
0x0003 bool True OTA schedule active / bound to server
0x0004 uint8 3 OTA image type or capability flags
0x0005 uint8 3 OTA image subtype or paired flags
0x0006 bool False Low battery / error flag (False = OK)
0x0007 bool True Reporting active / coordinator bound
0x0008 bool False Alarm or error flag (False = OK)
0x000D bool True Unknown
0x000E uint8 0 Unknown β€” same attribute number as FC11 0x200E/0x600E low byte
0x000F bool False OTA not currently downloading
0x0011 uint8 0xFF "No limit" / not set
0x0012 uint16 0xFFFF "No limit" / not set
0x0013 uint16 0 Counter / sequence / downloaded bytes
0xFFFD uint16 1 Cluster Revision = 1

FC11 Attribute Map (as understood)

Important note on discoverability: FC11 comfort threshold attributes (0x0003–0x0006) and device min/max attributes (0x2008–0x200D) do not appear in FC11's ZCL attribute discovery response. Only 0x0007, 0x200E, and 0x600E are discoverable. The remaining attributes are accessible only via direct reads using manufacturer code 0x1286, or received as unsolicited reports from the device.

Attribute Type R/W Status Description
0x0003 INT16 R/W Confirmed working Comfort temp max (:fire: threshold), Β°C Γ—100
0x0004 INT16 R/W Confirmed working Comfort temp min (:snowflake: threshold), Β°C Γ—100
0x0005 UINT16 R/W Confirmed working Comfort humidity min, % Γ—100
0x0006 UINT16 R/W Confirmed working Comfort humidity max, % Γ—100
0x0007 UINT16 R/W Confirmed working (write fixed in 1.12.2) LCD temperature unit (0=Β°C, 1=Β°F); exposed as lcdTempUnit. Device reports type 0x21; rejects UINT8 writes (0x8D)
0x2003 INT16 R/W? Not yet observed Temperature calibration offset, Β°C Γ—100
0x2004 INT16 R/W? Not yet observed Humidity calibration offset, % Γ—100
0x2008 INT16 R only Confirmed working Device max temp (24-hr), Β°C Γ—100
0x2009 INT16 R only Confirmed working Device min temp (24-hr), Β°C Γ—100
0x200A INT16 R only Received, meaning unknown Reference/previous-period temp
0x200B UINT16 R only Confirmed working Device max humidity (24-hr), % Γ—100
0x200C UINT16 R only Confirmed working Device min humidity (24-hr), % Γ—100
0x200D UINT16 R only Received, meaning unknown Reference/previous-period humidity
0x200E UINT8 R only? Newly discovered, discoverable, value=0 Unknown β€” sent in wake burst
0x600E UINT8 R only? Newly discovered, discoverable, value=0 Unknown β€” sent in wake burst

Changelog

Version Date Notes
1.0.0 2025-06-02 Initial release
1.1.0 2026-06-02 Added Min/Max Reset timestamp and Readings Since Reset counter
1.2.0 2026-06-02 Decoded FC11 0x2008–0x200D device-native 24-hr min/max via Zigbee sniff
1.6.0 2026-06-02 Added comfort threshold sentinels; added resetDeviceMinMax command
1.7.0 2026-06-03 Added Last Reading timestamp; added scheduled daily auto-reset of driver min/max
1.8.0 2026-06-03 Embedded occurrence timestamp in Temperature/Humidity Min/Max values
1.9.0 2026-06-04 Fixed FC11 attribute map (comfortTempMin corrected from 0x0002 to 0x0004; all comfort/calibration/unit IDs updated to match current zigbee-herdsman-converters). Replaced resetDeviceMinMax command with readDeviceMinMax β€” device 24-hr min/max is not remotely resettable.
1.10.0 2026-06-04 Removed readDeviceMinMax command β€” fully redundant with Refresh, which already reads device-native min/max explicitly.
1.11.0 2026-11-04 Fixed decimal preferences that could not be edited (threshold stuck at 0.0; offsets accepting only negative numbers) by removing range: from decimal inputs and range-checking in the driver; out-of-range saved values are corrected on Save. Save Preferences now sends the reporting configuration to the device. Added experimental LCD temperature unit preference and lcdTempUnit attribute. The log now shows whether the device accepted or rejected each reporting configuration and attribute write.
1.12.0 2026-11-06 Saving preferences now immediately re-publishes temperature and humidity from the last readings, so offset changes appear at once (raw readings are stored before the offset; tracked min/max are not recomputed). LCD temperature unit is now written as UINT8, matching attribute discovery (1.11.0 wrote UINT16). Ping timeout now sets rtt to -1 instead of the string timeout.
1.12.1 2026-11-06 Save Preferences now reads the comfort thresholds and LCD unit back after writing them, so comfort* and lcdTempUnit show what the device holds. Comfort humidity limits narrowed to 5–95 %, the range Zigbee2MQTT documents for this device.
1.12.2 2026-11-06 Fixed LCD temperature unit: written as UINT16, the type the device declares (1.12.0 and 1.12.1 wrote UINT8, which the device rejects with 0x8D). On a 0x8D rejection the driver retries with other data types while the device is awake. The log line for the LCD unit now includes the data type the device reports.

License

Licensed under the Apache License, Version 2.0.

I went ahead and bought a couple of these for Prime Day and your driver is working great for them so far. Thank you!

Hi John, looks like you have done a lot of great work on this driver. The device looks good but I’m not clear on a couple of things. 1) Is the 29 minute sleep cycle configurable? I hope to use it as a remote temp sensor for a virtual thermostat and in that scenario 29 mins is too long. 2) Are the temperature display units configurable as a preference? 3) Can the device get firmware updates using Hubitat as the gateway (probably no, but I had to ask.) Thanks for your time on this.

P.S. Claude was working for me and he didn’t mention any moonlighting projects. Going to have to talk to him.

Outstanding work on this driver! Thank you for all the effort.

I purchased 6 of these devices and placed them around the house to monitor temperatures of various rooms that either get too warm or not warm enough. The data coming from these devices has been invaluable in knowing my heating system's weaknesses.

I am experiencing one issue. On two of the 6 devices, the Temperature reporting threshold (Β°C) in the Preferences of the device are displaying 0.0 while the other 4 are 0.2. The 0.0 is causing oscillation in my waveform. It's not a big deal but I have tried to changed the 0.0 to be 0.2 like the others. The field will let me type it in but when I move to another preference field or click on Save, it reverts to 0.0. I have not found a way to set it back to 0.2.

I am not at all sure how the field got changed or whether it was like that when set up. I know at one point I wanted to change them all to 0.3 or 0.4 but was unable to do so. Perhaps while doing that and exploring why I was unable to make the changes I may have inadvertently set it to 0.0 somehow and save it as such.

Like I said, its not a huge issue but the driver seems otherwise perfect and felt you would at least like to know of the issue.

Again, thank you so much for this outstanding driver.

Apologies for such a belated reply, I just overlooked this! Here's what Claude AI says (note: I'll be posting a bug-fixed driver in a few minutes) --

(1) Reporting interval: Mostly yes, with v1.11.0. The ~29–30 minutes is the firmware’s default heartbeat. Tests describe the sensor as reporting on any change of β‰₯0.2 Β°C or β‰₯5% humidity, and otherwise at least every 30 minutes (default reporting interval). The same review notes Zigbee2MQTT can change the reporting interval, so the firmware does accept reporting configuration. In the driver, set β€œMax time between temperature reports” to something like 300–600 s and a threshold of 0.1–0.2 Β°C. Wake the device, then Save. For a thermostat, the threshold matters more than the heartbeat, because changes are reported as they happen. More frequent reporting costs battery, though one SmartThings user running SNZB-02s as thermostats at 0.1 Β°C / 5-minute reporting still had 65% battery after 3 years.

(2) Temperature units: Hubitat’s displayed values always follow the hub’s scale (Settings β†’ Location). The device’s LCD unit is now a driver preference (β€œLCD temperature unit”). One caveat: I couldn’t independently confirm the data type the device expects for that attribute. If it rejects the write, the log will show β€œwrite of attribute 0x0007 rejected (status 0x8D)”, and that would mean switching it to an 8-bit type.

(3) Firmware updates via Hubitat: Almost certainly not. Hubitat only pushes Zigbee firmware it hosts itself, and I’m not aware of any Sonoff images among them. Sonoff’s own guidance is to update through ZHA or Zigbee2MQTT, when the firmware has been published to those platforms’ repositories, or through an eWeLink/Sonoff hub. The practical route is to pair to one of those temporarily, update, then reset and re-pair to Hubitat.

Yep, that be some bugs. Post 1 has a new v. 1.11 with this fix:

Fix decimal preferences getting "stuck" (e.g. reporting threshold stuck at 0.0): removed range: from decimal inputs, because Hubitat's preference page treats a decimal range such as '0.1..5.0' as whole-number bounds and rejects values like 0.2. Ranges are now enforced in the driver, and an out-of-range saved value is corrected on the next Save.

Saving preferences now sends the reporting configuration to the device
(previously only sent on pairing / Initialize).

Added LCD temperature unit preference (FC11 0x0007).

Log whether the device accepted reporting-configuration and attribute writes.

New 1.12.2 version in Post #1, fixes some issues with Preferences.

See updated 1.12.2 version in Post #1, fixes some issues with Preferences.

I did something similar and bought a cheap anemometer off amazon and finally balanced my heat and A/C. Then I used a virtual thermostat and it made a huge difference to keeping the house in a narrower temperature range across the basement and the two upper floors.

Hi John_Land

First of all, thank you for you great work on this driver.

Second, please check these photos :grin:

This was only a small test made with Gemini Argon, based on your driver. I can share the modifications with you in private if you need it, and you can build it officially into your driver. I will not share in public, because it is based on your work.

Nice work! I'd love to see your code, but feel free to publish -- I dedicate all of my Hubitat Groovy work to the public domain as small compensation for all of the code of others that I've benefited from.

Here is the modified driver. I cannot test it int the next 2-3 days, so I hope everything works.

/* groovylint-disable CompileStatic, LineLength, NoDef, VariableTypeRequired */
/**
 *  Sonoff SNZB-02DR2 Temperature and Humidity Sensor (AirGuard TH) - Extended
 *
 *  Hubitat driver for the Sonoff SNZB-02DR2 Zigbee temperature/humidity sensor.
 *  Based on John Land's driver v1.12.2 (2026/11/06).
 *
 *  Features:
 *    - Temperature and humidity reporting (clusters 0x0402 / 0x0405)
 *    - Battery percentage reporting (cluster 0x0001)[cite: 5]
 *    - Health status monitoring[cite: 5]
 *    - Software-tracked min/max temperature and humidity (mirrors the device LCD 24-hr extremes)[cite: 5]
 *    - Read/write of FC11 comfort-zone thresholds (trigger ❄️ and πŸ”₯ icons on the LCD)[cite: 5]
 *    - LCD temperature unit setting (Β°C / Β°F) via FC11 cluster (0x0007)[cite: 5]
 *    - Hardware-level temperature and humidity calibration offsets via FC11 cluster (0x2003 / 0x2004)
 *    - External Display (EXT1) control via FC11 cluster (0x600E mode & 0x600D value) with
 *      wake-up piggybacking queue for reliable delivery on sleepy end-devices
 *    - Physical rear button press detection (cluster 0x0003) to flush pending writes
 *    - Configurable reporting intervals and sensitivity thresholds (sent to the device on Save)[cite: 5]
 *    - Reset of tracked min/max values via command[cite: 5]
 *
 *  Licensed under the Apache License, Version 2.0[cite: 5]
 *
 *  Changelog:
 *    1.12.2 2026-11-06  Original baseline by John Land[cite: 5]
 *    1.13.0 2026-11-17  - Added External Display (EXT1) support: setExt1Info command (writes 0x600D INT16)
 *                         and setExternalDisplayMode command (writes 0x600E UINT8). If already in EXT1 mode,
 *                         setExt1Info only writes 0x600D to minimize Zigbee traffic.
 *                       - Added wake-up piggybacking queue (state.pendingExtWrite) so EXT1 updates reliably
 *                         land on the next device report or button press if immediate polling misses.
 *                       - Switched temperatureOffset and humidityOffset from software-only math to hardware
 *                         calibration registers FC11 0x2003 and 0x2004 so the physical LCD and Hubitat match.
 *                       - Added cluster 0x0003 (physical back button press) and 0x8021 (ZDO Bind_rsp) handling.
 */

import groovy.transform.Field
import hubitat.zigbee.zcl.DataType

@Field static final String VERSION    = '1.13.0'
@Field static final String TIME_STAMP = '2026/11/17'

// Cluster constants
@Field static final Integer CLUSTER_POWER_CFG = 0x0001
@Field static final Integer CLUSTER_IDENTIFY  = 0x0003
@Field static final Integer CLUSTER_TEMP      = 0x0402
@Field static final Integer CLUSTER_HUMIDITY  = 0x0405
@Field static final Integer CLUSTER_FC11      = 0xFC11   // Sonoff private cluster[cite: 5]
@Field static final Integer CLUSTER_ZDO_BIND  = 0x8021   // ZDO Bind_rsp

// FC11 attribute IDs β€” verified via Zigbee Attribute Discovery (0x0C/0x0D) on firmware 1.0.2 (00001002)
@Field static final Integer FC11_ATTR_COMFORT_TEMP_MAX = 0x0003  // INT16 (0x29),  value * 100 (Β°C Γ— 100)
@Field static final Integer FC11_ATTR_COMFORT_TEMP_MIN = 0x0004  // INT16 (0x29),  value * 100 (Β°C Γ— 100)
@Field static final Integer FC11_ATTR_COMFORT_HUMI_MIN = 0x0005  // UINT16 (0x21), value * 100 (% Γ— 100)
@Field static final Integer FC11_ATTR_COMFORT_HUMI_MAX = 0x0006  // UINT16 (0x21), value * 100 (% Γ— 100)
@Field static final Integer FC11_ATTR_TEMP_UNIT        = 0x0007  // UINT16 (0x21), 0=Celsius 1=Fahrenheit
@Field static final Integer FC11_ATTR_TEMP_CALIBRATION = 0x2003  // INT16 (0x29),  offset * 100 (Β°C Γ— 100)
@Field static final Integer FC11_ATTR_HUMI_CALIBRATION = 0x2004  // INT16 (0x29),  offset * 100 (% Γ— 100)

// FC11 External Display (EXT1) attributes (confirmed on firmware <= 1.0.4)
@Field static final int FC11_EXT_TEMP_VAL  = 0x600D  // INT16 (0x29), external value * 100
@Field static final int FC11_EXT_TEMP_MODE = 0x600E  // UINT8 (0x20), 0=Internal Min/Max, 1=External (EXT1)

// Data types tried, in order, when writing the LCD unit (0x0007): UINT16, ENUM8, BOOLEAN, UINT8[cite: 5]
@Field static final List<Integer> LCD_UNIT_TYPES = [0x21, 0x30, 0x10, 0x20]

// FC11 device-native 24-hr min/max (unsolicited ~hourly)[cite: 5]
@Field static final int FC11_MAX_TEMP  = 0x2008  // UINT16/INT16 max temp x100 degC
@Field static final int FC11_MIN_TEMP  = 0x2009  // INT16  min temp x100 degC
@Field static final int FC11_PREV_TEMP = 0x200A  // INT16  reference temp
@Field static final int FC11_MAX_HUMI  = 0x200B  // UINT16 max humidity x100 %
@Field static final int FC11_MIN_HUMI  = 0x200C  // UINT16 min humidity x100 %
@Field static final int FC11_PREV_HUMI = 0x200D  // UINT16 reference humidity

// Valid ranges for decimal preferences[cite: 5]
@Field static final double TEMP_CHANGE_MIN  = 0.1
@Field static final double TEMP_CHANGE_MAX  = 5.0
@Field static final double OFFSET_MIN       = -20.0
@Field static final double OFFSET_MAX       = 20.0
@Field static final double COMFORT_TEMP_MIN = -10.0
@Field static final double COMFORT_TEMP_MAX = 60.0
@Field static final double EXT1_VAL_MIN     = -40.0
@Field static final double EXT1_VAL_MAX     = 99.9

@Field static final Integer PRESENCE_THRESHOLD = 4     // missed health-check cycles before "offline"[cite: 5]
@Field static final Integer PING_TIMEOUT_MS    = 10000
@Field static final Long    EXT_FLUSH_DEBOUNCE = 2500L // min ms between wake-up flushes

metadata {
    definition(
        name:      'Sonoff SNZB-02DR2 Temperature and Humidity Sensor (EXT1)',
        namespace: 'v. 1.13.0',
        author:    'John Land',
        importUrl: ''
    ) {
        capability 'Sensor'
        capability 'TemperatureMeasurement'
        capability 'RelativeHumidityMeasurement'
        capability 'Battery'
        capability 'Refresh'
        capability 'Health Check'

        // Running min/max tracked in software[cite: 5]
        attribute 'Humidity Max',         'string'
        attribute 'Humidity Min',         'string'
        attribute 'Temperature Max',      'string'
        attribute 'Temperature Min',      'string'

        attribute 'Min/Max Reset',        'string'
        attribute 'Last Reading',         'string'
        attribute 'Readings Since Reset', 'number'

        // Device-native 24-hr min/max from FC11 cluster[cite: 5]
        attribute 'Device Humidity Max',  'string'
        attribute 'Device Humidity Min',  'string'
        attribute 'Device Temp Max',      'string'
        attribute 'Device Temp Min',      'string'

        // Comfort zone thresholds and hardware calibration (readable state, set via preferences)
        attribute 'comfortTempMin',       'string'
        attribute 'comfortTempMax',       'string'
        attribute 'comfortHumiMin',       'string'
        attribute 'comfortHumiMax',       'string'
        attribute 'tempCalibration',      'string'
        attribute 'humiCalibration',      'string'

        // Temperature unit currently shown on the device LCD[cite: 5]
        attribute 'lcdTempUnit',          'string'

        // External display (EXT1) attributes
        attribute 'ext1Info',             'number'
        attribute 'externalDisplayMode',  'string'
        attribute 'extSyncStatus',        'string'

        attribute 'healthStatus',         'enum', ['unknown', 'online', 'offline']
        attribute 'rtt',                  'number'

        command 'resetMinMax', [[name: 'Reset the Hubitat-tracked min/max temperature and humidity values']]
        command 'initialize',  [[name: 'Re-initialize driver state and re-configure device reporting']]

        command 'setExt1Info', [
            [name: 'value*', type: 'DECIMAL', description: 'Numeric value (-40.0 to 99.9) to display in the EXT1 field on the LCD']
        ]
        command 'setExternalDisplayMode', [
            [name: 'mode*', type: 'ENUM', constraints: ['external', 'internal'], description: 'Switch LCD bottom section between EXT1 and internal 24-hr Min/Max']
        ]

        fingerprint profileId: '0104',
                    endpointId: '01',
                    inClusters: '0000,0001,0003,0402,0405,0020,FC57,FC11',
                    outClusters: '000A,0019',
                    model: 'SNZB-02DR2',
                    manufacturer: 'SONOFF',
                    deviceJoinName: 'Sonoff SNZB-02DR2 AirGuard TH'

        fingerprint profileId: '0104',
                    endpointId: '01',
                    inClusters: '0000,0001,0003,0402,0405,0020,FC57,FC11',
                    outClusters: '000A,0019',
                    model: 'SNZB-02DR2',
                    manufacturer: 'eWeLink',
                    deviceJoinName: 'Sonoff SNZB-02DR2 AirGuard TH'
    }

    preferences {
        input name: 'logEnable',
              type: 'bool',
              title: '<b>Debug logging</b>',
              description: 'Enable debug log output. Automatically disabled after 24 hours.',
              defaultValue: true

        input name: 'txtEnable',
              type: 'bool',
              title: '<b>Description text logging</b>',
              description: 'Log sensor readings in the Events log.',
              defaultValue: true

        input name: 'minReportTemp',
              type: 'number',
              title: '<b>Min time between temperature reports (seconds)</b>',
              description: 'Minimum reporting interval for temperature. Range 1 to 3600. Wake device before saving.',
              defaultValue: 10,
              range: '1..3600'

        input name: 'maxReportTemp',
              type: 'number',
              title: '<b>Max time between temperature reports (seconds)</b>',
              description: 'Maximum reporting interval (heartbeat) for temperature. Range 10 to 43200. Wake device before saving.',
              defaultValue: 3600,
              range: '10..43200'

        input name: 'tempChange',
              type: 'decimal',
              title: '<b>Temperature reporting threshold (Β°C)</b>',
              description: 'Minimum change to trigger a temperature report. Range 0.1 to 5.0. Wake device before saving.',
              defaultValue: 0.2

        input name: 'minReportHumi',
              type: 'number',
              title: '<b>Min time between humidity reports (seconds)</b>',
              description: 'Minimum reporting interval for humidity. Range 1 to 3600. Wake device before saving.',
              defaultValue: 10,
              range: '1..3600'

        input name: 'maxReportHumi',
              type: 'number',
              title: '<b>Max time between humidity reports (seconds)</b>',
              description: 'Maximum reporting interval (heartbeat) for humidity. Range 10 to 43200. Wake device before saving.',
              defaultValue: 3600,
              range: '10..43200'

        input name: 'humiChange',
              type: 'number',
              title: '<b>Humidity reporting threshold (%)</b>',
              description: 'Minimum change to trigger a humidity report. Range 1 to 10. Wake device before saving.',
              defaultValue: 1,
              range: '1..10'

        input name: 'temperatureOffset',
              type: 'decimal',
              title: '<b>Temperature hardware calibration offset (Β°C)</b>',
              description: 'Written directly to device hardware (FC11 0x2003) so LCD and Hubitat match. Always enter in Β°C. Range -20.0 to 20.0. Wake device before saving.',
              defaultValue: 0.0

        input name: 'humidityOffset',
              type: 'decimal',
              title: '<b>Humidity hardware calibration offset (%)</b>',
              description: 'Written directly to device hardware (FC11 0x2004) so LCD and Hubitat match. Range -20.0 to 20.0. Wake device before saving.',
              defaultValue: 0.0

        input name: 'lcdTempUnit',
              type: 'enum',
              title: '<b>LCD temperature unit</b>',
              description: 'Unit shown on the device screen. Hubitat itself always uses the hub\'s temperature scale (Settings β†’ Location). Wake device before saving.',
              options: ['nochange': 'Leave unchanged', 'C': 'Celsius (Β°C)', 'F': 'Fahrenheit (Β°F)'],
              defaultValue: 'nochange'

        input name: 'pref_comfortTempMin',
              type: 'decimal',
              title: '<b>Comfort temperature minimum (Β°C)</b>',
              description: 'Device shows ❄️ below this value. Always enter in Β°C regardless of hub scale. Range -10 to 60. Wake device before saving.',
              defaultValue: 18.0

        input name: 'pref_comfortTempMax',
              type: 'decimal',
              title: '<b>Comfort temperature maximum (Β°C)</b>',
              description: 'Device shows πŸ”₯ above this value. Always enter in Β°C regardless of hub scale. Range -10 to 60. Wake device before saving.',
              defaultValue: 26.0

        input name: 'pref_comfortHumiMin',
              type: 'number',
              title: '<b>Comfort humidity minimum (%)</b>',
              description: 'Lower end of the comfort humidity range (β˜€οΈ icon below it). Range 5 to 95. Wake device before saving.',
              defaultValue: 40,
              range: '5..95'

        input name: 'pref_comfortHumiMax',
              type: 'number',
              title: '<b>Comfort humidity maximum (%)</b>',
              description: 'Upper end of the comfort humidity range (πŸ’§ icon above it). Range 5 to 95. Wake device before saving.',
              defaultValue: 60,
              range: '5..95'

        input name: 'autoResetEnable',
              type: 'bool',
              title: '<b>Auto-reset min/max daily</b>',
              description: 'When enabled, the driver-tracked min/max values are reset automatically each day at the time set below.',
              defaultValue: false

        input name: 'autoResetTime',
              type: 'time',
              title: '<b>Auto-reset time</b>',
              description: 'Time of day at which the driver min/max is automatically reset (only used when auto-reset is enabled).',
              defaultValue: '00:00'
    }
}

// ── Lifecycle ────────────────────────────────────────────────────────────────

def installed() {
    logInfo 'installed()'
    initVars(true)
    configure()
}

def updated() {
    logInfo 'updated()'
    if (logEnable) { runIn(86400, 'logsOff') }

    validatePreferences()
    rescheduleAutoReset()

    // Push reporting configuration and FC11 settings (including hardware offsets) to the device
    List<String> cmds = []
    cmds += reportingConfigCmds()
    cmds += writeFC11Settings()
    cmds += fc11SettingsReadCmds()
    sendZigbeeCommands(cmds)
}

def configure() {
    logInfo 'configure()'
    if (logEnable) { runIn(86400, 'logsOff') }

    validatePreferences()

    List<String> cmds = []
    cmds += reportingConfigCmds()
    cmds += writeFC11Settings()

    // Read current values (after the writes, so the reads reflect them)[cite: 5]
    cmds += zigbee.readAttribute(CLUSTER_TEMP,      0x0000, [:], 200)
    cmds += zigbee.readAttribute(CLUSTER_HUMIDITY,  0x0000, [:], 200)
    cmds += zigbee.readAttribute(CLUSTER_POWER_CFG, 0x0021, [:], 200)
    cmds += fc11SettingsReadCmds()

    scheduleHealthCheck()   // also (re)schedules the daily auto-reset[cite: 5]
    sendZigbeeCommands(cmds)
}

def initialize() {
    logInfo 'initialize()'
    unschedule()
    initVars(true)
    configure()
}

def refresh() {
    logInfo 'refresh()'
    List<String> cmds = []
    cmds += zigbee.readAttribute(CLUSTER_TEMP,      0x0000, [:], 200)
    cmds += zigbee.readAttribute(CLUSTER_HUMIDITY,  0x0000, [:], 200)
    cmds += zigbee.readAttribute(CLUSTER_POWER_CFG, 0x0021, [:], 200)
    cmds += zigbee.readAttribute(CLUSTER_POWER_CFG, 0x0020, [:], 200)
    cmds += fc11SettingsReadCmds()
    // Read device-native min/max (FC11 0x2008-0x200D) and EXT1 state (0x600D-0x600E)
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_MAX_TEMP,      [mfgCode: '0x1286'], 200)
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_MIN_TEMP,      [mfgCode: '0x1286'], 200)
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_MAX_HUMI,      [mfgCode: '0x1286'], 200)
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_MIN_HUMI,      [mfgCode: '0x1286'], 200)
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_EXT_TEMP_MODE, [mfgCode: '0x1286'], 200)
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_EXT_TEMP_VAL,  [mfgCode: '0x1286'], 200)
    sendZigbeeCommands(cmds)
}

def ping() {
    logDebug 'ping()'
    state.pingTime = now()
    scheduleCommandTimeout()
    sendZigbeeCommands(zigbee.readAttribute(0x0000, 0x0001, [:], 0))
}

// ── External Display (EXT1) Commands & Wake-Up Queue ─────────────────────────

void setExt1Info(BigDecimal value) {
    if (value == null) { return }
    double clamped = clampD(value.toDouble(), EXT1_VAL_MIN, EXT1_VAL_MAX)
    BigDecimal rounded = BigDecimal.valueOf(clamped).setScale(1, BigDecimal.ROUND_HALF_UP)

    state.pendingExtVal = Math.round(rounded.toDouble() * 100) as int

    // Only queue a mode switch (0x600E -> 1) if the device is not already confirmed in EXT1 mode
    if ((state.currentExtMode as Integer) != 1) {
        state.pendingExtMode = 1
    } else {
        state.remove('pendingExtMode')
    }

    state.pendingExtWrite = true
    sendEvent(name: 'extSyncStatus', value: "pending (${rounded})")
    logInfo "setExt1Info(${rounded}) queued (raw=${state.pendingExtVal}, modeSwitchNeeded=${state.pendingExtMode != null})"
    flushPendingExtWrite(true)
}

void setExternalDisplayMode(String mode) {
    int targetMode = (mode == 'external') ? 1 : 0
    state.pendingExtMode  = targetMode
    state.pendingExtWrite = true

    sendEvent(name: 'extSyncStatus', value: "pending mode (${mode})")
    logInfo "setExternalDisplayMode(${mode}) queued (raw=${targetMode})"
    flushPendingExtWrite(true)
}

private void flushPendingExtWrite(boolean forceNow = false) {
    if (!state.pendingExtWrite) { return }
    long nowMs = now()
    if (!forceNow && state.lastExtFlush != null && (nowMs - (state.lastExtFlush as long)) < EXT_FLUSH_DEBOUNCE) {
        return
    }
    state.lastExtFlush = nowMs

    List<String> cmds = []

    // 1. Send display mode (0x600E, UINT8 = 0x20) only if a mode switch was requested or needed
    if (state.pendingExtMode != null) {
        int modeVal = state.pendingExtMode as int
        cmds += zigbee.writeAttribute(CLUSTER_FC11, FC11_EXT_TEMP_MODE, DataType.UINT8, modeVal, [mfgCode: '0x1286'], 50)
        cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_EXT_TEMP_MODE, [mfgCode: '0x1286'], 100)
    }

    // 2. Send external value (0x600D, INT16 = 0x29) if a value is pending and target mode is not 'internal'
    if (state.pendingExtVal != null && (state.pendingExtMode == null || (state.pendingExtMode as int) == 1)) {
        int rawVal = state.pendingExtVal as int
        cmds += zigbee.writeAttribute(CLUSTER_FC11, FC11_EXT_TEMP_VAL, DataType.INT16, rawVal, [mfgCode: '0x1286'], 50)
        cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_EXT_TEMP_VAL, [mfgCode: '0x1286'], 100)
    }

    if (cmds) {
        logDebug "Flushing pending EXT1 write (mode=${state.pendingExtMode}, rawVal=${state.pendingExtVal})"
        sendZigbeeCommands(cmds)
    }
}

// ── Standard Commands ────────────────────────────────────────────────────────

def resetMinMax() {
    logInfo 'Resetting min/max tracking'
    state.minTemp      = null
    state.maxTemp      = null
    state.minHumi      = null
    state.maxHumi      = null
    state.readingCount = 0
    String ts = new Date().format('yyyy-MM-dd HH:mm:ss', location.timeZone)
    sendEvent(name: 'Min/Max Reset',        value: ts,   descriptionText: "Min/max reset at ${ts}")
    sendEvent(name: 'Readings Since Reset', value: 0,    descriptionText: 'Reading counter reset to 0')
    sendEvent(name: 'Temperature Min',      value: '--', descriptionText: 'Min temperature reset')
    sendEvent(name: 'Temperature Max',      value: '--', descriptionText: 'Max temperature reset')
    sendEvent(name: 'Humidity Min',         value: '--', descriptionText: 'Min humidity reset')
    sendEvent(name: 'Humidity Max',         value: '--', descriptionText: 'Max humidity reset')
}

// ── Auto-reset scheduling ────────────────────────────────────────────────────

private void rescheduleAutoReset() {
    unschedule('autoResetMinMax')
    if (!autoResetEnable) {
        logInfo 'Auto-reset disabled'
        return
    }
    try {
        def t = timeToday(autoResetTime, location.timeZone)
        String cronExpr = "0 ${t.minutes} ${t.hours} * * ? *"
        schedule(cronExpr, 'autoResetMinMax')
        logInfo "Auto-reset scheduled daily at ${autoResetTime} (cron: ${cronExpr})"
    } catch (e) {
        logWarn "Auto-reset scheduling failed: ${e.message}"
    }
}

def autoResetMinMax() {
    logInfo 'Auto-reset: resetting driver min/max tracking'
    resetMinMax()
}

// ── Parse ────────────────────────────────────────────────────────────────────

def parse(String description) {
    setPresent()

    if (!(description?.startsWith('catchall:') || description?.startsWith('read attr -'))) {
        logDebug "unhandled description: ${description}"
        return
    }

    Map descMap = zigbee.parseDescriptionAsMap(description)
    logDebug "parse() descMap = ${descMap}"

    // Global responses: 0x04 = Write Attributes Response, 0x07 = Configure Reporting Response[cite: 5]
    if (description.startsWith('catchall:') && descMap.isClusterSpecific != true &&
            (descMap.command == '04' || descMap.command == '07')) {
        parseGlobalResponse(descMap)
        return
    }

    // Wake-up Piggybacking: Whenever the sensor wakes up and sends an attribute report or
    // button press, immediately flush any unacknowledged EXT1 write while its RX window is open.
    if (state.pendingExtWrite) {
        flushPendingExtWrite(false)
    }

    switch (descMap.clusterInt as Integer) {
        case CLUSTER_POWER_CFG:
            parsePowerCluster(descMap)
            break
        case CLUSTER_TEMP:
            parseTempCluster(descMap)
            break
        case CLUSTER_HUMIDITY:
            parseHumiCluster(descMap)
            break
        case CLUSTER_FC11:
            parseFC11Cluster(descMap)
            break
        case CLUSTER_IDENTIFY:
            logInfo 'Physical rear button pressed (device awake)'
            break
        case CLUSTER_ZDO_BIND:
            logDebug 'ZDO Bind response received (0x8021)'
            break
        case 0x0000:
            // Basic cluster – used for ping response[cite: 5]
            if (descMap.attrInt == 0x0001 && descMap.value) {
                def elapsed = now() - (state.pingTime ?: 0)
                if (elapsed < PING_TIMEOUT_MS && elapsed > 0) {
                    unschedule('commandTimeout')
                    sendEvent(name: 'rtt', value: elapsed, unit: 'ms', descriptionText: "Round-trip time ${elapsed} ms")
                    logInfo "ping RTT = ${elapsed} ms"
                }
            }
            break
        default:
            logDebug "unhandled cluster: 0x${Integer.toHexString(descMap.clusterInt ?: 0)}"
            break
    }
}

// Logs whether the device accepted a Configure Reporting or Write Attributes request[cite: 5].
private void parseGlobalResponse(Map descMap) {
    List data = (descMap.data ?: []) as List
    String status = data ? (data[0] as String) : '??'
    Integer clusterInt = descMap.clusterInt as Integer
    String cluster = clusterName(clusterInt)

    if (descMap.command == '07') {
        if (status == '00') {
            logInfo "${cluster} reporting configuration accepted by device"
        } else {
            String attr = data.size() >= 4 ? "0x${data[3]}${data[2]}" : '?'
            logWarn "${cluster} reporting configuration for attribute ${attr} rejected (status 0x${status})"
        }
    } else {
        if (status == '00') {
            logInfo "${cluster} attribute write accepted by device"
            if (clusterInt == CLUSTER_FC11 && state.pendingExtWrite) {
                state.pendingExtWrite = false
                if (state.pendingExtMode != null) {
                    state.currentExtMode = state.pendingExtMode as int
                    state.remove('pendingExtMode')
                }
                state.remove('pendingExtVal')
                String ts = new Date().format('HH:mm:ss', location.timeZone)
                sendEvent(name: 'extSyncStatus', value: "synced @ ${ts}")
            }
        } else {
            String attr = data.size() >= 3 ? "0x${data[2]}${data[1]}" : '?'
            logWarn "${cluster} write of attribute ${attr} rejected (status 0x${status})"
            if (clusterInt == CLUSTER_FC11 && attr == '0x0007' && status.equalsIgnoreCase('8D')) {
                retryLcdUnitWrite()
            }
        }
    }
}

private String clusterName(Integer clusterInt) {
    switch (clusterInt) {
        case CLUSTER_POWER_CFG: return 'Battery'
        case CLUSTER_TEMP:      return 'Temperature'
        case CLUSTER_HUMIDITY:  return 'Humidity'
        case CLUSTER_FC11:      return 'FC11'
        default:                return "Cluster 0x${Integer.toHexString(clusterInt ?: 0)}"
    }
}

// ── Cluster parsers ──────────────────────────────────────────────────────────

private void parsePowerCluster(Map descMap) {
    if (descMap.attrInt == 0x0021 && descMap.value && descMap.value.length() <= 8) {
        Integer raw = (Long.parseLong(descMap.value, 16) & 0xFF) as Integer
        Integer pct = Math.min(100, Math.round(raw / 2.0) as Integer)
        sendEvent(name: 'battery', value: pct, unit: '%',
                  descriptionText: "${device.displayName} battery is ${pct}%", type: 'physical')
        logInfo "battery ${pct}%"
    } else if (descMap.attrInt == 0x0020 && descMap.value && descMap.value.length() <= 8) {
        Integer raw = (Long.parseLong(descMap.value, 16) & 0xFF) as Integer
        double volts = raw / 10.0
        Integer pct = Math.min(100, Math.max(1, Math.round(((volts - 2.1) / 0.9) * 100) as Integer))
        sendEvent(name: 'battery', value: pct, unit: '%',
                  descriptionText: "${device.displayName} battery ~${pct}% (${volts}V)", type: 'physical')
        logInfo "battery voltage ${volts}V (~${pct}%)"
    }
}

private void parseTempCluster(Map descMap) {
    if (descMap.attrInt != null && descMap.attrInt != 0x0000) { return }
    if (!descMap.value || descMap.value.length() > 8) { return }
    Integer raw = (Long.parseLong(descMap.value, 16) & 0xFFFF) as Integer
    if (raw == 0x8000) { logDebug 'temperature: invalid sentinel value'; return }
    if (raw > 32767) { raw = raw - 65536 }
    state.rawTempC = raw / 100.0
    publishTemperature()
}

// Publishes temperature directly from the device reading (calibration offset is applied in hardware via 0x2003).
private void publishTemperature() {
    if (state.rawTempC == null) { return }
    double tempC = state.rawTempC as double

    double display
    String unit
    if (location.temperatureScale == 'F') {
        display = Math.round(((tempC * 1.8) + 32 - 0.05) * 10) / 10
        unit = '\u00B0F'
    } else {
        display = Math.round((tempC - 0.05) * 10) / 10
        unit = '\u00B0C'
    }

    sendEvent(name: 'temperature', value: display, unit: unit,
              descriptionText: "${device.displayName} temperature is ${display}${unit}",
              type: 'physical')
    logInfo "temperature ${display}${unit}"
    updateMinMax('temperature', tempC)
    String ts = new Date().format('yyyy-MM-dd HH:mm:ss', location.timeZone)
    sendEvent(name: 'Last Reading', value: ts, descriptionText: "Last reading at ${ts}")
}

private void parseHumiCluster(Map descMap) {
    if (descMap.attrInt != null && descMap.attrInt != 0x0000) { return }
    if (!descMap.value || descMap.value.length() > 8) { return }
    Integer raw = (Long.parseLong(descMap.value, 16) & 0xFFFF) as Integer
    state.rawHumi = raw / 100.0
    publishHumidity()
}

// Publishes humidity directly from the device reading (calibration offset is applied in hardware via 0x2004).
private void publishHumidity() {
    if (state.rawHumi == null) { return }
    double humi = clampD(state.rawHumi as double, 0.0, 100.0)
    Integer display = Math.round(humi) as Integer

    sendEvent(name: 'humidity', value: display, unit: '%',
              descriptionText: "${device.displayName} humidity is ${display}%",
              type: 'physical')
    logInfo "humidity ${display}%"
    updateMinMax('humidity', humi)
}

private void parseFC11Cluster(Map descMap) {
    if (descMap.additionalAttrs) {
        descMap.additionalAttrs.each { Map aa ->
            String v = aa.value as String
            if (v && v.length() <= 8) {
                parseFC11Attr(aa.attrInt as int, v, aa.encoding as String)
            }
        }
    }
    String val = descMap.value as String
    if (!val || val.length() > 8) {
        if (val && val.length() > 8) { logDebug "FC11 skipping blob len=${val.length()}" }
        return
    }
    parseFC11Attr(descMap.attrInt as int, val, descMap.encoding as String)
}

private void parseFC11Attr(int attrInt, String hexVal, String encoding = null) {
    Integer raw = (Long.parseLong(hexVal, 16) & 0xFFFF) as Integer

    if (attrInt == (FC11_ATTR_TEMP_UNIT as int)) {
        String unitName = raw == 1 ? 'Fahrenheit' : 'Celsius'
        sendEvent(name: 'lcdTempUnit', value: unitName, descriptionText: "LCD temperature unit is ${unitName}")
        logInfo "FC11 LCD temperature unit: ${unitName}${encoding ? " (device reports data type 0x${encoding})" : ''}"

    } else if (attrInt == (FC11_ATTR_COMFORT_TEMP_MIN as int)) {
        Integer signed = raw > 32767 ? raw - 65536 : raw
        double valC = signed / 100.0
        String display = formatTemp(valC)
        sendEvent(name: 'comfortTempMin', value: display,
                  descriptionText: "Comfort temp min = ${display} (${valC}\u00B0C device setting)")
        logInfo "FC11 comfort temp min = ${display}"

    } else if (attrInt == (FC11_ATTR_COMFORT_TEMP_MAX as int)) {
        Integer signed = raw > 32767 ? raw - 65536 : raw
        double valC = signed / 100.0
        String display = formatTemp(valC)
        sendEvent(name: 'comfortTempMax', value: display,
                  descriptionText: "Comfort temp max = ${display} (${valC}\u00B0C device setting)")
        logInfo "FC11 comfort temp max = ${display}"

    } else if (attrInt == (FC11_ATTR_COMFORT_HUMI_MIN as int)) {
        double val = raw / 100.0
        String humiMinDisplay = "${Math.round(val)}%"
        sendEvent(name: 'comfortHumiMin', value: humiMinDisplay,
                  descriptionText: "Comfort humidity min = ${humiMinDisplay}")
        logInfo "FC11 comfort humidity min = ${humiMinDisplay}"

    } else if (attrInt == (FC11_ATTR_COMFORT_HUMI_MAX as int)) {
        double val = raw / 100.0
        String humiMaxDisplay = "${Math.round(val)}%"
        sendEvent(name: 'comfortHumiMax', value: humiMaxDisplay,
                  descriptionText: "Comfort humidity max = ${humiMaxDisplay}")
        logInfo "FC11 comfort humidity max = ${humiMaxDisplay}"

    } else if (attrInt == (FC11_ATTR_TEMP_CALIBRATION as int)) {
        Integer signed = raw > 32767 ? raw - 65536 : raw
        String calStr = "${String.format('%.1f', signed / 100.0)}\u00B0C"
        sendEvent(name: 'tempCalibration', value: calStr, descriptionText: "Hardware temperature calibration = ${calStr}")
        logInfo "FC11 temp calibration = ${calStr}"

    } else if (attrInt == (FC11_ATTR_HUMI_CALIBRATION as int)) {
        Integer signed = raw > 32767 ? raw - 65536 : raw
        String calStr = "${String.format('%.1f', signed / 100.0)}%"
        sendEvent(name: 'humiCalibration', value: calStr, descriptionText: "Hardware humidity calibration = ${calStr}")
        logInfo "FC11 humidity calibration = ${calStr}"

    } else if (attrInt == FC11_MAX_TEMP) {
        Integer signed = raw > 32767 ? raw - 65536 : raw
        String display = formatTemp(signed / 100.0)
        sendEvent(name: 'Device Temp Max', value: display,
                  descriptionText: "Device max temp = ${display}")
        logInfo "FC11 device max temp = ${display}"

    } else if (attrInt == FC11_MIN_TEMP) {
        Integer signed = raw > 32767 ? raw - 65536 : raw
        String display = formatTemp(signed / 100.0)
        sendEvent(name: 'Device Temp Min', value: display,
                  descriptionText: "Device min temp = ${display}")
        logInfo "FC11 device min temp = ${display}"

    } else if (attrInt == FC11_PREV_TEMP) {
        Integer signed = raw > 32767 ? raw - 65536 : raw
        logInfo "FC11 0x200A ref temp = ${formatTemp(signed / 100.0)}"

    } else if (attrInt == FC11_MAX_HUMI) {
        String display = "${Math.round(raw / 100.0)}%"
        sendEvent(name: 'Device Humidity Max', value: display,
                  descriptionText: "Device max humidity = ${display}")
        logInfo "FC11 device max humidity = ${display}"

    } else if (attrInt == FC11_MIN_HUMI) {
        String display = "${Math.round(raw / 100.0)}%"
        sendEvent(name: 'Device Humidity Min', value: display,
                  descriptionText: "Device min humidity = ${display}")
        logInfo "FC11 device min humidity = ${display}"

    } else if (attrInt == FC11_PREV_HUMI) {
        logInfo "FC11 0x200D ref humidity = ${Math.round(raw / 100.0)}%"

    } else if (attrInt == FC11_EXT_TEMP_VAL) {
        Integer signed = raw > 32767 ? raw - 65536 : raw
        BigDecimal val = BigDecimal.valueOf(signed / 100.0).setScale(1, BigDecimal.ROUND_HALF_UP)
        sendEvent(name: 'ext1Info', value: val,
                  descriptionText: "EXT1 display value (0x600D) = ${val}")
        logInfo "FC11 EXT1 value (0x600D) = ${val}"

    } else if (attrInt == FC11_EXT_TEMP_MODE) {
        state.currentExtMode = raw
        String modeStr = (raw == 1) ? 'external (EXT1)' : 'internal (Min/Max)'
        sendEvent(name: 'externalDisplayMode', value: modeStr,
                  descriptionText: "LCD display mode (0x600E) = ${modeStr}")
        logInfo "FC11 external display mode (0x600E) = ${modeStr}"

    } else {
        logDebug "FC11 unhandled attr 0x${Integer.toHexString(attrInt)} = ${raw}"
    }
}

private String formatTemp(double tempC) {
    if (location.temperatureScale == 'F') {
        return "${Math.round((tempC * 1.8 + 32) * 10) / 10}\u00B0F"
    }
    return "${Math.round(tempC * 10) / 10}\u00B0C"
}

// ── Min/Max tracking ─────────────────────────────────────────────────────────

private void updateMinMax(String type, double value) {
    if (type == 'temperature') {
        state.readingCount = (state.readingCount ?: 0) + 1
        sendEvent(name: 'Readings Since Reset', value: state.readingCount,
                  descriptionText: "${state.readingCount} readings since last reset")
        double rounded = Math.round(value * 10) / 10
        String unit = location.temperatureScale == 'F' ? '\u00B0F' : '\u00B0C'
        double displayVal = location.temperatureScale == 'F' ? Math.round(((value * 1.8) + 32) * 10) / 10 : rounded

        if (state.minTemp == null || value < (state.minTemp as double)) {
            state.minTemp = value
            String ts = new Date().format('MM-dd HH:mm', location.timeZone)
            sendEvent(name: 'Temperature Min', value: "${displayVal}${unit} @ ${ts}",
                      descriptionText: "Min temperature is ${displayVal}${unit} (at ${ts}, since last reset)")
            logInfo "New min temperature: ${displayVal}${unit} @ ${ts}"
        }
        if (state.maxTemp == null || value > (state.maxTemp as double)) {
            state.maxTemp = value
            String ts = new Date().format('MM-dd HH:mm', location.timeZone)
            sendEvent(name: 'Temperature Max', value: "${displayVal}${unit} @ ${ts}",
                      descriptionText: "Max temperature is ${displayVal}${unit} (at ${ts}, since last reset)")
            logInfo "New max temperature: ${displayVal}${unit} @ ${ts}"
        }
    } else if (type == 'humidity') {
        Integer roundedPct = Math.round(value) as Integer
        if (state.minHumi == null || value < (state.minHumi as double)) {
            state.minHumi = value
            String ts = new Date().format('MM-dd HH:mm', location.timeZone)
            sendEvent(name: 'Humidity Min', value: "${roundedPct}% @ ${ts}",
                      descriptionText: "Min humidity is ${roundedPct}% (at ${ts}, since last reset)")
            logInfo "New min humidity: ${roundedPct}% @ ${ts}"
        }
        if (state.maxHumi == null || value > (state.maxHumi as double)) {
            state.maxHumi = value
            String ts = new Date().format('MM-dd HH:mm', location.timeZone)
            sendEvent(name: 'Humidity Max', value: "${roundedPct}% @ ${ts}",
                      descriptionText: "Max humidity is ${roundedPct}% (at ${ts}, since last reset)")
            logInfo "New max humidity: ${roundedPct}% @ ${ts}"
        }
    }
}

// ── Reporting configuration ──────────────────────────────────────────────────

private List<String> reportingConfigCmds() {
    List<String> cmds = []

    int tMin = Math.max(1, Math.min(3600, safeInt(minReportTemp, 10)))
    int tMax = Math.max(tMin, Math.min(43200, safeInt(maxReportTemp, 3600)))
    Integer tempDelta = Math.round(prefTempChange() * 100) as Integer
    cmds += zigbee.configureReporting(CLUSTER_TEMP, 0x0000, DataType.INT16,
        tMin, tMax, tempDelta, [:], 200)

    int hMin = Math.max(1, Math.min(3600, safeInt(minReportHumi, 10)))
    int hMax = Math.max(hMin, Math.min(43200, safeInt(maxReportHumi, 3600)))
    int humiStep = Math.max(1, Math.min(10, safeInt(humiChange, 1)))
    Integer humiDelta = humiStep * 100
    cmds += zigbee.configureReporting(CLUSTER_HUMIDITY, 0x0000, DataType.UINT16,
        hMin, hMax, humiDelta, [:], 200)

    cmds += zigbee.configureReporting(CLUSTER_POWER_CFG, 0x0021, DataType.UINT8,
        60, 14400, 1, [:], 200)

    logDebug "Reporting config: temp ${tMin}-${tMax}s / ${tempDelta / 100.0}\u00B0C, humidity ${hMin}-${hMax}s / ${humiStep}%"
    return cmds
}

// ── FC11 helpers ─────────────────────────────────────────────────────────────

private List<String> fc11SettingsReadCmds() {
    List<String> cmds = []
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_ATTR_COMFORT_TEMP_MIN, [mfgCode: '0x1286'], 200)
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_ATTR_COMFORT_TEMP_MAX, [mfgCode: '0x1286'], 200)
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_ATTR_COMFORT_HUMI_MIN, [mfgCode: '0x1286'], 200)
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_ATTR_COMFORT_HUMI_MAX, [mfgCode: '0x1286'], 200)
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_ATTR_TEMP_UNIT,        [mfgCode: '0x1286'], 200)
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_ATTR_TEMP_CALIBRATION, [mfgCode: '0x1286'], 200)
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_ATTR_HUMI_CALIBRATION, [mfgCode: '0x1286'], 200)
    return cmds
}

private List<String> writeFC11Settings() {
    List<String> cmds = []

    // comfort_temperature_min β€” INT16, scaled Γ— 100[cite: 5]
    Integer tempMinRaw = Math.round(prefComfortTempMin() * 100) as Integer
    cmds += zigbee.writeAttribute(CLUSTER_FC11, FC11_ATTR_COMFORT_TEMP_MIN,
            DataType.INT16, tempMinRaw, [mfgCode: '0x1286'], 200)

    // comfort_temperature_max β€” INT16, scaled Γ— 100[cite: 5]
    Integer tempMaxRaw = Math.round(prefComfortTempMax() * 100) as Integer
    cmds += zigbee.writeAttribute(CLUSTER_FC11, FC11_ATTR_COMFORT_TEMP_MAX,
            DataType.INT16, tempMaxRaw, [mfgCode: '0x1286'], 200)

    // comfort_humidity_min β€” UINT16, scaled Γ— 100[cite: 5]
    Integer humiMinRaw = Math.max(5, Math.min(95, safeInt(pref_comfortHumiMin, 40))) * 100
    cmds += zigbee.writeAttribute(CLUSTER_FC11, FC11_ATTR_COMFORT_HUMI_MIN,
            DataType.UINT16, humiMinRaw, [mfgCode: '0x1286'], 200)

    // comfort_humidity_max β€” UINT16, scaled Γ— 100[cite: 5]
    Integer humiMaxRaw = Math.max(5, Math.min(95, safeInt(pref_comfortHumiMax, 60))) * 100
    cmds += zigbee.writeAttribute(CLUSTER_FC11, FC11_ATTR_COMFORT_HUMI_MAX,
            DataType.UINT16, humiMaxRaw, [mfgCode: '0x1286'], 200)

    // Hardware temperature calibration (0x2003) β€” INT16, scaled Γ— 100
    Integer tempCalRaw = Math.round(prefTempOffset() * 100) as Integer
    cmds += zigbee.writeAttribute(CLUSTER_FC11, FC11_ATTR_TEMP_CALIBRATION,
            DataType.INT16, tempCalRaw, [mfgCode: '0x1286'], 200)

    // Hardware humidity calibration (0x2004) β€” INT16, scaled Γ— 100
    Integer humiCalRaw = Math.round(prefHumiOffset() * 100) as Integer
    cmds += zigbee.writeAttribute(CLUSTER_FC11, FC11_ATTR_HUMI_CALIBRATION,
            DataType.INT16, humiCalRaw, [mfgCode: '0x1286'], 200)

    // LCD temperature unit β€” UINT16, 0 = Celsius, 1 = Fahrenheit (confirmed on firmware 1.0.2)[cite: 3, 5]
    String unitPref = (lcdTempUnit ?: 'nochange') as String
    if (unitPref == 'C' || unitPref == 'F') {
        int type = (state.lcdUnitType ?: LCD_UNIT_TYPES[0]) as int
        state.lcdUnitTried = [type]
        cmds += lcdUnitWriteCmd(unitPref, type)
    }

    logDebug "Writing FC11 settings: tempMin=${tempMinRaw / 100.0} tempMax=${tempMaxRaw / 100.0} humiMin=${humiMinRaw / 100.0} humiMax=${humiMaxRaw / 100.0} tempCal=${tempCalRaw / 100.0} humiCal=${humiCalRaw / 100.0} lcdUnit=${unitPref}"
    return cmds
}

private List<String> lcdUnitWriteCmd(String unitPref, int type) {
    state.lcdUnitType = type
    logDebug "Writing LCD temperature unit ${unitPref} as data type 0x${Integer.toHexString(type)}"
    return zigbee.writeAttribute(CLUSTER_FC11, FC11_ATTR_TEMP_UNIT, type,
            unitPref == 'F' ? 1 : 0, [mfgCode: '0x1286'], 200)
}

private void retryLcdUnitWrite() {
    String unitPref = (lcdTempUnit ?: 'nochange') as String
    if (unitPref != 'C' && unitPref != 'F') { return }
    List<Integer> tried = ((state.lcdUnitTried ?: []) as List).collect { it as int }
    Integer next = LCD_UNIT_TYPES.find { !(it in tried) }
    if (next == null) {
        logWarn 'LCD temperature unit: the device rejected every data type tried; ' +
                'change the unit on the device or in the eWeLink app instead'
        state.remove('lcdUnitType')
        return
    }
    tried << next
    state.lcdUnitTried = tried
    logInfo "LCD temperature unit: retrying with data type 0x${Integer.toHexString(next)}"
    List<String> cmds = lcdUnitWriteCmd(unitPref, next)
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_ATTR_TEMP_UNIT, [mfgCode: '0x1286'], 200)
    sendZigbeeCommands(cmds)
}

// ── Preference validation ────────────────────────────────────────────────────

private double prefTempChange()     { return clampD(safeDouble(tempChange, 0.2),          TEMP_CHANGE_MIN,  TEMP_CHANGE_MAX)  }
private double prefTempOffset()     { return clampD(safeDouble(temperatureOffset, 0.0),   OFFSET_MIN,       OFFSET_MAX)       }
private double prefHumiOffset()     { return clampD(safeDouble(humidityOffset, 0.0),      OFFSET_MIN,       OFFSET_MAX)       }
private double prefComfortTempMin() { return clampD(safeDouble(pref_comfortTempMin, 18.0), COMFORT_TEMP_MIN, COMFORT_TEMP_MAX) }
private double prefComfortTempMax() { return clampD(safeDouble(pref_comfortTempMax, 26.0), COMFORT_TEMP_MIN, COMFORT_TEMP_MAX) }

private void validatePreferences() {
    fixDecimalSetting('tempChange',          tempChange,          prefTempChange())
    fixDecimalSetting('temperatureOffset',   temperatureOffset,   prefTempOffset())
    fixDecimalSetting('humidityOffset',      humidityOffset,      prefHumiOffset())
    fixDecimalSetting('pref_comfortTempMin', pref_comfortTempMin, prefComfortTempMin())
    fixDecimalSetting('pref_comfortTempMax', pref_comfortTempMax, prefComfortTempMax())
}

private void fixDecimalSetting(String name, Object current, double valid) {
    if (current == null) { return }
    if (safeDouble(current, valid) != valid) {
        logWarn "Preference '${name}' value ${current} is out of range; using ${valid}"
        device.updateSetting(name, [value: valid, type: 'decimal'])
    }
}

private static double clampD(double v, double lo, double hi) {
    return Math.max(lo, Math.min(hi, v))
}

// ── Health check ─────────────────────────────────────────────────────────────

def setPresent() {
    if ((device.currentValue('healthStatus') ?: 'unknown') != 'online') {
        sendEvent(name: 'healthStatus', value: 'online', type: 'digital')
        logInfo 'device is present (online)'
    }
    state.missedChecks = 0
}

def deviceHealthCheck() {
    state.missedChecks = (state.missedChecks ?: 0) + 1
    if (state.missedChecks > PRESENCE_THRESHOLD) {
        if ((device.currentValue('healthStatus', true) ?: 'unknown') != 'offline') {
            sendEvent(name: 'healthStatus', value: 'offline', type: 'digital')
            logWarn 'device has not reported β€” marking offline'
        }
    } else {
        logDebug "health check β€” ok (missed=${state.missedChecks})"
    }
}

private void scheduleHealthCheck() {
    Random rnd = new Random()
    schedule("${rnd.nextInt(59)} ${rnd.nextInt(59)} 1/3 * * ? *", 'deviceHealthCheck')
    rescheduleAutoReset()
}

private void scheduleCommandTimeout() {
    runIn(10, 'commandTimeout')
}

void commandTimeout() {
    logWarn 'command timed out (no response from device)'
    sendEvent(name: 'rtt', value: -1, unit: 'ms', descriptionText: 'No ping response (timeout)', type: 'digital')
}

// ── Init helpers ─────────────────────────────────────────────────────────────

private void initVars(boolean fullInit) {
    if (fullInit) {
        state.minTemp         = null
        state.maxTemp         = null
        state.minHumi         = null
        state.maxHumi         = null
        state.missedChecks    = 0
        state.pingTime        = 0
        state.readingCount    = 0
        state.rawTempC        = null
        state.rawHumi         = null
        state.pendingExtWrite = false
        String ts = new Date().format('yyyy-MM-dd HH:mm:ss', location.timeZone)
        sendEvent(name: 'healthStatus',         value: 'unknown')
        sendEvent(name: 'Last Reading',         value: '--', descriptionText: 'No reading yet')
        sendEvent(name: 'Min/Max Reset',        value: ts,   descriptionText: "Min/max reset at ${ts}")
        sendEvent(name: 'Readings Since Reset', value: 0,    descriptionText: 'Reading counter initialized')
        sendEvent(name: 'Temperature Min',      value: '--')
        sendEvent(name: 'Temperature Max',      value: '--')
        sendEvent(name: 'Humidity Min',         value: '--')
        sendEvent(name: 'Humidity Max',         value: '--')
        sendEvent(name: 'Device Temp Max',      value: '--', descriptionText: 'Waiting for device report')
        sendEvent(name: 'Device Temp Min',      value: '--', descriptionText: 'Waiting for device report')
        sendEvent(name: 'Device Humidity Max',  value: '--', descriptionText: 'Waiting for device report')
        sendEvent(name: 'Device Humidity Min',  value: '--', descriptionText: 'Waiting for device report')
        sendEvent(name: 'comfortTempMin',       value: '--')
        sendEvent(name: 'comfortTempMax',       value: '--')
        sendEvent(name: 'comfortHumiMin',       value: '--')
        sendEvent(name: 'comfortHumiMax',       value: '--')
        sendEvent(name: 'tempCalibration',      value: '--')
        sendEvent(name: 'humiCalibration',      value: '--')
        sendEvent(name: 'lcdTempUnit',          value: '--')
        sendEvent(name: 'externalDisplayMode',  value: '--')
        sendEvent(name: 'extSyncStatus',        value: 'idle')
    }
    state.driverVersion = "${VERSION} ${TIME_STAMP}"
}

// ── Utilities ────────────────────────────────────────────────────────────────

private void sendZigbeeCommands(List<String> cmds) {
    if (!cmds) { return }
    logDebug "sendZigbeeCommands: ${cmds}"
    hubitat.device.HubMultiAction allActions = new hubitat.device.HubMultiAction()
    cmds.each { allActions.add(new hubitat.device.HubAction(it, hubitat.device.Protocol.ZIGBEE)) }
    sendHubCommand(allActions)
}

private double safeDouble(val, double defaultVal = 0.0) {
    try { return val != null ? (val as double) : defaultVal } catch (e) { return defaultVal }
}

private int safeInt(val, int defaultVal = 0) {
    try { return val != null ? (val as int) : defaultVal } catch (e) { return defaultVal }
}

def logsOff() {
    log.warn "${device.displayName} debug logging disabled"
    device.updateSetting('logEnable', [value: 'false', type: 'bool'])
}

private void logDebug(String msg) { if (logEnable) { log.debug "${device.displayName} ${msg}" } }
private void logInfo(String msg)  { if (txtEnable) { log.info  "${device.displayName} ${msg}" } }
private void logWarn(String msg)  {                  log.warn  "${device.displayName} ${msg}"   }

Please remember, This driver mod was made with Gemini Argon AI, unfortunately my programming knowledge is too weak to do this (or understand everything).

I asked the AI to make a summary about the modification on your driver, maybe it can help you in the development.

=============================================================================
SONOFF SNZB-02DR2 -TECHNICAL FINDINGS, FULL 0xFC11 ATTRIBUTE DUMP & v1.13.0
=============================================================================


1. SUMMARY OF DRIVER MODIFICATIONS (v1.13.0)
-----------------------------------------------------------------------------

A) External Display (EXT1) Control (0xFC11 Attributes 0x600E & 0x600D)
   Contrary to earlier assumptions that the secondary EXT display zone could
   only be activated by a proprietary Sonoff hub, it can be freely switched
   and written over standard Zigbee ZCL Write Attribute commands using the
   Sonoff manufacturer code (0x1286):

   - 0x600E (DataType.UINT8 / 0x20): Controls the bottom LCD display mode.
     * 0 = Internal 24-hour Min/Max extremes
     * 1 = External value display (EXT1)
   - 0x600D (DataType.INT16 / 0x29): Signed value displayed in the EXT1 zone,
     scaled by x100 (e.g., 2250 displays 22.5 on the LCD).

   New Commands & Traffic Optimization:
   - setExt1Info(BigDecimal value): Writes any numeric value (-40.0 to 99.9)
     to the EXT1 field (ideal for room heating setpoints or external sensors).
   - setExternalDisplayMode(String mode): Switches between 'external' (EXT1)
     and 'internal' (24-hr Min/Max).
   - Optimization: Once the driver confirms that the sensor is already in
     EXT1 mode (state.currentExtMode == 1), subsequent setExt1Info() calls
     skip writing 0x600E and only write/read 0x600D, cutting Zigbee traffic
     in half.

B) Fast Background Polling Discovery & Wake-Up Piggybacking Queue
   - Fast Polling Finding: Live logs showed that even when the sensor has not
     sent a temperature or humidity report for several minutes (and without
     pressing the rear button), it performs background Zigbee MAC Data Request
     polls to its parent router roughly every 1-2 seconds. While a 16-command
     Save Preferences burst is too long for a single poll window, a compact
     1-2 attribute write (0x600D) is delivered by the parent router and
     acknowledged (status 0x00) within 0.27s to 1.48s during normal operation.
   - Wake-Up Piggybacking Queue (state.pendingExtWrite): Because temperature
     reports can be very infrequent in rooms with stable temperatures (and an
     immediate poll might occasionally miss due to mesh traffic), setExt1Info
     and setExternalDisplayMode keep state.pendingExtWrite = true until the
     device responds with ZCL Write Attributes Response (command 0x04, status
     0x00) on cluster 0xFC11. Whenever any frame arrives from the device
     (temperature, humidity, battery report, or physical button press),
     parse() immediately flushes the pending write while the sensor's Zigbee
     RX window is still open (with a 2.5s debounce).

C) Hardware Calibration Offsets (0x2003 & 0x2004) Instead of Software Math
   - In v1.12.2, FC11_ATTR_TEMP_CALIBRATION (0x2003) and
     FC11_ATTR_HUMI_CALIBRATION (0x2004) were defined and parsed on read, but
     temperatureOffset and humidityOffset were only applied in software.
     Software-only offsets cause the physical LCD screen on the wall and the
     Hubitat attribute to show different values.
   - In v1.13.0, writeFC11Settings() writes temperatureOffset * 100 to 0x2003
     (INT16) and humidityOffset * 100 to 0x2004 (INT16), and reads them back
     into tempCalibration and humiCalibration attributes. Because the device
     firmware applies these offsets directly to both the physical LCD and its
     0x0402/0x0405 Zigbee reports, software offset addition was removed from
     publishTemperature() and publishHumidity() to prevent double-offsetting.

D) Physical Rear Button Press (0x0003) & ZDO Bind Response (0x8021)
   - Short-pressing the physical rear button immediately sends a cluster-
     specific Identify frame on cluster 0x0003:
     catchall: 0104 0003 01 01 0040 00 <DNI> 01 00 0000 00 00 0100
     (clusterInt: 0x0003, command: 0x00, data: [01, 00]).
   - In v1.13.0, this is logged cleanly, triggers the piggybacking flush if
     an EXT1 write is pending, and could also be exposed as a PushableButton
     capability in the future.
   - Added handling for cluster 0x8021 (ZDO Bind_rsp) so zdo bind responses
     during configure()/updated() no longer log as unhandled cluster: 0x8021.


2. COMPLETE 0xFC11 ATTRIBUTE DISCOVERY DUMP (FIRMWARE 00001002 / v1.0.2)
-----------------------------------------------------------------------------

Sending ZCL Discover Attributes (0x0C) across cluster 0xFC11 returned
complete=0x01 with 25 attributes (identical list returned with mfgCode 0x1286
and without mfgCode):

[Comfort Zone & Display Unit Registers - 0x00xx]
  * 0x0003 (type 0x29 = INT16)  : Comfort temp max (degC x 100)
  * 0x0004 (type 0x29 = INT16)  : Comfort temp min (degC x 100)
  * 0x0005 (type 0x21 = UINT16) : Comfort humidity min (% x 100)
  * 0x0006 (type 0x21 = UINT16) : Comfort humidity max (% x 100)
  * 0x0007 (type 0x21 = UINT16) : LCD temperature unit (0=Celsius, 1=Fahr.)

[Calibration, Sensor Config, 24-Hr Min/Max & History Buffers - 0x20xx]
  * 0x2003 (type 0x29 = INT16)  : Hardware temperature calibration (degC x 100)
  * 0x2004 (type 0x29 = INT16)  : Hardware humidity calibration (% x 100)
  * 0x2005 (type 0x21 = UINT16) : Internal sensor config register 1
  * 0x2006 (type 0x21 = UINT16) : Internal sensor config register 2
  * 0x2008 (type 0x21 = UINT16) : Device 24-hr max temp (degC x 100)
                                  (Note: device declares 0x21 UINT16 for 0x2008,
                                  while 0x2009/0x200A are declared 0x29 INT16)
  * 0x2009 (type 0x29 = INT16)  : Device 24-hr min temp (degC x 100)
  * 0x200A (type 0x29 = INT16)  : Device reference temp (degC x 100)
  * 0x200B (type 0x21 = UINT16) : Device 24-hr max humidity (% x 100)
  * 0x200C (type 0x21 = UINT16) : Device 24-hr min humidity (% x 100)
  * 0x200D (type 0x21 = UINT16) : Device reference humidity (% x 100)
  * 0x200E (type 0x20 = UINT8)  : History log control / index register
  * 0x200F (type 0x21 = UINT16) : History log timestamp / interval register
  * 0x2011 (type 0x48 = ARRAY)  : Historical data flash buffer 1 (eWeLink graph)
  * 0x2012 (type 0x48 = ARRAY)  : Historical data flash buffer 2 (eWeLink graph)
  * 0x2013 (type 0x20 = UINT8)  : History log status register
  * 0x2014 (type 0x48 = ARRAY)  : Historical data flash buffer 3 (eWeLink graph)

[External Display Registers - 0x60xx & Cluster Revision]
  * 0x600D (type 0x29 = INT16)  : External display (EXT1) value (x 100)
  * 0x600E (type 0x20 = UINT8)  : External display mode (0=Internal, 1=EXT1)
  * 0x6014 (type 0x21 = UINT16) : Undocumented 16-bit register in the 0x60xx
                                  block (likely external value timeout/validity)
  * 0xFFFD (type 0x21 = UINT16) : Standard ZCL Cluster Revision


3. FIRMWARE VERSION COMPATIBILITY & NEWER ATTRIBUTES
-----------------------------------------------------------------------------

Cross-referencing our hardware discovery on 00001002 with upstream Zigbee2MQTT
(zigbee-herdsman-converters / sonoff.ts) shows three firmware generations for
the external display feature:

1) Firmware <= 1.0.3 (Confirmed on 00001002 / v1.0.2):
   - Uses 0x600E (UINT8: 0=Internal, 1=EXT1) and 0x600D (INT16: value x 100).
   - Does NOT support external humidity (0x6018 is absent in discovery).

2) Firmware 1.0.4 (00001004):
   - Uses the exact same 0x600E and 0x600D registers for EXT1 temperature
     (100% compatible with this v1.13.0 implementation).
   - Adds attribute 0x6018 (UINT16 / 0x21) for External Humidity (% x 100).

3) Firmware >= 1.0.5 (00001005 and newer):
   - Refactors the external display to support two external sources (EXT1 and
     EXT2) with both temperature and humidity using new attribute IDs:
     * 0x6015 (UINT8  / 0x20) : Display mode (0=Internal, 1=EXT1, 2=EXT2)
     * 0x6016 (INT16  / 0x29) : EXT1 Temperature (degC x 100)
     * 0x6017 (INT16  / 0x29) : EXT2 Temperature (degC x 100)
     * 0x6018 (UINT16 / 0x21) : EXT1 Humidity (% x 100)
     * 0x6019 (UINT16 / 0x21) : EXT2 Humidity (% x 100)
   - Future driver versions can check device.getDataValue('softwareBuild')
     against '00001005' to automatically branch between 0x600E/0x600D and
     0x6015/0x6016.
=============================================================================

Have a nice day (and testing) :wink:

Thank you! I'll having my coding team (Claude) take a look at your code for ideas.

In the meantime, based on your prompt that this could be done, last night and earlier today I had Claude code up a revised version of my driver (which now unifies drivers for 4 different Sonoff T&H sensors), giving you credit in the README.md file for the findings about sending data to the SNZB-02DR2 display:

https://github.com/JohnFLand/Sonoff_SNZB-02_Series-Zigbee-driver-for-Hubitat

2026-11-17_01-13: Updated code and README here: GitHub - JohnFLand/Sonoff_SNZB-02_Series-Zigbee-driver-for-Hubitat: A unified driver for the Sonoff SNZB-02 series of Zigbee temperature and humidity sensors: SNZB-02P, SNZB-02D, SNZB-02DR2, and SNZB-02M Β· GitHub

Edit 2026/11/17: update v1.13.3, eliminating some race conditions.

New version of the modified driver based on John_Land driver codes:

It has a Heating Indicator Mode, so it can show the 'heating' state with the flame icon. Details is in the next post.

Driver:

/* groovylint-disable CompileStatic, LineLength, NoDef, VariableTypeRequired */
/**
 *  Sonoff SNZB-02DR2 Temperature and Humidity Sensor (AirGuard TH) - Extended
 *
 *  Hubitat driver for the Sonoff SNZB-02DR2 Zigbee temperature/humidity sensor.
 *  Based on John Land's driver v1.12.2 (2026/11/06).
 *
 *  Features:
 *    - Temperature and humidity reporting (clusters 0x0402 / 0x0405)
 *    - Battery percentage reporting (cluster 0x0001)
 *    - Health status monitoring
 *    - Software-tracked min/max temperature and humidity (mirrors the device LCD 24-hr extremes)
 *    - Dual-mode FC11 comfort-zone thresholds (0x0003 / 0x0004):
 *        1) Standard mode: user-defined min/max temperature thresholds trigger ❄️ and πŸ”₯ icons
 *        2) Heating Indicator mode: external setHeatingIndicator('heating'/'idle') command controls
 *           the πŸ”₯ flame icon on the LCD (min fixed at 0.0Β°C; max set to 5.0Β°C for heating, 50.0Β°C for idle)
 *    - LCD temperature unit setting (Β°C / Β°F) via FC11 cluster (0x0007)
 *    - Hardware-level temperature and humidity calibration offsets via FC11 cluster (0x2003 / 0x2004)
 *    - External Display (EXT1) control via FC11 cluster (0x600E mode & 0x600D value) with
 *      unified wake-up piggybacking queue for reliable delivery on sleepy end-devices
 *    - Physical rear button press detection (cluster 0x0003) to flush pending writes
 *    - Configurable reporting intervals and sensitivity thresholds (sent to the device on Save)
 *    - Reset of tracked min/max values via command
 *
 *  Licensed under the Apache License, Version 2.0
 *
 *  Changelog:
 *    1.12.2 2026-11-06  Original baseline by John Land
 *    1.13.0 2026-11-17  - Added External Display (EXT1) support: setExt1Info command (writes 0x600D INT16)
 *                         and setExternalDisplayMode command (writes 0x600E UINT8).
 *                       - Added wake-up piggybacking queue (state.pendingExtWrite) so EXT1 updates reliably
 *                         land on the next device report or button press if immediate polling misses.
 *                       - Switched temperatureOffset and humidityOffset from software-only math to hardware
 *                         calibration registers FC11 0x2003 and 0x2004 so the physical LCD and Hubitat match.
 *                       - Added cluster 0x0003 (physical back button press) and 0x8021 (ZDO Bind_rsp) handling.
 *    1.13.1 2026-11-17  - Added selectable Heating Indicator mode (heatingIndicatorEnable preference) and
 *                         setHeatingIndicator('heating'/'idle') command to drive the LCD πŸ”₯ icon via
 *                         FC11 0x0003 (5.0Β°C = heating, 50.0Β°C = idle) and 0x0004 (0.0Β°C) using the unified
 *                         wake-up piggybacking queue. Ignores external commands when in standard comfort mode.
 *    1.13.2 2026-11-17  - Capped EXT1_VAL_MAX at 98.9 (values >= 99.0 display "HHH" on firmware 1.0.2).
 *                       - Removed cached mode/min-threshold skipping so setExt1Info always writes 0x600E=1
 *                         and setHeatingIndicator always writes 0x0004=0, ensuring automatic recovery after
 *                         a sensor battery replacement or reboot.
 *    1.13.3 2026-11-17  - Switched pending queue storage to atomicState to prevent race conditions when
 *                         setHeatingIndicator and setExt1Info are called back-to-back by Rule Machine.
 *                       - Deferred heatingIndicator attribute update until hardware read-back confirmation
 *                         of 0x0003, and replaced bulk queue clearing on first 0x04 response with per-register
 *                         read-back verification in parseFC11Attr().
 *                       - Added 'unsynced' detection and automatic re-queueing if 0x0003 resets on battery swap.
 */

import groovy.transform.Field
import hubitat.zigbee.zcl.DataType

@Field static final String VERSION    = '1.13.3'
@Field static final String TIME_STAMP = '2026/11/17'

// Cluster constants
@Field static final Integer CLUSTER_POWER_CFG = 0x0001
@Field static final Integer CLUSTER_IDENTIFY  = 0x0003
@Field static final Integer CLUSTER_TEMP      = 0x0402
@Field static final Integer CLUSTER_HUMIDITY  = 0x0405
@Field static final Integer CLUSTER_FC11      = 0xFC11   // Sonoff private cluster
@Field static final Integer CLUSTER_ZDO_BIND  = 0x8021   // ZDO Bind_rsp

// FC11 attribute IDs β€” verified via Zigbee Attribute Discovery (0x0C/0x0D) on firmware 1.0.2 (00001002)
@Field static final Integer FC11_ATTR_COMFORT_TEMP_MAX = 0x0003  // INT16 (0x29),  value * 100 (Β°C Γ— 100)
@Field static final Integer FC11_ATTR_COMFORT_TEMP_MIN = 0x0004  // INT16 (0x29),  value * 100 (Β°C Γ— 100)
@Field static final Integer FC11_ATTR_COMFORT_HUMI_MIN = 0x0005  // UINT16 (0x21), value * 100 (% Γ— 100)
@Field static final Integer FC11_ATTR_COMFORT_HUMI_MAX = 0x0006  // UINT16 (0x21), value * 100 (% Γ— 100)
@Field static final Integer FC11_ATTR_TEMP_UNIT        = 0x0007  // UINT16 (0x21), 0=Celsius 1=Fahrenheit
@Field static final Integer FC11_ATTR_TEMP_CALIBRATION = 0x2003  // INT16 (0x29),  offset * 100 (Β°C Γ— 100)
@Field static final Integer FC11_ATTR_HUMI_CALIBRATION = 0x2004  // INT16 (0x29),  offset * 100 (% Γ— 100)

// FC11 External Display (EXT1) attributes (confirmed on firmware <= 1.0.4)
@Field static final int FC11_EXT_TEMP_VAL  = 0x600D  // INT16 (0x29), external value * 100
@Field static final int FC11_EXT_TEMP_MODE = 0x600E  // UINT8 (0x20), 0=Internal Min/Max, 1=External (EXT1)

// Heating Indicator fixed thresholds (scaled Γ— 100 in Β°C)
@Field static final int HEAT_IND_MIN_RAW     = 0     // 0.0Β°C  (disables ❄️ icon in heated rooms)
@Field static final int HEAT_IND_HEATING_RAW = 500   // 5.0Β°C  (forces πŸ”₯ icon ON when room > 5.0Β°C)
@Field static final int HEAT_IND_IDLE_RAW    = 5000  // 50.0Β°C (forces πŸ”₯ icon OFF when room < 50.0Β°C)

// Data types tried, in order, when writing the LCD unit (0x0007): UINT16, ENUM8, BOOLEAN, UINT8
@Field static final List<Integer> LCD_UNIT_TYPES = [0x21, 0x30, 0x10, 0x20]

// FC11 device-native 24-hr min/max (unsolicited ~hourly)
@Field static final int FC11_MAX_TEMP  = 0x2008  // UINT16/INT16 max temp x100 degC
@Field static final int FC11_MIN_TEMP  = 0x2009  // INT16  min temp x100 degC
@Field static final int FC11_PREV_TEMP = 0x200A  // INT16  reference temp
@Field static final int FC11_MAX_HUMI  = 0x200B  // UINT16 max humidity x100 %
@Field static final int FC11_MIN_HUMI  = 0x200C  // UINT16 min humidity x100 %
@Field static final int FC11_PREV_HUMI = 0x200D  // UINT16 reference humidity

// Valid ranges for decimal preferences
@Field static final double TEMP_CHANGE_MIN  = 0.1
@Field static final double TEMP_CHANGE_MAX  = 5.0
@Field static final double OFFSET_MIN       = -20.0
@Field static final double OFFSET_MAX       = 20.0
@Field static final double COMFORT_TEMP_MIN = -10.0
@Field static final double COMFORT_TEMP_MAX = 60.0
@Field static final double EXT1_VAL_MIN     = -40.0
@Field static final double EXT1_VAL_MAX     = 98.9

@Field static final Integer PRESENCE_THRESHOLD = 4     // missed health-check cycles before "offline"
@Field static final Integer PING_TIMEOUT_MS    = 10000
@Field static final Long    EXT_FLUSH_DEBOUNCE = 3000L // min ms between wake-up flushes

metadata {
    definition(
        name:      'Sonoff SNZB-02DR2 Temperature and Humidity Sensor (EXT1)',
        namespace: 'v. 1.13.3',
        author:    'John Land',
        importUrl: ''
    ) {
        capability 'Sensor'
        capability 'TemperatureMeasurement'
        capability 'RelativeHumidityMeasurement'
        capability 'Battery'
        capability 'Refresh'
        capability 'Health Check'

        // Running min/max tracked in software
        attribute 'Humidity Max',         'string'
        attribute 'Humidity Min',         'string'
        attribute 'Temperature Max',      'string'
        attribute 'Temperature Min',      'string'

        attribute 'Min/Max Reset',        'string'
        attribute 'Last Reading',         'string'
        attribute 'Readings Since Reset', 'number'

        // Device-native 24-hr min/max from FC11 cluster
        attribute 'Device Humidity Max',  'string'
        attribute 'Device Humidity Min',  'string'
        attribute 'Device Temp Max',      'string'
        attribute 'Device Temp Min',      'string'

        // Comfort zone thresholds and hardware calibration (readable state, set via preferences)
        attribute 'comfortTempMin',       'string'
        attribute 'comfortTempMax',       'string'
        attribute 'comfortHumiMin',       'string'
        attribute 'comfortHumiMax',       'string'
        attribute 'tempCalibration',      'string'
        attribute 'humiCalibration',      'string'

        // Temperature unit currently shown on the device LCD
        attribute 'lcdTempUnit',          'string'

        // External display (EXT1) and Heating Indicator attributes
        attribute 'ext1Info',             'number'
        attribute 'externalDisplayMode',  'string'
        attribute 'heatingIndicator',     'string'
        attribute 'extSyncStatus',        'string'

        attribute 'healthStatus',         'enum', ['unknown', 'online', 'offline']
        attribute 'rtt',                  'number'

        command 'resetMinMax', [[name: 'Reset the Hubitat-tracked min/max temperature and humidity values']]
        command 'initialize',  [[name: 'Re-initialize driver state and re-configure device reporting']]

        command 'setExt1Info', [
            [name: 'value*', type: 'DECIMAL', description: 'Numeric value (-40.0 to 98.9) to display in the EXT1 field on the LCD']
        ]
        command 'setExternalDisplayMode', [
            [name: 'mode*', type: 'ENUM', constraints: ['external', 'internal'], description: 'Switch LCD bottom section between EXT1 and internal 24-hr Min/Max']
        ]
        command 'setHeatingIndicator', [
            [name: 'state*', type: 'STRING', description: "Set LCD πŸ”₯ flame icon state: 'heating' (πŸ”₯ ON, max=5Β°C) or 'idle' (πŸ”₯ OFF, max=50Β°C). Requires Heating Indicator mode enabled in Preferences."]
        ]

        fingerprint profileId: '0104',
                    endpointId: '01',
                    inClusters: '0000,0001,0003,0402,0405,0020,FC57,FC11',
                    outClusters: '000A,0019',
                    model: 'SNZB-02DR2',
                    manufacturer: 'SONOFF',
                    deviceJoinName: 'Sonoff SNZB-02DR2 AirGuard TH'

        fingerprint profileId: '0104',
                    endpointId: '01',
                    inClusters: '0000,0001,0003,0402,0405,0020,FC57,FC11',
                    outClusters: '000A,0019',
                    model: 'SNZB-02DR2',
                    manufacturer: 'eWeLink',
                    deviceJoinName: 'Sonoff SNZB-02DR2 AirGuard TH'
    }

    preferences {
        input name: 'logEnable',
              type: 'bool',
              title: '<b>Debug logging</b>',
              description: 'Enable debug log output. Automatically disabled after 24 hours.',
              defaultValue: true

        input name: 'txtEnable',
              type: 'bool',
              title: '<b>Description text logging</b>',
              description: 'Log sensor readings in the Events log.',
              defaultValue: true

        input name: 'minReportTemp',
              type: 'number',
              title: '<b>Min time between temperature reports (seconds)</b>',
              description: 'Minimum reporting interval for temperature. Range 1 to 3600. Wake device before saving.',
              defaultValue: 10,
              range: '1..3600'

        input name: 'maxReportTemp',
              type: 'number',
              title: '<b>Max time between temperature reports (seconds)</b>',
              description: 'Maximum reporting interval (heartbeat) for temperature. Range 10 to 43200. Wake device before saving.',
              defaultValue: 3600,
              range: '10..43200'

        input name: 'tempChange',
              type: 'decimal',
              title: '<b>Temperature reporting threshold (Β°C)</b>',
              description: 'Minimum change to trigger a temperature report. Range 0.1 to 5.0. Wake device before saving.',
              defaultValue: 0.2

        input name: 'minReportHumi',
              type: 'number',
              title: '<b>Min time between humidity reports (seconds)</b>',
              description: 'Minimum reporting interval for humidity. Range 1 to 3600. Wake device before saving.',
              defaultValue: 10,
              range: '1..3600'

        input name: 'maxReportHumi',
              type: 'number',
              title: '<b>Max time between humidity reports (seconds)</b>',
              description: 'Maximum reporting interval (heartbeat) for humidity. Range 10 to 43200. Wake device before saving.',
              defaultValue: 3600,
              range: '10..43200'

        input name: 'humiChange',
              type: 'number',
              title: '<b>Humidity reporting threshold (%)</b>',
              description: 'Minimum change to trigger a humidity report. Range 1 to 10. Wake device before saving.',
              defaultValue: 1,
              range: '1..10'

        input name: 'temperatureOffset',
              type: 'decimal',
              title: '<b>Temperature hardware calibration offset (Β°C)</b>',
              description: 'Written directly to device hardware (FC11 0x2003) so LCD and Hubitat match. Always enter in Β°C. Range -20.0 to 20.0. Wake device before saving.',
              defaultValue: 0.0

        input name: 'humidityOffset',
              type: 'decimal',
              title: '<b>Humidity hardware calibration offset (%)</b>',
              description: 'Written directly to device hardware (FC11 0x2004) so LCD and Hubitat match. Range -20.0 to 20.0. Wake device before saving.',
              defaultValue: 0.0

        input name: 'lcdTempUnit',
              type: 'enum',
              title: '<b>LCD temperature unit</b>',
              description: 'Unit shown on the device screen. Hubitat itself always uses the hub\'s temperature scale (Settings β†’ Location). Wake device before saving.',
              options: ['nochange': 'Leave unchanged', 'C': 'Celsius (Β°C)', 'F': 'Fahrenheit (Β°F)'],
              defaultValue: 'nochange'

        input name: 'heatingIndicatorEnable',
              type: 'bool',
              title: '<b>Use temperature comfort icons (πŸ”₯/❄️) as Heating Indicator</b>',
              description: 'When enabled, setHeatingIndicator("heating"/"idle") controls the πŸ”₯ icon on the LCD (min=0Β°C, max=5Β°C for heating / 50Β°C for idle) and manual temperature comfort thresholds below are ignored. When disabled, standard comfort thresholds are used and setHeatingIndicator() commands are ignored.',
              defaultValue: false

        input name: 'pref_comfortTempMin',
              type: 'decimal',
              title: '<b>Comfort temperature minimum (Β°C)</b>',
              description: 'Used when Heating Indicator mode is disabled. Device shows ❄️ below this value. Always enter in Β°C. Range -10 to 60. Wake device before saving.',
              defaultValue: 18.0

        input name: 'pref_comfortTempMax',
              type: 'decimal',
              title: '<b>Comfort temperature maximum (Β°C)</b>',
              description: 'Used when Heating Indicator mode is disabled. Device shows πŸ”₯ above this value. Always enter in Β°C. Range -10 to 60. Wake device before saving.',
              defaultValue: 26.0

        input name: 'pref_comfortHumiMin',
              type: 'number',
              title: '<b>Comfort humidity minimum (%)</b>',
              description: 'Lower end of the comfort humidity range (β˜€οΈ icon below it). Range 5 to 95. Wake device before saving.',
              defaultValue: 40,
              range: '5..95'

        input name: 'pref_comfortHumiMax',
              type: 'number',
              title: '<b>Comfort humidity maximum (%)</b>',
              description: 'Upper end of the comfort humidity range (πŸ’§ icon above it). Range 5 to 95. Wake device before saving.',
              defaultValue: 60,
              range: '5..95'

        input name: 'autoResetEnable',
              type: 'bool',
              title: '<b>Auto-reset min/max daily</b>',
              description: 'When enabled, the driver-tracked min/max values are reset automatically each day at the time set below.',
              defaultValue: false

        input name: 'autoResetTime',
              type: 'time',
              title: '<b>Auto-reset time</b>',
              description: 'Time of day at which the driver min/max is automatically reset (only used when auto-reset is enabled).',
              defaultValue: '00:00'
    }
}

// ── Lifecycle ────────────────────────────────────────────────────────────────

def installed() {
    logInfo 'installed()'
    initVars(true)
    configure()
}

def updated() {
    logInfo 'updated()'
    if (logEnable) { runIn(86400, 'logsOff') }

    validatePreferences()
    rescheduleAutoReset()

    if (!heatingIndicatorEnable) {
        atomicState.remove('pendingHeatIndMin')
        atomicState.remove('pendingHeatIndMax')
        atomicState.remove('targetHeatInd')
        checkExtSyncComplete()
        sendEvent(name: 'heatingIndicator', value: 'disabled (comfort mode)')
    } else if ((device.currentValue('heatingIndicator') ?: '--') in ['--', 'disabled (comfort mode)']) {
        sendEvent(name: 'heatingIndicator', value: 'idle')
    }

    // Push reporting configuration and FC11 settings (including hardware offsets) to the device
    List<String> cmds = []
    cmds += reportingConfigCmds()
    cmds += writeFC11Settings()
    cmds += fc11SettingsReadCmds()
    sendZigbeeCommands(cmds)
}

def configure() {
    logInfo 'configure()'
    if (logEnable) { runIn(86400, 'logsOff') }

    validatePreferences()

    List<String> cmds = []
    cmds += reportingConfigCmds()
    cmds += writeFC11Settings()

    // Read current values (after the writes, so the reads reflect them)
    cmds += zigbee.readAttribute(CLUSTER_TEMP,      0x0000, [:], 200)
    cmds += zigbee.readAttribute(CLUSTER_HUMIDITY,  0x0000, [:], 200)
    cmds += zigbee.readAttribute(CLUSTER_POWER_CFG, 0x0021, [:], 200)
    cmds += fc11SettingsReadCmds()

    scheduleHealthCheck()   // also (re)schedules the daily auto-reset
    sendZigbeeCommands(cmds)
}

def initialize() {
    logInfo 'initialize()'
    unschedule()
    initVars(true)
    configure()
}

def refresh() {
    logInfo 'refresh()'
    List<String> cmds = []
    cmds += zigbee.readAttribute(CLUSTER_TEMP,      0x0000, [:], 200)
    cmds += zigbee.readAttribute(CLUSTER_HUMIDITY,  0x0000, [:], 200)
    cmds += zigbee.readAttribute(CLUSTER_POWER_CFG, 0x0021, [:], 200)
    cmds += zigbee.readAttribute(CLUSTER_POWER_CFG, 0x0020, [:], 200)
    cmds += fc11SettingsReadCmds()
    // Read device-native min/max (FC11 0x2008-0x200D) and EXT1 state (0x600D-0x600E)
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_MAX_TEMP,      [mfgCode: '0x1286'], 200)
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_MIN_TEMP,      [mfgCode: '0x1286'], 200)
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_MAX_HUMI,      [mfgCode: '0x1286'], 200)
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_MIN_HUMI,      [mfgCode: '0x1286'], 200)
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_EXT_TEMP_MODE, [mfgCode: '0x1286'], 200)
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_EXT_TEMP_VAL,  [mfgCode: '0x1286'], 200)
    sendZigbeeCommands(cmds)
}

def ping() {
    logDebug 'ping()'
    state.pingTime = now()
    scheduleCommandTimeout()
    sendZigbeeCommands(zigbee.readAttribute(0x0000, 0x0001, [:], 0))
}

// ── External Display (EXT1), Heating Indicator & Wake-Up Queue ───────────────

void setExt1Info(BigDecimal value) {
    if (value == null) { return }
    double clamped = clampD(value.toDouble(), EXT1_VAL_MIN, EXT1_VAL_MAX)
    BigDecimal rounded = BigDecimal.valueOf(clamped).setScale(1, BigDecimal.ROUND_HALF_UP)

    int targetRaw = Math.round(rounded.toDouble() * 100) as int
    atomicState.pendingExtVal   = targetRaw
    atomicState.pendingExtMode  = 1
    atomicState.pendingExtWrite = true

    sendEvent(name: 'extSyncStatus', value: "pending (EXT1: ${rounded})")
    logInfo "setExt1Info(${rounded}) queued (raw=${targetRaw}, mode=1)"
    flushPendingExtWrite(true)
}

void setExternalDisplayMode(String mode) {
    String norm = mode ? mode.trim().toLowerCase() : ''
    if (norm != 'external' && norm != 'internal') {
        logWarn "setExternalDisplayMode('${mode}') rejected: invalid mode '${mode}'. Expected values are 'external' or 'internal'."
        return
    }
    int targetMode = (norm == 'external') ? 1 : 0
    atomicState.pendingExtMode = targetMode
    if (targetMode == 0) {
        atomicState.remove('pendingExtVal')
    }
    atomicState.pendingExtWrite = true

    sendEvent(name: 'extSyncStatus', value: "pending mode (${norm})")
    logInfo "setExternalDisplayMode(${norm}) queued (raw=${targetMode})"
    flushPendingExtWrite(true)
}

void setHeatingIndicator(String indicatorState) {
    if (!heatingIndicatorEnable) {
        logWarn "setHeatingIndicator('${indicatorState}') ignored: 'Use temperature comfort icons as Heating Indicator' is disabled in Preferences (device is operating in standard comfort threshold mode)."
        return
    }
    String norm = indicatorState ? indicatorState.trim().toLowerCase() : ''
    if (norm != 'heating' && norm != 'idle') {
        logWarn "setHeatingIndicator('${indicatorState}') rejected: invalid value '${indicatorState}'. Expected values are 'heating' or 'idle'."
        return
    }

    int targetMaxRaw = (norm == 'heating') ? HEAT_IND_HEATING_RAW : HEAT_IND_IDLE_RAW
    atomicState.targetHeatInd     = norm
    atomicState.pendingHeatIndMin = HEAT_IND_MIN_RAW
    atomicState.pendingHeatIndMax = targetMaxRaw
    atomicState.pendingExtWrite   = true

    sendEvent(name: 'extSyncStatus', value: "pending (indicator: ${norm})")
    logInfo "setHeatingIndicator('${norm}') queued (comfortTempMax=${targetMaxRaw / 100.0}\u00B0C, comfortTempMin=0.0\u00B0C)"
    flushPendingExtWrite(true)
}

private void flushPendingExtWrite(boolean forceNow = false) {
    if (!atomicState.pendingExtWrite) { return }
    long nowMs = now()
    Long lastFlush = atomicState.lastExtFlush as Long
    if (!forceNow && lastFlush != null && (nowMs - lastFlush) < EXT_FLUSH_DEBOUNCE) {
        return
    }
    atomicState.lastExtFlush = nowMs

    Integer extMode    = atomicState.pendingExtMode as Integer
    Integer extVal     = atomicState.pendingExtVal as Integer
    Integer heatIndMin = atomicState.pendingHeatIndMin as Integer
    Integer heatIndMax = atomicState.pendingHeatIndMax as Integer

    List<String> cmds = []

    // 1. Send display mode (0x600E, UINT8 = 0x20) if pending
    if (extMode != null) {
        cmds += zigbee.writeAttribute(CLUSTER_FC11, FC11_EXT_TEMP_MODE, DataType.UINT8, extMode, [mfgCode: '0x1286'], 50)
        cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_EXT_TEMP_MODE, [mfgCode: '0x1286'], 100)
    }

    // 2. Send external value (0x600D, INT16 = 0x29) if pending and target mode is not 'internal'
    if (extVal != null && (extMode == null || extMode == 1)) {
        cmds += zigbee.writeAttribute(CLUSTER_FC11, FC11_EXT_TEMP_VAL, DataType.INT16, extVal, [mfgCode: '0x1286'], 50)
        cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_EXT_TEMP_VAL, [mfgCode: '0x1286'], 100)
    }

    // 3. Send Heating Indicator lower bound (0x0004 = 0.0Β°C, INT16 = 0x29) if pending
    if (heatIndMin != null) {
        cmds += zigbee.writeAttribute(CLUSTER_FC11, FC11_ATTR_COMFORT_TEMP_MIN, DataType.INT16, heatIndMin, [mfgCode: '0x1286'], 50)
        cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_ATTR_COMFORT_TEMP_MIN, [mfgCode: '0x1286'], 100)
    }

    // 4. Send Heating Indicator upper bound (0x0003 = 5.0Β°C or 50.0Β°C, INT16 = 0x29) if pending
    if (heatIndMax != null) {
        cmds += zigbee.writeAttribute(CLUSTER_FC11, FC11_ATTR_COMFORT_TEMP_MAX, DataType.INT16, heatIndMax, [mfgCode: '0x1286'], 50)
        cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_ATTR_COMFORT_TEMP_MAX, [mfgCode: '0x1286'], 100)
    }

    if (cmds) {
        logDebug "Flushing pending FC11 writes (extMode=${extMode}, extVal=${extVal}, heatIndMin=${heatIndMin}, heatIndMax=${heatIndMax})"
        sendZigbeeCommands(cmds)
    } else {
        atomicState.pendingExtWrite = false
    }
}

private void checkExtSyncComplete() {
    boolean stillPending = (atomicState.pendingExtMode != null ||
                            atomicState.pendingExtVal != null ||
                            atomicState.pendingHeatIndMin != null ||
                            atomicState.pendingHeatIndMax != null)
    atomicState.pendingExtWrite = stillPending
    if (!stillPending) {
        String ts = new Date().format('HH:mm:ss', location.timeZone)
        sendEvent(name: 'extSyncStatus', value: "synced @ ${ts}")
        logInfo "All pending FC11 writes confirmed by device @ ${ts}"
    }
}

// ── Standard Commands ────────────────────────────────────────────────────────

def resetMinMax() {
    logInfo 'Resetting min/max tracking'
    state.minTemp      = null
    state.maxTemp      = null
    state.minHumi      = null
    state.maxHumi      = null
    state.readingCount = 0
    String ts = new Date().format('yyyy-MM-dd HH:mm:ss', location.timeZone)
    sendEvent(name: 'Min/Max Reset',        value: ts,   descriptionText: "Min/max reset at ${ts}")
    sendEvent(name: 'Readings Since Reset', value: 0,    descriptionText: 'Reading counter reset to 0')
    sendEvent(name: 'Temperature Min',      value: '--', descriptionText: 'Min temperature reset')
    sendEvent(name: 'Temperature Max',      value: '--', descriptionText: 'Max temperature reset')
    sendEvent(name: 'Humidity Min',         value: '--', descriptionText: 'Min humidity reset')
    sendEvent(name: 'Humidity Max',         value: '--', descriptionText: 'Max humidity reset')
}

// ── Auto-reset scheduling ────────────────────────────────────────────────────

private void rescheduleAutoReset() {
    unschedule('autoResetMinMax')
    if (!autoResetEnable) {
        logInfo 'Auto-reset disabled'
        return
    }
    try {
        def t = timeToday(autoResetTime, location.timeZone)
        String cronExpr = "0 ${t.minutes} ${t.hours} * * ? *"
        schedule(cronExpr, 'autoResetMinMax')
        logInfo "Auto-reset scheduled daily at ${autoResetTime} (cron: ${cronExpr})"
    } catch (e) {
        logWarn "Auto-reset scheduling failed: ${e.message}"
    }
}

def autoResetMinMax() {
    logInfo 'Auto-reset: resetting driver min/max tracking'
    resetMinMax()
}

// ── Parse ────────────────────────────────────────────────────────────────────

def parse(String description) {
    setPresent()

    if (!(description?.startsWith('catchall:') || description?.startsWith('read attr -'))) {
        logDebug "unhandled description: ${description}"
        return
    }

    Map descMap = zigbee.parseDescriptionAsMap(description)
    logDebug "parse() descMap = ${descMap}"

    // Global responses: 0x04 = Write Attributes Response, 0x07 = Configure Reporting Response
    if (description.startsWith('catchall:') && descMap.isClusterSpecific != true &&
            (descMap.command == '04' || descMap.command == '07')) {
        parseGlobalResponse(descMap)
        return
    }

    // Wake-up Piggybacking: Whenever the sensor wakes up and sends an attribute report or
    // button press, immediately flush any unacknowledged FC11 write while its RX window is open.
    if (atomicState.pendingExtWrite) {
        flushPendingExtWrite(false)
    }

    switch (descMap.clusterInt as Integer) {
        case CLUSTER_POWER_CFG:
            parsePowerCluster(descMap)
            break
        case CLUSTER_TEMP:
            parseTempCluster(descMap)
            break
        case CLUSTER_HUMIDITY:
            parseHumiCluster(descMap)
            break
        case CLUSTER_FC11:
            parseFC11Cluster(descMap)
            break
        case CLUSTER_IDENTIFY:
            logInfo 'Physical rear button pressed (device awake)'
            break
        case CLUSTER_ZDO_BIND:
            logDebug 'ZDO Bind response received (0x8021)'
            break
        case 0x0000:
            // Basic cluster – used for ping response
            if (descMap.attrInt == 0x0001 && descMap.value) {
                def elapsed = now() - (state.pingTime ?: 0)
                if (elapsed < PING_TIMEOUT_MS && elapsed > 0) {
                    unschedule('commandTimeout')
                    sendEvent(name: 'rtt', value: elapsed, unit: 'ms', descriptionText: "Round-trip time ${elapsed} ms")
                    logInfo "ping RTT = ${elapsed} ms"
                }
            }
            break
        default:
            logDebug "unhandled cluster: 0x${Integer.toHexString(descMap.clusterInt ?: 0)}"
            break
    }
}

// Logs whether the device accepted a Configure Reporting or Write Attributes request.
private void parseGlobalResponse(Map descMap) {
    List data = (descMap.data ?: []) as List
    String status = data ? (data[0] as String) : '??'
    Integer clusterInt = descMap.clusterInt as Integer
    String cluster = clusterName(clusterInt)

    if (descMap.command == '07') {
        if (status == '00') {
            logInfo "${cluster} reporting configuration accepted by device"
        } else {
            String attr = data.size() >= 4 ? "0x${data[3]}${data[2]}" : '?'
            logWarn "${cluster} reporting configuration for attribute ${attr} rejected (status 0x${status})"
        }
    } else {
        if (status == '00') {
            logInfo "${cluster} attribute write accepted by device"
        } else {
            String attr = data.size() >= 3 ? "0x${data[2]}${data[1]}" : '?'
            logWarn "${cluster} write of attribute ${attr} rejected (status 0x${status})"
            if (clusterInt == CLUSTER_FC11 && attr == '0x0007' && status.equalsIgnoreCase('8D')) {
                retryLcdUnitWrite()
            }
        }
    }
}

private String clusterName(Integer clusterInt) {
    switch (clusterInt) {
        case CLUSTER_POWER_CFG: return 'Battery'
        case CLUSTER_TEMP:      return 'Temperature'
        case CLUSTER_HUMIDITY:  return 'Humidity'
        case CLUSTER_FC11:      return 'FC11'
        default:                return "Cluster 0x${Integer.toHexString(clusterInt ?: 0)}"
    }
}

// ── Cluster parsers ──────────────────────────────────────────────────────────

private void parsePowerCluster(Map descMap) {
    if (descMap.attrInt == 0x0021 && descMap.value && descMap.value.length() <= 8) {
        Integer raw = (Long.parseLong(descMap.value, 16) & 0xFF) as Integer
        Integer pct = Math.min(100, Math.round(raw / 2.0) as Integer)
        sendEvent(name: 'battery', value: pct, unit: '%',
                  descriptionText: "${device.displayName} battery is ${pct}%", type: 'physical')
        logInfo "battery ${pct}%"
    } else if (descMap.attrInt == 0x0020 && descMap.value && descMap.value.length() <= 8) {
        Integer raw = (Long.parseLong(descMap.value, 16) & 0xFF) as Integer
        double volts = raw / 10.0
        Integer pct = Math.min(100, Math.max(1, Math.round(((volts - 2.1) / 0.9) * 100) as Integer))
        sendEvent(name: 'battery', value: pct, unit: '%',
                  descriptionText: "${device.displayName} battery ~${pct}% (${volts}V)", type: 'physical')
        logInfo "battery voltage ${volts}V (~${pct}%)"
    }
}

private void parseTempCluster(Map descMap) {
    if (descMap.attrInt != null && descMap.attrInt != 0x0000) { return }
    if (!descMap.value || descMap.value.length() > 8) { return }
    Integer raw = (Long.parseLong(descMap.value, 16) & 0xFFFF) as Integer
    if (raw == 0x8000) { logDebug 'temperature: invalid sentinel value'; return }
    if (raw > 32767) { raw = raw - 65536 }
    state.rawTempC = raw / 100.0
    publishTemperature()
}

// Publishes temperature directly from the device reading (calibration offset is applied in hardware via 0x2003).
private void publishTemperature() {
    if (state.rawTempC == null) { return }
    double tempC = state.rawTempC as double

    double display
    String unit
    if (location.temperatureScale == 'F') {
        display = Math.round(((tempC * 1.8) + 32 - 0.05) * 10) / 10
        unit = '\u00B0F'
    } else {
        display = Math.round((tempC - 0.05) * 10) / 10
        unit = '\u00B0C'
    }

    sendEvent(name: 'temperature', value: display, unit: unit,
              descriptionText: "${device.displayName} temperature is ${display}${unit}",
              type: 'physical')
    logInfo "temperature ${display}${unit}"
    updateMinMax('temperature', tempC)
    String ts = new Date().format('yyyy-MM-dd HH:mm:ss', location.timeZone)
    sendEvent(name: 'Last Reading', value: ts, descriptionText: "Last reading at ${ts}")
}

private void parseHumiCluster(Map descMap) {
    if (descMap.attrInt != null && descMap.attrInt != 0x0000) { return }
    if (!descMap.value || descMap.value.length() > 8) { return }
    Integer raw = (Long.parseLong(descMap.value, 16) & 0xFFFF) as Integer
    state.rawHumi = raw / 100.0
    publishHumidity()
}

// Publishes humidity directly from the device reading (calibration offset is applied in hardware via 0x2004).
private void publishHumidity() {
    if (state.rawHumi == null) { return }
    double humi = clampD(state.rawHumi as double, 0.0, 100.0)
    Integer display = Math.round(humi) as Integer

    sendEvent(name: 'humidity', value: display, unit: '%',
              descriptionText: "${device.displayName} humidity is ${display}%",
              type: 'physical')
    logInfo "humidity ${display}%"
    updateMinMax('humidity', humi)
}

private void parseFC11Cluster(Map descMap) {
    if (descMap.additionalAttrs) {
        descMap.additionalAttrs.each { Map aa ->
            String v = aa.value as String
            if (v && v.length() <= 8) {
                parseFC11Attr(aa.attrInt as int, v, aa.encoding as String)
            }
        }
    }
    String val = descMap.value as String
    if (!val || val.length() > 8) {
        if (val && val.length() > 8) { logDebug "FC11 skipping blob len=${val.length()}" }
        return
    }
    parseFC11Attr(descMap.attrInt as int, val, descMap.encoding as String)
}

private void parseFC11Attr(int attrInt, String hexVal, String encoding = null) {
    Integer raw = (Long.parseLong(hexVal, 16) & 0xFFFF) as Integer

    if (attrInt == (FC11_ATTR_TEMP_UNIT as int)) {
        String unitName = raw == 1 ? 'Fahrenheit' : 'Celsius'
        sendEvent(name: 'lcdTempUnit', value: unitName, descriptionText: "LCD temperature unit is ${unitName}")
        logInfo "FC11 LCD temperature unit: ${unitName}${encoding ? " (device reports data type 0x${encoding})" : ''}"

    } else if (attrInt == (FC11_ATTR_COMFORT_TEMP_MIN as int)) {
        Integer signed = raw > 32767 ? raw - 65536 : raw
        double valC = signed / 100.0
        String display = formatTemp(valC)
        sendEvent(name: 'comfortTempMin', value: display,
                  descriptionText: "Comfort temp min = ${display} (${valC}\u00B0C device setting)")
        logInfo "FC11 comfort temp min = ${display}"
        if (atomicState.pendingHeatIndMin != null && signed == (atomicState.pendingHeatIndMin as int)) {
            atomicState.remove('pendingHeatIndMin')
            checkExtSyncComplete()
        }

    } else if (attrInt == (FC11_ATTR_COMFORT_TEMP_MAX as int)) {
        Integer signed = raw > 32767 ? raw - 65536 : raw
        double valC = signed / 100.0
        String display = formatTemp(valC)
        sendEvent(name: 'comfortTempMax', value: display,
                  descriptionText: "Comfort temp max = ${display} (${valC}\u00B0C device setting)")
        logInfo "FC11 comfort temp max = ${display}"

        if (atomicState.pendingHeatIndMax != null && signed == (atomicState.pendingHeatIndMax as int)) {
            atomicState.remove('pendingHeatIndMax')
            checkExtSyncComplete()
        }

        if (heatingIndicatorEnable) {
            if (signed == HEAT_IND_HEATING_RAW) {
                sendEvent(name: 'heatingIndicator', value: 'heating',
                          descriptionText: 'Heating indicator (πŸ”₯ icon) confirmed: heating')
            } else if (signed == HEAT_IND_IDLE_RAW) {
                sendEvent(name: 'heatingIndicator', value: 'idle',
                          descriptionText: 'Heating indicator (πŸ”₯ icon) confirmed: idle')
            } else {
                sendEvent(name: 'heatingIndicator', value: 'unsynced',
                          descriptionText: "Heating indicator unsynced (device max=${valC}\u00B0C)")
                String targetInd = atomicState.targetHeatInd as String
                if (targetInd == 'heating' || targetInd == 'idle') {
                    logWarn "Device comfortTempMax (${valC}\u00B0C) out of sync with target '${targetInd}'; re-queueing"
                    atomicState.pendingHeatIndMin = HEAT_IND_MIN_RAW
                    atomicState.pendingHeatIndMax = (targetInd == 'heating') ? HEAT_IND_HEATING_RAW : HEAT_IND_IDLE_RAW
                    atomicState.pendingExtWrite   = true
                }
            }
        }

    } else if (attrInt == (FC11_ATTR_COMFORT_HUMI_MIN as int)) {
        double val = raw / 100.0
        String humiMinDisplay = "${Math.round(val)}%"
        sendEvent(name: 'comfortHumiMin', value: humiMinDisplay,
                  descriptionText: "Comfort humidity min = ${humiMinDisplay}")
        logInfo "FC11 comfort humidity min = ${humiMinDisplay}"

    } else if (attrInt == (FC11_ATTR_COMFORT_HUMI_MAX as int)) {
        double val = raw / 100.0
        String humiMaxDisplay = "${Math.round(val)}%"
        sendEvent(name: 'comfortHumiMax', value: humiMaxDisplay,
                  descriptionText: "Comfort humidity max = ${humiMaxDisplay}")
        logInfo "FC11 comfort humidity max = ${humiMaxDisplay}"

    } else if (attrInt == (FC11_ATTR_TEMP_CALIBRATION as int)) {
        Integer signed = raw > 32767 ? raw - 65536 : raw
        String calStr = "${String.format('%.1f', signed / 100.0)}\u00B0C"
        sendEvent(name: 'tempCalibration', value: calStr, descriptionText: "Hardware temperature calibration = ${calStr}")
        logInfo "FC11 temp calibration = ${calStr}"

    } else if (attrInt == (FC11_ATTR_HUMI_CALIBRATION as int)) {
        Integer signed = raw > 32767 ? raw - 65536 : raw
        String calStr = "${String.format('%.1f', signed / 100.0)}%"
        sendEvent(name: 'humiCalibration', value: calStr, descriptionText: "Hardware humidity calibration = ${calStr}")
        logInfo "FC11 humidity calibration = ${calStr}"

    } else if (attrInt == FC11_MAX_TEMP) {
        Integer signed = raw > 32767 ? raw - 65536 : raw
        String display = formatTemp(signed / 100.0)
        sendEvent(name: 'Device Temp Max', value: display,
                  descriptionText: "Device max temp = ${display}")
        logInfo "FC11 device max temp = ${display}"

    } else if (attrInt == FC11_MIN_TEMP) {
        Integer signed = raw > 32767 ? raw - 65536 : raw
        String display = formatTemp(signed / 100.0)
        sendEvent(name: 'Device Temp Min', value: display,
                  descriptionText: "Device min temp = ${display}")
        logInfo "FC11 device min temp = ${display}"

    } else if (attrInt == FC11_PREV_TEMP) {
        Integer signed = raw > 32767 ? raw - 65536 : raw
        logInfo "FC11 0x200A ref temp = ${formatTemp(signed / 100.0)}"

    } else if (attrInt == FC11_MAX_HUMI) {
        String display = "${Math.round(raw / 100.0)}%"
        sendEvent(name: 'Device Humidity Max', value: display,
                  descriptionText: "Device max humidity = ${display}")
        logInfo "FC11 device max humidity = ${display}"

    } else if (attrInt == FC11_MIN_HUMI) {
        String display = "${Math.round(raw / 100.0)}%"
        sendEvent(name: 'Device Humidity Min', value: display,
                  descriptionText: "Device min humidity = ${display}")
        logInfo "FC11 device min humidity = ${display}"

    } else if (attrInt == FC11_PREV_HUMI) {
        logInfo "FC11 0x200D ref humidity = ${Math.round(raw / 100.0)}%"

    } else if (attrInt == FC11_EXT_TEMP_VAL) {
        Integer signed = raw > 32767 ? raw - 65536 : raw
        BigDecimal val = BigDecimal.valueOf(signed / 100.0).setScale(1, BigDecimal.ROUND_HALF_UP)
        sendEvent(name: 'ext1Info', value: val,
                  descriptionText: "EXT1 display value (0x600D) = ${val}")
        logInfo "FC11 EXT1 value (0x600D) = ${val}"
        if (atomicState.pendingExtVal != null && signed == (atomicState.pendingExtVal as int)) {
            atomicState.remove('pendingExtVal')
            checkExtSyncComplete()
        }

    } else if (attrInt == FC11_EXT_TEMP_MODE) {
        String modeStr = (raw == 1) ? 'external (EXT1)' : 'internal (Min/Max)'
        sendEvent(name: 'externalDisplayMode', value: modeStr,
                  descriptionText: "LCD display mode (0x600E) = ${modeStr}")
        logInfo "FC11 external display mode (0x600E) = ${modeStr}"
        if (atomicState.pendingExtMode != null && raw == (atomicState.pendingExtMode as int)) {
            atomicState.remove('pendingExtMode')
            checkExtSyncComplete()
        }

    } else {
        logDebug "FC11 unhandled attr 0x${Integer.toHexString(attrInt)} = ${raw}"
    }
}

private String formatTemp(double tempC) {
    if (location.temperatureScale == 'F') {
        return "${Math.round((tempC * 1.8 + 32) * 10) / 10}\u00B0F"
    }
    return "${Math.round(tempC * 10) / 10}\u00B0C"
}

// ── Min/Max tracking ─────────────────────────────────────────────────────────

private void updateMinMax(String type, double value) {
    if (type == 'temperature') {
        state.readingCount = (state.readingCount ?: 0) + 1
        sendEvent(name: 'Readings Since Reset', value: state.readingCount,
                  descriptionText: "${state.readingCount} readings since last reset")
        double rounded = Math.round(value * 10) / 10
        String unit = location.temperatureScale == 'F' ? '\u00B0F' : '\u00B0C'
        double displayVal = location.temperatureScale == 'F' ? Math.round(((value * 1.8) + 32) * 10) / 10 : rounded

        if (state.minTemp == null || value < (state.minTemp as double)) {
            state.minTemp = value
            String ts = new Date().format('MM-dd HH:mm', location.timeZone)
            sendEvent(name: 'Temperature Min', value: "${displayVal}${unit} @ ${ts}",
                      descriptionText: "Min temperature is ${displayVal}${unit} (at ${ts}, since last reset)")
            logInfo "New min temperature: ${displayVal}${unit} @ ${ts}"
        }
        if (state.maxTemp == null || value > (state.maxTemp as double)) {
            state.maxTemp = value
            String ts = new Date().format('MM-dd HH:mm', location.timeZone)
            sendEvent(name: 'Temperature Max', value: "${displayVal}${unit} @ ${ts}",
                      descriptionText: "Max temperature is ${displayVal}${unit} (at ${ts}, since last reset)")
            logInfo "New max temperature: ${displayVal}${unit} @ ${ts}"
        }
    } else if (type == 'humidity') {
        Integer roundedPct = Math.round(value) as Integer
        if (state.minHumi == null || value < (state.minHumi as double)) {
            state.minHumi = value
            String ts = new Date().format('MM-dd HH:mm', location.timeZone)
            sendEvent(name: 'Humidity Min', value: "${roundedPct}% @ ${ts}",
                      descriptionText: "Min humidity is ${roundedPct}% (at ${ts}, since last reset)")
            logInfo "New min humidity: ${roundedPct}% @ ${ts}"
        }
        if (state.maxHumi == null || value > (state.maxHumi as double)) {
            state.maxHumi = value
            String ts = new Date().format('MM-dd HH:mm', location.timeZone)
            sendEvent(name: 'Humidity Max', value: "${roundedPct}% @ ${ts}",
                      descriptionText: "Max humidity is ${roundedPct}% (at ${ts}, since last reset)")
            logInfo "New max humidity: ${roundedPct}% @ ${ts}"
        }
    }
}

// ── Reporting configuration ──────────────────────────────────────────────────

private List<String> reportingConfigCmds() {
    List<String> cmds = []

    int tMin = Math.max(1, Math.min(3600, safeInt(minReportTemp, 10)))
    int tMax = Math.max(tMin, Math.min(43200, safeInt(maxReportTemp, 3600)))
    Integer tempDelta = Math.round(prefTempChange() * 100) as Integer
    cmds += zigbee.configureReporting(CLUSTER_TEMP, 0x0000, DataType.INT16,
        tMin, tMax, tempDelta, [:], 200)

    int hMin = Math.max(1, Math.min(3600, safeInt(minReportHumi, 10)))
    int hMax = Math.max(hMin, Math.min(43200, safeInt(maxReportHumi, 3600)))
    int humiStep = Math.max(1, Math.min(10, safeInt(humiChange, 1)))
    Integer humiDelta = humiStep * 100
    cmds += zigbee.configureReporting(CLUSTER_HUMIDITY, 0x0000, DataType.UINT16,
        hMin, hMax, humiDelta, [:], 200)

    cmds += zigbee.configureReporting(CLUSTER_POWER_CFG, 0x0021, DataType.UINT8,
        60, 14400, 1, [:], 200)

    logDebug "Reporting config: temp ${tMin}-${tMax}s / ${tempDelta / 100.0}\u00B0C, humidity ${hMin}-${hMax}s / ${humiStep}%"
    return cmds
}

// ── FC11 helpers ─────────────────────────────────────────────────────────────

private List<String> fc11SettingsReadCmds() {
    List<String> cmds = []
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_ATTR_COMFORT_TEMP_MIN, [mfgCode: '0x1286'], 200)
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_ATTR_COMFORT_TEMP_MAX, [mfgCode: '0x1286'], 200)
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_ATTR_COMFORT_HUMI_MIN, [mfgCode: '0x1286'], 200)
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_ATTR_COMFORT_HUMI_MAX, [mfgCode: '0x1286'], 200)
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_ATTR_TEMP_UNIT,        [mfgCode: '0x1286'], 200)
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_ATTR_TEMP_CALIBRATION, [mfgCode: '0x1286'], 200)
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_ATTR_HUMI_CALIBRATION, [mfgCode: '0x1286'], 200)
    return cmds
}

private List<String> writeFC11Settings() {
    List<String> cmds = []

    Integer tempMinRaw
    Integer tempMaxRaw
    if (heatingIndicatorEnable) {
        tempMinRaw = HEAT_IND_MIN_RAW
        String currentInd = (atomicState.targetHeatInd ?: (device.currentValue('heatingIndicator') ?: 'idle')) as String
        tempMaxRaw = (currentInd == 'heating') ? HEAT_IND_HEATING_RAW : HEAT_IND_IDLE_RAW
    } else {
        tempMinRaw = Math.round(prefComfortTempMin() * 100) as Integer
        tempMaxRaw = Math.round(prefComfortTempMax() * 100) as Integer
    }

    // comfort_temperature_min (0x0004) β€” INT16, scaled Γ— 100
    cmds += zigbee.writeAttribute(CLUSTER_FC11, FC11_ATTR_COMFORT_TEMP_MIN,
            DataType.INT16, tempMinRaw, [mfgCode: '0x1286'], 200)

    // comfort_temperature_max (0x0003) β€” INT16, scaled Γ— 100
    cmds += zigbee.writeAttribute(CLUSTER_FC11, FC11_ATTR_COMFORT_TEMP_MAX,
            DataType.INT16, tempMaxRaw, [mfgCode: '0x1286'], 200)

    // comfort_humidity_min (0x0005) β€” UINT16, scaled Γ— 100
    Integer humiMinRaw = Math.max(5, Math.min(95, safeInt(pref_comfortHumiMin, 40))) * 100
    cmds += zigbee.writeAttribute(CLUSTER_FC11, FC11_ATTR_COMFORT_HUMI_MIN,
            DataType.UINT16, humiMinRaw, [mfgCode: '0x1286'], 200)

    // comfort_humidity_max (0x0006) β€” UINT16, scaled Γ— 100
    Integer humiMaxRaw = Math.max(5, Math.min(95, safeInt(pref_comfortHumiMax, 60))) * 100
    cmds += zigbee.writeAttribute(CLUSTER_FC11, FC11_ATTR_COMFORT_HUMI_MAX,
            DataType.UINT16, humiMaxRaw, [mfgCode: '0x1286'], 200)

    // Hardware temperature calibration (0x2003) β€” INT16, scaled Γ— 100
    Integer tempCalRaw = Math.round(prefTempOffset() * 100) as Integer
    cmds += zigbee.writeAttribute(CLUSTER_FC11, FC11_ATTR_TEMP_CALIBRATION,
            DataType.INT16, tempCalRaw, [mfgCode: '0x1286'], 200)

    // Hardware humidity calibration (0x2004) β€” INT16, scaled Γ— 100
    Integer humiCalRaw = Math.round(prefHumiOffset() * 100) as Integer
    cmds += zigbee.writeAttribute(CLUSTER_FC11, FC11_ATTR_HUMI_CALIBRATION,
            DataType.INT16, humiCalRaw, [mfgCode: '0x1286'], 200)

    // LCD temperature unit β€” UINT16, 0 = Celsius, 1 = Fahrenheit (confirmed on firmware 1.0.2)
    String unitPref = (lcdTempUnit ?: 'nochange') as String
    if (unitPref == 'C' || unitPref == 'F') {
        int type = (state.lcdUnitType ?: LCD_UNIT_TYPES[0]) as int
        state.lcdUnitTried = [type]
        cmds += lcdUnitWriteCmd(unitPref, type)
    }

    logDebug "Writing FC11 settings (heatingIndicatorMode=${heatingIndicatorEnable}): tempMin=${tempMinRaw / 100.0} tempMax=${tempMaxRaw / 100.0} humiMin=${humiMinRaw / 100.0} humiMax=${humiMaxRaw / 100.0} tempCal=${tempCalRaw / 100.0} humiCal=${humiCalRaw / 100.0} lcdUnit=${unitPref}"
    return cmds
}

private List<String> lcdUnitWriteCmd(String unitPref, int type) {
    state.lcdUnitType = type
    logDebug "Writing LCD temperature unit ${unitPref} as data type 0x${Integer.toHexString(type)}"
    return zigbee.writeAttribute(CLUSTER_FC11, FC11_ATTR_TEMP_UNIT, type,
            unitPref == 'F' ? 1 : 0, [mfgCode: '0x1286'], 200)
}

private void retryLcdUnitWrite() {
    String unitPref = (lcdTempUnit ?: 'nochange') as String
    if (unitPref != 'C' && unitPref != 'F') { return }
    List<Integer> tried = ((state.lcdUnitTried ?: []) as List).collect { it as int }
    Integer next = LCD_UNIT_TYPES.find { !(it in tried) }
    if (next == null) {
        logWarn 'LCD temperature unit: the device rejected every data type tried; ' +
                'change the unit on the device or in the eWeLink app instead'
        state.remove('lcdUnitType')
        return
    }
    tried << next
    state.lcdUnitTried = tried
    logInfo "LCD temperature unit: retrying with data type 0x${Integer.toHexString(next)}"
    List<String> cmds = lcdUnitWriteCmd(unitPref, next)
    cmds += zigbee.readAttribute(CLUSTER_FC11, FC11_ATTR_TEMP_UNIT, [mfgCode: '0x1286'], 200)
    sendZigbeeCommands(cmds)
}

// ── Preference validation ────────────────────────────────────────────────────

private double prefTempChange()     { return clampD(safeDouble(tempChange, 0.2),          TEMP_CHANGE_MIN,  TEMP_CHANGE_MAX)  }
private double prefTempOffset()     { return clampD(safeDouble(temperatureOffset, 0.0),   OFFSET_MIN,       OFFSET_MAX)       }
private double prefHumiOffset()     { return clampD(safeDouble(humidityOffset, 0.0),      OFFSET_MIN,       OFFSET_MAX)       }
private double prefComfortTempMin() { return clampD(safeDouble(pref_comfortTempMin, 18.0), COMFORT_TEMP_MIN, COMFORT_TEMP_MAX) }
private double prefComfortTempMax() { return clampD(safeDouble(pref_comfortTempMax, 26.0), COMFORT_TEMP_MIN, COMFORT_TEMP_MAX) }

private void validatePreferences() {
    fixDecimalSetting('tempChange',          tempChange,          prefTempChange())
    fixDecimalSetting('temperatureOffset',   temperatureOffset,   prefTempOffset())
    fixDecimalSetting('humidityOffset',      humidityOffset,      prefHumiOffset())
    fixDecimalSetting('pref_comfortTempMin', pref_comfortTempMin, prefComfortTempMin())
    fixDecimalSetting('pref_comfortTempMax', pref_comfortTempMax, prefComfortTempMax())
}

private void fixDecimalSetting(String name, Object current, double valid) {
    if (current == null) { return }
    if (safeDouble(current, valid) != valid) {
        logWarn "Preference '${name}' value ${current} is out of range; using ${valid}"
        device.updateSetting(name, [value: valid, type: 'decimal'])
    }
}

private static double clampD(double v, double lo, double hi) {
    return Math.max(lo, Math.min(hi, v))
}

// ── Health check ─────────────────────────────────────────────────────────────

def setPresent() {
    if ((device.currentValue('healthStatus') ?: 'unknown') != 'online') {
        sendEvent(name: 'healthStatus', value: 'online', type: 'digital')
        logInfo 'device is present (online)'
    }
    state.missedChecks = 0
}

def deviceHealthCheck() {
    state.missedChecks = (state.missedChecks ?: 0) + 1
    if (state.missedChecks > PRESENCE_THRESHOLD) {
        if ((device.currentValue('healthStatus', true) ?: 'unknown') != 'offline') {
            sendEvent(name: 'healthStatus', value: 'offline', type: 'digital')
            logWarn 'device has not reported β€” marking offline'
        }
    } else {
        logDebug "health check β€” ok (missed=${state.missedChecks})"
    }
}

private void scheduleHealthCheck() {
    Random rnd = new Random()
    schedule("${rnd.nextInt(59)} ${rnd.nextInt(59)} 1/3 * * ? *", 'deviceHealthCheck')
    rescheduleAutoReset()
}

private void scheduleCommandTimeout() {
    runIn(10, 'commandTimeout')
}

void commandTimeout() {
    logWarn 'command timed out (no response from device)'
    sendEvent(name: 'rtt', value: -1, unit: 'ms', descriptionText: 'No ping response (timeout)', type: 'digital')
}

// ── Init helpers ─────────────────────────────────────────────────────────────

private void initVars(boolean fullInit) {
    if (fullInit) {
        state.minTemp               = null
        state.maxTemp               = null
        state.minHumi               = null
        state.maxHumi               = null
        state.missedChecks          = 0
        state.pingTime              = 0
        state.readingCount          = 0
        state.rawTempC              = null
        state.rawHumi               = null
        atomicState.pendingExtWrite = false
        atomicState.remove('pendingExtMode')
        atomicState.remove('pendingExtVal')
        atomicState.remove('pendingHeatIndMin')
        atomicState.remove('pendingHeatIndMax')
        String ts = new Date().format('yyyy-MM-dd HH:mm:ss', location.timeZone)
        sendEvent(name: 'healthStatus',         value: 'unknown')
        sendEvent(name: 'Last Reading',         value: '--', descriptionText: 'No reading yet')
        sendEvent(name: 'Min/Max Reset',        value: ts,   descriptionText: "Min/max reset at ${ts}")
        sendEvent(name: 'Readings Since Reset', value: 0,    descriptionText: 'Reading counter initialized')
        sendEvent(name: 'Temperature Min',      value: '--')
        sendEvent(name: 'Temperature Max',      value: '--')
        sendEvent(name: 'Humidity Min',         value: '--')
        sendEvent(name: 'Humidity Max',         value: '--')
        sendEvent(name: 'Device Temp Max',      value: '--', descriptionText: 'Waiting for device report')
        sendEvent(name: 'Device Temp Min',      value: '--', descriptionText: 'Waiting for device report')
        sendEvent(name: 'Device Humidity Max',  value: '--', descriptionText: 'Waiting for device report')
        sendEvent(name: 'Device Humidity Min',  value: '--', descriptionText: 'Waiting for device report')
        sendEvent(name: 'comfortTempMin',       value: '--')
        sendEvent(name: 'comfortTempMax',       value: '--')
        sendEvent(name: 'comfortHumiMin',       value: '--')
        sendEvent(name: 'comfortHumiMax',       value: '--')
        sendEvent(name: 'tempCalibration',      value: '--')
        sendEvent(name: 'humiCalibration',      value: '--')
        sendEvent(name: 'lcdTempUnit',          value: '--')
        sendEvent(name: 'externalDisplayMode',  value: '--')
        sendEvent(name: 'heatingIndicator',     value: heatingIndicatorEnable ? 'idle' : 'disabled (comfort mode)')
        sendEvent(name: 'extSyncStatus',        value: 'idle')
    }
    state.driverVersion = "${VERSION} ${TIME_STAMP}"
}

// ── Utilities ────────────────────────────────────────────────────────────────

private void sendZigbeeCommands(List<String> cmds) {
    if (!cmds) { return }
    logDebug "sendZigbeeCommands: ${cmds}"
    hubitat.device.HubMultiAction allActions = new hubitat.device.HubMultiAction()
    cmds.each { allActions.add(new hubitat.device.HubAction(it, hubitat.device.Protocol.ZIGBEE)) }
    sendHubCommand(allActions)
}

private double safeDouble(val, double defaultVal = 0.0) {
    try { return val != null ? (val as double) : defaultVal } catch (e) { return defaultVal }
}

private int safeInt(val, int defaultVal = 0) {
    try { return val != null ? (val as int) : defaultVal } catch (e) { return defaultVal }
}

def logsOff() {
    log.warn "${device.displayName} debug logging disabled"
    device.updateSetting('logEnable', [value: 'false', type: 'bool'])
}

private void logDebug(String msg) { if (logEnable) { log.debug "${device.displayName} ${msg}" } }
private void logInfo(String msg)  { if (txtEnable) { log.info  "${device.displayName} ${msg}" } }
private void logWarn(String msg)  {                  log.warn  "${device.displayName} ${msg}"   }

Details for Driver v1.13.1:

=============================================================================
SONOFF SNZB-02DR2 - TECHNICAL FINDINGS, FULL 0xFC11 DUMP & v1.13.1 CHANGES
=============================================================================


1. SUMMARY OF DRIVER MODIFICATIONS (v1.13.1)
-----------------------------------------------------------------------------

A) External Display (EXT1) Control (0xFC11 Attributes 0x600E & 0x600D)
   Contrary to earlier assumptions that the secondary EXT display zone could
   only be driven by a proprietary Sonoff hub, it can be freely switched and
   written over standard Zigbee ZCL Write Attribute commands using the Sonoff
   manufacturer code (0x1286):

   - 0x600E (DataType.UINT8 / 0x20): Controls the bottom LCD display mode.
     * 0 = Internal 24-hour Min/Max extremes
     * 1 = External value display (EXT1)
   - 0x600D (DataType.INT16 / 0x29): Signed value displayed in the EXT1 zone,
     scaled by x100 (e.g., 2250 displays 22.5 on the LCD).

   New Commands & Traffic Optimization:
   - setExt1Info(BigDecimal value): Writes any numeric value (-40.0 to 99.9)
     to the EXT1 field (ideal for room heating setpoints or external sensors).
   - setExternalDisplayMode(String mode): Switches between 'external' (EXT1)
     and 'internal' (24-hr Min/Max).
   - Optimization: Once the driver confirms that the sensor is already in
     EXT1 mode (state.currentExtMode == 1), subsequent setExt1Info() calls
     skip writing 0x600E and only write/read 0x600D, cutting Zigbee traffic
     in half.

B) Selectable Heating Indicator Mode Using the LCD Flame Icon (0x0003/0x0004)
   Added a preference switch ('heatingIndicatorEnable') to choose how the
   temperature comfort icons (snowflake / flame) operate:
   - Disabled (Default - Standard Comfort Mode): The sensor uses the manual
     pref_comfortTempMin and pref_comfortTempMax thresholds set in Preferences
     to automatically show the snowflake/flame icons when the room is too
     cold or hot. External setHeatingIndicator() commands are ignored.
   - Enabled (Heating Indicator Mode): Repurposes the LCD flame icon to show
     whether a room's thermostat is actively heating or idle via the new
     command setHeatingIndicator(String state):
     * Lower threshold (0x0004, snowflake icon) is locked at 0.0 degC (raw=0)
       so the snowflake icon never appears in heated indoor rooms.
     * When state == 'heating': Upper threshold (0x0003, flame icon) is set
       to 5.0 degC (raw=500). Since indoor temperature is > 5.0 degC, the
       flame icon turns ON and stays lit regardless of room temp fluctuations.
     * When state == 'idle': Upper threshold (0x0003) is set to 50.0 degC
       (raw=5000), turning the flame icon OFF.
     * Strict Input Validation: Accepts 'heating' or 'idle' (case-insensitive,
       allowing direct %value% pass-through from Rule Machine thermostatOperatingState).
       Any other string is rejected with a warning log stating both the
       invalid value received and the expected values ('heating' or 'idle').

C) Fast Background Polling Discovery & Unified Wake-Up Piggybacking Queue
   - Fast Polling Finding: Live logs showed that even when the sensor has not
     sent a temperature or humidity report for several minutes (and without
     pressing the rear button), it performs background Zigbee MAC Data Request
     polls to its parent router roughly every 1-2 seconds. While a 16-command
     Save Preferences burst is too long for a single poll window, a compact
     1-2 attribute write is delivered by the parent router and acknowledged
     (status 0x00) within 0.27s to 1.48s during normal operation.
   - Unified Piggybacking Queue (state.pendingExtWrite): Because temperature
     reports can be very infrequent in rooms with stable temperatures (and an
     immediate poll might occasionally miss due to mesh traffic), both
     setExt1Info() and setHeatingIndicator() queue their writes and keep
     state.pendingExtWrite = true until the device responds with ZCL Write
     Attributes Response (command 0x04, status 0x00) on cluster 0xFC11.
     Whenever any frame arrives from the device (temperature, humidity,
     battery report, or physical button press), parse() immediately flushes
     all pending writes in a single batch while the sensor's Zigbee RX window
     is open (with a 2.5s debounce).

D) Hardware Calibration Offsets (0x2003 & 0x2004) Instead of Software Math
   - In v1.12.2, FC11_ATTR_TEMP_CALIBRATION (0x2003) and
     FC11_ATTR_HUMI_CALIBRATION (0x2004) were defined and parsed on read, but
     temperatureOffset and humidityOffset were only applied in software.
     Software-only offsets cause the physical LCD screen on the wall and the
     Hubitat attribute to show different values.
   - In v1.13.1, writeFC11Settings() writes temperatureOffset * 100 to 0x2003
     (INT16) and humidityOffset * 100 to 0x2004 (INT16), and reads them back
     into tempCalibration and humiCalibration attributes. Because the device
     firmware applies these offsets directly to both the physical LCD and its
     0x0402/0x0405 Zigbee reports, software offset addition was removed from
     publishTemperature() and publishHumidity() to prevent double-offsetting.

E) Physical Rear Button Press (0x0003) & ZDO Bind Response (0x8021)
   - Short-pressing the physical rear button immediately sends a cluster-
     specific Identify frame on cluster 0x0003:
     catchall: 0104 0003 01 01 0040 00 <DNI> 01 00 0000 00 00 0100
     (clusterInt: 0x0003, command: 0x00, data: [01, 00]).
   - In v1.13.1, this is logged cleanly and triggers the piggybacking flush
     if any EXT1 or Heating Indicator write is pending.
   - Added handling for cluster 0x8021 (ZDO Bind_rsp) so zdo bind responses
     during configure()/updated() no longer log as unhandled cluster: 0x8021.


2. COMPLETE 0xFC11 ATTRIBUTE DISCOVERY DUMP (FIRMWARE 00001002 / v1.0.2)
-----------------------------------------------------------------------------

Sending ZCL Discover Attributes (0x0C) across cluster 0xFC11 returned
complete=0x01 with 25 attributes (identical list returned with mfgCode 0x1286
and without mfgCode):

[Comfort Zone & Display Unit Registers - 0x00xx]
  * 0x0003 (type 0x29 = INT16)  : Comfort temp max (degC x 100)
  * 0x0004 (type 0x29 = INT16)  : Comfort temp min (degC x 100)
  * 0x0005 (type 0x21 = UINT16) : Comfort humidity min (% x 100)
  * 0x0006 (type 0x21 = UINT16) : Comfort humidity max (% x 100)
  * 0x0007 (type 0x21 = UINT16) : LCD temperature unit (0=Celsius, 1=Fahr.)

[Calibration, Sensor Config, 24-Hr Min/Max & History Buffers - 0x20xx]
  * 0x2003 (type 0x29 = INT16)  : Hardware temperature calibration (degC x 100)
  * 0x2004 (type 0x29 = INT16)  : Hardware humidity calibration (% x 100)
  * 0x2005 (type 0x21 = UINT16) : Internal sensor config register 1
  * 0x2006 (type 0x21 = UINT16) : Internal sensor config register 2
  * 0x2008 (type 0x21 = UINT16) : Device 24-hr max temp (degC x 100)
  * 0x2009 (type 0x29 = INT16)  : Device 24-hr min temp (degC x 100)
  * 0x200A (type 0x29 = INT16)  : Device reference temp (degC x 100)
  * 0x200B (type 0x21 = UINT16) : Device 24-hr max humidity (% x 100)
  * 0x200C (type 0x21 = UINT16) : Device 24-hr min humidity (% x 100)
  * 0x200D (type 0x21 = UINT16) : Device reference humidity (% x 100)
  * 0x200E (type 0x20 = UINT8)  : History log control / index register
  * 0x200F (type 0x21 = UINT16) : History log timestamp / interval register
  * 0x2011 (type 0x48 = ARRAY)  : Historical data flash buffer 1 (eWeLink graph)
  * 0x2012 (type 0x48 = ARRAY)  : Historical data flash buffer 2 (eWeLink graph)
  * 0x2013 (type 0x20 = UINT8)  : History log status register
  * 0x2014 (type 0x48 = ARRAY)  : Historical data flash buffer 3 (eWeLink graph)

[External Display Registers - 0x60xx & Cluster Revision]
  * 0x600D (type 0x29 = INT16)  : External display (EXT1) value (x 100)
  * 0x600E (type 0x20 = UINT8)  : External display mode (0=Internal, 1=EXT1)
  * 0x6014 (type 0x21 = UINT16) : Undocumented 16-bit register in the 0x60xx
                                  block (likely external value timeout/validity)
  * 0xFFFD (type 0x21 = UINT16) : Standard ZCL Cluster Revision


3. FIRMWARE VERSION COMPATIBILITY & NEWER ATTRIBUTES
-----------------------------------------------------------------------------

Cross-referencing our hardware discovery on 00001002 with upstream Zigbee2MQTT
(zigbee-herdsman-converters / sonoff.ts) shows three firmware generations for
the external display feature:

1) Firmware <= 1.0.3 (Confirmed on 00001002 / v1.0.2):
   - Uses 0x600E (UINT8: 0=Internal, 1=EXT1) and 0x600D (INT16: value x 100).
   - Does NOT support external humidity (0x6018 is absent in discovery).

2) Firmware 1.0.4 (00001004):
   - Uses the exact same 0x600E and 0x600D registers for EXT1 temperature
     (100% compatible with this v1.13.1 implementation).
   - Adds attribute 0x6018 (UINT16 / 0x21) for External Humidity (% x 100).

3) Firmware >= 1.0.5 (00001005 and newer):
   - Refactors the external display to support two switchable external
     channels (EXT1 and EXT2) with both temperature and humidity using new
     attribute IDs:
     * 0x6015 (UINT8  / 0x20) : Display mode (0=Internal, 1=EXT1, 2=EXT2)
     * 0x6016 (INT16  / 0x29) : EXT1 Temperature (degC x 100)
     * 0x6017 (INT16  / 0x29) : EXT2 Temperature (degC x 100)
     * 0x6018 (UINT16 / 0x21) : EXT1 Humidity (% x 100)
     * 0x6019 (UINT16 / 0x21) : EXT2 Humidity (% x 100)
=============================================================================

I tried the Heating Indicator trick on my SNZB-02DR2 (firmware 1.0.2): comfort min 32 Β°F, max 40 Β°F, room at 68 Β°F. The sensor confirmed both values on read-back, but no flame or other icon appeared, with EXT1 off. Could you post a photo of the flame showing on your screen, and tell me your firmware version and the comfort values you used?

Gemini says that flame icon refreshes with the next temperature reading of the device. Please wait some time. Unfortunately I can test it on Friday at soonest. With your base driver (2026-11-06) I could set comfort min. and max., and flame appeared/disappeared as it should so it has a good chance that it works. I will come back with test results as soon as possible.

I can't get temp icons to show at all, but the "drop" icon does show for humidity.