2018年8月24日 星期五

IoT with ESP8266 Temperature and humidity sender (MQTT)

IoT with ESP8266 Temperature and humidity sender










/*
 Basic ESP8266 MQTT example
 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 <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <ArduinoJson.h>
#include <dht.h>
dht DHT;

//********************************************************************
// Update these with values suitable for your network.
//const char* ssid = "PTS-2F";
//const char* password = "";
const char* ssid = "74170287";
const char* password = "24063173";
//const char* ssid = "your_ssid";
//const char* password = "your_password";

#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
//********************************************************************
long lastMsg = 0;
char jsonChar[100];
#define DHTTYPE DHT11   //DHT11 or DHT22
#define DHTPIN  D5
#define ONE_WIRE_BUS D6
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensor(&oneWire);

float humi, temp_DHT , temp_DS1820 ;  // Values read from sensor
char dev_name[50] , json_buffer[512] , json_buffer_status[512] , my_ip_s[16];

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);
/********************************************************************
* FunctionName:  mqttConnectedCb                                   
* Description : 
*                 
* Parameters  :                           
* Returns     :         
*********************************************************************/
void mqttConnectedCb() {
  Serial.println("connected");
 
  // Once connected, publish an announcement...
  client.publish("alex9ufo/DS18B20/temp", jsonChar, MQTTpubQos, true); // true means retain
  client.publish("alex9ufo/DHT11/temp_humi", jsonChar, MQTTpubQos, true); // true means retain
  // ... and resubscribe
  client.subscribe("alex9ufo/inTopic", MQTTsubQos);

}
/********************************************************************
* FunctionName:  mqttDisconnectedCb                                   
* Description : 
*                 
* Parameters  :                           
* Returns     :         
*********************************************************************/
void mqttDisconnectedCb() {
  Serial.println("disconnected");
}
/********************************************************************
* FunctionName:  mqttDataCb                                   
* Description : 
*                 
* Parameters  :                           
* Returns     :         
*********************************************************************/
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);
 }
/********************************************************************
* FunctionName: setup_wifi                           
* Description : 
*                 
* Parameters  :                           
* Returns     :         
*********************************************************************/
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(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
/********************************************************************
* FunctionName: setup                           
* Description : 
*                 
* Parameters  :                           
* Returns     :         
*********************************************************************/
void setup() {
  Serial.begin(115200);
  setup_wifi();
  //
  Serial.println( "Booting" );
  Serial.println();
  Serial.printf( "Sketch size: %u\n", ESP.getSketchSize() );
  Serial.printf( "Free size: %u\n", ESP.getFreeSketchSpace() );
  Serial.printf( "Heap: %u\n", ESP.getFreeHeap() );
  Serial.printf( "Boot Vers: %u\n", ESP.getBootVersion() );
  Serial.printf( "CPU: %uMHz\n", ESP.getCpuFreqMHz() );
  Serial.printf( "SDK: %s\n", ESP.getSdkVersion() );
  Serial.printf( "Chip ID: %u\n", ESP.getChipId() );
  Serial.printf( "Flash ID: %u\n", ESP.getFlashChipId() );
  Serial.printf( "Flash Size: %u\n", ESP.getFlashChipRealSize() );
  Serial.printf( "Vcc: %u\n", ESP.getVcc() );
  Serial.println();
  //
  show_basicmessage();
}
/********************************************************************
* FunctionName: process_mqtt                         
* Description : 
*                 
* Parameters  :                           
* Returns     :         
*********************************************************************/
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();
  }
}
/********************************************************************
* FunctionName: get_DHT_temp_humi                                         
* Description : Read temperature and humidity from sensor DHT11 / DHT22
*               Values are stored in humi and temp_C 
* Parameters  : None                           
* Returns     : temp_DHT ,  humi                                                 
*********************************************************************/
void get_DHT_temp_humi()
{
  int runs=0;
  do {
       delay(2000);
       //temp_f = dht.readTemperature(false);   
       //humidity = dht.readHumidity();
       int chk = DHT.read11(DHTPIN);   
       temp_DHT= (DHT.temperature) ;
       humi = (DHT.humidity);
       

       if(runs > 0)
           Serial.println("##Failed to read from DHT sensor! ###");
       Serial.print("DHT11 Temperature=");
       Serial.print(String(temp_DHT ).c_str());
       Serial.print(", Humidity   =");
       Serial.println(String(humi ).c_str());
       runs++;
    }
    while(isnan(temp_DHT) && isnan(humi));
}
/********************************************************************
* FunctionName: get_DS1820_temp                                       
* Description : Read temperature from sensor DS18B20
*               Values are stored in temp_DS1820 
* Parameters  : None                           
* Returns     : temp_DS1820       
*********************************************************************/
 void get_DS1820_temp()
{
  int runs=0;
  do {
      delay(2000);
      // Get the current temperature from the DS18b20 sensor
      sensor.requestTemperatures();
      temp_DS1820 =sensor.getTempCByIndex(0);
       if(runs > 0)
           Serial.println("##Failed to read from DS18B20 sensor! ###");
       Serial.print("DS18B20 Temperature=");
       Serial.println(String(temp_DS1820).c_str());
       runs++;
    }
    while(isnan(temp_DS1820) > 0);
}

/********************************************************************
* FunctionName:                                       
* Description : 
*                 
* Parameters  :                           
* Returns     :         
*********************************************************************/
void show_basicmessage()
{
  //This one is dynamic one (just for fun). Avoid this in embeded system
  //Can be changed to Static one like: StaticJsonBuffer<512> jsonDeviceStatus;
  DynamicJsonBuffer jsonDeviceStatus;
  JsonObject& jsondeviceStatus = jsonDeviceStatus.createObject();
  sprintf(dev_name, "ESP_%d", ESP.getChipId());
  IPAddress my_ip_addr = WiFi.localIP();
  sprintf(my_ip_s, "%d.%d.%d.%d", my_ip_addr[0],my_ip_addr[1],my_ip_addr[2],my_ip_addr[3]);
  String IPaddr = String(my_ip_s).c_str();
 
  jsondeviceStatus ["device_name"] = dev_name;
  jsondeviceStatus["type"] = "dth";
  jsondeviceStatus["ipaddress"] = IPaddr ;
  jsondeviceStatus["bgn"] = 3;
  jsondeviceStatus["sdk"] = ESP.getSdkVersion();
  jsondeviceStatus["version"] = "1";
  jsondeviceStatus["uptime"] = 0;
  jsondeviceStatus.printTo(json_buffer_status, sizeof(json_buffer_status)); 
  Serial.println(json_buffer_status);
}
/********************************************************************
* FunctionName: loop                         
* Description : 
*                 
* Parameters  :                           
* Returns     :         
*********************************************************************/
void loop() {
  process_mqtt();

  long now = millis();
  if (now - lastMsg > 6000) {   // wait for 6sec
     lastMsg = now;
   
     // Get the current temperature from the DS18b20 sensor
     get_DS1820_temp();
     char tChar[10];
     dtostrf( temp_DS1820, 6, 2, tChar);
   
     // Convert data to JSON string
     String json =
     "{\"data\":{"
     "\"DS18B20\": \"" + String(temp_DS1820) + "\"}"
     "}";
    json.toCharArray(jsonChar, json.length()+1);
   
    //this one is static allocation
    StaticJsonBuffer<512> jsonBuffer;
    JsonObject & root = jsonBuffer.createObject();
    get_DHT_temp_humi();     //Read temperature and humidity from sensor Values are stored in humi and temp_C 
    String hum , temp ;
    hum = String(humi).c_str(); 
    temp = String(temp_DHT).c_str(); 

    char dev_name[50]; 
    sprintf(dev_name, "ESP_%d", ESP.getChipId());
    root["device_name"] = dev_name;
    root["type"] = "dth"; 
    root["temperature"] = temp;
    root["humidity"]    = hum;
    root.printTo(json_buffer, sizeof(json_buffer)); 
     // Convert JSON string to character array


     if  (client.connected()) {
         Serial.println("Publish message: ");
         Serial.print("alex9ufo/DS18B20/temp");
         Serial.println(json);
         // Publish JSON character array to MQTT topic
         client.publish("alex9ufo/DS18B20/temp",jsonChar);
       
         Serial.print("alex9ufo/DHT11/temp_humi");
         Serial.println(json_buffer);       
         client.publish("alex9ufo/DHT11/temp_humi" , json_buffer);

    } // if  (client.connected()) {
  }  //if (now - lastMsg > 6000)
}
//*********************************************************************/

沒有留言:

張貼留言

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

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