Openremote default configuration suffers the illness of cheap Chinese devices — it forgets almost everything after power on/off cycle. This article describes how to preserve in-memory variables. If you want to save your in memory variables with rules presented here, please follow these guidelines:
- A name of in-memory variable, which should be preserved between restarts, must begin with capital string “GV”, for example “GVRememberThis”;
- This in-memory variable should have command ‘status’;
- Sensor associated with this command should have exactly the same name — in our example “GVRememberThis”;
- The sensor should be of type ‘custom’.
When you follow these guidelines and add following rules in the designer then Openremote controller will miraculously remember all “GV” started in-memory variables. GV stays for Global Variable.
package org.openremote.controller.protocol.preserve;
import java.io.*;
import org.openremote.controller.protocol.Event;
global org.openremote.controller.statuscache.CommandFacade execute;
function void _WriteToFile(String fn, Object o){
String vl = o.toString();
PrintWriter writer = new PrintWriter(fn+".txt", "UTF-8");
try{
writer.println(vl);
} finally {
writer.close();
}
}
function String _ReadFromFile(String fn, String dft){
String result = dft;
try{
BufferedReader fr = new BufferedReader(new InputStreamReader(new FileInputStream(fn+".txt"), "UTF-8"));
try{
result = fr.readLine();
} finally {
fr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return(result);
}
rule "Store values"
timer(int: 1s)
when
Event($s:source matches "^GV.*", $v:value!="status")
then
_WriteToFile($s, $v);
end
rule "Init values"
salience 100
when
(OR
Event($s:source matches "^GV.*", value=="")
Event($s:source matches "^GV.*", value=="status")
)
then
execute.command($s, _ReadFromFile($s, "-"));
end
You can either use these rules in designer or save it separately in your controller’s subdirectory [path to the controller]/webapps/controller/rules/. The second solution has an advantage that these rules will always be available — even if there are no rules in the designer or rules are with errors. It should be a part of the standard Openremote distribution if you ask me 😉