Thirdreality Smart Presence Sensor R2

Does the Thirdreality Smart Presence Sensor R2 work with C-8? I have the Zigbee pairing but not luck with it working as a motion or presence sensor. Any suggestions appreciated.

What driver are you using?

I have not installed additional drivers. Using the options for the device. Tried options on the Device Info tab for Generic Zigbee Motion Sensor (no temp), as indicated in the hardware documentation. Tried several others including Generic Component Motion Sensor. Hope this answers the question.

Many thanks if the response

As an experiment, you might want to try this driver that I created for the Thirdreality R3 product:

Many thanks. This did not seem to be what is needed. I had a discussion with GROK and found a Thirdreality Motion R1 driver and it did not work. Interesting the Hubitat delivered Compatible Devices for Thirdreality are not available in the “Type” drop down on the Device Info tab after Zigbee pairing.

Again, thanks for your reply and assistance.

This one seems to work for my R2 that I just bought, nothing else seemed to have.

/**

ThirdReality Presence Sensor R2 (24GHz mmWave)

Hubitat driver



Handles BOTH reporting paths because the R2 fingerprint isn't documented:

IAS Zone (cluster 0x0500)        -> motion via zone status

Occupancy Sensing (cluster 0x0406) -> motion via occupancy bitmap

Whichever the device actually uses will drive the "motion" attribute.



Enable "debug logging", trip the sensor, and check Logs to see which

cluster fires. That confirms the real reporting path.
*/

import hubitat.zigbee.zcl.DataType

metadata {
definition(name: "ThirdReality Presence Sensor R2",
namespace: "heph",
author: "heph") {
capability "Motion Sensor"
capability "Battery"
capability "Configuration"
capability "Refresh"
capability "Sensor"

    attribute "lastUpdate", "string"

    // Generic 24GHz radar fingerprint. inClusters list is permissive:
    // 0000 basic, 0001 power, 0003 identify, 0406 occupancy, 0500 IAS.
    fingerprint profileId: "0104", endpointId: "01",
        inClusters: "0000,0001,0003,0406,0500",
        outClusters: "0019",
        manufacturer: "Third Reality, Inc", model: "3RPR"
    fingerprint profileId: "0104", endpointId: "01",
        inClusters: "0000,0001,0003,0500",
        outClusters: "0019",
        manufacturer: "Third Reality, Inc", model: "3RPR"
}

preferences {
    input name: "resetSeconds", type: "number",
        title: "Auto-reset motion after N seconds of no report (0 = trust device)",
        defaultValue: 0, range: "0..3600"
    input name: "logEnable", type: "bool",
        title: "Enable debug logging", defaultValue: true
    input name: "txtEnable", type: "bool",
        title: "Enable description text logging", defaultValue: true
}

}

/* ---------------- lifecycle ---------------- */

def installed() {
log.info "installed"
configure()
}

def updated() {
log.info "updated"
if (logEnable) runIn(1800, logsOff)
configure()
}

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

/* ---------------- parse ---------------- */

def parse(String description) {
if (logEnable) log.debug "parse: ${description}"

// IAS zone status can arrive as a plain string, not a descMap
if (description?.startsWith("zone status") || description?.startsWith("zone report")) {
    def zs = description.contains("0x") ?
        Integer.decode((description =~ /0x[0-9A-Fa-f]+/)[0]) : 0
    handleMotion((zs & 0x01) != 0)
    return
}

Map d = zigbee.parseDescriptionAsMap(description)
if (logEnable) log.debug "descMap: ${d}"

// IAS Zone Status Change Notification (cluster-specific cmd 0x00)
// payload: zoneStatus(uint16 LE) + extStatus + zoneId + delay
if (d.clusterInt == 0x0500 && d.isClusterSpecific && d.command == "00" && d.data?.size() >= 2) {
    Integer zs = zigbee.convertHexToInt("${d.data[1]}${d.data[0]}")
    handleMotion((zs & 0x01) != 0)
    return
}

// collect main attr + any nested additional attrs into one list
List<Map> attrs = []
if (d.attrInt != null) attrs << [cluster: d.clusterInt, attr: d.attrInt, value: d.value]
d.additionalAttrs?.each {
    attrs << [cluster: d.clusterInt, attr: Integer.parseInt(it.attrId, 16), value: it.value]
}

attrs.each { a -> handleAttr(a.cluster, a.attr, a.value) }

}

private handleAttr(Integer cluster, Integer attr, String value) {
if (value == null) return
switch (cluster) {
case 0x0406: // Occupancy Sensing
if (attr == 0x0000) {
handleMotion((Integer.parseInt(value, 16) & 0x01) != 0)
}
break
case 0x0500: // IAS Zone status attribute
if (attr == 0x0002) {
handleMotion((Integer.parseInt(value, 16) & 0x01) != 0)
}
break
case 0x0001: // Power Configuration
if (attr == 0x0021) {        // battery percentage (0-200)
Integer pct = Math.round(Integer.parseInt(value, 16) / 2)
pct = Math.min(100, Math.max(0, pct))
sendBattery(pct)
} else if (attr == 0x0020) { // battery voltage (100mV units)
Integer mv = Integer.parseInt(value, 16) * 100
// 2 AA ~ 3.0V full, 2.1V empty (rough fallback only)
Integer pct = Math.round(((mv - 2100) / (3000 - 2100)) * 100)
pct = Math.min(100, Math.max(0, pct))
if (device.currentValue("battery") == null) sendBattery(pct)
}
break
}
}

