Subscribing to device states from API

I am trying to make my first app. After a couple of hours I finally figured out how to grab information from devices not in my app. But I want to make a trigger based of changes to other devices. How can I subscribe to them?

I have been looking at registerCapabilityListener and registerMultipleCapabilityListener, but I cant really get them to work (from the https://apps-sdk-v3.developer.homey.app)

Here is small sample just to illustrate why I am trying to do:

'use strict';

const Homey = require('homey');
const { HomeyAPI } = require('homey-api');

class MyApp extends Homey.App {

  async onInit() {
    this.homeyApi = await HomeyAPI.createAppAPI({
      homey: this.homey,
    });

    const deviceId = "<someid>";

    const testDevice = await this.homeyApi.devices.getDevice({ id: deviceId });
    this.log(testDevice);

    const measurePowerValue = await this.homeyApi.devices.getCapabilityValue({ deviceId: deviceId, capabilityId: "measure_power" });
    this.log(`${deviceId}: measure_power value: ${measurePowerValue}`);


    // attempt at something
    this.testDevice.registerCapabilityListener('measure_power', async (value, opts) =>{
      this.log('value', value);
      this.log('opts', opts);
    });

    // another attempt at something
        testDevice.on('capability.measure_power', (newValue, oldValue) => {
          this.log(`value changed from ${oldValue}W to ${newValue}W`);
          this._onDeviceUpdate().catch(err => this.error('Error in HAN measure_power update handler:', err));
        });
        this.listeners.push({ device: testDevice, capability: 'measure_power' });

    this.log('MyApp initialized');

  }

}

module.exports = MyApp;

Is this even possible, or do I have to rely on intervals?

There are two distinct API’s: to manage the devices your app created, you use the SDK. To manage devices from other apps, you use the Web API.

To listen for changes on capabilities from devices not managed by your app, you need to use the Web API device.makeCapabilityInstance().

Nice, exactly what I was looking for, Thanks :smiley:

Adding an example here for others:

'use strict';

const Homey = require('homey');
const { HomeyAPI } = require('homey-api');

class MyApp extends Homey.App {

  async onInit() {
    this.homeyApi = await HomeyAPI.createAppAPI({
      homey: this.homey,
    });

    const deviceId = "<someid>";

    const testDevice = await this.homeyApi.devices.getDevice({ id: deviceId });
    this.log(testDevice);

    testDevice.makeCapabilityInstance('measure_power', value =>{
      this.log('Device measure_power changed to:', value);
    });

    this.log('MyApp initialized');

  }

}

module.exports = MyApp;
2 Likes