How to read and Set the logic variables with HomeyScript?

Hi,

I am writing a script to set my screens on a certain percentage. Therefore I need to set/read the new 2.0 logic variables from Homey Script.

Does anybody know how to do this?

Kind regards,

Marcel

From this post onwards, there’s some discussion on how to set Logic variables.

Thanks!

Found this from google search and this is how I got variables to update:

const variables = await Homey.logic.getVariables()

console.log('variables', variables)
const id = "2df501f3-f1d7-4f40-bbba-6a8e29b51fee" // my variable id 
const dimLevel = await Homey.logic.getVariable({id: id})

const newLevel = dimLevel.value > 0.2 ? dimLevel.value - 0.2 : 0

await Homey.logic.updateVariable({id: dimLevel.id, variable: {value: newLevel}})
1 Like

If you want to look up a variable by name instead of id, you can use lodash like:

const vars = await Homey.logic.getVariables(); 
const myVar = _.find(vars, (o) => o.name === "Variable name");

log(`Changed switch is ${myVar.value}`)

await Homey.logic.updateVariable({id: myVar.id, variable: {value: "foo"}}) 
2 Likes

you really don’t need lodash to convert an object into an array so you can find a variable by a field property. you can just write:

const myVar = Object.values(await Homey.logic.getVariables()).find(({name}) => name === "Variable name");

But lodash.find() is faster :face_with_hand_over_mouth:

I really don’t think so:

The native array and object methods are almost always faster than Lodash, plus they require less memory.

benchmark says otherwise:

✔ lodash.find  5,137,273.76  ops/sec  ±2.87%  (96 runs)  fastest
✔ Array.find   3,212,320.51  ops/sec  ±2.05%  (96 runs)  -37.47%

âž” Fastest is lodash.find

Duh never mind, getVariables() returns an object, I tested incorrectly :sweat_smile: