/*
This example uses FreeRTOS softwaretimers as there is no built-in Ticker library
*/
#include <WiFi.h>
extern "C" {
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
}
#include <AsyncMqttClient.h>
#define BUILTIN_LED 33
AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
TimerHandle_t wifiReconnectTimer;
void connectToWifi() {
WiFi.begin("F314", "cin@5701");
}
void connectToMqtt() {
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}
void WiFiEvent(WiFiEvent_t event) {
switch(event) {
case SYSTEM_EVENT_STA_GOT_IP:
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
connectToMqtt();
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
Serial.println("WiFi lost connection");
xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
xTimerStart(wifiReconnectTimer, 0);
}
}
void onMqttConnect(bool sessionPresent) {
Serial.println("Connected to MQTT.");
uint16_t packetIdSub = mqttClient.subscribe("cookiedog0206/feeds/led", 2);
Serial.print("Subscribing at QoS 2, packetId: ");
Serial.println(packetIdSub);
}
void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
Serial.print("Subscribe packetId: ");
Serial.println(packetId);
}
void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
Serial.print("Publish received.\n payload: ");
payload[len]=0;
Serial.println(payload);
String myString = String((char *)payload);
// Switch on the LED if an 1 was received as first character
if (myString == "1") {
Serial.println("ON");
digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because it is active low on the ESP32-CAM)
} else {
Serial.println("OFF");
digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH
}
}
void setup() {
Serial.begin(115200);
Serial.println();
pinMode(BUILTIN_LED, OUTPUT);
mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));
WiFi.onEvent(WiFiEvent);
mqttClient.setCredentials("cookiedog0206", "aio_tKPz41jbscIuPoEZAL1VTISeQ2bE");
mqttClient.setServer("io.adafruit.com", 1883);
mqttClient.onConnect(onMqttConnect);
mqttClient.onSubscribe(onMqttSubscribe);
mqttClient.onMessage(onMqttMessage);
mqttClient.onDisconnect(onMqttDisconnect);
connectToWifi();
}
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
if (WiFi.isConnected())
xTimerStart(mqttReconnectTimer, 0);
}
void loop() {
}