Setting a device capability value from app.js

Hi, I am a new Homey user and making my first app. I created a device with a certain capability of which I can set the value from device.js. However, I calculated a value in app.js (copy & paste code of other existing app) which I want to write to the device capability. Probably it is an easy thing to do but I am missing something. Can someone help me?

Hi I have moved this thread to the develoeprs forum where you will get a better response.

Also :

this.setCapabilityValue('alarm_motion', false).catch(this.error);

That’s how you set it from the Homey.Device instance. Setting it from app.js means that you need to transfer the value from the app instance to the device instance and set it there.

One solution would be to create an event emitter in the app instance, that all device instances subscribe to.

Untested example code:

// app.js
const { EventEmitter } = require('events');
...
class MyApp extends Homey.App {
  onInit() {
    this.eventBus = new EventEmitter();
    ...
  }

  calculateValue() {
    ...
    this.eventBus.emit('new_value', value);
  }
}

// device.js
class MyDevice extends Homey.Device {
  onInit() {
    this.app.eventBus.on('new_value', value => {
      this.setCapabilityValue(...);
    });
    ...
  }
}

Caveat: all device instances will listen for the same new_value event, so if the value is calculated for a specific device, you need to be able to differentiate for which device the value is for.

More info on Node.js’ EventEmitter here.

Thanks @robertklep for your suggestion. I tried it, but it fails in device.js at

this.app.eventBus.on

I get the message “Cannot read property ‘eventBus’ of undefined”. Also when trying:

this.App.eventBus.on
this.MyApp.eventBus.on
this.eventBus.on

Try Homey.app.eventBus (and make sure to add const Homey = require('homey') at the top of device.js).

Thanks! It works now.