I have used Claude 3.7 to generate a response -> including a test case (which I thought was quite cool)
I am not sure the rules in using AI to generate response however from my perpesctive this is an appropriate use of Claude. If it contravenes any rules feel free to delete
The answers seem sensible although the context on the global set seems out of whack however it appears to do no harm
You will notice at the bottom it has able to create a nice test flow. From my testing it appears work. I am not keen on it returning NULL so I have changed the code to return the unchanged msg (even that is not great)
In case the link does not work and for longevity
It looks like you're working with Node-RED or a similar flow-based programming environment. There are a few potential issues that could be causing your code not to work:
The most likely issue is with how you're accessing msg.topic. If msg.topic doesn't contain a "/" character or it's undefined, then split("/")[1] will return undefined.
You're setting a global variable with global.set() but you might be missing a context to attach it to.
Let me help you debug this. Here's a corrected version that includes error handling:
// First, validate that msg.topic exists and has the correct format
if (!msg.topic || !msg.topic.includes("/")) {
node.error("Invalid msg.topic: " + msg.topic);
return msg; // Exit the function early
}
// Extract the name from the topic
let gname = msg.topic.split("/")[1];
// Check if gname is valid
if (!gname) {
node.error("Could not extract gname from msg.topic: " + msg.topic);
return msg;
}
// Convert payload to "0" or "1"
let OneZero = (msg.payload === "true" || msg.payload === true) ? "1" : "0";
// Set the global variable
global.set(gname + ".State", OneZero);
// Debug output to help troubleshoot
node.log("Set global variable: " + gname + ".State = " + OneZero);
return msg;
Thank you for your suggestion. I found out what my disconnect was. I am using the node-red-contrib-state which, it turns out, is not connected to the global variables (although I thought it was). I found the answer here.