Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSON parse exception if receiving multiple codes #10

Open
Killerameise opened this issue Nov 25, 2017 · 1 comment
Open

JSON parse exception if receiving multiple codes #10

Killerameise opened this issue Nov 25, 2017 · 1 comment

Comments

@Killerameise
Copy link

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));
  }
};
@svaccari
Copy link

svaccari commented Jan 4, 2020

Thank you, I had the same problem!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants