2019年9月22日 星期日

ESP8266 Json & MQTT

//WemosD1


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

//const char* ssid = "yourNetworkName";
//const char* password =  "yourNetworkPassword";
//const char *ssid = "PTS-2F";
//const char *pass = "";
const char *ssid = "74170287";
const char *pass = "24063173";

#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
bool Flash = false;  //true
long lastMsg = 0;
//=============================================================================
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); 
char JSONmessageBuffer[100];
//=============================================================================
void mqttConnectedCb() {
  Serial.println("connected");
  // Once connected, publish an announcement...
  client.publish("alex9ufo/outTopic/Json", JSONmessageBuffer, 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 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 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() {
  delay(10);
  Serial.begin(115200);
  setup_wifi();
  pinMode(BUILTIN_LED, OUTPUT);
  Serial.println(F("Booting...."));
  Serial.println(F("Ready!"));
}
//====================================================== 
void loop() {
  process_mqtt();
  if (Flash)  //Test Flash Command
  {
    digitalWrite(BUILTIN_LED, !digitalRead(BUILTIN_LED));
    delay(250);
  }
  long now = millis();
  if ( now - lastMsg > 10000)
  {  // 等10秒
    lastMsg = now;
    StaticJsonBuffer<300> JSONbuffer;
    JsonObject & JSONencoder = JSONbuffer.createObject();
    JSONencoder["device"] = "WeMosD1";
    JSONencoder["sensorType"] = "Random";
    JsonArray& values = JSONencoder.createNestedArray("values");
    int i = random(100);
    values.add(i);
    int j = random(100);
    values.add(j);
    int k = random(100);
    values.add(k);
    JSONencoder.printTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
    Serial.println("Sending message to MQTT topic..");
    Serial.println(JSONmessageBuffer);
    if  (client.connected()) {
      client.publish("alex9ufo/outTopic/Json", JSONmessageBuffer);
      Serial.println("Success sending message");
    } else {
      Serial.println("Error sending message");
    }
    Serial.println("-------------");
  } // if ( now - lastMsg > 10000)
}
//===============================================








沒有留言:

張貼留言

113 學年度第 1 學期 RFID應用課程 Arduino程式

113 學年度第 1 學期 RFID應用課程 Arduino程式 https://www.mediafire.com/file/zr0h0p3iosq12jw/MFRC522+(2).7z/file 內含修改過後的 MFRC522 程式庫 (原程式有錯誤) //定義MFRC522...