# Trying to write a Function Node for monitoring temperatures

**URL:** https://discourse.nodered.org/t/trying-to-write-a-function-node-for-monitoring-temperatures/81642
**Category:** General
**Tags:** function-node
**Created:** [28 September 2023 15:32 UTC](https://discourse.nodered.org/t/trying-to-write-a-function-node-for-monitoring-temperatures/81642 "2023-09-28T15:32:52Z")
**Posts on this page:** 10
**Page:** 2

<div class="post-metadata">

### Author: ![jbudd](https://avatars.discourse-cdn.com/v4/letter/j/5f8ce5/32.png) [@jbudd](https://discourse.nodered.org/u/jbudd)
#### Post date: [29 September 2023 16:22 UTC](https://discourse.nodered.org/t/trying-to-write-a-function-node-for-monitoring-temperatures/81642/21 "2023-09-29T16:22:59Z")

</div>

Interesting that the temperature rises almost linearly with very little sign of tailing off, and it doesn't seem to be maintained at the maximum for a significant period.

---

<div class="post-metadata">

### Author: ![terminus](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/terminus/32/38378_2.png) [@terminus](https://discourse.nodered.org/u/terminus)
#### Post date: [29 September 2023 18:31 UTC](https://discourse.nodered.org/t/trying-to-write-a-function-node-for-monitoring-temperatures/81642/22 "2023-09-29T18:31:10Z")

</div>

Stable State whilst the day

 ![Bildschirmfoto 2023-09-29 um 20.29.02](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/f/9/f9b972d2a1c3b8fad5c816d672634a44d0863808.png)

Decresing Part, highest Zoom Level

 ![Bildschirmfoto 2023-09-29 um 20.28.21](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/b/b/bb0400c76e32f3d426e50d27afd6cebe700dd7bb.png)

---

<div class="post-metadata">

### Author: ![ralphwetzel](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/ralphwetzel/32/53713_2.png) [@ralphwetzel](https://discourse.nodered.org/u/ralphwetzel)
#### Post date: [29 September 2023 18:33 UTC](https://discourse.nodered.org/t/trying-to-write-a-function-node-for-monitoring-temperatures/81642/23 "2023-09-29T18:33:34Z")

</div>

> [@terminus](#):
>
> The code btw. doesn't

It does - of course. Inject "20", wait a few seconds, then inject "34". You'll get your message.  
The issue I tried to put your attention to is rather that you'd not detect when the temperature level change peaks and falls back (up - down) within the timespan you're monitoring. You'll need additional logic if you intend to cover that case.

---

<div class="post-metadata">

### Author: ![terminus](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/terminus/32/38378_2.png) [@terminus](https://discourse.nodered.org/u/terminus)
#### Post date: [29 September 2023 18:36 UTC](https://discourse.nodered.org/t/trying-to-write-a-function-node-for-monitoring-temperatures/81642/24 "2023-09-29T18:36:50Z")

</div>

> [@ralphwetzel](#):
>
> It does - of course.

```auto
[{"id":"df8c984ddabd30e4","type":"function","z":"65879b662c0554cb","name":"Temperatur stieg um 5° innerhab 1 Minute","func":"// Get the previous values from the context store\nvar previousValues = context.get(\"previousValues\") || [];\nvar threshold = 4; // Temperaturschwelle in Grad Celsius\nvar timeWindow = 60; // Zeitfenster in Sekunden\n\nvar ret;\n\n// Add debug statements here\nconsole.log(\"Incoming Message Payload:\", msg.payload);\n\nvar currentTimestamp = Date.now();\nvar currentValue = parseFloat(msg.payload); // Umwandlung in Gleitkommazahl\n\nif (isNaN(currentValue)) {\n console.log(\"Ungültige Payload:\", msg.payload);\n} else {\n // Suchen Sie den am weitesten entfernten Wert innerhalb einer Minute\n var furthestValue = null;\n\n for (var i = 0; i < previousValues.length; i++) {\n if (currentTimestamp - previousValues[i].timestamp <= timeWindow * 1000) {\n furthestValue = previousValues[i].value;\n node.warn(furthestValue);\n } else {\n // Wenn der Wert älter als eine Minute ist, brechen Sie die Schleife ab\n break;\n }\n }\n\n \n\n // Wenn ein Wert gefunden wurde, vergleichen Sie ihn mit dem aktuellen Wert\n if (furthestValue !== null) {\n var deltaValue = currentValue - furthestValue;\n\n if (deltaValue >= threshold) {\n ret = \"Temperatur erhöht sich um \" + deltaValue + \" Grad Celsius innerhalb einer Minute.\";\n }\n }\n\n // Aktualisieren Sie die Liste der vorherigen Werte\n previousValues.push({ value: currentValue, timestamp: currentTimestamp });\n\n // Entfernen Sie alte Werte, die älter als eine Minute sind\n var cutoffTimestamp = currentTimestamp - (timeWindow * 1000);\n previousValues = previousValues.filter(function (item) {\n return item.timestamp >= cutoffTimestamp;\n });\n\n // Schreiben Sie die aktualisierte Liste in den Kontext\n context.set(\"previousValues\", previousValues);\n}\n\nif (ret) return { payload: ret };\nreturn;","outputs":1,"timeout":"","noerr":0,"initialize":"","finalize":"","libs":[],"x":440,"y":1680,"wires":[["bd638a3a8d3097ce"]]},{"id":"bd638a3a8d3097ce","type":"debug","z":"65879b662c0554cb","name":"debug 17","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","statusVal":"","statusType":"auto","x":740,"y":1680,"wires":[]},{"id":"573256e42d0bd41b","type":"inject","z":"65879b662c0554cb","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"24","payloadType":"str","x":110,"y":1740,"wires":[["df8c984ddabd30e4"]]},{"id":"93262112d7fb3756","type":"inject","z":"65879b662c0554cb","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"34","payloadType":"str","x":110,"y":1780,"wires":[["df8c984ddabd30e4"]]},{"id":"96c056c3a0a84ee4","type":"inject","z":"65879b662c0554cb","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"20","payloadType":"str","x":110,"y":1580,"wires":[["df8c984ddabd30e4"]]},{"id":"041aefd845cc3632","type":"inject","z":"65879b662c0554cb","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"21","payloadType":"str","x":110,"y":1620,"wires":[["df8c984ddabd30e4"]]},{"id":"2340c5a79093b489","type":"inject","z":"65879b662c0554cb","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"22","payloadType":"str","x":110,"y":1660,"wires":[["df8c984ddabd30e4"]]},{"id":"05bc41703f604c86","type":"inject","z":"65879b662c0554cb","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"23.3","payloadType":"str","x":110,"y":1700,"wires":[["df8c984ddabd30e4"]]}]

```

With this, I don't get any ☹

---

<div class="post-metadata">

### Author: ![ralphwetzel](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/ralphwetzel/32/53713_2.png) [@ralphwetzel](https://discourse.nodered.org/u/ralphwetzel)
#### Post date: [29 September 2023 18:49 UTC](https://discourse.nodered.org/t/trying-to-write-a-function-node-for-monitoring-temperatures/81642/25 "2023-09-29T18:49:32Z")

</div>

The code you have under

```auto
    // Suchen Sie den am weitesten entfernten Wert innerhalb einer Minute

```

is completely useless and not at all necessary. When you push (new) incoming data to the (back of the) array, the oldest value will always be at index 0. Values that fall out of your monitoring window will be removed by the code under

```auto
    // Entfernen Sie alte Werte, die älter als eine Minute sind

```

keeping the array crisp - with the oldest value valid for you monitoring window **always** at index 0.

Keep the code as it was (using `push`!), inject the values, enjoy the result!

 ![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/b/b/bbcdedad94444113cc809281f939b36b3261fab9.png)

---

<div class="post-metadata">

### Author: ![terminus](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/terminus/32/38378_2.png) [@terminus](https://discourse.nodered.org/u/terminus)
#### Post date: [29 September 2023 20:48 UTC](https://discourse.nodered.org/t/trying-to-write-a-function-node-for-monitoring-temperatures/81642/26 "2023-09-29T20:48:57Z")

</div>

> [@terminus](#):
>
> ```auto
> // Get the previous values from the context store
> var previousValues = context.get("previousValues") || [];
> var threshold = 4; // Temperaturschwelle in Grad Celsius
> var timeWindow = 60; // Zeitfenster in Sekunden
> 
> var ret;
> 
> // Add debug statements here
> console.log("Incoming Message Payload:", msg.payload);
> 
> var currentTimestamp = Date.now();
> var currentValue = parseFloat(msg.payload); // Umwandlung in Gleitkommazahl
> 
> if (isNaN(currentValue)) {
> console.log("Ungültige Payload:", msg.payload);
> } else {
> // Holen Sie die vorherigen Werte aus dem Kontext
> if (previousValues.length > 0) {
> var previousValueBeforeMinute = previousValues[0].value;
> var previousTimestampBeforeMinute = previousValues[0].timestamp;
> var deltaTime = (currentTimestamp - previousTimestampBeforeMinute) / 1000;
> var deltaValue = currentValue - previousValueBeforeMinute;
> 
> if (deltaTime <= timeWindow && deltaValue >= threshold) {
> ret = "Temperatur erhöht sich um " + deltaValue + " Grad Celsius innerhalb von " + deltaTime + " Sekunden."
> }
> }
> 
> // Aktualisieren Sie die Liste der vorherigen Werte
> previousValues.unshift({ value: currentValue, timestamp: currentTimestamp });
> 
> // Entfernen Sie alte Werte, die älter als eine Minute sind
> var cutoffTimestamp = currentTimestamp - (timeWindow * 1000);
> previousValues = previousValues.filter(function (item) {
> return item.timestamp >= cutoffTimestamp;
> });
> 
> // Schreiben Sie die aktualisierte Liste in den Kontext
> context.set("previousValues", previousValues);
> }
> 
> if (ret) return { payload: ret };
> return;
> 
> ```

OMG turns out, that there was sth. wrong with my debug node, so it doesn't show anything. Reloaded the page and it works. Sorry for the inconvinience and thank you so much for your help!

---

<div class="post-metadata">

### Author: ![Colin](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/colin/32/17040_2.png) [@Colin](https://discourse.nodered.org/u/Colin)
#### Post date: [29 September 2023 20:53 UTC](https://discourse.nodered.org/t/trying-to-write-a-function-node-for-monitoring-temperatures/81642/27 "2023-09-29T20:53:28Z")

</div>

Since you have not included the scale in the first image it is not possible to know the size of the steps.

---

<div class="post-metadata">

### Author: ![terminus](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/terminus/32/38378_2.png) [@terminus](https://discourse.nodered.org/u/terminus)
#### Post date: [29 September 2023 20:56 UTC](https://discourse.nodered.org/t/trying-to-write-a-function-node-for-monitoring-temperatures/81642/28 "2023-09-29T20:56:34Z")

</div>

That's right and I think I can explain it:  
Sensor is on the outside of the pipe, not washed around by the fluid and showering usually doesn't last long. So it increases whilst the water is flowing and if the fresh water gets stopped, it starts decreasing...

---

<div class="post-metadata">

### Author: ![terminus](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/terminus/32/38378_2.png) [@terminus](https://discourse.nodered.org/u/terminus)
#### Post date: [29 September 2023 20:57 UTC](https://discourse.nodered.org/t/trying-to-write-a-function-node-for-monitoring-temperatures/81642/29 "2023-09-29T20:57:57Z")

</div>

My bad, sorry:

here it is at steady state

 ![Bildschirmfoto 2023-09-29 um 22.57.20](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/c/5/c583f4e4ffbd5066d0098c9ba3dece784d7057e4.png)

---

<div class="post-metadata">

### Author: ![system](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/1X/d073cd938eafa2e558d7c2cd59003b3ef4963033.png) [@system](https://discourse.nodered.org/u/system)
#### Post date: [13 October 2023 20:58 UTC](https://discourse.nodered.org/t/trying-to-write-a-function-node-for-monitoring-temperatures/81642/30 "2023-10-13T20:58:01Z")

</div>

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

[Previous page](https://discourse.nodered.org/t/trying-to-write-a-function-node-for-monitoring-temperatures/81642.md?page=1)
