MartinPham / homebridge-api

Homebridge GraphQL API, with characteristic subscriptions
16 stars 6 forks source link

Unexpected token E in JSON (when parsing characteristics) #5

Open tomnis opened 4 years ago

tomnis commented 4 years ago

Hello, thanks for this library.

I am using this together with homebridge-nest to read my thermostat temp.

I started seeing errors like this:

SyntaxError: Unexpected token E in JSON at position 54
  at JSON.parse (<anonymous>)
  at Socket.<anonymous> (/homebridge/node_modules/homebridge-api/index.js:220:58)
  ...

I printed out body:

EVENT/1.0 200 OK
Content-Type: application/hap+json
Content-Length: 54

{"characteristics":[{"aid":4,"iid":16,"value":121.7}]}EVENT/1.0 200 OK
Content-Type: application/hap+json
Content-Length: 52

{"characteristics":[{"aid":4,"iid":17,"value":4.3}]}

The parsing code seems to be including EVENT and headers when calling JSON.parse. I hackily worked around this by attempting to parse each line individually:

    const lines = body.replace(/\r/g, "").split(/\n/)
    for(let line of lines)
    {
        if(line.startsWith('{'))
        {
        const start = line.indexOf('{')
        const end = line.lastIndexOf('}')
                 const characteristics = JSON.parse(line.substr(start, end - start + 1)).characteristics
                 ...
            }
        }

I am new to homebridge and not sure what kind of assumptions I can make about these characteristic payloads. Would a payload ever be split across multiple lines?

Is it possible this was caused by subtle interaction with another plugin? Here is my deps section from homebridge package.json:

  "dependencies": {
    "homebridge-dummy": "^0.4.0",
    "homebridge-nest": "4.4.6",
    "homebridge-api": "1.0.5",
    "homebridge-tplink-smarthome": "5.1.0"
  }
MartinPham commented 4 years ago

thanks, i belive the subscription handler is having problem

MartinPham commented 4 years ago

probably it's sending 2 events at the same time