# HomeyScript - Dead device checks

**URL:** <https://community.homey.app/t/homeyscript-dead-device-checks/109584>\
**Category:** Questions & Help\
**Tags:** homeyscript\
**Created:** [May 9, 2024, 10:55am UTC](https://community.homey.app/t/homeyscript-dead-device-checks/109584 "2024-05-09T10:55:36Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![mikkel\_Antonsen](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/mikkel_antonsen/32/78910_2.png) [@mikkel\_Antonsen](https://community.homey.app/u/mikkel_Antonsen)\
**Post date:** [May 9, 2024, 10:55am UTC](https://community.homey.app/t/homeyscript-dead-device-checks/109584/1 "2024-05-09T10:55:36Z")

</div>

I have had some challenges with devices being “dead” as in not reporting updates or actually being dead. Primairly the problem has been related to zigbee devices which is reporting temperature which again is used as input to advanced flows to control temperature. It ends up being quite elaborate and I am wondering if there is some better way to do this. Process consist of a homey flow which triggers scripts where the output from the script is then used to determine if action should be taken to check the device ( meaning restart etc manually).

```auto
// Get all Zigbee devices and convert to array
const zigbeeDevicesArray = Object.values(await Homey.devices.getDevices());

// Filter Zigbee devices based on the 'measure_temperature' capability and a specific driver ID
const zigbeeFilteredDevices = zigbeeDevicesArray.filter(device =>
  device.capabilitiesObj &&
  device.capabilitiesObj.measure_temperature &&
  device.driverId === 'homey:app:com.xiaomi-mi:weather' // Filtering to include only Xiaomi Mi weather devices
);

// Map Zigbee devices to include name and last update information from all relevant capabilities
const zigbeeDeviceInfoArray = zigbeeFilteredDevices.map(device => {
  const temperatureCapability = device.capabilitiesObj.measure_temperature;
  const humidityCapability = device.capabilitiesObj.measure_humidity;
  const pressureCapability = device.capabilitiesObj.measure_pressure;

  const tempUpdated = new Date(temperatureCapability.lastUpdated);
  const humidityUpdated = humidityCapability ? new Date(humidityCapability.lastUpdated) : tempUpdated;
  const pressureUpdated = pressureCapability ? new Date(pressureCapability.lastUpdated) : tempUpdated;
  const mostRecentUpdate = new Date(Math.max(tempUpdated, humidityUpdated, pressureUpdated));

  const formattedMostRecentDate = new Intl.DateTimeFormat('en-GB', {
    year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit', second: '2-digit',
    timeZone: 'Europe/Oslo',
    timeZoneName: 'short'
  }).format(mostRecentUpdate);

  return {
    name: device.name,
    lastUpdated: formattedMostRecentDate,
    lastUpdatedRaw: mostRecentUpdate
  };
});

// Find the Zigbee device with the oldest temperature update
const oldestZigbeeDevice = zigbeeDeviceInfoArray.reduce((oldest, device) => {
  return (!oldest || device.lastUpdatedRaw < oldest.lastUpdatedRaw) ? device : oldest;
}, null);

// Actions based on the found oldest device
if (oldestZigbeeDevice) {
  // Calculate the number of hours since the last update of the oldest device
  const currentTime = new Date();
  const zigbeeDevice_hoursSinceUpdate = Math.round(
    (currentTime - oldestZigbeeDevice.lastUpdatedRaw) / (1000 * 60 * 60)
  );

  // Set tags for Homey flow, ensuring they are descriptive and protocol-specific
  await tag('zigbee_oldestDeviceName', oldestZigbeeDevice.name);
  await tag('zigbee_oldestReadingDate', oldestZigbeeDevice.lastUpdated);
  await tag('zigbee_hoursSinceLastUpdate', zigbeeDevice_hoursSinceUpdate);

  // Return values for testing and further use in flows or debugging
  return {
    zigbee_oldestDeviceName: oldestZigbeeDevice.name,
    zigbee_oldestReadingDate: oldestZigbeeDevice.lastUpdated,
    zigbee_hoursSinceLastUpdate: zigbeeDevice_hoursSinceUpdate
  };
} else {
  log('No Zigbee devices found with temperature measurement capabilities from Xiaomi Mi weather.');
  return 'No Zigbee devices found';
}

```

 ![image](https://us1.discourse-cdn.com/flex025/uploads/athom/original/3X/9/b/9b8eb013e4df26b40b59b63119d18e79a695925f.jpeg)

---

<div class="post-metadata">

**Author:** ![Sharkys](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/sharkys/32/54029_2.png) [@Sharkys](https://community.homey.app/u/Sharkys)\
**Post date:** [May 9, 2024, 11:15am UTC](https://community.homey.app/t/homeyscript-dead-device-checks/109584/2 "2024-05-09T11:15:00Z")

</div>

> [@A script to check sensor last update](https://community.homey.app/t/a-script-to-check-sensor-last-update/63142/39):
>
> As there is for some time options to see Lastseen timestamp for Zigbee devices, here is the script for Zigbee devices only, which might be more accurate for Zigbee devices. Thanks @Caseda for your overview script wink // Version 0.2 // Script checks LastSeen property of Zigbee device // Using 2 hours default threshold // Thanks Caseda for [Homey Pro] overview script, which this was originally inspired by // Thanks to ChatGPT for consultations ;-) const NotReportingThreshold = 2; // 2 hours c…

---

<div class="post-metadata">

**Author:** ![mikkel\_Antonsen](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/mikkel_antonsen/32/78910_2.png) [@mikkel\_Antonsen](https://community.homey.app/u/mikkel_Antonsen)\
**Post date:** [May 9, 2024, 12:10pm UTC](https://community.homey.app/t/homeyscript-dead-device-checks/109584/3 "2024-05-09T12:10:15Z")

</div>

thanks. So this script basically does the same I guess.

---

<div class="post-metadata">

**Author:** ![Peter\_Kawa](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/peter_kawa/32/173848_2.png) [@Peter\_Kawa](https://community.homey.app/u/Peter_Kawa)\
**Post date:** [May 9, 2024, 5:07pm UTC](https://community.homey.app/t/homeyscript-dead-device-checks/109584/4 "2024-05-09T17:07:42Z")

</div>

Of course sensors shouldn’t go silent to start with.  
Do you happen to have Aqara sensors and Ikea tradfri lights in Homey’s zigbee mesh?  
This combo caused the Aqara’s to go silent @ Pro 2019.  
Replacing the Ikea with Lidl lights solved it.

---

<div class="post-metadata">

**Author:** ![Marius\_Stensrod](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/marius_stensrod/32/56540_2.png) [@Marius\_Stensrod](https://community.homey.app/u/Marius_Stensrod)\
**Post date:** [May 10, 2024, 3:38pm UTC](https://community.homey.app/t/homeyscript-dead-device-checks/109584/5 "2024-05-10T15:38:07Z")

</div>

What is the solution for Z-Wave? I see you have a script for it, but the script you have published is only for ZigBee with Aqara app as i see it.

---

<div class="post-metadata">

**Author:** ![Sharkys](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/sharkys/32/54029_2.png) [@Sharkys](https://community.homey.app/u/Sharkys)\
**Post date:** [May 10, 2024, 10:11pm UTC](https://community.homey.app/t/homeyscript-dead-device-checks/109584/6 "2024-05-10T22:11:45Z")

</div>

> [@Marius\_Stensrod](#):
>
> What is the solution for Z-Wave?

Not directly for ZWAVE, but for anything else this can be used :

> [@A script to check sensor last update](https://community.homey.app/t/a-script-to-check-sensor-last-update/63142/25):
>
> Updated script I posted above - added counter of non responding devices - eg, in case you would like to initiate some action based on number of not-responding devices - please note this is the version I’m using, so feel free to change relevant variables below the section // Filter devices to check Changelog : 0.1 - update - converting notReportingCount to a number - if you used previous version of script, delete tag by await tag(‘notReportingCount’, null);\* 0.2 - added filtering based on dev…

_Z-Wave do not have “Last seen” data available, so it can be based only on capabilities update date._

---

<div class="post-metadata">

**Author:** ![Marius\_Stensrod](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/marius_stensrod/32/56540_2.png) [@Marius\_Stensrod](https://community.homey.app/u/Marius_Stensrod)\
**Post date:** [May 10, 2024, 10:29pm UTC](https://community.homey.app/t/homeyscript-dead-device-checks/109584/7 "2024-05-10T22:29:50Z")

</div>

> [@Sharkys](#):
>
> Z-Wave do not have “Last seen” data available, so it can be based only on capabilities update date

Yeah, that is right. That’s why i was asking for the Z-Wave . Maybe @mikkel_Antonsen , do now, something we do not 😊 Ps @Sharkys : you should update your script. “DriverUri” does not work for people that are adding new script. “ownerUri” works better.

---

<div class="post-metadata">

**Author:** ![Peter\_Kawa](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/peter_kawa/32/173848_2.png) [@Peter\_Kawa](https://community.homey.app/u/Peter_Kawa)\
**Post date:** [May 10, 2024, 11:38pm UTC](https://community.homey.app/t/homeyscript-dead-device-checks/109584/8 "2024-05-10T23:38:11Z")

</div>

> [@Marius\_Stensrod](#):
>
> “DriverUri” does not work for people that are adding new script. “ownerUri” works better.

It might be very possible you are using the test version of Homeyscript?  
Please use the stable version when you are not busy or wanting to test the script, now it’s all becoming very confusing imho  
I think when HS app test version gets promoted to stable, we can discuss what does not work anymore in existing scripts added as new scripts?  
Just a thought.

> [@HomeyScript looking for testers](https://community.homey.app/t/homeyscript-looking-for-testers/109249/1):
>
> We are looking for some test users for the new HomeyScript version [HomeyScript | Homey](https://homey.app/en-nl/app/com.athom.homeyscript/HomeyScript/test/) that uses our new [homey-api - npm](https://www.npmjs.com/package/homey-api) library under the hood for new scripts.
> 
> All old scripts will keep working and can be upgraded but it’s not necessary. To upgrade scripts the following guide can be followed. [Tutorial: Migrating deprecated scripts - HomeyScript (athombv.github.io)](https://athombv.github.io/com.athom.homeyscript/tutorial-migrate.html)
> 
> This has been a pain point for some time since the web api docs have been for our new api but HomeyScript was still using the old one.
> 
> Let us know if you encounter any bugs or if anything is unclear.

---

<div class="post-metadata">

**Author:** ![Sharkys](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/sharkys/32/54029_2.png) [@Sharkys](https://community.homey.app/u/Sharkys)\
**Post date:** [May 11, 2024, 6:59am UTC](https://community.homey.app/t/homeyscript-dead-device-checks/109584/9 "2024-05-11T06:59:40Z")

</div>

> [@Marius\_Stensrod](#):
>
> you should update your script.

I have it actually already updated locally, both of them but there is existing issue which Athom shall address. Waiting for their actions until HomeyScript 3.5.2 will be released.

---

<div class="post-metadata">

**Author:** ![mikkel\_Antonsen](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/mikkel_antonsen/32/78910_2.png) [@mikkel\_Antonsen](https://community.homey.app/u/mikkel_Antonsen)\
**Post date:** [August 11, 2024, 8:00am UTC](https://community.homey.app/t/homeyscript-dead-device-checks/109584/10 "2024-08-11T08:00:27Z")

</div>

I have done it this way 🙂 Seems to work fine

```auto
async function fetchOldestZWaveDeviceDetails() {
    // Get all Z-Wave devices and convert to array
    const zWaveDevicesArray = Object.values(await Homey.devices.getDevices());

    // Filter Z-Wave devices based on the ‘measure_temperature’ capability and the specific driver ID for Z-TRM3
    const zWaveFilteredDevices = zWaveDevicesArray.filter(device =>
      device.capabilitiesObj &&
      device.capabilitiesObj.measure_temperature &&
      device.driverId === 'homey:app:no.thermofloor:Z-TRM3'
    );

    // Check if any devices are found after filtering
    if (zWaveFilteredDevices.length === 0) {
        console.log('No Z-Wave devices found with temperature measurement capabilities for the specified driver.');
        return 'No Z-Wave devices found';
    }

    // Map Z-Wave devices to include name and last update information from all relevant capabilities
    const zWaveDeviceInfoArray = zWaveFilteredDevices.map(device => {
      const temperatureCapability = device.capabilitiesObj.measure_temperature;
      const humidityCapability = device.capabilitiesObj.measure_humidity;
      const pressureCapability = device.capabilitiesObj.measure_pressure;

      const tempUpdated = new Date(temperatureCapability.lastUpdated);
      const humidityUpdated = humidityCapability ? new Date(humidityCapability.lastUpdated) : tempUpdated;
      const pressureUpdated = pressureCapability ? new Date(pressureCapability.lastUpdated) : tempUpdated;
      const mostRecentUpdate = new Date(Math.max(tempUpdated, humidityUpdated, pressureUpdated));

      const formattedMostRecentDate = new Intl.DateTimeFormat('en-GB', {
        year: 'numeric', month: '2-digit', day: '2-digit',
        hour: '2-digit', minute: '2-digit', second: '2-digit',
        timeZone: 'Europe/Oslo',
        timeZoneName: 'short'
      }).format(mostRecentUpdate);

      return {
        name: device.name,
        lastUpdated: formattedMostRecentDate,
        lastUpdatedRaw: mostRecentUpdate
      };
    });

    // Find the Z-Wave device with the oldest temperature update
    const oldestZWaveDevice = zWaveDeviceInfoArray.reduce((oldest, device) => {
      return (!oldest || device.lastUpdatedRaw < oldest.lastUpdatedRaw) ? device : oldest;
    });

    // Calculate the number of hours since the last update of the oldest device
    const currentTime = new Date();
    console.log(`Current Time: ${currentTime.toISOString()}`);
    console.log(`Last Updated: ${oldestZWaveDevice.lastUpdatedRaw.toISOString()}`);

    if (isNaN(oldestZWaveDevice.lastUpdatedRaw.getTime())) {
        console.log("Invalid date detected for last update.");
        return 'Invalid date';
    }

    const zWaveDevice_hoursSinceUpdate = Math.round(
      (currentTime - oldestZWaveDevice.lastUpdatedRaw) / (1000 * 60 * 60)
    );

    if (zWaveDevice_hoursSinceUpdate < 0) {
        console.log("Detected negative hours since last update, which may indicate future timestamp in device data.");
    }

    // Set tags for Homey flow, ensuring they are descriptive and protocol-specific
    await tag('oldest_zwave_DeviceName', oldestZWaveDevice.name);
    await tag('oldest_zwave_ReadingDate', oldestZWaveDevice.lastUpdated);
    await tag('z_wavedevice_hourssinceupdate', zWaveDevice_hoursSinceUpdate);

    // Log details for further actions or debugging
    console.log(`Oldest Z-Wave device details: Name - ${oldestZWaveDevice.name}, Last Update - ${oldestZWaveDevice.lastUpdated}, Hours Since Last Update - ${zWaveDevice_hoursSinceUpdate}`);

    // Return a structured object with relevant details
    return {
        oldest_zwave_DeviceName: oldestZWaveDevice.name,
        oldest_zwave_ReadingDate: oldestZWaveDevice.lastUpdated,
        z_wavedevice_hourssinceupdate: zWaveDevice_hoursSinceUpdate
    };
}

// Execute the function
fetchOldestZWaveDeviceDetails().then(details => {
    console.log("Z-Wave device details fetched successfully.");
    console.log("Returned:", details);
});

```
