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}" }