/* ---------------- helpers ---------------- */

private handleMotion(boolean active) {
String v = active ? "active" : "inactive"
if (device.currentValue("motion") != v) {
if (txtEnable) log.info "motion is ${v}"
sendEvent(name: "motion", value: v)
}
sendEvent(name: "lastUpdate", value: new Date().format("yyyy-MM-dd HH:mm:ss"))

unschedule(resetMotion)
if (active && (resetSeconds as Integer) > 0) {
    runIn(resetSeconds as Integer, resetMotion)
}

}

def resetMotion() {
if (txtEnable) log.info "motion auto-reset to inactive"
sendEvent(name: "motion", value: "inactive")
}

private sendBattery(Integer pct) {
if (txtEnable) log.info "battery ${pct}%"
sendEvent(name: "battery", value: pct, unit: "%")
}

/* ---------------- commands ---------------- */

def refresh() {
if (logEnable) log.debug "refresh"
List cmds = 

cmds += zigbee.readAttribute(0x0406, 0x0000)   // occupancy
cmds += zigbee.readAttribute(0x0500, 0x0002)   // IAS zone status
cmds += zigbee.readAttribute(0x0001, 0x0021)   // battery %
cmds += zigbee.readAttribute(0x0001, 0x0020)   // battery voltage
return cmds
}

def configure() {
if (logEnable) log.debug "configure"
List cmds = 


// IAS enrollment (harmless if device uses 0x0406 instead)
cmds += zigbee.enrollResponse()
cmds += zigbee.writeAttribute(0x0500, 0x0010, DataType.IEEE_ADDRESS,
                              "${device.hub.zigbeeEui}")

// bind + reporting for both possible paths
cmds += zigbee.configureReporting(0x0406, 0x0000, DataType.BITMAP8, 0, 3600, null)
cmds += zigbee.configureReporting(0x0500, 0x0002, DataType.BITMAP16, 0, 3600, null)
cmds += zigbee.configureReporting(0x0001, 0x0021, DataType.UINT8, 3600, 21600, 1)

cmds += refresh()
return cmds

}

Heph,

Many thanks. Updated the driver and look great. Will test and see results.

John

How do I update this driver. I always used the dropdown list.

If you are referring to my driver, you can copy the code from here (no dropdown list that I know of)

ChatGPT and I cobbled together an "improved" driver for the ThirdReality Smart Presence Sensor R2, for those brave enough to try it. This is based on the original Hubitat R2 driver by @heph.

Testers should press Configure once after assigning the driver, then calibrate with the intended detection area empty (really, you must calibrate).

/**
 * THIRDREALITY Smart Presence Sensor R2 (3RPS01083Z)
 * Version 0.5 BETA
 *
 * Hubitat driver providing:
 *  - 24 GHz mmWave presence as MotionSensor plus custom occupancy
 *  - Native battery percentage
 *  - Radar sensitivity read/write (levels 1-5)
 *  - Manual environment/sensor calibration with calibration-status feedback
 *  - IAS enrollment/reporting diagnostics
 *  - Firmware version reporting and Zigbee OTA update request
 *  - Optional driver-side motion/presence clear timeout
 *  - Optional 30-minute automatic debug-log shutoff
 *
 * Primary presence path:
 *  - IAS Zone cluster 0x0500, Zone Status attribute 0x0002.
 *  - Configure explicitly enables 0x0002 attribute reporting. This was required
 *    on the tested R2 for autonomous occupied/clear events.
 *
 * Compatibility:
 *  - A passive 0x0406 Occupancy Sensing parser is retained for possible firmware
 *    variants, but the driver does not bind or configure that speculative path.
 *
 * Tested hardware:
 *  - THIRDREALITY Smart Presence Sensor R2, model 3RPS01083Z
 *  - Device firmware v1.00.19
 *
 * Calibration:
 *  - On the tested device, 0xFF01/0x0003 reports 1 while calibrating and 0 when
 *    calibration is complete/idle. Calibrate with the intended detection area
 *    empty and leave it empty until Calibration Status returns to "idle".
 *
 * Credits:
 *  - Based on the original Hubitat R2 driver by heph.
 *
 * Version 0.5 BETA:
 *  - Promotes the explicit IAS Zone Status reporting fix validated in v0.4.
 *  - Uses a stable driver namespace rather than embedding the version number.
 *  - Removes duplicate Configure/Refresh reads and other development cruft.
 *  - Removes unused battery-voltage and IAS-zone-type diagnostic parsers.
 *  - Cleans unused locals and reduces routine preference-save log noise.
 *  - Adds clearer CIE-address mismatch diagnostics and ZCL response decoding.
 *  - Refresh remains useful but is lighter than Configure.
 */

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

@Field static final String DRIVER_VERSION = "0.5"

@Field static final Integer CLUSTER_BASIC      = 0x0000
@Field static final Integer CLUSTER_POWER      = 0x0001
@Field static final Integer CLUSTER_OCCUPANCY  = 0x0406   // fallback parser only
@Field static final Integer CLUSTER_IAS_ZONE   = 0x0500
@Field static final Integer CLUSTER_RADAR      = 0xFF01

