2018年7月29日 星期日

NodeMCU Lesson 2—Hello World!













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

// Update these with values suitable for your network.
const char* ssid = "PTS-2F";
const char* password = "";
//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;
int value = 0;
char jsonChar[100];

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/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] == '1') {
    digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is acive low on the ESP-01)
    Serial.println("Received 1 , LED turn on");
  }
  else
  {
      digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
      Serial.println("LED turn off ");
  }
}
//======================================================
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());
}
//======================================================
void setup() {
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(115200);
  setup_wifi();
}

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 > 6000) {
    lastMsg = now;
    ++value;
   // Convert data to JSON string
   String json =
   "{\"data\":{"
   "\"hello world\": \"" + String(value) + "\"}"
   "}";

   // 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/json",jsonChar);
    }
  }
}


[{"id":"97bc1ce5.5db0e","type":"mongodb out","z":"2070d58e.5f652a","mongodb":"9913f70e.21caf8","name":"mongodb save","collection":"helloworld","payonly":true,"upsert":true,"multi":false,"operation":"insert","x":740,"y":100,"wires":[]},{"id":"f2e3c6b.b9fb538","type":"mqtt in","z":"2070d58e.5f652a","name":"alex9ufo/outTopic/json","topic":"alex9ufo/outTopic/json","qos":"2","broker":"b0f7c1ff.aede5","x":140,"y":80,"wires":[["50f748a2.c43ce8"]]},{"id":"5f14b11b.58652","type":"mongodb in","z":"2070d58e.5f652a","mongodb":"9913f70e.21caf8","name":"helloworld","collection":"helloworld","operation":"find","x":360,"y":300,"wires":[["79628a43.e9b804"]]},{"id":"79628a43.e9b804","type":"http response","z":"2070d58e.5f652a","name":"Hello response","statusCode":"","headers":{},"x":580,"y":300,"wires":[]},{"id":"ccdbf699.adc548","type":"http in","z":"2070d58e.5f652a","name":"[get] /showhello","url":"/showhello","method":"get","upload":false,"swaggerDoc":"","x":120,"y":300,"wires":[["5f14b11b.58652"]]},{"id":"2a47be08.c16ef2","type":"comment","z":"2070d58e.5f652a","name":"Lesson2 Hello World Data in HTML/JSON View","info":"","x":220,"y":240,"wires":[]},{"id":"74cdf07e.e1aa4","type":"function","z":"2070d58e.5f652a","name":"timestamp and format data","func":"msg.payload.data.date = new Date();\nmsg.payload = msg.payload.data;\nreturn msg;","outputs":1,"noerr":0,"x":480,"y":140,"wires":[["97bc1ce5.5db0e","165986d6.43bd49"]]},{"id":"50f748a2.c43ce8","type":"json","z":"2070d58e.5f652a","name":"","x":330,"y":80,"wires":[["74cdf07e.e1aa4"]]},{"id":"165986d6.43bd49","type":"debug","z":"2070d58e.5f652a","name":"json debug","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","x":730,"y":180,"wires":[]},{"id":"c8efd5d5.f64358","type":"comment","z":"2070d58e.5f652a","name":"Lesson2 Hello world MQTT Flow","info":"","x":170,"y":40,"wires":[]},{"id":"9913f70e.21caf8","type":"mongodb","z":"","hostname":"127.0.0.1","port":"27017","db":"lesson2","name":""},{"id":"b0f7c1ff.aede5","type":"mqtt-broker","z":"","name":"mqtt","broker":"broker.mqtt-dashboard.com","port":"1883","clientid":"","usetls":false,"compatmode":true,"keepalive":"60","cleansession":true,"willTopic":"","willQos":"0","willPayload":"","birthTopic":"","birthQos":"0","birthPayload":""}]

沒有留言:

張貼留言

Wokwi ESP32 Simulator : ESP32 + NTP+MQTT+ Node-RED Dashboard

Wokwi ESP32 Simulator : ESP32 + NTP+MQTT+ Node-RED Dashboard  Wokwi ESP32程式 // Learn about the ESP32 WiFi simulation in // https://docs.wokw...