2022/04/23

Android #34 用一塊ESP32來學IOT - Android手機也能通 (Learn IOT with an ESP32 / remote control w/ MQTTDash)

Android #34 用一塊ESP32來學IOT - Android手機也能通 Learn IOT with an ESP32 / remote control w/ MQTTDash

** ENGLISH closed captions is now available for this video ** Learn IOT with an ESP32 / remote control w/ MQTTDash APP

Video timeline:

00:58 Download MQTTDash App 01:29 Create an MQTT connection 03:20 Dashboard Design 04:17 Review subscriptions on MQTTLens 05:15 Enter subscription topics in MQTTDash 10:30 See the Demo on the phone 12:39 Modify ESP32 code accordingly 大家好, 歡迎收看本週的Weekend project with Stonez56。 本周是Android 第34集,"用一塊ESP32來學IOT - Android 手機也能通”。這個是一個專門為初學者來開發的一個系列。 繼上集之後, 有網友反應無法在手機上用 MQTTlens. 所以我們今天要把只能在電腦上使用的 MQTTLens 改成 MQTTDash 這支Android APP. 這樣子, 只要帶著手機, 我們就可真正隨時隨地的遠端控制IOT設備了~ 那我們就一起來學習吧。 Android MQTTDash App: https://play.google.com/store/apps/details?id=net.routix.mqttdash&hl=zh_TW&gl=US&showAllReviews=true 尚未看過這系列的朋友, 建議從這裡依序學習: * 用一塊ESP32來學 IOT https://youtu.be/rjPU4YZG338 * 溫溼度篇 https://youtu.be/x3k_dZXua1I * Android App 也能通 https://youtu.be/0IjQOxD2j48 如果時間不夠的朋友, 也可以從以下的時間軸挑選想看的部份即可! 影片時間軸: 00:00 開始 00:58 下載 MQTTDash APP 01:29 建立 EMQX MQTT 連線 03:20 儀表板設計 04:17 查看之前 MQTTLens 上的訂閱/發佈主題 05:15 在 MQTTDash 中加入訂閱/發佈主題 10:30 看實際手機+ESP32 展示 12:39 如何修改 ESP32 相應代碼

Source code:

/*
 Basic ESP8266 MQTT example
 This sketch demonstrates the capabilities of the pubsub library in combination
 with the ESP8266 board/library.
 It connects to an MQTT server then:
  - publishes "hello world" to the topic "outTopic" every two seconds
  - subscribes to the topic "inTopic", printing out any messages
    it receives. NB - it assumes the received payloads are strings not binary
  - If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,
    else switch it off
 It will reconnect to the server if the connection is lost using a blocking
 reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
 achieve the same result without blocking the main loop.
 To install the ESP8266 board, (using Arduino 1.6.4+):
  - Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":
       http://arduino.esp8266.com/stable/package_esp8266com_index.json
  - Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"
  - Select your ESP8266 in "Tools -> Board"
*/

#include <WiFi.h>
#include <PubSubClient.h>
#include <EasyButton.h>
#define LED 2        //built-in LED on ESP32

#include "DHT.h"
#define DHTPIN 23     // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT11
DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor.
// Set up the temp / humidity update cycle
const int updateCycle = 5000;

// Update these with values suitable for your network.
const char *ssid = "Wi-Fi SSID";
const char *password = "Wi-Fi Password";

// Define your client ID on EMQX
String mqtt_ClientID = "stonez56_IOT_Station_";

// Define your topics to subscribe / publish
const char* sub_topic = "stonez56/esp32s";
const char* pub_led_topic = "stonez56/esp32s_led_state";
const char* pub_init_topic = "stonez56/esp32s_is_back";
const char* pub_temp_topic = "stonez56/esp32s_temp";
const char* pub_humd_topic = "stonez56/esp32s_humd";

// EMQX broker parameters
const char *mqtt_server = "broker.emqx.io";
const char *mqtt_userName = "emqx";
const char *mqtt_password = "public";

WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
char msg1[MSG_BUFFER_SIZE];

int value = 0;

void setup_wifi()
{
    delay(10);
    // We start by connecting to a WiFi network
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);

    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");
    }

    randomSeed(micros());

    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
}

void callback(char *topic, byte *payload, unsigned int length)
{
    Serial.print("Message arrived [");
    Serial.print(topic);
    Serial.print("] ");
    for (int i = 0; i < length; i++)
    {
        Serial.print((char)payload[i]);
    }
    Serial.println();

    payload[length] = '\0';
    String message = (char *)payload;
    
    if (strcmp(topic, sub_topic) == 0)
    {
        if (message == "off")
        {
            digitalWrite(LED, LOW); //Turn off
            client.publish(pub_led_topic, "off");
        }
        if (message == "on")
        {
            digitalWrite(LED, HIGH); //Turn on
            client.publish(pub_led_topic, "on");
        }
    }

    /* Switch on the LED if an 1 was received as first character
    // if ((char)payload[0] == '1')
    // {
    //     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 ESP-01)
    // }
    // else
    // {
    //     digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH
    // } */
}

void reconnect()
{
    // Loop until we're reconnected
    while (!client.connected())
    {

        Serial.println("Attempting EMQX MQTT connection...");
        // Create a random client ID
        mqtt_ClientID += String(random(0xffff), HEX);
        // Attempt to connect
        if (client.connect((mqtt_ClientID, mqtt_userName, mqtt_password)))
        {
            Serial.print(" connected with Client ID: ");
            Serial.println(mqtt_ClientID);
            // Once connected, publish an announcement...
            client.publish(pub_init_topic, "Hi, I'm online!");
            // ... and resubscribe
            client.subscribe(sub_topic);
        }
        else
        {
            Serial.print("failed, rc=");
            Serial.print(client.state());
            Serial.println(" try again in 5 seconds");
            // Wait 5 seconds before retrying
            delay(5000);
        }
    }
}

void setup()
{
    //Start DH11 sensor
    dht.begin();

    pinMode(LED, OUTPUT); // Initialize the _LED pin as an output
    digitalWrite(LED, LOW); //default ESP32 LOW is turn off

    Serial.begin(115200);
    setup_wifi();
    client.setServer(mqtt_server, 1883);
    client.setCallback(callback);
}

void loop()
{

    if (!client.connected())
    {
        reconnect();
    }
    client.loop();

    unsigned long now = millis();
    if (now - lastMsg > updateCycle)
    {
        lastMsg = now;
        float humidity = dht.readHumidity();
        float temperature = dht.readTemperature();
        // Check if any reads failed and exit early (to try again).
        if (isnan(humidity) || isnan(temperature))
        {
            Serial.println(F("Failed to read from DHT sensor!"));
            return;
        }else{ // publish the message
            snprintf(msg, MSG_BUFFER_SIZE, "%.1lf°", temperature);
            snprintf(msg1, MSG_BUFFER_SIZE,"%.0lf%%", humidity);
            Serial.print("Publish message: ");
            Serial.println(msg);
            client.publish(pub_temp_topic, msg);
            client.publish(pub_humd_topic, msg1);
            
        }

    }
}

;