Skip to content

JSON parse exception if receiving multiple codes #10

Description

@Killerameise

Hi,

if the Sniffer receives more than one code in a short time period the module crashs with a Syntax error:

_{"code": 1361, "pulseLength": 310}{"code": 1361, "pulseLength": 310}{"code": 1361, "pulseLength": 311}
^
SyntaxError: Unexpected token { in JSON at position 34
at JSON.parse ()
at Sniffer.onData (/usr/local/lib/node_modules/homebridge-rc433-motion-sensor/node_modules/rpi-433/Sniffer.js:61:26)
at Socket. (/usr/local/lib/node_modules/homebridge-rc433-motion-sensor/node_modules/underscore/underscore.js:841:23)
at emitOne (events.js:96:13)
at Socket.emit (events.js:191:7)
at readableAddChunk (_stream_readable.js:178:18)
at Socket.Readable.push (stream_readable.js:136:10)
at Pipe.onread (net.js:560:20)

That is because the onData method tries to parse multiple JSON Strings: {"code": 1361, "pulseLength": 310}{"code": 1361, "pulseLength": 310}{"code": 1361, "pulseLength": 311}.

To solve this problem I suggest something like this:

Sniffer.prototype.onData = function (buffer) {
buffer = buffer.toString('utf8');
  if(buffer.includes("}{")){
        buffer = buffer.replace("}{","}${");
        var bufferArray = buffer.split("$");
        for (str in bufferArray) {
                this.emit('data', JSON.parse(str));
        }
  }else{
        this.emit('data', JSON.parse(buffer));
  }
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions