Perhaps the most instructive aspect of this exercise was the
matching of theory & practice. Previously I've described
switches and endowed them with properties: on/off/toggle.
I don't have moisture sensors installed & all I really want is
a blast of water for about 30 seconds in the evening. I could
arrange a Node-RED flow to do this but I decided that another
useful parameter for a switch should be pulse<nn>
wherein the switch is on for <nn> seconds. The
Node-RED flow looks like:
So, as well as on/off/toggle, I have two new inputs, the
pulse button sends the message: pulse<nn> & the
MQTT subscriber (my watering system) parses this message and
switches the pump on for <nn> seconds.
The node marked timed does exactly the same thing at a
specified date/time - this is a part of Node-RED.
The subscriber code which handles the messages is shown below:
Serial.print("MQTT topic => ");
Serial.print(pub.topic());
Serial.print(", Payload => ");
String Payload = pub.payload_string();
Serial.println(Payload);
if (Payload == "toggle")
{
Serial.println("Toggle the relay!!"); //this isn't very elegant code?
switch_state ^= 1; //toggle
}
if (Payload == "on")
{
Serial.println("Switch the relay on!!");
switch_state = ON;
}
if (Payload == "off")
{
Serial.println("Switch the relay off!!");
switch_state = OFF;
}
if (Payload.startsWith("pulse"))
{
String Seconds = Payload.substring(5); //separate xxx from pulsexxx
int seconds = Seconds.toInt(); //string to int
Serial.print("Switch the relay on for ");
Serial.print(seconds);
Serial.println(" seconds");
switch_state = ON;
digitalWrite(RELAY, switch_state);
delay(1000 * seconds);
Serial.println("Switch the relay off!!");
switch_state = OFF;
}
digitalWrite(RELAY, switch_state);