2015-12-26 23:29:30 +00:00
|
|
|
#include <user_config.h>
|
|
|
|
#include <common_config.h>
|
|
|
|
#include <SmingCore/SmingCore.h>
|
|
|
|
|
2015-12-27 12:30:10 +00:00
|
|
|
bool state = false;
|
|
|
|
|
2015-12-26 23:29:30 +00:00
|
|
|
MqttClient mqtt(MQTT_BROKER, MQTT_PORT, *[](String topic, String message) {
|
|
|
|
Serial.printf("*** message received @ %s:\n\t%s\n***\n", topic.c_str(), message.c_str());
|
2015-12-27 12:30:10 +00:00
|
|
|
if(message == "on" || message == "1") {
|
|
|
|
state = true;
|
|
|
|
} else if(message == "off" || message == "0") {
|
|
|
|
state = false;
|
|
|
|
} else if(message == "toggle") {
|
|
|
|
state = !state;
|
|
|
|
}
|
|
|
|
|
|
|
|
digitalWrite(LED_PIN, !state);
|
2015-12-26 23:29:30 +00:00
|
|
|
});
|
|
|
|
|
2015-12-27 12:30:10 +00:00
|
|
|
Timer keepaliveTimer;
|
|
|
|
String deviceName;
|
|
|
|
|
2015-12-26 23:29:30 +00:00
|
|
|
void startMqttClient()
|
|
|
|
{
|
|
|
|
Serial.println("*** Connecting to MQTT as " + deviceName);
|
2015-12-27 12:30:10 +00:00
|
|
|
|
|
|
|
mqtt.setWill("main/status/" + deviceName, "offline", 1, true);
|
2015-12-26 23:29:30 +00:00
|
|
|
mqtt.connect(deviceName);
|
2015-12-27 12:30:10 +00:00
|
|
|
mqtt.publish("main/status/" + deviceName, "online");
|
|
|
|
|
|
|
|
keepaliveTimer.initializeMs(5000, *[] {
|
|
|
|
mqtt.publish("main/status/" + deviceName, "alive " + String(millis()));
|
|
|
|
}).start();
|
|
|
|
|
|
|
|
mqtt.subscribe("light/status");
|
2015-12-26 23:29:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
void init()
|
|
|
|
{
|
2015-12-27 12:30:10 +00:00
|
|
|
deviceName = "light-" + WifiStation.getMAC().substring(6, 12);
|
|
|
|
|
2015-12-26 23:29:30 +00:00
|
|
|
Serial.begin(SERIAL_BAUD_RATE); // 115200 by default
|
|
|
|
Serial.systemDebugOutput(true); // Debug output to serial
|
|
|
|
|
2015-12-27 12:30:10 +00:00
|
|
|
Serial.println("*** Starting " + deviceName + " ...");
|
|
|
|
|
2015-12-26 23:29:30 +00:00
|
|
|
WifiStation.config(WIFI_SSID, WIFI_PWD);
|
|
|
|
WifiStation.enable(true);
|
|
|
|
|
|
|
|
WifiAccessPoint.enable(false);
|
|
|
|
|
2015-12-27 12:30:10 +00:00
|
|
|
|
2015-12-26 23:29:30 +00:00
|
|
|
WifiStation.waitConnection(*[] {
|
|
|
|
Serial.println("*** Connection succeeded");
|
|
|
|
startMqttClient();
|
|
|
|
}, 20, *[] {
|
|
|
|
Serial.println("*** Connection failed");
|
|
|
|
});
|
|
|
|
|
|
|
|
pinMode(LED_PIN, OUTPUT);
|
2015-12-27 12:30:10 +00:00
|
|
|
digitalWrite(LED_PIN, HIGH);
|
2015-12-26 23:29:30 +00:00
|
|
|
}
|