2019年9月21日 星期六

MQTT Basic實驗 + 說明

MQTT Basic實驗 + 說明

Arduino程式
https://mega.nz/#!ohETSa4R!iAQetpxalah6lcvWDORTe7TzzUQd5hFfjPApk9iorH4

說明文件
https://mega.nz/#!sxUzDSJK!TL2PlisodVTU8pIWUQPwQa-e8ssGGInOtGsoN_3Z1Uw


/*
Many thanks to nikxha from the ESP8266 or WEMOSD1 forum
*/

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.
//const char *ssid = "PTS-2F";
//const char *pass = "";
const char *ssid = "74170287";
const char *pass = "24063173";
//const char *ssid =  "yourSSID";     // change according to your Network - cannot be longer than 32 characters!
//const char *pass =  "yourPASSWORD"; // change according to your Network


#define MQTTid              ""                           //id of this mqtt client
#define MQTTip              "broker.mqtt-dashboard.com"  //ip address or hostname of the mqtt broker
#define MQTTport            1883                         //port of the mqtt broker
#define MQTTuser            "alex9ufo"                   //username of this mqtt client
#define MQTTpsw             "alex9981"                   //password of this mqtt client
//#define MQTTuser          "your_username"              //username of this mqtt client
//#define MQTTpsw           "your_password"              //password of this mqtt client
#define MQTTpubQos          2                            //qos of publish (see README)
#define MQTTsubQos          1                            //qos of subscribe

#define BUILTIN_LED        2                             // Arduino standard is GPIO13 but lolin nodeMCU is 2
//Variables
long lastMsg = 0;
char jsonChar[100];
long IDNo=0;
bool Flash = false;  //true
//=============================================================================
boolean pendingDisconnect = false;
void mqttConnectedCb(); // on connect callback
void mqttDisconnectedCb(); // on disconnect callback
void mqttDataCb(char* topic, byte* payload, unsigned int length); // on new message callback

WiFiClient wclient;
PubSubClient client(MQTTip, MQTTport, mqttDataCb, wclient);
//=============================================================================
void mqttConnectedCb() {
  Serial.println("connected");
 
  // Once connected, publish an announcement...
  client.publish("alex9ufo/outTopic/Hello/json", jsonChar, MQTTpubQos, true); // true means retain
  // ... and resubscribe
  client.subscribe("alex9ufo/inTopic", MQTTsubQos);

}
//=============================================================================
void mqttDisconnectedCb() {
  Serial.println("disconnected");
}
//=============================================================================
void mqttDataCb(char* topic, byte* payload, unsigned int length) {

  /*
  you can convert payload to a C string appending a null terminator to it;
  this is possible when the message (including protocol overhead) doesn't
  exceeds the MQTT_MAX_PACKET_SIZE defined in the library header.
  you can consider safe to do so when the length of topic plus the length of
  message doesn't exceeds 115 characters
  */
  char* message = (char *) payload;
  message[length] = 0;

  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  Serial.println(message);
  String message1;
  for (int i = 0; i < length; i++) {
    message1 = message1 + (char)payload[i];  //Conver *byte to String
  }
  Serial.println(message1);
  //Serial.print(message);
  if(message1 == "#on" || message1 == "0")
  {
      digitalWrite(BUILTIN_LED,LOW);
      Flash = false;
      Serial.println("Received #on or 0 , Send LOW TO BuildIn_LED");
  }   //LED on 
  if(message1 == "#off" || message1 == "1")
  {
    digitalWrite(BUILTIN_LED,HIGH);
    Flash = false;
    Serial.println("Received #off or 1 , Send HIGH TO BuildIn_LED");
  } //LED off
  if(message1== "#flash" || message1 == "2" ) {
     Flash = true;
     digitalWrite(BUILTIN_LED, HIGH);
     Serial.println("Received #flash or 2 , Flashing BuildIn_LED ");
   } // if(message== "#flashLED")
}
//======================================================
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, pass);

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

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
 
}
//======================================================
void setup() {
  Serial.begin(115200);
  setup_wifi();
  pinMode(BUILTIN_LED, OUTPUT);
  Serial.println(F("Booting...."));
  Serial.println(F("Ready!"));
}
//======================================================
void process_mqtt() {
  if (WiFi.status() == WL_CONNECTED) {
    if (client.connected()) {
      client.loop();
    } else {
    // client id, client username, client password, last will topic, last will qos, last will retain, last will message
      if (client.connect(MQTTid, MQTTuser, MQTTpsw, MQTTid "/status", 2, true, "0")) {
          pendingDisconnect = false;
          mqttConnectedCb();
      }
    }
  } else {
    if (client.connected())
      client.disconnect();
  }
  if (!client.connected() && !pendingDisconnect) {
    pendingDisconnect = true;
    mqttDisconnectedCb();
  }
}
//======================================================
void loop() {
  process_mqtt();
  long now = millis();
 
  if (Flash)  //Test Flash Command
  {
    digitalWrite(BUILTIN_LED, !digitalRead(BUILTIN_LED));
    delay(250);
  }
 
  if ( now - lastMsg > 5000)
  {  // 等5秒
    lastMsg = now;
    // Convert data to JSON string
    String json =
        "{\"data\":{"
         "\"Hello word\": \"" + String(IDNo) + "\"}"
         "}";
         // Convert JSON string to character array
         json.toCharArray(jsonChar, json.length()+1);
   
         if  (client.connected()) {
              Serial.print("Publish message: ");
              Serial.println(json);
              // Publish JSON character array to MQTT topic
             client.publish("alex9ufo/outTopic/Hello/json",jsonChar);
         }
      IDNo++;
      } // if ((IDNo != IDNo_buf) || (now - lastMsg > 5000))

}   //Loop
//======================================================

沒有留言:

張貼留言

WOKWI DHT22 & LED , Node-Red + SQLite database

 WOKWI DHT22 & LED , Node-Red + SQLite database Node-Red程式 [{"id":"6f0240353e534bbd","type":"comment&...