# Setting Logic Variable by HomeyScript

**URL:** <https://community.homey.app/t/setting-logic-variable-by-homeyscript/14819>\
**Category:** Questions & Help\
**Created:** [June 25, 2019, 3:11pm UTC](https://community.homey.app/t/setting-logic-variable-by-homeyscript/14819 "2019-06-25T15:11:16Z")\
**Posts on this page:** 18\
**Page:** 3

<div class="post-metadata">

**Author:** ![Marcel\_Ubels](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/marcel_ubels/32/18860_2.png) [@Marcel\_Ubels](https://community.homey.app/u/Marcel_Ubels)\
**Post date:** [October 7, 2022, 9:29am UTC](https://community.homey.app/t/setting-logic-variable-by-homeyscript/14819/42 "2022-10-07T09:29:52Z")

</div>

Very nice, now i don’t need to copy/paste al those ID’s. Here an example how i get all those Id’s at once in a script;

```auto
var varName = ['varName0','varName1','varName2'];
var logicId = []
var count = 0;

while(count <= varName.length -1)
{
var Logic = await Homey.logic.getVariables();
let idArr = Object.entries(Logic);
let filtered = idArr.filter(([key, value]) => value.name==varName[count]);
let [[ ,{ id: varNameId }]] = filtered;
logicId.splice(count, 1,varNameId);
count++
}

```

---

<div class="post-metadata">

**Author:** ![Hamster](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/hamster/32/16580_2.png) [@Hamster](https://community.homey.app/u/Hamster)\
**Post date:** [December 27, 2022, 5:09pm UTC](https://community.homey.app/t/setting-logic-variable-by-homeyscript/14819/43 "2022-12-27T17:09:01Z")

</div>

Here I have created two functions which you can add to your scripts.

```auto
//Name of Logic Variable
var name = "TVProgramma";

//Read Logic Var
var value = await ReadLogicVar(name);
console.log("The parameter '"+name+"' has a value '"+value+"'");

//Write Logic Var
var new_value = "NOS Journaal";
await WriteLogicVar(name,new_value);

async function ReadLogicVar(name){
  let Logic = await Homey.logic.getVariables();
  let idArr = Object.entries(Logic);
  let filtered = idArr.filter(([key,value]) => value.name==name);
  let [[,{id:varID}]] = filtered;

  var varArr = await Homey.logic.getVariable({id:varID});

  return varArr.value;
}

async function WriteLogicVar(name,value){
  let Logic = await Homey.logic.getVariables();
  let idArr = Object.entries(Logic);
  let filtered = idArr.filter(([key,value]) => value.name==name);
  let [[,{id:varID}]] = filtered;
  
  var varArr = await Homey.logic.getVariable({id:varID});

  if (typeof(value) == varArr.type){
    await Homey.logic.updateVariable({id:varID,variable:{value:value}})
    //console.log("Value has been updated")
    return true;
  }
  else{
    console.log("New value has the wrong type! Expected type is '"+varArr.type+"', not '"+typeof(value)+"'. Value has NOT been updated!")
    return false;
  }
}

```

---

<div class="post-metadata">

**Author:** ![Eko\_taas](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/eko_taas/32/74256_2.png) [@Eko\_taas](https://community.homey.app/u/Eko_taas)\
**Post date:** [November 25, 2023, 2:08pm UTC](https://community.homey.app/t/setting-logic-variable-by-homeyscript/14819/44 "2023-11-25T14:08:55Z")

</div>

ReadLogicVar and WriteLogicVar functions seems very useful to me as has been using JSONs as arguments earlier, but as many data needed also in trends decided to recode current approach with these funtions

Can someone advice how to make these functions “global”, so all of my codes/Scripts would be able to use them w/o repeating same in each one?

---

<div class="post-metadata">

**Author:** ![robertklep](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/robertklep/32/160628_2.png) [@robertklep](https://community.homey.app/u/robertklep)\
**Post date:** [November 25, 2023, 2:20pm UTC](https://community.homey.app/t/setting-logic-variable-by-homeyscript/14819/45 "2023-11-25T14:20:32Z")

</div>

> [@Eko\_taas](#):
>
> Can someone advice how to make these functions “global”, so all of my codes/Scripts would be able to use them w/o repeating same in each one?

~~You can’t.~~

Okay, you can, with a hack:

```auto
// homeyscript-a.js
_.myFunc = function() { ... };

// homeyscript-b.js
_.myFunc();

```

However, this requires `homeyscript-a.js` to be run first, otherwise `_.myFunc()` doesn’t exist.

It’s also a hack because it changes the `_` object (which is the Lodash module that is made available to every script).

---

<div class="post-metadata">

**Author:** ![Eko\_taas](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/eko_taas/32/74256_2.png) [@Eko\_taas](https://community.homey.app/u/Eko_taas)\
**Post date:** [November 25, 2023, 6:15pm UTC](https://community.homey.app/t/setting-logic-variable-by-homeyscript/14819/46 "2023-11-25T18:15:59Z")

</div>

Excelent.

Sufficient to run 2nd one only once at star-up of Homey?

---

<div class="post-metadata">

**Author:** ![robertklep](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/robertklep/32/160628_2.png) [@robertklep](https://community.homey.app/u/robertklep)\
**Post date:** [November 25, 2023, 6:19pm UTC](https://community.homey.app/t/setting-logic-variable-by-homeyscript/14819/47 "2023-11-25T18:19:18Z")

</div>

The first one (which declares the function and makes it available to other scripts) can be run once at startup.

---

<div class="post-metadata">

**Author:** ![Eko\_taas](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/eko_taas/32/74256_2.png) [@Eko\_taas](https://community.homey.app/u/Eko_taas)\
**Post date:** [November 26, 2023, 4:36pm UTC](https://community.homey.app/t/setting-logic-variable-by-homeyscript/14819/49 "2023-11-26T16:36:12Z")

</div>

Got bit mixed results:  
This is working fine (i.e. value changed as planned:

> \_.myWriteLogicVar(“Test\_Var”,“abcd”)

where (as conbination from above messages):

> //myWriteLogicVar
> 
> \_.myWriteLogicVar = async function (name,value) {
> 
> let Logic = await Homey.logic.getVariables();  
> let idArr = Object.entries(Logic);  
> let filtered = idArr.filter(([key,value]) =\> value.name==name);  
> let [[,{id:varID}]] = filtered;
> 
> var varArr = await Homey.logic.getVariable({id:varID});
> 
> if (typeof(value) == varArr.type){  
> await Homey.logic.updateVariable({id:varID,variable:{value:value}})  
> [//console.log](https://console.log)(“Value has been updated”)  
> return true;  
> }  
> else{  
> console.log(“New value has the wrong type! Expected type is '”+varArr.type+“', not '”+typeof(value)+“'. Value has NOT been updated!”)  
> return false;  
> }  
> }

But having issue with reading-test:

> let value = \_.myReadLogicVar(“Test\_Var”)  
> console.log(“value :”, value)

and (with similar mods):

> //myReadLogicVar
> 
> \_.myReadLogicVar = async function (name){
> 
> let Logic = await Homey.logic.getVariables();  
> let idArr = Object.entries(Logic);  
> let filtered = idArr.filter(([key,value]) =\> value.name==name);  
> let [[,{id:varID}]] = filtered;
> 
> var varArr = await Homey.logic.getVariable({id:varID});
> 
> return varArr.value;  
> }

but getting only ('-marks added to show full message)):

> value : Promise { ‘\<pending’\> }

Any quickfix?

---

<div class="post-metadata">

**Author:** ![robertklep](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/robertklep/32/160628_2.png) [@robertklep](https://community.homey.app/u/robertklep)\
**Post date:** [November 26, 2023, 4:50pm UTC](https://community.homey.app/t/setting-logic-variable-by-homeyscript/14819/50 "2023-11-26T16:50:40Z")

</div>

Since `myReadLogicVar` is marked `async`, it will always return a promise, which means you have to use `await` to retrieve the value:

```auto
let value = await _.myReadLogicVar("Test_Var");
console.log("value :", value)

```

---

<div class="post-metadata">

**Author:** ![Eko\_taas](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/eko_taas/32/74256_2.png) [@Eko\_taas](https://community.homey.app/u/Eko_taas)\
**Post date:** [November 26, 2023, 5:11pm UTC](https://community.homey.app/t/setting-logic-variable-by-homeyscript/14819/51 "2023-11-26T17:11:39Z")

</div>

> [@robertklep](#):
>
> `await `

Thanks, made the trick… now both works like a dream 🙂

---

<div class="post-metadata">

**Author:** ![Eko\_taas](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/eko_taas/32/74256_2.png) [@Eko\_taas](https://community.homey.app/u/Eko_taas)\
**Post date:** [November 26, 2023, 5:20pm UTC](https://community.homey.app/t/setting-logic-variable-by-homeyscript/14819/52 "2023-11-26T17:20:23Z")

</div>

Would be also great to automatize even creation of variables - e.g. when creating identical “environment”.

i.e. Any command I could use in script to create variable named based on text-combo like “def1”&“def2”&“def3”.

---

<div class="post-metadata">

**Author:** ![Eko\_taas](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/eko_taas/32/74256_2.png) [@Eko\_taas](https://community.homey.app/u/Eko_taas)\
**Post date:** [November 28, 2023, 6:49pm UTC](https://community.homey.app/t/setting-logic-variable-by-homeyscript/14819/53 "2023-11-28T18:49:25Z")

</div>

Just is case some other newbees (like me) around, made one also for sensors (as need those values as well in several scripts), combined above advice and Homey example-script:

> \_.myReadSensor = async function (sensorName, capabilityName) {  
> const devices = await Homey.devices.getDevices();
> 
> for (const device of Object.values(devices)) {  
> if (!device.capabilitiesObj || device.class !== ‘sensor’) continue;
> 
> ```
> if (device.name === sensorName) {
> const sensorCapability = device.capabilitiesObj[capabilityName];
> if (sensorCapability) {
> return sensorCapability.value;
> } else {
> return null; 
> }
> }
> 
> ```
> 
> }  
> return null;  
> }

---

<div class="post-metadata">

**Author:** ![ducktales](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/ducktales/32/98541_2.png) [@ducktales](https://community.homey.app/u/ducktales)\
**Post date:** [January 20, 2024, 10:01am UTC](https://community.homey.app/t/setting-logic-variable-by-homeyscript/14819/54 "2024-01-20T10:01:54Z")

</div>

To get a variable you can use the `filter` property of `getVariables()`.

```js
_.myReadLogicVar = async function ( name ) {
  return Homey.logic.getVariables( { filter: { name } } ).then( itm => Object.values( itm )[0] );
};

```

The same goes for `getDevices()`.

```js
_.myReadSensor = async function ( sensorName, capabilityName ) {
  return Homey.devices.getDevices( { filter: { name: sensorName, class: 'sensor' } } )
    .then( itm => Object.values( itm )[0] )
    .then( itm => itm.capabilitiesObj?.[capabilityName]?.value ?? null );
};

```

---

<div class="post-metadata">

**Author:** ![Eko\_taas](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/eko_taas/32/74256_2.png) [@Eko\_taas](https://community.homey.app/u/Eko_taas)\
**Post date:** [January 28, 2024, 6:48am UTC](https://community.homey.app/t/setting-logic-variable-by-homeyscript/14819/55 "2024-01-28T06:48:15Z")

</div>

Looks great, need to test soonest 🙂

Would it be possible also to simplify write commands with filtering, pls ?

---

<div class="post-metadata">

**Author:** ![ducktales](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/ducktales/32/98541_2.png) [@ducktales](https://community.homey.app/u/ducktales)\
**Post date:** [March 2, 2024, 2:11am UTC](https://community.homey.app/t/setting-logic-variable-by-homeyscript/14819/56 "2024-03-02T02:11:25Z")

</div>

Sure. Note that you don’t need the type checking, because Homey will throw an ‘invalid\_value\_type’ error. Though you can catch it if you want to adjust your scripts behavior in that case.

```js
_.myWriteLogicVar = async function ( name, value ) {
  const thevar = await _.myReadLogicVar( name );
  return Homey.logic.updateVariable( {
    id: thevar.id,
    variable: { value },
  } );
};

```

Use it like this:

```js
await _.myWriteLogicVar( 'Test stuff', 123 );

```

---

<div class="post-metadata">

**Author:** ![ducktales](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/ducktales/32/98541_2.png) [@ducktales](https://community.homey.app/u/ducktales)\
**Post date:** [June 9, 2024, 7:43pm UTC](https://community.homey.app/t/setting-logic-variable-by-homeyscript/14819/57 "2024-06-09T19:43:47Z")

</div>

The `filter` property doesn’t work anymore for me. So here is a rewrite:

```js
_.myReadLogicVar = async function ( name ) {
  const vars = await Homey.logic.getVariables();
  const key = _.findKey( vars, o => o.name === name );
  return vars[key];
};

```

```js
_.myReadSensor = async function ( sensorName, capabilityName ) {
  const devices = await Homey.devices.getDevices();
  const key = _.findKey( devices, o => ( o.name === sensorName && o.class === 'sensor' ) );
  return devices[key]?.capabilitiesObj?.[capabilityName].value ?? null;
};

```

---

<div class="post-metadata">

**Author:** ![Andreas\_Kjork](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/andreas_kjork/32/8354_2.png) [@Andreas\_Kjork](https://community.homey.app/u/Andreas_Kjork)\
**Post date:** [October 3, 2024, 2:10pm UTC](https://community.homey.app/t/setting-logic-variable-by-homeyscript/14819/58 "2024-10-03T14:10:22Z")

</div>

Hi. Im trying to make a script. I want to get the time when a flow starts, for example, the sun rises → run script → the the script updates a variable named Tid,

I want to use that variable in another flow

---

<div class="post-metadata">

**Author:** ![Eko\_taas](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/eko_taas/32/74256_2.png) [@Eko\_taas](https://community.homey.app/u/Eko_taas)\
**Post date:** [November 15, 2024, 2:47pm UTC](https://community.homey.app/t/setting-logic-variable-by-homeyscript/14819/59 "2024-11-15T14:47:31Z")

</div>

Not sure if you still look for this…

If name always the same, then tag would do? I use them to pass info between scripts (e.g. if all OK / pass other data). Also avail. for flows (logic cards) when ones created…

On script-examples (at least in my HP2023) was easy to catch:

> - This script will create a few Tags for use in Flow.
> - It will remove them after 5 seconds.  
> // Create Tags  
> log(‘Creating My String…’);  
> await tag(‘My String’, ‘abcdef’);  
> log(‘Creating My Number…’);  
> await tag(‘My Number’, 123);  
> log(‘Creating My Boolean…’);  
> await tag(‘My Boolean’, true);
> 
> // Wait 15s  
> for (let i = 0; i \< 5; i++) {  
> log(‘.’);  
> await wait(1000); // in milliseconds  
> }
> 
> // Delete Tags  
> log(‘Deleting My String…’);  
> await tag(‘My String’, null);  
> log(‘Deleting My Number…’);  
> await tag(‘My Number’, null);  
> log(‘Deleting My Boolean…’);  
> await tag(‘My Boolean’, null);

---

<div class="post-metadata">

**Author:** ![Andreas\_Kjork](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/andreas_kjork/32/8354_2.png) [@Andreas\_Kjork](https://community.homey.app/u/Andreas_Kjork)\
**Post date:** [November 15, 2024, 3:10pm UTC](https://community.homey.app/t/setting-logic-variable-by-homeyscript/14819/60 "2024-11-15T15:10:11Z")

</div>

Thanks

[Previous page](https://community.homey.app/t/setting-logic-variable-by-homeyscript/14819.md?page=2)