@Field static final Integer ATTR_SW_BUILD_ID           = 0x4000
@Field static final Integer ATTR_BATTERY_PERCENT       = 0x0021
@Field static final Integer ATTR_OCCUPANCY             = 0x0000
@Field static final Integer ATTR_IAS_ZONE_STATE        = 0x0000
@Field static final Integer ATTR_IAS_ZONE_STATUS       = 0x0002
@Field static final Integer ATTR_IAS_CIE_ADDRESS       = 0x0010
@Field static final Integer ATTR_IAS_ZONE_ID           = 0x0011
@Field static final Integer ATTR_RADAR_CALIBRATION     = 0x0003
@Field static final Integer ATTR_RADAR_SENSITIVITY     = 0x0060

@Field static final String MFG_CODE = "0x1407"

metadata {
    definition(
        name: "THIRDREALITY Smart Presence Sensor R2",
        namespace: "openai",
        author: "OpenAI; based on heph",
        singleThreaded: true
    ) {
        capability "Sensor"
        capability "MotionSensor"
        capability "Battery"
        capability "Refresh"
        capability "Configuration"

        attribute "occupancy", "enum", ["occupied", "clear"]
        attribute "sensorSensitivity", "number"
        attribute "presenceReportingPath", "enum", ["IAS Zone", "Occupancy Sensing"]
        attribute "iasZoneStatus", "string"
        attribute "iasEnrollmentState", "enum", ["enrolled", "not enrolled", "unknown"]
        attribute "iasZoneId", "number"
        attribute "iasCieAddress", "string"
        attribute "iasZoneReporting", "enum", ["configured", "rejected", "unknown"]
        attribute "calibrationStatus", "enum", ["idle", "calibrating", "unknown"]
        attribute "lastUpdate", "string"
        attribute "firmwareVersion", "string"
        attribute "driverVersion", "string"

        command "applyDeviceSettings"
        command "calibrateSensor"
        command "updateFirmware"

        // Manufacturer/model-only fingerprint is intentionally permissive about the
        // cluster list while still targeting the exact R2 model.
        fingerprint manufacturer: "Third Reality, Inc",
            model: "3RPS01083Z",
            deviceJoinName: "THIRDREALITY Smart Presence Sensor R2"
    }

    preferences {
        input name: "radarSensitivity", type: "enum", title: "Radar sensitivity",
            options: [[1:"1 (lowest)"], [2:"2"], [3:"3 (medium)"], [4:"4"], [5:"5 (highest)"]],
            required: false,
            description: "Device setting. Use Apply Device Settings to write the selected value to the R2."

        input name: "motionClearSeconds", type: "number",
            title: "Driver motion/presence clear timeout (seconds)",
            description: "Normally leave at 0 to follow the R2's own clear reports. A value > 0 provides an optional driver-side fallback clear timeout.",
            defaultValue: 0, range: "0..3600"

        input name: "logEnable", type: "bool",
            title: "Enable debug logging", defaultValue: true

        input name: "autoDisableDebugLogging", type: "bool",
            title: "Automatically disable debug logging after 30 minutes",
            description: "Hubitat convention. Turn this OFF when extended debug logging is needed.",
            defaultValue: true

        input name: "txtEnable", type: "bool",
            title: "Enable descriptionText logging", defaultValue: true
    }
}

/* ---------------- lifecycle ---------------- */

def installed() {
    log.info "installed..."
    publishDriverVersion()
    sendEvent(name: "motion", value: "inactive")
    sendEvent(name: "occupancy", value: "clear")
    sendEvent(name: "iasEnrollmentState", value: "unknown")
    sendEvent(name: "iasZoneReporting", value: "unknown")
    sendEvent(name: "calibrationStatus", value: "unknown")
    unschedule("syntheticMotionClear")
}

def updated() {
    log.info "updated..."
    publishDriverVersion()

    Integer clearSeconds = Math.max(0, safeToInt(settings.motionClearSeconds, 0))
    if (logEnable) {
        log.debug "Preferences: debug=${logEnable == true}, autoDebugOff30m=${debugAutoDisableEnabled()}, descriptionText=${txtEnable == true}, driverClearTimeout=${clearSeconds}s"
        log.debug "Radar sensitivity preferences are written only by Apply Device Settings."
    }

    scheduleDebugLoggingAutoOff()
    if (clearSeconds <= 0) unschedule("syntheticMotionClear")
}

def deviceTypeUpdated() {
    if (logEnable) log.debug "deviceTypeUpdated()"
    updated()
    runIn(1, "configure")
}

def logsOff() {
    // Re-check the preference when the scheduled job actually runs. This makes
    // it safe to disable the auto-off preference after a job was already queued.
    if (!debugAutoDisableEnabled()) {
        if (logEnable) log.debug "Scheduled debug-log shutoff skipped because automatic shutoff is disabled."
        return
    }
    if (logEnable) {
        log.warn "debug logging disabled after 30 minutes..."
        device.updateSetting("logEnable", [value: "false", type: "bool"])
    }
}

