MQTT to InfluxDB function

I just about went nuts trying to get the right incantation of a Regex for JavaScript to do a simple job of parsing out the device name from a MQTT String so I decided to share because I didn't find it here.

I've used Regex infrequently for decades but every damn language/system has its own take on what is a special character, quote or not, single or double quote if used...

The incoming string looks like this

{"topic":"System_Info/cam-gaz/bitrate","payload":"5.5","qos":1,"retain":false,"_topic":"System_Info/cam-gaz/bitrate","_msgid":"b220fd5c.db4f9"}

And the InfluxDB node needs this

{"device":"cam-gaz","value":5.5,"units":"Mb/s"}

To get the right info in the right form I use this function

var device = msg.topic.match("System_Info/([-0-9A-z]*)/");
var rate = parseFloat(msg.payload);

var newMsg = { "payload": {
        "device": device[1],
        "value": rate,
        "units": "Mb/s"
    } };
return newMsg;

I emphasize string because I got easier to parse input than with the JSON Object option in the MQTT node.

Hi

I skipped over your topic as i dont know influx. Had you said "help splitting value from topic to make new msg" - it would have been open to a wider audience than "MQTT to InfuxDB"

Anyhoo, here is how I would do it...

var device = msg.topic.split("/")
var rate = parseFloat(msg.payload);
msg.payload = {
    "device": device[1],
    "value": rate,
    "units": "Mb/s"
}
return msg;

Points of interest...

  1. I recommend you dont create new messages - always better to modify and pass on the original msg.
  2. Split is way easier than regex

And yet here you are posting to it :wink:

Split! Damn. Rookie error. Thanks for that.

:joy:

I think you understand my point.

1 Like

Licking my wounds... at least there's an example here like I couldn't find and some strings will need a regex.

I have to point out that the terms are mixed up there. The string is JSON. JSON is by definition a string. When you set the MQTT node to output parsed JSON that means that it parses the JSON string and outputs the result, which is a javascript object.

1 Like

Uh...yeah, yeah...that's what I meant. :roll_eyes:

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.