aarons22 / homebridge-bond

Homebridge plugin for Bond
MIT License
64 stars 31 forks source link

Uncaught JSON Parsing Error Terminating Plugin #239

Open acartola opened 1 year ago

acartola commented 1 year ago

Describe the bug An uncaught JSON parsing error in setupBPUP() in platform.js causes the plugin to terminate and restart. I haven't quite figured out why the received message has non-ASCII characters, but it seems to be on random devices on my Bond bridge (eg, I deleted the one device it always seemed to be occurring on before, then it's appeared again). Nevertheless, the below changes seem to allow the bridge to function normally again.

Information (please complete the following information):

Logs Logs are the most helpful thing you can provide. Please exclude logs from other plugin. ((Sorry, I don't have debug mode logs, but this should be pretty close))

Original error: [homebridge-bond] [Patio Fan] actions: DecreaseSpeed,IncreaseSpeed,OEMRandom,OEMTimer,SetDirection,SetSpeed,StartDecreasingBrightness,StartIncreasingBrightness,Stop,ToggleDirection,ToggleLight,TogglePower,TurnLightOff,TurnLightOn,TurnOff,TurnOn

/usr/local/lib/node_modules/homebridge-bond/dist/platform.js:217 const packet = JSON.parse(msg); ^ SyntaxError: Unexpected token � in JSON at position 0 at JSON.parse () at Socket. (/usr/local/lib/node_modules/homebridge-bond/dist/platform.js:217:33) at Socket.emit (node:events:513:28) at UDP.onMessage (node:dgram:930:8) [2/19/2023, 12:48:24 PM] [homebridge-bond] Child bridge process ended

I'm not entirely proficient in js syntax so I had chatGPT add printing of the received and trimmed message and a try/catch block around the JSON parse request... which got me here:

Received message: �AUSPRAMA@�WHUFY Trimmed message: �AUSPRAMA@�WHUFY [2/19/2023, 12:51:17 PM] [homebridge-bond] Error parsing message: SyntaxError: Unexpected token � in JSON at position 0

I then had chatGPT parse out the offending characters and things seem to be happy again:

Received message: {"B":"ZZEC17318","d":0,"v":"v3.8.4"}

Trimmed message: {"B":"ZZEC17318","d":0,"v":"v3.8.4"}

Here's the code changes I used (platform.js, starting line 215):

    client.on('message', (message, remote) => {
        console.log(`Received message: ${message}`);
        let msg = message.toString().trim();
        msg = msg.replace(/^[^\x00-\x7F]+/, ''); // Remove any non-ASCII characters from the beginning of the string

        try {
            const packet = JSON.parse(msg);
            log.debug(`UDP Message received from ${remote.address}:${remote.port} - ${msg}`);
            bond.receivedBPUPPacket(packet);
        } catch (error) {
        log.error(`Error parsing message: ${error}`);
        }
    });