private Boolean debugAutoDisableEnabled() {
    // A null value can occur before the preference has been explicitly saved
    // after an upgrade. Treat null as the documented default ON.
    Object raw = settings.autoDisableDebugLogging
    if (raw == null) return true
    if (raw instanceof Boolean) return raw
    return raw.toString().equalsIgnoreCase("true")
}

private void scheduleDebugLoggingAutoOff() {
    unschedule("logsOff")
    if (logEnable && debugAutoDisableEnabled()) {
        runIn(1800, "logsOff")
        if (logEnable) log.debug "Debug logging will automatically disable in 30 minutes."
    } else if (logEnable && !debugAutoDisableEnabled()) {
        log.debug "Debug logging automatic shutoff is disabled; debug logging will remain enabled until manually turned off."
    }
}

private void publishDriverVersion() {
    device.updateDataValue("driverVersion", DRIVER_VERSION)
    sendEventIfChanged("driverVersion", DRIVER_VERSION, null, null)
}

/* ---------------- parse ---------------- */

def parse(String description) {
    if (logEnable) log.debug "parse description: ${description}"
    if (!description) return

    // IAS Zone devices may explicitly request enrollment. Respond only to an
    // actual request rather than sending an unsolicited/redundant response
    // every time Configure is pressed.
    if (description.toLowerCase().startsWith("enroll request")) {
        log.warn "IAS enroll request received; sending enroll response..."
        return zigbee.enrollResponse()
    }

    // Hubitat may deliver IAS zone status as a plain text description rather
    // than a map. Handle this before calling parseDescriptionAsMap().
    if (parsePlainIasZoneStatus(description)) return

    Map descMap
    try {
        descMap = zigbee.parseDescriptionAsMap(description)
    } catch (Exception e) {
        log.warn "Unable to parse Zigbee message: ${description}; ${e.message}"
        return
    }

    if (logEnable) log.debug "descMap: ${descMap}"
    if (!descMap) return

    Integer clusterInt = getClusterInt(descMap)
    Integer commandInt = descMap.commandInt != null ?
        safeToInt(descMap.commandInt, -1) : hexToInt(descMap.command, -1)

    // Manufacturer-specific Write Attributes Response.
    if (clusterInt == CLUSTER_RADAR && descMap.attrId == null && commandInt == 0x04) {
        reportRadarWriteStatus(descMap.data as List)
        return
    }

    // IAS Zone Status Change Notification, command 0x00.
    // Payload starts with zoneStatus as uint16 little-endian.
    if (clusterInt == CLUSTER_IAS_ZONE && commandInt == 0x00 && descMap.data?.size() >= 2) {
        Integer zoneStatus = hexToInt("${descMap.data[1]}${descMap.data[0]}", -1)
        if (zoneStatus >= 0) {
            handleIasZoneStatus(zoneStatus)
            return
        }
    }

    if (descMap.attrId != null || descMap.attrInt != null) {
        parseAttributeReport(descMap)

        descMap.additionalAttrs?.each { Map additional ->
            Map merged = [:]
            merged.putAll(additional)
            if (merged.cluster == null) merged.cluster = descMap.cluster
            if (merged.clusterId == null) merged.clusterId = descMap.clusterId
            if (merged.clusterInt == null) merged.clusterInt = clusterInt
            parseAttributeReport(merged)
        }
        return
    }

    if (handleKnownZigbeeResponse(descMap, clusterInt, commandInt)) return

    if (logEnable) {
        log.debug "Unhandled Zigbee message: cluster=${descMap.clusterId ?: descMap.cluster}, command=${descMap.command}, data=${descMap.data}"
    }
}

private Boolean handleKnownZigbeeResponse(Map descMap, Integer clusterInt, Integer commandInt) {
    // ZDO/network-management responses use profile 0x0000. They are normal
    // coordinator/device management traffic and are not sensor-state reports.
    if (descMap?.profileId?.toString()?.equalsIgnoreCase("0000")) {
        if (logEnable) {
            log.debug "Zigbee management response: cluster=${descMap.clusterId ?: descMap.cluster}, data=${descMap.data}"
        }
        return true
    }

    // ZCL Write Attributes Response.
    if (commandInt == 0x04 && descMap.data) {
        String status = descMap.data[0]?.toString()?.toUpperCase()
        String statusName = zclStatusName(status)
        String clusterHex = zigbee.convertToHexString(clusterInt, 4)
        if (status != "00") {
            log.warn "Write Attributes Response for cluster 0x${clusterHex}: status=0x${status} (${statusName})"
        } else if (logEnable) {
            log.debug "Write Attributes Response for cluster 0x${clusterHex}: status=0x${status} (${statusName})"
        }
        return true
    }

    // ZCL Configure Reporting Response.
    if (commandInt == 0x07 && descMap.data) {
        String status = descMap.data[0]?.toString()?.toUpperCase()
        String statusName = zclStatusName(status)
        if (clusterInt == CLUSTER_IAS_ZONE) {
            String reportingState = status == "00" ? "configured" : "rejected"
            sendEventIfChanged(
                "iasZoneReporting", reportingState,
                "${device.displayName} IAS Zone reporting is ${reportingState}", null
            )
        }
        if (logEnable) {
            log.debug "Configure Reporting Response for cluster 0x${zigbee.convertToHexString(clusterInt, 4)}: status=0x${status} (${statusName})"
        }
        return true
    }

    // ZCL Default Response. Payload is original command ID + status.
    if (commandInt == 0x0B && descMap.data) {
        String originalCommand = descMap.data.size() > 0 ? descMap.data[0]?.toString()?.toUpperCase() : "??"
        String status = descMap.data.size() > 1 ? descMap.data[1]?.toString()?.toUpperCase() : "??"
        String statusName = zclStatusName(status)
        if (status != "00") {
            log.warn "Default Response for cluster 0x${zigbee.convertToHexString(clusterInt, 4)} command 0x${originalCommand}: status=0x${status} (${statusName})"
        } else if (logEnable) {
            log.debug "Default Response for cluster 0x${zigbee.convertToHexString(clusterInt, 4)} command 0x${originalCommand}: status=0x${status} (${statusName})"
        }
        return true
    }

    return false
}

private static String zclStatusName(String statusHex) {
    switch (statusHex?.toUpperCase()) {
        case "00": return "Success"
        case "01": return "Failure"
        case "7E": return "Not Authorized"
        case "80": return "Malformed Command"
        case "81": return "Unsupported Cluster Command"
        case "82": return "Unsupported General Command"
        case "85": return "Invalid Field"
        case "86": return "Unsupported Attribute"
        case "87": return "Invalid Value"
        case "88": return "Read Only"
        case "8B": return "Not Found"
        case "8C": return "Unreportable Attribute"
        case "8D": return "Invalid Data Type"
        case "8F": return "Write Only"
        case "93": return "Action Denied"
        case "94": return "Timeout"
        default:   return "Unknown"
    }
}

private Boolean parsePlainIasZoneStatus(String description) {
    String lower = description?.toLowerCase()
    if (!(lower?.startsWith("zone status") || lower?.startsWith("zone report"))) return false

    try {
        def matcher = (description =~ /(?i)0x([0-9a-f]{1,4})/)
        if (!matcher.find()) {
            if (logEnable) log.debug "IAS zone text message had no zone-status hex value: ${description}"
            return true
        }

        Integer zoneStatus = Integer.parseInt(matcher.group(1), 16)
        handleIasZoneStatus(zoneStatus)
    } catch (Exception e) {
        log.warn "Unable to parse IAS zone text message: ${description}; ${e.message}"
    }
    return true
}

private void parseAttributeReport(Map descMap) {
    Integer clusterInt = getClusterInt(descMap)
    Integer attrInt = getAttrInt(descMap)

    if (clusterInt == null || attrInt == null) {
        if (logEnable) log.debug "Attribute report missing cluster/attribute: ${descMap}"
        return
    }

    if (descMap.value == null) {
        if (logEnable) {
            log.debug "No value for cluster 0x${zigbee.convertToHexString(clusterInt, 4)} attr 0x${zigbee.convertToHexString(attrInt, 4)} status=${descMap.status}"
        }
        return
    }

    switch (clusterInt) {
        case CLUSTER_BASIC:
            if (attrInt == ATTR_SW_BUILD_ID) handleFirmwareVersion(descMap.value)
            break

        case CLUSTER_POWER:
            if (attrInt == ATTR_BATTERY_PERCENT) {
                handleBatteryPercentage(descMap.value)
            }
            break

        case CLUSTER_IAS_ZONE:
            if (attrInt == ATTR_IAS_ZONE_STATE) {
                Integer zoneState = hexToInt(descMap.value, -1)
                String enrollment = zoneState == 1 ? "enrolled" :
                    (zoneState == 0 ? "not enrolled" : "unknown")
                sendEventIfChanged(
                    "iasEnrollmentState", enrollment,
                    "${device.displayName} IAS enrollment state is ${enrollment}", null
                )
                if (logEnable) log.debug "IAS Zone State raw value: ${descMap.value} (${enrollment})"
                touchLastUpdate()
            } else if (attrInt == ATTR_IAS_ZONE_STATUS) {
                Integer zoneStatus = hexToInt(descMap.value, -1)
                if (zoneStatus >= 0) handleIasZoneStatus(zoneStatus)
            } else if (attrInt == ATTR_IAS_CIE_ADDRESS) {
                String cie = descMap.value?.toString()?.toUpperCase()
                String hubEui = device.hub.zigbeeEui?.toString()?.toUpperCase()
                if (cie) {
                    sendEventIfChanged(
                        "iasCieAddress", cie,
                        "${device.displayName} IAS CIE address is ${cie}", null
                    )
                    if (hubEui && cie != hubEui) {
                        log.warn "${device.displayName} IAS CIE address ${cie} does not match this hub's Zigbee EUI ${hubEui}"
                    } else if (logEnable) {
                        log.debug "IAS CIE address matches hub Zigbee EUI: ${cie}"
                    }
                    touchLastUpdate()
                }
            } else if (attrInt == ATTR_IAS_ZONE_ID) {
                Integer zoneId = hexToInt(descMap.value, -1)
                if (zoneId >= 0) {
                    sendEventIfChanged(
                        "iasZoneId", zoneId,
                        "${device.displayName} IAS Zone ID is ${zoneId}", null
                    )
                    touchLastUpdate()
                }
            }
            break

        case CLUSTER_OCCUPANCY:
            // Compatibility fallback only. Current R2 definitions use IAS Zone.
            if (attrInt == ATTR_OCCUPANCY) {
                Integer raw = hexToInt(descMap.value, -1)
                if (raw >= 0) handleOccupancyFallback((raw & 0x01) == 0x01)
            }
            break

        case CLUSTER_RADAR:
            if (attrInt == ATTR_RADAR_SENSITIVITY) {
                Integer level = hexToInt(descMap.value, -1)
                if (level >= 1 && level <= 5) {
                    sendEventIfChanged(
                        "sensorSensitivity", level,
                        "${device.displayName} radar sensitivity is ${level}", null
                    )
                    updateSettingIfDifferent("radarSensitivity", level.toString(), "enum")
                    touchLastUpdate()
                } else if (logEnable) {
                    log.debug "Ignoring out-of-range radar sensitivity value: ${descMap.value}"
                }
            } else if (attrInt == ATTR_RADAR_CALIBRATION) {
                Integer raw = hexToInt(descMap.value, -1)
                String status = raw == 1 ? "calibrating" :
                    (raw == 0 ? "idle" : "unknown")
                sendEventIfChanged(
                    "calibrationStatus", status,
                    "${device.displayName} calibration status is ${status}", null
                )
                if (logEnable) log.debug "Sensor calibration attribute response: ${descMap.value} (${status})"
                touchLastUpdate()
            } else if (logEnable) {
                log.debug "Unknown R2 radar attribute 0x${zigbee.convertToHexString(attrInt, 4)} value=${descMap.value}"
            }
            break

        default:
            if (logEnable) {
                log.debug "Ignoring cluster 0x${zigbee.convertToHexString(clusterInt, 4)} attr 0x${zigbee.convertToHexString(attrInt, 4)}"
            }
            break
    }
}

