2018年8月21日 星期二

ESP8266-DS18B20-MQTT-Node-RED

ESP8266 Arduino DS18B20 Temperature sensor.  Node-RED , MongoDB













Gmail需要降低安全性  讓node-red 有權限存取Gmail

/*
MQTT temperature with ESP8266 and DS18b20
*/
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>

/* Wiring DS18B20
=============================================================================
Black =  GND    RED = 3.3V   Yellow = Data  D7
=============================================================================
*/

#define ONE_WIRE_BUS D7

// 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

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensor(&oneWire);

//Variables
long lastMsg = 0;
char jsonChar[100];
float celcius = 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);

//=============================================================================
void mqttConnectedCb() {
  Serial.println("connected");
 
  // Once connected, publish an announcement...
  client.publish("alex9ufo/outTopic/DS18B20/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);
  /*
  // Switch on the LED if an 1 was received as first character
  if (message[0] == '0') {
     digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
     // but actually the LED is on; this is because
     Serial.print("Received 0 , BMP280 sensor read Pressure ");
    }
   if (message[0] == '1') {
     digitalWrite(BUILTIN_LED, HIGH);   // Turn the LED off (Note that HIGH is the voltage level
     // but actually the LED is on; this is because
     Serial.print("Received 1 , BMP280 sensor read Temperature ");
   }
    if (message[0] == '2') {
     digitalWrite(BUILTIN_LED, HIGH);   // Turn the LED off (Note that HIGH is the voltage level
     // but actually the LED is on; this is because
     Serial.print("Received 2 , BMP280 sensor read Altimeter ");
   }
   */
 }
//======================================================
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();
  sensor.begin();
}
//======================================================
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 (now - lastMsg > 5000) { 
     lastMsg = now;
     // Get the current temperature from the DS18b20 sensor
     sensor.requestTemperatures();
     celcius=sensor.getTempCByIndex(0);
     char tChar[10];
     dtostrf( celcius, 6, 2, tChar);
     // Publish the temperature to our topic
     // Convert data to JSON string
     String json =
     "{\"data\":{"
      "\"DS18B20\": \"" + String(celcius) + "\"}"
      "}";
      // 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/DS18B20/json",jsonChar);
          client.publish("alex9ufo/outTopic/DS18B20/temperature", tChar);
         }
      } // if  (now - lastMsg > 5000))
}   //Loop
//======================================================

沒有留言:

張貼留言

Messaging API作為替代方案

  LINE超好用功能要沒了!LINE Notify明年3月底終止服務,有什麼替代方案? LINE Notify將於2025年3月31日結束服務,官方建議改用Messaging API作為替代方案。 //CHANNEL_ACCESS_TOKEN = 'Messaging ...