I’m trying to create my own custom profile and need to write a js transformation. I would like to supply that transformation some parameters (ie. thresholds). Is that possible from the MainUI? I would rather not get into file based scripting. I’ve tried this, but the parameters don’t seem to come trough to the transformation.
This works for me:
config:js:timeFilter?name="Garage_Door_Sensor"&filterTime="PT4S"
Thanks! I made a stupid mistake…i forgot to append the parameters to the last line of my script…
The working solution is:
With the script like:
(function(data, fallingThreshold, risingThreshold) {
var qty = Quantity(data);
// Check the current time (before or after noon) and check the appropriate threshold.
const c_Threshold = ( time.toZDT().hour() >= 12 ) ? fallingThreshold : risingThreshold;
return (qty.greaterThan(c_Threshold)? "ON" : "OFF";
})(input, eveningThreshold, morningThreshold) // <<-- THIS LINE IS IMPORTANT :)
Almost all of the JS Transformation examples you see on the forum will use this format:
(function(data) {
// code goes here
})(input)
This is called a self calling anonymous function. This is a JS best practice. But in this context it’s really not doing much of anything productive for you. The whole reason for doing it like this is to keep variables from polluting the global context. But in a transformation, the transformation is the global context. So all we are doing is preventing the transformation from polluting itself, which isn’t even a thing.
By creating a self executing function, you create a little context in which you can control what variables are available and avoid any collisions with other variables that might already exist. But that means, if you are passing additional variables into the transformation, you have to pass those as arguments to the self calling function and make sure your self calling function accepts those additional variables.
There are a couple of other advantages of using a self calling function like this such as making it so you can use const
and let
and use a return
. But if you don’t care about that the equivalent to your current transformation could be written as:
var qty = Quantity(input);
// Check the current time (before or after noon) and check the appropriate threshold.
var c_Threshold = ( time.toZDT().hour() >= 12 ) ? eveningThreshold : morningThreshold;
(qty.greaterThan(c_Threshold)? "ON" : "OFF";
The last line executed becomes what gets returned by the transformation, same as with script conditions in rules.