/**
ESP32 + DHT22 Example for Wokwi
https://wokwi.com/arduino/projects/322410731508073042
https://wokwi.com/projects/377781004761822209
*/
#include <WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
//#include "DHTesp.h"
/************************* WiFi Access Point ***************************/
#define WLAN_SSID "Wokwi-GUEST"
#define WLAN_PASS ""
/************************* Adafruit.io Setup ***************************/
#define AIO_SERVER "io.adafruit.com"
#define AIO_SERVERPORT 1883 // use 8883 for SSL
#define AIO_USERNAME "raylee0106"
#define AIO_KEY "aio_csPj22vXOyRaqBfC1REcgrKGUNfN"
#define AIO_FEED_1 "/feeds/bedroom.temp"
#define AIO_FEED_2 "/feeds/bedroom.humi"
#define AIO_FEED_3 "/feeds/bedroom.light"
/************ Global State (you don't need to change this!) ************/
#define DHT_PIN 15
#ifndef LED_BUILTIN
#define LED_BUILTIN 13
#endif
#define MQTT_RECONNECT_INTERVAL 10000 // millisecond
//DHTesp dhtSensor;
float humidity=0; // 宣告一個資料型態為float的全域變數humidity
float temperature=0; // 宣告一個資料型態為float的全域變數temperature
// Create an ESP8266 WiFiClient class to connect to the MQTT server.
WiFiClient client;
// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqttClient(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_USERNAME, AIO_KEY);
/****************************** Feeds ***************************************/
// Setup feeds 'temp' and 'hmdt' for publishing.
Adafruit_MQTT_Publish temp = Adafruit_MQTT_Publish(&mqttClient, AIO_USERNAME AIO_FEED_1);
Adafruit_MQTT_Publish hmdt = Adafruit_MQTT_Publish(&mqttClient, AIO_USERNAME AIO_FEED_2);
// Setup a feed called 'onoff' for subscribing to changes to the ON/OFF button
Adafruit_MQTT_Subscribe onoffbtn = Adafruit_MQTT_Subscribe(&mqttClient, AIO_USERNAME AIO_FEED_3, MQTT_QOS_1);
boolean mqtt_nonblock_reconnect();
void mqtt_callback(char *data, uint16_t len);
void setup(void) {
pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output
// Debug console
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
delay(10);
Serial.println(F("Adafruit MQTT demo"));
// Connect to WiFi access point.
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);
WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) { //Check for the connection
Serial.print(".");
delay(500);
}
Serial.println(); Serial.println("WiFi connected");
Serial.print("IP address: "); Serial.println(WiFi.localIP());
Serial.println("Starting MQTT broker");
// Set the callback function to be called when feed's message arrives
onoffbtn.setCallback(mqtt_callback);
// Setup MQTT subscription for time feed.
mqttClient.subscribe(&onoffbtn);
}
unsigned long lastTime = 0;
void loop(void) {
// Ensure the connection to the MQTT server is alive (this will make the first
// connection and automatically reconnect when disconnected). See the mqtt_nonblock_reconnect
// function definition further below.
mqtt_nonblock_reconnect();
// this is our 'wait for incoming subscription packets and callback em' busy subloop
// try to spend your time here:
mqttClient.processPackets(10000);
// ping the server to keep the mqtt connection alive
// NOT required if you are publishing once every KEEPALIVE seconds
if(! mqttClient.ping()) {
mqttClient.disconnect();
}
// Publish feeds
char strTemperature[20], strHumidity[20];
unsigned long currTime = millis();
if (currTime - lastTime > MQTT_RECONNECT_INTERVAL) {
lastTime = currTime;
// TempAndHumidity data = dhtSensor.getTempAndHumidity();
humidity = random(100);
temperature = random(50);
Serial.println("Temperature: " + String(temperature, 1) + "°C");
Serial.println("Humidity...: " + String(humidity, 0) + "%");
Serial.println("---");
sprintf(strTemperature, "%.1f", temperature);
sprintf(strHumidity, "%.0f", humidity);
temp.publish(strTemperature);
hmdt.publish(strHumidity);
}
}
// Function called back when an onoffbutton feed message arrives
void mqtt_callback(char *data, uint16_t len) {
Serial.print("Hey we're in an onoff callback, the button value is: ");
Serial.println(data);
if (strcmp(data, "ON") == 0) {
Serial.println("Turning AC ON");
digitalWrite(LED_BUILTIN, HIGH);
} else {
Serial.println("Turning AC OFF");
digitalWrite(LED_BUILTIN, LOW);
}
}
// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
boolean mqtt_nonblock_reconnect() {
boolean doConn = false;
int8_t ret;
// Stop if already connected.
if (mqttClient.connected()) {
return doConn;
}
Serial.println("Connecting to MQTT... ");
uint8_t retries = 3;
while ((ret = mqttClient.connect()) != 0) { // connect will return 0 for connected
Serial.println(mqttClient.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 10 seconds...");
mqttClient.disconnect();
delay(10000); // wait 10 seconds
retries--;
if (retries == 0) {
doConn = true;
// basically die and wait for WDT to reset me
while (1);
}
}
Serial.println("MQTT Connected!");
return doConn;
}