/* ---------------- presence ---------------- */

private void handleIasZoneStatus(Integer zoneStatus) {
    Boolean active = (zoneStatus & 0x0001) != 0
    Boolean batteryLow = (zoneStatus & 0x0008) != 0
    String rawStatus = "0x${zigbee.convertToHexString(zoneStatus & 0xFFFF, 4).toUpperCase()}"

    sendEventIfChanged(
        "iasZoneStatus", rawStatus,
        "${device.displayName} IAS Zone status is ${rawStatus}", null
    )

    sendEventIfChanged(
        "presenceReportingPath", "IAS Zone",
        "${device.displayName} presence reporting path is IAS Zone", null
    )

    if (batteryLow && state.lastIasBatteryLow != true) {
        log.warn "${device.displayName} IAS Zone status indicates low battery"
    }
    state.lastIasBatteryLow = batteryLow

    handlePresence(active, "IAS Zone")
}

private void handleOccupancyFallback(Boolean active) {
    sendEventIfChanged(
        "presenceReportingPath", "Occupancy Sensing",
        "${device.displayName} presence reporting path is Occupancy Sensing", null
    )
    handlePresence(active, "Occupancy Sensing")
}

private void handlePresence(Boolean occupied, String source) {
    Integer clearSeconds = Math.max(0, safeToInt(settings.motionClearSeconds, 0))
    if (occupied) {
        sendEventIfChanged(
            "motion", "active",
            "${device.displayName} motion is active", null
        )
        sendEventIfChanged(
            "occupancy", "occupied",
            "${device.displayName} occupancy is occupied", null
        )

        state.lastOccupiedReportMs = now()

        if (clearSeconds > 0) {
            runIn(clearSeconds, "syntheticMotionClear")
            if (logEnable) {
                log.debug "Scheduled synthetic motion clear in ${clearSeconds} second(s) after ${source} occupied report"
            }
        }
    } else {
        unschedule("syntheticMotionClear")

        sendEventIfChanged(
            "motion", "inactive",
            "${device.displayName} motion is inactive", null
        )
        sendEventIfChanged(
            "occupancy", "clear",
            "${device.displayName} occupancy is clear", null
        )
    }

    // "Last Update" means the last recognized presence report, not merely the
    // last state change. This is especially useful when diagnosing a device
    // repeatedly reporting the same occupied/clear value.
    touchLastUpdate()
}

def syntheticMotionClear() {
    Integer clearSeconds = Math.max(0, safeToInt(settings.motionClearSeconds, 0))
    if (clearSeconds <= 0) return

    Long lastOccupiedMs = state.lastOccupiedReportMs != null ?
        (state.lastOccupiedReportMs as Long) : 0L
    Long elapsedMs = lastOccupiedMs > 0L ? (now() - lastOccupiedMs) : Long.MAX_VALUE
    Long targetMs = clearSeconds * 1000L

    if (elapsedMs < targetMs) {
        Integer remainingSeconds = Math.max(
            1, Math.ceil((targetMs - elapsedMs) / 1000.0d) as Integer
        )
        runIn(remainingSeconds, "syntheticMotionClear")
        return
    }

    Boolean changed = false
    if (sendEventIfChanged(
        "motion", "inactive",
        "${device.displayName} motion is inactive", null
    )) changed = true
    if (sendEventIfChanged(
        "occupancy", "clear",
        "${device.displayName} occupancy is clear", null
    )) changed = true

    if (changed && txtEnable) {
        log.info "${device.displayName} motion/presence was cleared by driver timeout (${clearSeconds}s)"
    }
}

/* ---------------- battery / firmware ---------------- */

