Fix mallformed (nullish) messages handling (#4347)

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
This commit is contained in:
John Doe
2020-09-13 21:38:10 +08:00
committed by GitHub
parent 59812f1ef6
commit 2caaaa8d24
5 changed files with 26 additions and 4 deletions
+4 -2
View File
@@ -80,8 +80,10 @@ class Frontend extends Extension {
onWebSocketConnection(ws) {
ws.on('message', (message) => {
const {topic, payload} = utils.parseJSON(message, message);
this.mqtt.onMessage(`${this.mqttBaseTopic}/${topic}`, stringify(payload));
if (message) {
const {topic, payload} = utils.parseJSON(message, message);
this.mqtt.onMessage(`${this.mqttBaseTopic}/${topic}`, stringify(payload));
}
});
for (const [key, value] of this.retainedMessages) {
+5 -1
View File
@@ -125,10 +125,14 @@ class EntityPublish extends Extension {
json = {state: message};
} else {
logger.error(`Invalid JSON '${message}', skipping...`);
return false;
}
}
}
if (!json) {
logger.error(`Invalid JSON '${message}', skipping...`);
return;
}
/**
* Home Assistant always publishes 'state', even when e.g. only setting
+1 -1
View File
@@ -91,7 +91,7 @@ class MQTT extends events.EventEmitter {
}
onMessage(topic, message) {
this.emit('message', {topic, message: message.toString()});
this.emit('message', {topic, message: message + ''});
}
isConnected() {
+4
View File
@@ -139,6 +139,10 @@ describe('Frontend', () => {
{ retain: false, qos: 0 },
expect.any(Function)
);
mockWSClient.events.message(undefined);
mockWSClient.events.message("");
mockWSClient.events.message(null);
await flushPromises();
// Received message on socket
expect(mockWSClient.implementation.send).toHaveBeenCalledTimes(4);
+12
View File
@@ -66,6 +66,18 @@ describe('Publish', () => {
expect(MQTT.publish.mock.calls[0][2]).toStrictEqual({"qos": 0, "retain": false});
});
it('Should corretly handle mallformed messages', async () => {
await MQTT.events.message('zigbee2mqtt/foo', undefined);
await MQTT.events.message('zigbee2mqtt/foo', null);
await MQTT.events.message('zigbee2mqtt/foo', "");
await MQTT.events.message('zigbee2mqtt/bulb_color/set', undefined);
await MQTT.events.message('zigbee2mqtt/bulb_color/set', null);
await MQTT.events.message('zigbee2mqtt/bulb_color/set', "");
await flushPromises();
expectNothingPublished();
});
it('Should publish messages to zigbee devices when there is no converters', async () => {
await MQTT.events.message('zigbee2mqtt/bulb_color/set', stringify({brightness_no: '200'}));
await flushPromises();