Set Logic variable by NAME?

Hi,

Is there a way to update/set a Logic variable by NAME and not by id please?

Many thanks!

I wouldn’t even know how to set/update a variable per ID, so please show your code/flow to we can have a better understanding of your problem.

Not directly, you’ll need to get the ID by searching the name between all variables.
(Get all variables, search name, see what ID belongs to it, update variable however you want).

The update function itself only works with IDs.

@Pat_M If you mean per homeyscript, this should do it:

//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;
  }
}
1 Like

Hi again, thanks for all input.

Here is my current script:

let testDay = new Date();
let dateNum = testDay.getDate();
let monthTxtShort = testDay.toLocaleString('fefault', { month: 'short'})

let TodaysDate = Object.values(await Homey.logic.getVariables()).find(({name}) => name === "TodaysDate");
let TodaysDateId = TodaysDate.id
let MonthTextShort = Object.values(await Homey.logic.getVariables()).find(({name}) => name === "MonthTextShort");
let MonthTextShortId = MonthTextShort.id

Homey.logic.updateVariable({id: TodaysDateId, variable: {'value' : dateNum}} )
Homey.logic.updateVariable({id: MonthTextShortId, variable: {'value' : monthTxtShort}} )

I just find it awkard to first have to get the ID of the variable. Is it because (which seems fair) you can have multiple variables with the same name and ID is the only key?

Thanks!

Yes. This is also true for flows and devices. The name does not have to be unique, the ID always is.

1 Like

Thank you Mr. Kawa, once again good advice! :grinning:

1 Like