//you may use this code under GPL v3 at your own risk :) var net = require('net'); const mqtt = require('mqtt') var sleep = require('sleep'); //base_topic can contain more than one level of mqtt topic string, but it must not have a slash at the begining or the end. var JSONconfig=` { "vdcd_host" : "127.0.0.1", "vdcd_port" : 8999, "base_topic" : "myvdc", "initmsg" : [ { "message":"init", "tag":"sonoff", "protocol":"json", "group":1, "uniqueid":"mctest1", "name":"mctest1", "output":"light", "buttons": [ { "id":"button1", "buttontype":0, "group":1, "element":1 } ] } ] }` config = JSON.parse(JSONconfig); console.log(config); var base_topic=config.base_topic; var vdcd_host=config.vdcd_host; var vdcd_port=config.vdcd_port; var tags = []; if ( Array.isArray(config.initmsg)){ for ( i in config.initmsg ){ tags.push(config.initmsg[i].tag); } } else { tags.push(config.initmsg.tag); } console.log(tags); var client = new net.Socket(); client.connect(vdcd_port,vdcd_host,function() { console.log("connected to: "+vdcd_host+":"+vdcd_port); client.write(JSON.stringify(config.initmsg)); }); client.on('data', function(data) { console.log("raw data: "+data); //split lines: lines=data.toString().split("\n"); for ( var i in lines ){ console.log ("parsing message "+i); line=lines[i]; if(line.trim() != ""){ d=JSON.parse(line); switch(d.message){ case "status": console.log("STATUS: "+line); break; case "channel": console.log("CHANNEL: "+line); console.log("value: "+d.value); mclient.publish(base_topic+"/status/"+d.tag+"/value",d.value.toString()); break default : console.log('DATA: ' + line); } } } }); client.on('close', function() { console.log('Connection closed'); process.exit(); }); // MQTT: const mclient = mqtt.connect('mqtt://mqtt.psuter.ch') mclient.on('connect', () => { for ( i in tags ) { mclient.subscribe(base_topic+'/set/'+tags[i]+'/#'); } }); mclient.on('message',(topic,message) => { // /set//// regex="^"+base_topic+"/set/([^/]+)/([^/]+)/([^/]+)/([^/]+)$"; console.log("regex: "+regex); ptopic=topic.match(regex); if ( ptopic != null ){ tag=ptopic[1]; type=ptopic[2]; id=ptopic[3]; action=ptopic[4]; console.log("parsed topic: " + ptopic); switch(action){ case "click": //will send one or more button clicks (push and release) console.log(type+" click status changed to "+message); for ( i=1;i <= message ; i++){ console.log("sending "+type+" click " +i+ " to dss"); JSONaction=` { "message":"${type}", "id":"${id}", "value":100, "tag":"${tag}", }` client.write(JSONaction); console.log("WRITING: "+JSONaction); if( message > 1 ) { console.log("sleep"); sleep.msleep(150); } } break; case "on": //message=1 pushes the button / switches the input to on //message=0 releases the button /switches the input to off //message=n pushes the button for n milliseconds / switches input on for n milliseconds console.log(type+" push set to "+message); JSONaction=` { "message":"${type}", "id":"${id}", "value":${message}, "tag":"${tag}", }` client.write(JSONaction); break; } } });