This Node.js library provides an easy solution for receiving MQTT messages, extracting specific JSON keys, and forwarding them to custom callback functions.
I developed this library to streamline data collection from various MQTT-enabled devices within my home network. My objective is to archive this data in a database, enabling visualization with tools like Grafana. Existing solutions, such as NodeRED, proved to be too demanding for such small tasks on resources for small-scale projects, especially when operating on single-board computers.
Checkout this repository to see the script based solution, utilizing the mqttJsonParser: MQTT-Influx-Bridge
Before using the script, make sure you have the following:
- Node.js installed on your system.
mqttNode.js package installed. Install it usingnpm install mqttif not already installed.dotenvNode.js package installed for environment variable management. Install it usingnpm install dotenvif not already installed.- MQTT broker credentials.
- Clone this repository to your local machine:
git clone https://github.com/mgiesen/mqttJsonParser.git- Install the required Node.js packages:
npm install- Create a .env file with your MQTT settings in the repository folder:
MQTT_HOST=
MQTT_USERNAME=
MQTT_PASSWORD=
MQTT_PROTOCOL=- Customize the subscriptions object in
example.jsto fit your needs. I recommend using MQTT-Explorer to identify topics and key mappings.
{
topic: "YOUR_MQTT_TOPIC",
enabled: true,
mappings: [
{
schema: "YOUR_JSON_MAPPING_TO_SPECIFIC_VALUE",
onMessage: YOUR_CALLBACK_FUNCTION,
messageParameter: {
// ADDITIONAL PARAMETERS YOU WANT TO PASS TO CALLBACK FUNCTION
}
}
]
}- Run the script with the configuration file as a command-line argument:
node example.jsShelly Plus 1PM - WiFi Relais and Energy Meter
{
"id": 0,
"source": "init",
"output": true,
"apower": 0.0,
"voltage": 235.0,
"current": 0.034,
"aenergy": {
"total": 13371.121,
"by_minute": [0.0, 0.0, 0.0],
"minute_ts": 1694723159
},
"temperature": {
"tC": 56.9,
"tF": 134.4
}
}[mqttJsonParser] MQTT connection successfully
[mqttJsonParser] Shelly temperature 57 °C
[mqttJsonParser] Shelly solar energy 13371.121 W