heyu
Version:
Simple heyu X10 relay
115 lines (90 loc) • 3.84 kB
JavaScript
function Heyu() {
this.x10confObject = {};
this.x10confFileRead = "";
this.heyuExecutable = "heyu"
this.debug = null;
this.x10sorted = [];
this.x10grouped = [];
};
//reads x10.conf file, parsing for aliases in order to populate the x10config object
//assumed is alias line in format "alias <alias_name> <module_address> <module_type> # <group>
Heyu.prototype.readConfigFile = function(filename,callback) {
that = this;
//helper function
function x10sort_and_group() {
//sorting groups
that.x10sorted = [];
that.x10grouped = [];
for(var alias in that.x10confObject) {
that.x10sorted.push(that.x10confObject[alias]);
}
that.x10sorted.sort(function(a,b) {
return (a.group < b.group? -1 : (a.group == b.group ? (a.alias < b.alias ? -1 : 1) : 1));
});
var prevgroup = '';
for(var i in that.x10sorted) {
if (that.x10sorted[i].group !== prevgroup) {
//insert here new group
if(prevgroup !== '') {
//if this is not the first group
newgroup = new Object();
newgroup.groupTitle = prevgroup;
newgroup.groupCode = prevgroupCode;
newgroup.devices = devices;
that.x10grouped.push(newgroup);
}
devices = new Array();
}
//insert device
devices.push({"deviceTitle" : that.x10sorted[i].alias , "deviceCode" : that.x10sorted[i].address });
prevgroupCode = that.x10sorted[i].address[0];
prevgroup = that.x10sorted[i].group;
}
//and the last group to push
newgroup = new Object();
newgroup.groupTitle = prevgroup;
newgroup.groupCode = prevgroupCode;
newgroup.devices = devices;
that.x10grouped.push(newgroup);
}
var fs = require('fs');
if (!filename) {
filename = "/etc/heyu/x10.conf";
}
fs.readFile(filename,encoding='ASCII', function (err,x10confData) {
if (err) throw err;
that.x10confFileRead = filename;
var pattern = new RegExp('\nalias.*','ig');
var match=[];
while((match=pattern.exec(x10confData))!==null) {
var line=match[0].split(/[ \t]+/);
if ( line[3] == '#' )
that.x10confObject[line[1]]={'alias':line[1],'address':line[2],'group':line[4].replace('_', ' '), 'groupHouse':line[2].substring(0,1)};
else
that.x10confObject[line[1]]={'alias':line[1],'address':line[2],'group':line[5].replace('_', ' '), 'groupHouse':line[2].substring(0,1)};
}
x10sort_and_group();
process.nextTick(function(){
callback(that.x10grouped);
});
});
};
Heyu.prototype.execHeyu = function (device, command, comparam, callback) {
// validate command
switch ( command ) {
case 'alloff':
case 'obdim':
case 'on':
case 'off':
break;
default:
callback( new Error('Heyu error: invalid command ' + command ));
return;
}
var exec = require('child_process').execFile;
console.log('Exec> '+this.heyuExecutable+' '+command+' '+device+' '+comparam);
if (!this.debug) {
exec(this.heyuExecutable, [ command+' '+device+' '+comparam ], callback);
}
}
exports = module.exports = new Heyu();