Skip to content

Commit

Permalink
json codec: collect changes before publishing
Browse files Browse the repository at this point in the history
  • Loading branch information
arachnetech committed May 11, 2020
1 parent 1047a14 commit 61dc956
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 12 deletions.
29 changes: 24 additions & 5 deletions codecs/json.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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;
}

/**
Expand All @@ -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;
Expand Down
22 changes: 15 additions & 7 deletions test/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down

0 comments on commit 61dc956

Please sign in to comment.