Hi,
I have an app with a device that has a measure_battery capability. I created a Web API GET handler as described in Web API | Homey Apps SDK.
There is a method batteryStatus in the /api.js
file as it is for the getSomething method from the documentation.
My hardware device will make a GET request to this web api with the query parameters .../batteryStatus?deviceId=xxx&voltage=xxx
So far everything works fine. But how can I get the device by the given deviceId to update the capability value?
kind regards,
Christian
You need to retrieve the device instance and call setCapabilityValue
on it. I’m not sure if you can access ManagerDrivers
from the API, so it would be easiest to call an app method from your API endpoint:
// api.js
async setBatteryStatus({ homey, query }) {
return homey.app.setBatteryStatus(query.deviceId, query.voltage);
}
// app.js
class MyApp extends Homey.App {
...
async setBatteryStatus(deviceId, voltage) {
for (const [ driverId, driver ] in Object.entries(this.homey.drivers.getDrivers())) {
for (const device of await driver.getDevices()) {
if (device.id === device.getId()) {
await device.setCapabilityValue('measure_battery', voltage);
return true;
}
}
}
return false;
}
(untested)
Sadly the way to retrieve a device by id in the SDK is hopelessly convoluted and inconsistent (getDrivers()
returns an object, getDevices()
returns an array )
FWIW, semantically speaking you should use either PUT
or POST
instead of GET
, but I assume there’s a reason you want to use the latter.
1 Like
Thank you for your answer Robert.
I have now found a solution to access the device. I am not sure if it is the right solution, but it works.
async getDeviceById(homey, deviceId) {
const driver = await homey.drivers.getDriver("<my.device.id>");
let devices = await driver.getDevices();
...iterate over devices and retrieve the device...