Help with what is happening with code

Folks, I am a gluten for punishment.

Chat GPT took me down some weird places. It kind of helped but then again: it didn't.

Scenario:

I have an alternating output (on/off) which works fine as is, but - of course - I complicated things and how they don't.

Basic overview:

The subflow toggles the message received by the button node.
On/Off.
It has text and colour to control/adjust how the button looks.
If the button is pressed, it toggles things and .... anyway.
That works.
P.S. The payload also toggles from 0 to 1 for OFF and ON.

Complication:

There is another factor that determines how the button looks.
That is alternating weeks.

So now rather than just having fixed text (explaining what the button does) I have thought I would also tweak the text.

Truth table - of sorts:

OFF - msg.colour = firebrick msg.txt = "NAME"
ON (week 0) - msg.colour = springgreen msg.txt = this week
ON (week 1) - msg.colour = green msg.txt = next week

The problem is this:
It is ON, and I press the OFF button. It turns from what ever colour/text to firebrick and shows the NAME for msg.txt.
Then when I turn it ON again it restores the previous text and colour.
If it is ON and the week goes to the other, the text and colour adjust.

So there are two nodes sending messages:

Code:

node 1:

const timestamp = msg.payload;
const date = new Date(timestamp);
let msg2 = {}

// Calculate the week number
const weekno = Math.floor((timestamp + 345600000) / 604800000);

// Determine the parity of the week (odd or even)
const result_ = Number(weekno) % 2;

// Get the weekday (0 for Sunday, 1 for Monday, ..., 6 for Saturday)
const weekday = date.getDay();

if (result_ === 0) {
    if (weekday == 6) {
        //
        msg.showBan = false;
        msg.flag = "Wash";
    }
    else {
        //
        msg.showBan = true;
        msg.flag = " ";
    }
}
else {
    msg.showBan = true;
    msg.flag = " ";
}

//// Assign weekday to the message object
//msg.weekday = weekday;

//  Create msg2 to adjust colour of button
if (msg.flag == "Wash")
{
    msg2.colour = "springgreen"
//    msg2.txt = "Wash cloths"
    msg2.txt = "This week"
    msg2.week = 0
}
if (msg.flag == " ")
{
    msg2.colour = "green"
    msg2.txt = "Next week"
    msg2.week = 1
}

return [msg,msg2];

Using msg2 for the input.

node 2:

let pass = context.get("pass") || false
let colour = ''
if (context.get("colour") != undefined)
{
    colour = context.get("colour")
}
else
{
    colour = "yellow"
}

let text = msg.txt
const message = msg.payload
const week = msg.week

node.warn("Initial colour is " + colour)

if (week !== undefined) 
{
    node.warn("Week setting colour")
    context.set("colour", colour)
    context.set("text",text)
    node.warn("Setting colour to " + colour + " And text to " + text)
    //return msg
}

text = context.get("text") || "oops"

if (message == 0)
{
    //  Inactive
    node.warn("InActive")
    //msg.colour = colour
    msg.text = text
}

if (message == 1)
{
    //  Active
    node.warn("Active")
    msg.colour = colour
    msg.txt = text
}

node.status({text:colour})

return msg;

This receives the msg2 from the first node OR it receives (alternately) these two messages:
{"_msgid":"5669a8dea20a1f33","payload":0,"topic":"","colour":"firebrick","txt":"Wash Cloths"}
or
{"_msgid":"230ad34770d6b9c5","payload":1,"topic":"","colour":"springgreen","txt":"Wash Cloths"}

Despite my best efforts I am getting WEIRD messages.

Forgive the messy way I test if context exists. But I am not sure if having || "text" works if the context is not set and that sets a default value.

So where's the confusion?

Indulge me:
I have just edited the second node's code. So all its context is empty.
It receives a message from the other node.

And to put things in perspective I'll go back and emphasise this bit of code:

if (context.get("colour") != undefined)
{
    colour = context.get("colour")
}
else
{
    colour = "yellow"
}

