Parsing MQTT responses

I have what I suppose may be a terribly naive question. I have a bunch of Sonoff switches running just fine, have their status on Dashboard, etc....

What I cannot figure out is how to parse data received from a Sonoff TH10 (tasmota) device to extract variable data (like temp and humidity). I have looked around and if I've seen it explained, I didn't know it. Here is an example response:

Beechnut/Sauna-TH10/stat/STATUS10 : msg : Object
object
topic: "Beechnut/Sauna-TH10/stat/STATUS10"
payload: "{"StatusSNS":{"Time":"2019-11-28T16:11:11","SI7021":{"Temperature":22.3,"Humidity":45.5},"TempUnit":"C"}}"
qos: 0
retain: false
_msgid: "57bab8b7.eff8a8"

I actually can get it to work (if the MQTT respons ehas the proper data) by using

    temperature = msg.payload.StatusSNS.SI7021.Temperature;
    humidity = msg.payload.StatusSNS.SI7021.Humidity;

however there are a bunch of MQTT messages that cause the error msg in debug of:

function : (error)
"TypeError: Cannot read property 'SI7021' of undefined"

that I can't seem to stop occurring. There has to be a better method, I just don't know what it is.
st

You need to figure out what kind of data is coming from your sonoff device, as your function receives data that is undefined in the function node. ie. the payload that you test for is not always the same.

Filter out messages where required property exists

image

1 Like

Thanks, this is working for me. I like that I can separate "cmnd", "stat" and "tele" to individual outputs using this.
st

Inside the function node you can use hasOwnProperty() to check that you are dealing with the expected object type:

if ( msg.payload.hasOwnProperty("StatusSNS") ) {
  let temperature = msg.payload.StatusSNS.SI7021.Temperature;
  let humidity = msg.payload.StatusSNS.SI7021.Humidity;
  ;
  ;
}

Very helpful feedback, thank you.
st