I have a sonoff esp8266 s-20 AC power relay. I have a toggle switch on adafruit.io which switches the relay on/off. The sonoff has a button which does the same, and then it updates the adafruit.io toggle to the appropriate status. If I activate the sonoff button or aio toggle too quickly, it creates throttling issues. I even inserted code to slow the AIO updates. What is the proper way to do this?
Here is my code:
Code: Select all
// Adafruit IO hot water pump
#include "config.h"
#include <queue>
#define UPDATE_INTERVAL 3000 // Maximum adafruit.io update frequency (ms).
// Sonoff S-20 pins.
const unsigned int RELAY = 12; // Relay and status LED (HIGH == ON).
const unsigned int BUTTON = 0; // Pushbutton (LOW == pressed).
unsigned int relayState = LOW; // Relay status.
boolean SwitchReset = true; // Flag indicating that the hardware button has been released
std::queue<unsigned int> updateQ; // Queue holding adafruit.io updates to push.
AdafruitIO_Feed *pump = io.feed("hot_water_pump");
void RelayOn()
{
digitalWrite(RELAY, HIGH);
relayState = true;
}
void RelayOff()
{
digitalWrite(RELAY, LOW);
relayState = false;
}
// Called whenever a hot-water-pump feed message is received from Adafruit IO.
void handleAIOMessage(AdafruitIO_Data *data)
{
if (data->toPinLevel() == HIGH)
RelayOn();
else
RelayOff();
}
// Handle hardware switch activation.
void ButtonCheck()
{
// look for new button press
boolean SwitchState = digitalRead(BUTTON);
// Toggle the switch if there's a new button press
if (!SwitchState && SwitchReset == true)
{
if (relayState)
RelayOff();
else
RelayOn();
// Save status change for update.
updateQ.push(relayState);
// Flag that indicates the physical button hasn't been released.
SwitchReset = false;
// Debounce.
delay(50);
}
else if (SwitchState)
{
// Flag physical button release.
SwitchReset = true;
}
}
void updateAIO(void)
{
static uint32_t lastSave = 0;
// Throttle update rate.
if (!updateQ.empty() && (millis() > (lastSave + UPDATE_INTERVAL)))
{
lastSave = millis();
// Update adafruit.io
pump->save(updateQ.front());
// Remove update from queue.
updateQ.pop();
}
}
void setup()
{
// Initialize pins.
pinMode(RELAY, OUTPUT);
pinMode(BUTTON, INPUT_PULLUP);
delay(10);
digitalWrite(RELAY, LOW); // off.
// Start the serial connection.
Serial.begin(115200);
while(!Serial);
// Connect to io.adafruit.com.
Serial.print("Connecting to Adafruit IO");
io.connect();
// Setup incoming message handler.
pump->onMessage(handleAIOMessage);
// Wait for a connection.
while(io.status() < AIO_CONNECTED)
{
Serial.print(".");
delay(500);
}
// We are connected.
Serial.println();
Serial.println(io.statusText());
// Flush incoming msg.
pump->get();
}
void loop()
{
io.run();
ButtonCheck();
if (!updateQ.empty())
updateAIO();
}