I'm working on a web-based on/off controller for multiple switches. I'm looking for a good way to manage the current state of a switch and updating the current state on change.
So far I've got a lib.json
file which looks like this:
{
"Lights":[{
"name": "light-one",
"pin":"3",
"command":"gpioDo",
"actions": {
"on":"1",
"off":"0"
}
},{
"name": "light-two",
"pin":"5",
"command":"gpioDo",
"actions": {
"on":"1",
"off":"0"
}
},{
"name": "light-three",
"pin":"7",
"command":"gpioDo",
"actions": {
"on":"1",
"off":"0"
}
}],
"Locks":[{
"name": "lock-one",
"pin":"8",
"command":"gpioDo",
"actions": {
"on":"1",
"off":"0"
}
},{
"name": "lock-two",
"pin":"12",
"command":"gpioDo",
"actions": {
"on":"1",
"off":"0"
}
}]
}
A web-page is dynamically created using some jQuery and appropriate groups of buttons are created according to the lib.json
.
On the server I take that lib.json
file and create a state
object via this little snippet (note that on initial run all states must be off):
var state = [];
var lib = JSON.parse(fs.readFileSync('lib.json', 'utf8'));
...
for (i in lib) {
for (x in lib[i]){
state.push({pin:lib[i][x].pin, val:0});
}
}
which produces:
[ { pin: '5', val: 0 },
{ pin: '7', val: 0 },
{ pin: '8', val: 0 },
{ pin: '12', val: 0 } ]
When a web-page button is pushed, the server receives a string containing misc elements of the lib.json
referencing a command with parameters to perform.
It also updates the state
object to represent the change with an updateVal()
command.
function updateVal(pinId, valId){
var i;
for (i = 0; i < state.length; ++i) {
if (state[i].pin == pinId) {
state[i].val = valId;
}
}
}
I also have a controller designer which allows you to create groups of buttons which in turn modifies the lib.json
. It's basically a hacked up JSON tree editor.
How efficient is this code? Could I be doing something better, and if so, what? I can imagine that creating and updating a state
key and value in lib.json
could be more effective and reliable.
var lib = require('./lib.json');
and it will do the conversion for you. :) \$\endgroup\$lib.json
can change quite often andrequire();
holds a cached version. I'd get into time-stamped versioning stuff but it's a bit excessive with no real value apart from being able to userequire();
. Thanks though :) keen to hear your other thoughts \$\endgroup\$