Exploring Smart Home Automation with JavaScript

Exploring Smart Home Automation with JavaScript

Hi everyone,

I’ve been diving into the world of smart home automation lately, and I’m absolutely fascinated by the possibilities it offers. One of the projects I’ve been working on involves using JavaScript to modify values in my openHAB setup. Specifically, I wanted to adjust the fuel prices I receive from different sources to ensure consistency in my dashboard.

I came across a helpful resource that showed me how to use JavaScript transformations to add a small value to the prices I get from Clever Tanken. The idea was to make the prices match the precision of the premium prices I get directly from the fuel stations. Here’s the script I used:

javascript
(function(i) {
return parseFloat(i) + 0.009;
})(input)

I set this up in my channel configuration with the HTTP binding, and it worked like a charm for most values. However, I noticed some odd behavior with certain entries. For example, one price changed from 1.869 to 1.819, and another from 2.129 to 2.1189999999999998. At first, I was a bit puzzled, but I realized that it wasn’t critical for my setup since I fixed the decimal places in Grafana to three, and the displayed values were correct.

Still, I wanted to understand what was causing this discrepancy. After some research, I found that it had to do with floating-point precision in JavaScript. To address this, I considered rounding the values to three decimal places within the transformation script. Here’s the adjusted script I came up with:

javascript
(function(i) {
return Math.round(parseFloat(i) + 0.009 * 1000) / 1000;
})(input)

This change ensured that the values were consistently rounded to three decimal places, eliminating the strange behavior I was seeing. It was a great learning experience, and I’m now more confident in using JavaScript for value transformations in my smart home projects.

If anyone has similar experiences or tips for working with JavaScript in openHAB, I’d love to hear about them! Let’s continue to explore and share our findings in this amazing community.

Best regards,
Michael