Setting Logic Variable by HomeyScript

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

//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;
  }
}
4 Likes