private void handleBatteryPercentage(Object rawValue) {
    Integer raw = hexToInt(rawValue, -1)

    // Zigbee batteryPercentageRemaining is 0-200 in 0.5% units; 0xFF = unknown.
    if (raw < 0 || raw == 0xFF) {
        if (logEnable) log.debug "Ignoring invalid/unknown battery percentage value: ${rawValue}"
        return
    }

    Integer pct = Math.max(0, Math.min(100, Math.round(raw / 2.0d) as Integer))
    sendEventIfChanged(
        "battery", pct,
        "${device.displayName} battery is ${pct}%", "%"
    )
    touchLastUpdate()
}

private void handleFirmwareVersion(Object rawValue) {
    String version = decodeZigbeeString(rawValue)
    if (!version) return

    device.updateDataValue("firmware", version)
    sendEventIfChanged(
        "firmwareVersion", version,
        "${device.displayName} firmware version is ${version}", null
    )
    touchLastUpdate()
}

/* ---------------- commands ---------------- */

def refresh() {
    if (logEnable) log.debug "refresh()"
    return refreshReadCommands()
}

def configure() {
    log.info "configure..."
    publishDriverVersion()
    scheduleDebugLoggingAutoOff()
    sendEventIfChanged("iasEnrollmentState", "unknown", null, null)
    sendEventIfChanged("iasZoneReporting", "unknown", null, null)

    List cmds = []

    // Keep the IAS CIE address pointed at the current hub.
    try {
        cmds += zigbee.writeAttribute(
            CLUSTER_IAS_ZONE, ATTR_IAS_CIE_ADDRESS, DataType.IEEE_ADDRESS,
            "${device.hub.zigbeeEui}"
        )
        cmds << "delay 500"
    } catch (Exception e) {
        log.warn "Unable to build IAS CIE-address write: ${e.message}"
    }

    // Critical R2 behavior: explicit Zone Status attribute reporting is needed
    // for autonomous occupied/clear events on the tested firmware.
    cmds += zigbee.configureReporting(
        CLUSTER_IAS_ZONE, ATTR_IAS_ZONE_STATUS, DataType.BITMAP16,
        0, 3600, null
    )
    cmds << "delay 400"

    // Native battery percentage reporting.
    cmds += zigbee.configureReporting(
        CLUSTER_POWER, ATTR_BATTERY_PERCENT, DataType.UINT8,
        3600, 21600, 1
    )
    cmds << "delay 400"

    // Configuration verification plus one normal state refresh. This is kept
    // separate from refresh() so routine Refresh does not repeatedly read IAS
    // enrollment/CIE diagnostics.
    cmds += configurationReadbackCommands()
    return cmds.flatten()
}


def applyDeviceSettings() {
    Integer level = nullableInt(settings.radarSensitivity)
    if (level == null) {
        log.warn "Radar sensitivity is blank; no device setting was written."
        return []
    }

    level = Math.max(1, Math.min(5, level))
    log.info "Applying R2 radar sensitivity level ${level}..."

    List cmds = []
    cmds += zigbee.writeAttribute(
        CLUSTER_RADAR, ATTR_RADAR_SENSITIVITY, DataType.UINT8, level,
        [mfgCode: MFG_CODE]
    )
    cmds << "delay 1000"
    cmds += radarReadCommands()
    return cmds.flatten()
}

def calibrateSensor() {
    log.warn "Starting R2 calibration; keep the intended detection area empty until Calibration Status returns to idle."
    sendEventIfChanged(
        "calibrationStatus", "calibrating",
        "${device.displayName} calibration status is calibrating", null
    )

    List cmds = []
    cmds += zigbee.writeAttribute(
        CLUSTER_RADAR, ATTR_RADAR_CALIBRATION, DataType.UINT8, 1,
        [mfgCode: MFG_CODE]
    )
    return cmds.flatten()
}

def updateFirmware() {
    log.warn "Requesting a Zigbee OTA firmware check/update..."
    return zigbee.updateFirmware()
}

private List refreshReadCommands() {
    List cmds = [
        readAttrCmd(CLUSTER_BASIC, ATTR_SW_BUILD_ID),        "delay 150",
        readAttrCmd(CLUSTER_POWER, ATTR_BATTERY_PERCENT),    "delay 150",
        readAttrCmd(CLUSTER_IAS_ZONE, ATTR_IAS_ZONE_STATUS), "delay 150"
    ]
    cmds += radarReadCommands(true)
    return cmds.flatten()
}

private List configurationReadbackCommands() {
    List cmds = [
        readAttrCmd(CLUSTER_IAS_ZONE, ATTR_IAS_ZONE_STATE),  "delay 150",
        readAttrCmd(CLUSTER_IAS_ZONE, ATTR_IAS_ZONE_ID),     "delay 150",
        readAttrCmd(CLUSTER_IAS_ZONE, ATTR_IAS_CIE_ADDRESS), "delay 150"
    ]
    cmds += refreshReadCommands()
    return cmds.flatten()
}

/* ---------------- manufacturer-specific helpers ---------------- */

