simple_iot/examples/01_actions.ino

62 lines
2.2 KiB
C++

#include <simple_iot.h>
/**
* This example shows how to use actions.
* Three actions are defined:
* * "on" and "off" set Pin 13 to HIGH or LOW, respectively. They are provided as lambda functions
* and don't care about the payload they're given.
* * "set" is defined as function reference triggering only if the payload is "ON" or "OFF".
*
* You can access them via HTTP by sending a POST request to `/on`, `/off` or `/set`. There's a
* nice-ish website at `/`, listing all registered handlers. If you kept the suggested hostname,
* this link should lead you there: http://basic-test/.
*
* If you enabled MQTT, cou can also publish data via MQTT to trigger those actions. Again, if you
* didn't change the topic below, it would be `basic-test-mqtt-topic/on`, `basic-test-mqtt-topic/off`
* and `basic-test-mqtt-topic/set`.
*/
SimpleIOT* iot = NULL;
/** Do something
*/
bool setValue(String payload) {
// Check the payload.
if (payload.compareTo("ON")==0) {
// Turn the pin to HIGH.
digitalWrite(13, HIGH);
// return true to indicate that the action was successful.
return true;
} else if (payload.compareTo("OFF")==0) {
// Turn the pin to LOW.
digitalWrite(13, LOW);
// return true to indicate that the action was successful.
return true;
}
// If we reach this point, the payload was neither "ON" nor "OFF". So we don't do nothing.
// If the action was initiated using a HTTP POST request, an error will be returned instead of "OK".
return false;
}
void setup() {
// Set pin 13 to be an OUTPUT.
pinMode(13, OUTPUT);
// Initialize SimpleIOT, giving it a WiFi SSID and the matching password to connect as well as a hostname to use.
iot = new SimpleIOT("ssid", "password", "basic-test");
// Set data for an MQTT server. You can omit this line if you don't want to use MQTT.
iot->setMQTTData("1.2.3.4", 1883, "basic-test-mqtt-user", "basic-test-mqtt-password", "basic-test-mqtt-topic/");
// Define three actions.
iot->act_on("on", [](String payload)->bool{ digitalWrite(13, HIGH); return true; });
iot->act_on("off", [](String payload)->bool{ digitalWrite(13, LOW); return true; });
iot->act_on("set", setValue);
iot->begin();
}
void loop() {
iot->loop();
}