diff --git a/codecs/json.js b/codecs/json.js index 5f794a7..d3ef5bc 100644 --- a/codecs/json.js +++ b/codecs/json.js @@ -73,6 +73,29 @@ function init( params ) { } }; + // pending messages/timers by MQTT topic + let pending = {}; + + // get message object which will be published (automatically) + let publishMessage = function( topic, publish ) { + let entry = pending[ topic ]; + if( entry ) { + // existing entry - clear timer + clearTimeout( entry.tmr ); + } else { + // new entry + entry = pending[ topic ] = { msg: emptyMessage() }; + } + + // publish later + entry.tmr = setTimeout( () => { + pending[ topic ] = null; + publish( JSON.stringify( entry.msg ) ); + }, 50 ); + + return entry.msg; + } + /** * Encode message before sending. * The output function may be called to deliver an encoded value for the property later. @@ -86,18 +109,15 @@ function init( params ) { function encode( message, info, output ) { // eslint-disable-line no-unused-vars let diag = ! jsonConfig || jsonConfig.diag; let jpath = readJPath( info.property ); - let encoded; if( jpath ) { - let msg = emptyMessage(); + let msg = publishMessage( info.topic, output ); setJson( msg, jpath, message ); - encoded = JSON.stringify( msg ); } else { diag = true; } if( diag ) { log( `json-codec: encode() called for topic [${info.topic}], property [${info.property}] with message [${message}]` ); } - return encoded; } /** @@ -116,7 +136,6 @@ function init( params ) { let decoded; if( jpath ) { let msg = JSON.parse( message ); - log( msg ); decoded = getJson( msg, jpath ); } else { diag = true; diff --git a/test/config.json b/test/config.json index e3ec0c8..02c067a 100644 --- a/test/config.json +++ b/test/config.json @@ -143,16 +143,24 @@ "name": "Test RGBW Light 2", "url": "http://192.168.10.35:1883", "topics": { - "getRGB": "test/rgbwlight2/rgb", - "setRGB": "test/rgbwlight2/rgb/set", - "getWhite": "test/rgbwlight2/white", - "setWhite": "test/rgbwlight2/white/set", - "getOn": "test/rgbwlight2/on", - "setOn": "test/rgbwlight2/on/set" + "getRGB": "test/rgbwlight2", + "setRGB": "test/rgbwlight2/set", + "getWhite": "test/rgbwlight2", + "setWhite": "test/rgbwlight2/set", + "getOn": "test/rgbwlight2", + "setOn": "test/rgbwlight2/set" }, "logMqtt": true, "integerValue": true, - "hexPrefix": "#" + "hexPrefix": "#", + "codec": "json", + "jsonCodec": { + "properties": { + "RGB": "state.rgb", + "white": "state.white", + "on": "state.on" + } + } }, { "accessory": "mqttthing",