(So if the context is empty, it sets the colour to yellow.

Ready? :wink:

HOW did it change from yellow to green?

So anyway:

Have I explained it clearly enough?

I would like to make the testing better, but I can't see any shortcuts to doing it.

Thanks in advance.

Mr CHAT GPT threw this at me....
Along with a bit of digging by me.

let pass = context.get("pass") || false;  // Initialize pass variable with default value from context
let colour = context.get("colour") || "yellow";  // Initialize colour with default value "yellow" if not set in context

let text = msg.txt;  // Initialize text variable from msg.txt
const message = msg.payload;  // Initialize message variable from msg.payload
const week = msg.week;  // Initialize week variable from msg.week

// Set colour and text in context if week is defined
if (week !== undefined) {
    context.set("colour", msg.colour);
    context.set("text", text);
}

// Retrieve text from context or set default "oops"
text = context.get("text") || "Week not set";

// Handle message values
if (message === 0) {
    // Set text for inactive state
    msg.text = text;
}

if (message === 1) {
    // Set colour and text for active state
    msg.colour = colour;
    msg.txt = text;
}

node.status({ text: msg.colour });  // Update node status with current colour

return msg;  // Return updated msg object

The Problem was my constant use of colour rather than msg.colour in later lines.

I changed it to msg.colour and it seems to be working better.
(So maybe it is resolved. But I am still not confident enough to believe everything computers tell me.)

And neither should you be! The so-called "AI" tools are really "Large Language Model" machine learning tools. They only "know" what someone has already thought and then written down somewhere it can be sucked into the model.

Though that is a slightly simplistic view of course with a couple of exceptions. They CAN "infer" relationships between people's content that isn't obvious to humans - that is one of the real benefits but also one of the biggest threats because inference based on language can never be 100% accurate.

The other exception is that, as people start to publish stuff that AI's have generated, those may also get fed back into models which can really mess up reality!

Anyway, bottom line is that you wouldn't 100% trust what someone in an online forum told you and you shouldn't 100% trust what an LLM tells you.

Like any other Internet "knowledge", you need to apply your own thinking and knowledge. The models can be great boons but you need to sanity check everything.

By the way, the Inject Enhanced contributed node has even/odd week numbers available.

Personally, I would have a separate flow that generates an odd/even flag, at maybe just after midnight on Monday morning. I would output that to MQTT and save to a Node-RED global variable for use anywhere.

Then you could use the MQTT change as an event but more importantly in this case, use the global to help populate your web page.

Wow, that looks nice.

But this is an established machine and it is running the older NR.

3.0.2

So the code:

Was my adjustment the solution?
msg.colour vs colour

If it works, probably :slight_smile:

I don't think that node is dependent on Node-RED v4. I've been using it for ages on my live system. Certainly from early v3 maybe even v2, can't remember.

I did a quick search but am not clear on the name.

Ah, I forgot, it isn't obvious.

image

I use a number of their nodes, really useful stuff.

Um, sorry.

But even searching inject enhanced doesn't give me anything useful.

Inject gives me a lot of choices. Inject enhanced gives me none.

Found it.

It is called node-red-contrib-sun-position.

Yeah, ok, but the thing is:

On a valid week I can se the colour to something.
And on the other weeks, I can se the colour to something else.

So looking at it and seeing the COLOUR I can tell what's going on too.

There may be a way to do that other ways, but this way is the way I know.

I added something to my own test dashboard:

image

So the even/odd week info is fully independent of everything else. There is a (UIBUILDER in my case) page with a response flow that currently only has responses from buttons that control my PC monitors brightness (not relevant here of course). But there is another flow (3rd image) that monitors the week via MQTT and updates the UI (noting that the output is cached).

All really simple. I could, of course, go further and make the UI into a button to be clicked if the sheets have been washed - but I'm mostly too lazy to do that. :grinning: If it isn't a sheet washing week, it looks like this:

Yes, the colours need sorting out but this was only a test after all.

1 Like

Thanks.

Alas most of my stuff is not on the new dashboard.

Am still very much at the starting gate for learning that stuff.

Well, as you know, I don't really use Dashboard 1 or 2 other than for testing or really simple stuff. Most things are now so easy to do with native HTML and JS that, with a little help from UIBUILDER, I never need the use of Vue or Angular even for complex requirements.

Hi, if you share your pc via anydesk, I can assist you.

@Sandrei That's not really the way we do things on this forum, apart from the obvious security concerns, questions and answers posted here can be peer reviewed, and also benefit others with the same issues.

I'm sure @Trying_to_learn would be more than happy to receive some help via the forum :wink:

4 Likes