2018年11月10日 星期六

ESP32 Home automation (Simple On/Off control using MQTT)


Arduino: ESP32 Home automation (Simple On/Off control using MQTT)









/* Change the
 * file:///C:/Users/alex/Documents/Arduino/libraries/pubsubclient-2.7/src/PubSubClient.h
// MQTT_VERSION : Pick the version
//#define MQTT_VERSION MQTT_VERSION_3_1
#ifndef MQTT_VERSION
#define MQTT_VERSION MQTT_VERSION_3_1_1
#endif

// MQTT_MAX_PACKET_SIZE : Maximum packet size
#ifndef MQTT_MAX_PACKET_SIZE
#define MQTT_MAX_PACKET_SIZE 1024  (128----change into 1024 )
#endif

publish load
{"switches":[
{"status":false,"id":1,"lable":"GPIO 25"},
{"status":false,"id":2,"lable":"GPIO 26"},
{"status":false,"id":3,"lable":"GPIO 27"},
{"status":false,"id":4,"lable":"GPIO 14"},
{"status":true,"id":5,"lable":"GPIO 12"}]}

*/

#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>

// Update these with values suitable for your network.
const char* ssid = "alex9ufo";
const char* password = "alex9981";
//const char* mqtt_server = "iot.eclipse.org";
const char* mqtt_server = "broker.mqtt-dashboard.com";
#define mqtt_port 1883
#define MQTT_USER "alex9ufo"
#define MQTT_PASSWORD "alex9981"
#define MQTT_SERIAL_PUBLISH_CH "/alex9ufo/ha/outTopic/esp32/gpio/"
#define MQTT_SERIAL_RECEIVER_CH "/alex9ufo/ha/inTopic/esp32/gpio/"
#define ID_MAP_LENGTH 5
WiFiClient wifiClient;
/*id - GPIO
 * 1 - 25
 * 2 - 26
 * 3 - 27
 * 4 - 14
 * 5 - 12
 */
int iomap[ID_MAP_LENGTH]={25,26,27,14,12};

PubSubClient client(wifiClient);
//===========================================================
void setup_wifi() {
    delay(10);
    // We start by connecting to a WiFi network
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);
    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 reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP32Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str(),MQTT_USER,MQTT_PASSWORD)) {
      Serial.println("connected");
      //Once connected, publish an announcement...
      client.publish("/alex9ufo/ESP32/HApresence/ESP32/", "ESP32 Home automation (Simple On/Off control using MQTT)");
      // ... and resubscribe
      client.subscribe(MQTT_SERIAL_RECEIVER_CH);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
//===========================================================
void callback(char* topic, byte *payload, unsigned int length) {
  //print recevied messages on the serial console
    Serial.println("-------new message from broker-----");
    Serial.print("channel:");
    Serial.println(topic);
    Serial.print("data:");
    Serial.write(payload, length);
    Serial.println();
    StaticJsonBuffer<500> jsonBuffer;
    JsonObject& message = jsonBuffer.parseObject((char *)payload);

    if (!message.success()) {
      Serial.println("JSON parse failed");
      return;
    }
    // loop through each switch and swith IO sate
    JsonArray& switches=message["switches"];
    int i=0,id,io_status;
    for(i=0;i<switches.size();i++){
      id=switches[i]["id"];
      io_status=switches[i]["status"];
      Serial.print("id=");
      Serial.print(String(id).c_str());
      Serial.print("  io_pin=");
      Serial.print(String(iomap[id-1]).c_str());
      Serial.print("  io_status=");
      Serial.print(String(io_status).c_str());
      Serial.println();
         
      digitalWrite(iomap[id-1],io_status);
    }
    Serial.println("Setting LED On/Off");
 
}
//===========================================================
void setup() {
  Serial.begin(115200);
  Serial.setTimeout(500);// Set time out for
  int i=0;
  for(i=0;i<ID_MAP_LENGTH;i++){
    pinMode(iomap[i],OUTPUT);
  }
  for(i=0;i<=5;i++){    //test LED Flash
      digitalWrite(25,LOW);    //iomap[ID_MAP_LENGTH]={25,26,27,14,12};
      digitalWrite(26,LOW);
      digitalWrite(27,LOW);
      digitalWrite(14,LOW);
      digitalWrite(12,LOW);
      delay(600);
      digitalWrite(25,HIGH);
      digitalWrite(26,HIGH);
      digitalWrite(27,HIGH);
      digitalWrite(14,HIGH);
      digitalWrite(12,HIGH);
      delay(600);
  }


  setup_wifi();
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);
  reconnect();
}
//===========================================================
void loop() {
   client.loop();
 }

沒有留言:

張貼留言

2024_09 作業3 以Node-Red 為主

 2024_09 作業3  (以Node-Red 為主  Arduino 可能需要配合修改 ) Arduino 可能需要修改的部分 1)mqtt broker  2) 主題Topic (發行 接收) 3) WIFI ssid , password const char br...