Combining JS and JSON in MQTT Transformations: A Step-by-Step Guide

As a homeowner who loves tinkering with smart home tech, I’ve recently been diving into the world of MQTT transformations. It’s been a bit of a learning curve, but I’m excited to share my journey and hopefully help others who might be facing similar challenges.

The Challenge

I was trying to combine a JSON transformation with a JavaScript function in MQTT to control a rain gauge. The goal was to take the raw data from my sensors and convert it into a user-friendly format. However, I ran into an issue where the transformation wasn’t working as expected. The error message indicated that the JavaScript service wasn’t found, which was puzzling because I knew both transformations were installed.

The Solution

After some trial and error, I realized that the order of transformations was crucial. By adjusting the pattern to first extract the JSON data and then apply the JavaScript function, everything started working smoothly. Here’s how I did it:

Step 1: Configure the Thing

markdown

Type number : raingauge “Niederschlagmesser” [stateTopic=“C-BoilerRoom/tele/SENSOR”, transformationPattern=“JSONPATH:$.COUNTER.C1∩JS:counter_precipitation.js”]

This configuration tells the system to first extract the value from the JSON payload and then apply the JavaScript transformation.

Step 2: Create the JavaScript Function

markdown
javascript
(function(i) {
if (isNaN(i)) {
return (i);
}
return(i * 0.2);
}) (input)

This function takes the input value, checks if it’s a number, and then multiplies it by 0.2 to convert it into millimeters of rain.

Step 3: Define the Item

markdown
java
Number:Length OU_Garden_Rain_Gauge “Niederschlag total [%.1f mm]” (OU_Garden, Weather) {channel=“mqtt:topic:mosquitto:cboilerroom:raingauge”}

This item displays the transformed data in a readable format on my dashboard.

Tips for Success

  • Order Matters: Always ensure that JSON transformations come before JavaScript functions in your pattern.
  • Test Incrementally: If you’re having trouble, test each transformation separately before combining them.
  • Log Files: Don’t underestimate the power of log files. They can provide invaluable insights into where things might be going wrong.

Final Thoughts

It’s amazing how a little tweak can make such a big difference. By understanding how transformations work together, I was able to create a system that not only works but also provides meaningful data. If you’re still struggling with similar issues, I’d be happy to help troubleshoot or share more detailed configurations. Happy tinkering! :rocket: