Subtraction within function node

Hi all - Apologies in advance as I am new to Node-Red and this may be an easy fix, but after multiple attempts I cannot seem to find the fix.

I am using node-red version 2.1.3.

What I am trying to do is pull data into node red from MQTT.

Once the data arrives I am identifying two separate figures. One being current time and the other being time since last motion was detected.

What I want to do is subtract time since last motion, from current time.

Within my function node, this is what I have most recently tried;

msg.payload = msg.payload - msg.payload.tslm;
return msg;

The debug node gives me the output of 'NaaN'

Any help or guidance would be greatly appreciated.

Thanks in advance!

What does the input object look like ?

The start of the flow is the MQTT in - this provides me with the data that I need.

I then filter this into two separate change nodes, to specify and pump out only the current time in one change node and time since last motion in the other. I have checked with a debug that these pump out the correct data which they do.

I then join both of the change nodes to the function node where I then attempt the subtraction.

Hope that makes sense?

Please copy/paste the output of the join/debug node here.

That doesn't make sense.

Your "current time" must be msg.payload.something.
Use a debug node to see the message coming out of your Join node.

So in the change node for current time is;

Set msg.payload
to the value msg.payload.currentTime

And the change node for the time since last motion is

Set msg.payload.tslm
to the value msg.payload.motion.stats

The debug node gives me two messages:
One being current time:

164206230

The second being time since last motion:

tslm: 1642061678

Unless you share your flow or a screenshot we will struggle to help you.

This makes no sense because an object property msg.payload cannot be a number and an object with a sub property at the same time.

At a guess, you should probably remove the change node and do this...

msg.payload = msg.payload.currentTime - msg.payload.motion.stats;
return msg;

but as i said, difficult to say without seeing the flow.

1 Like

Please copy/paste the output of the join/debug node here.

edit I concur with @Steve-Mcl , please follow the documentation.

So now we can see the issue.

A basic understanding of node- red is that messages NEVER arrive from 2 different wires at the same time into a single node. You need to join the 2 messages using a join node.

See this article in the cookbook for an example of how to join messages into one object.

I got rid of the change node and it worked! Thanks a lot!

Actually, you also dont need 2 MQTT nodes if they are the same topic.

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