-
Notifications
You must be signed in to change notification settings - Fork 97
Javascript Formula Engine
SimHub now offers a full javascript engine as an alternative to the legacy NCALC engine.
It relies on Jint (https://github.com/sebastienros/jint). The engine is full ECMAScript 5.1 compliant.
The formulas written are all executed separately in their own environment, it means that you can't interact between formulas directly.
The JS engine is reinitialized on the formula scope when any errors occurs with a 30s timeout between retries, please make sure to avoid any execution errors, all the errors are logged (inside the "log" folder).
The engine is not running inside a browser so common properties such as window
or document
does not exists,
As an alternative you can use the root property to store data across calls for instance, here is an evaluation counter :
// Initialize the conter if not done
if(root["counter"]==null){
root["counter"] = 0;
}
// Increments counter
root["counter"]++;
// Return the result
return root["counter"];
It is possible to load common functions available everywhere by putting a JS file into the "JavascriptExtensions" folder, A sample file is available here. As stated previously these scripts will be loaded for each binding/mapping.
Simhub offers two types of formula :
-
Binding editor (found in DashStudio, leds, custom protocol ..), to use the JS engine simply check "use javascript"
-
Ini files, they are used for Nextion mappings or LCD templates Simply use the "js:" prefix in front of your formula to specify the use of the JS engine :
[Progressbar]
X=0
Y=64-8
Color=2
Width=128
cornerradius=0
Height=10
Minvalue=0
Maxvalue=100
value=js:return $prop("SerialDashPlugin.ComputedRPMPercent");
Obviously ini file does not allow multiline scritps, but you can add complex function using Common functions and use them in the ini file
All the formulas must return a result using the return
keyword. If no result is given the result will be evaluated as
null
The function $prop(propertyname)
allows you to access any SimHub property
// Read the current rpm
var rpm = $prop('DataCorePlugin.GameData.NewData.Rpms');
// if rpm value is zero return "stalled" text
if(rpm==0){
return "Stalled";
}
// Otherwise return the current rpm
return format(rpm,"0");
var a = new Array();
for(i=1;i<=5;i++){
var dn = drivername(i);
if(dn!=null){
a.push(dn);
}
}
return a.join(", ");