private List radarReadCommands(Boolean includeCalibration = false) {
    List cmds = []
    cmds += zigbee.readAttribute(
        CLUSTER_RADAR, ATTR_RADAR_SENSITIVITY,
        [mfgCode: MFG_CODE]
    )
    if (includeCalibration) {
        cmds << "delay 150"
        cmds += zigbee.readAttribute(
            CLUSTER_RADAR, ATTR_RADAR_CALIBRATION,
            [mfgCode: MFG_CODE]
        )
    }
    return cmds.flatten()
}

private void reportRadarWriteStatus(List data) {
    if (!data) return

    if (data.size() == 1 && data[0]?.toString()?.equalsIgnoreCase("00")) {
        if (logEnable) log.debug "R2 radar setting write accepted"
        return
    }

    for (Integer i = 0; i + 2 < data.size(); i += 3) {
        String status = data[i]?.toString()?.toUpperCase()
        if (status == "00") continue

        String attrId = "${data[i + 2]}${data[i + 1]}".toUpperCase()
        log.warn "R2 radar setting write to 0x${attrId} rejected: status=0x${status} (${zclStatusName(status)})"
    }
}

/* ---------------- generic helpers ---------------- */

private void touchLastUpdate() {
    TimeZone tz = location?.timeZone ?: TimeZone.getDefault()
    String stamp = new Date().format("yyyy-MM-dd HH:mm:ss", tz)
    sendEventIfChanged("lastUpdate", stamp, null, null)
}

private Integer getClusterInt(Map descMap) {
    if (descMap?.clusterInt != null) return safeToInt(descMap.clusterInt, -1)

    Object raw = descMap?.cluster ?: descMap?.clusterId
    Integer parsed = hexToInt(raw, -1)
    return parsed >= 0 ? parsed : null
}

private Integer getAttrInt(Map descMap) {
    if (descMap?.attrInt != null) return safeToInt(descMap.attrInt, -1)

    Integer parsed = hexToInt(descMap?.attrId, -1)
    return parsed >= 0 ? parsed : null
}

private void updateSettingIfDifferent(String settingName, Object value, String type) {
    if (value == null) return

    Object current = settings?.get(settingName)
    if (current != null && current.toString() == value.toString()) return

    device.updateSetting(settingName, [value: value, type: type])
}

private Boolean sendEventIfChanged(
    String name,
    Object value,
    String descriptionText = null,
    String unit = null
) {
    if (name == null) return false

    String current = device.currentValue(name)?.toString()
    String incoming = value?.toString()
    if (current == incoming) return false

    Map evt = [name: name, value: value]
    if (descriptionText != null) evt.descriptionText = descriptionText
    if (unit != null) evt.unit = unit

    sendEvent(evt)
    if (txtEnable && descriptionText) log.info descriptionText
    return true
}

private static Integer nullableInt(Object value) {
    if (value == null) return null

    String s = value.toString().trim()
    if (!s || s.equalsIgnoreCase("null")) return null

    try {
        return value instanceof Number ?
            ((Number) value).intValue() : new BigDecimal(s).intValue()
    } catch (ignored) {
        return null
    }
}

private static Integer hexToInt(Object value, Integer defaultValue = 0) {
    try {
        if (value == null) return defaultValue
        if (value instanceof Number) return ((Number) value).intValue()

        String s = value.toString().trim()
        if (!s) return defaultValue
        if (s.startsWith("0x") || s.startsWith("0X")) s = s.substring(2)

        return Integer.parseInt(s, 16)
    } catch (ignored) {
        return defaultValue
    }
}

private static Integer safeToInt(Object value, Integer defaultValue = 0) {
    try {
        if (value == null) return defaultValue
        if (value instanceof Number) return ((Number) value).intValue()

        String s = value.toString().trim()
        if (!s) return defaultValue
        if (s.startsWith("0x") || s.startsWith("0X")) {
            return Integer.parseInt(s.substring(2), 16)
        }

        if (s ==~ /[0-9A-Fa-f]+/ && s.length() > 1 && !(s ==~ /\d+/)) {
            return Integer.parseInt(s, 16)
        }

        return Integer.parseInt(s)
    } catch (ignored) {
        return defaultValue
    }
}

private static String decodeZigbeeString(Object rawValue) {
    if (rawValue == null) return null

    String raw = rawValue.toString().trim()
    if (!raw) return null
    if (!(raw ==~ /(?i)[0-9a-f]+/) || (raw.length() % 2 != 0)) return raw

    try {
        List<Integer> bytes = []
        for (Integer i = 0; i < raw.length(); i += 2) {
            bytes << Integer.parseInt(raw.substring(i, i + 2), 16)
        }

        // Some Zigbee string encodings include the string length as byte zero.
        if (bytes && bytes[0] == bytes.size() - 1) bytes = bytes.drop(1)

        byte[] byteArray = new byte[bytes.size()]
        bytes.eachWithIndex { Integer b, Integer index ->
            byteArray[index] = (byte) (b & 0xFF)
        }

        String decoded = new String(byteArray, "UTF-8")
        decoded = decoded.replace("\u0000", "").trim()
        return decoded ?: raw
    } catch (ignored) {
        return raw
    }
}

private String readAttrCmd(Integer cluster, Integer attrId) {
    return "he rattr 0x${device.deviceNetworkId} 0x${device.endpointId} " +
        "0x${zigbee.convertToHexString(cluster, 4)} " +
        "0x${zigbee.convertToHexString(attrId, 4)} {}"
}