2018年7月24日 星期二

DHT11, LDR , MQTT, Node-RED, Google Chart, MongoDB





















//D1 --SSD1305 SCL
//D2 --SSD1306 SDA

// Including the ESP8266 WiFi library
#include <ESP8266WiFi.h>
#include "DHT.h"
#include  "Adafruit_Sensor.h"
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
//---------MQTT------------------------
#include <PubSubClient.h>
//---------SSD1306----------------------
#define OLED_RESET LED_BUILTIN  //4
Adafruit_SSD1306 display(OLED_RESET);

// Uncomment one of the lines below for whatever DHT sensor type you're using!
#define DHTTYPE DHT11   // DHT 11
//#define DHTTYPE DHT21   // DHT 21 (AM2301)
//#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321

// Replace with your network details
//const char* ssid = "YOUR_NETWORK_NAME";
//const char* password = "YOUR_NETWORK_PASSWORD";
const char* ssid = "74170287";
const char* password = "24063173";

// Web Server on port 80
WiFiServer server(80);

// DHT Sensor
const int DHTPin = D3;
// Initialize DHT sensor.
DHT dht(DHTPin, DHTTYPE);

// Temporary variables
static char celsiusTemp[7];
static char fahrenheitTemp[7];
static char humidityTemp[7];
//static char LDRTemp[7];

//--------CDS LDR---------------------
//double data;
int light;
const int lightPin = A0;
//---------MQTT------------------------
const char* mqtt_server = "broker.mqtt-dashboard.com";
//const char* mqtt_server = "iot.eclipse.org";
WiFiClient espClient;
PubSubClient client_mqtt(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
const int DHT11_PIN= D3;

String ipToString(IPAddress ip){
  String s="";
  for (int i=0; i<4; i++)
    s += i  ? "." + String(ip[i]) : String(ip[i]);
  return s;
}
//---------MQTT------------------------
void callback(char* topic, byte* payload, unsigned int length)
{
  Serial.print("Command is : [");
  Serial.print(topic);
  int p =(char)payload[0]-'0';
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);
  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
        Serial.println("Failed to read from DHT sensor!");
        strcpy(celsiusTemp,"Failed");
        strcpy(fahrenheitTemp, "Failed");
        strcpy(humidityTemp, "Failed");       
        }
   else{

  // if MQTT comes a 0 message, show humidity
  if(p==0)
  {
    Serial.println("to show humidity!]");
    Serial.print(" Humidity is: " );
    float h = dht.readHumidity();     
    Serial.print(h,2);
    Serial.println('%');
  }
  // if MQTT comes a 1 message, show temperature
  if(p==1)
  {
  // digitalWrite(BUILTIN_LED, HIGH);
   Serial.println(" is to show temperature!] ");
   float t = dht.readTemperature();     
   Serial.print(" Temp is: " );
   Serial.print(t,2);
   Serial.println(' C');
  }
   if(p==2)
  {
  // digitalWrite(BUILTIN_LED, HIGH);
   Serial.println(" is to show LDR Sensor!] ");
   light = analogRead (lightPin);
   light = map (light, 0, 1023, 0, 100); // scaled from 100 - 0 (lower is darker)
   Serial.print(" LDR is: " );
   Serial.print(light);     
   //float Analogdata = analogRead(A0);     
   //Serial.print(" LDR is: " );
   //Serial.print(Analogdata,2);
   Serial.println();
  }
  Serial.println();
 }
} //end callback

void reconnect() {
  // Loop until we're reconnected
  while (!client_mqtt.connected())
  {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    //if you MQTT broker has clientID,username and password
    //please change following line to    if (client.connect(clientId,userName,passWord))
    if (client_mqtt.connect(clientId.c_str()))
    {
      Serial.println("connected");
     //once connected to MQTT broker, subscribe command if any
      client_mqtt.subscribe("alex9ufoCommand");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client_mqtt.state());
      Serial.println(" try again in 5 seconds");
      // Wait 6 seconds before retrying
      delay(6000);
    }
  }
} //end reconnect()

// only runs once on boot
void setup() {
  pinMode(A0, INPUT);
  // Initializing serial port for debugging purposes
  Serial.begin(115200);
  delay(10);
  dht.begin();

  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  // Clear the buffer.
  display.clearDisplay();
  display.display();

  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0,0);
  display.println("Hello from:");
  display.println("http://alex9ufo.blogspot.com/");
  display.display();

  // Connecting to 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");

  // Starting the web server
  server.begin();
  Serial.println("Web server running. Waiting for the ESP IP...");
  delay(10000);

  // Printing the ESP IP address
  Serial.println(WiFi.localIP());
  //---------MQTT------------------------
  client_mqtt.setServer(mqtt_server, 1883);
  client_mqtt.setCallback(callback);
  //---------MQTT------------------------

  String ips=ipToString(WiFi.localIP());
  display.setCursor(0,36);
  display.print("IP Add:");
  display.println(ips);
  display.display();
}


// runs over and over again
void loop() {
  // Listenning for new clients
  WiFiClient client = server.available();

  if (client) {
    Serial.println("New client");
    // bolean to locate when the http request ends
    boolean blank_line = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
     
        if (c == '\n' && blank_line) {
            // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
            float h = dht.readHumidity();
            // Read temperature as Celsius (the default)
            float t = dht.readTemperature();
            // Read temperature as Fahrenheit (isFahrenheit = true)
            float f = dht.readTemperature(true);
            // Check if any reads failed and exit early (to try again).
            if (isnan(h) || isnan(t) || isnan(f)) {
              Serial.println("Failed to read from DHT sensor!");
              strcpy(celsiusTemp,"Failed");
              strcpy(fahrenheitTemp, "Failed");
              strcpy(humidityTemp, "Failed");       
            }
            else{
              /*
              // Compute heat index in Fahrenheit (the default)
              float hif = dht.computeHeatIndex(f, h);
              // Compute heat index in Celsius (isFahreheit = false)
              float hic = dht.computeHeatIndex(t, h, false); */
           
              // Computes temperature values in Celsius + Fahrenheit and Humidity
              float hic = dht.computeHeatIndex(t, h, false);     
              dtostrf(hic, 6, 2, celsiusTemp);           
              float hif = dht.computeHeatIndex(f, h);
           
              dtostrf(hif, 6, 2, fahrenheitTemp);       
              dtostrf(h, 6, 2, humidityTemp);
           
              //data = analogRead(A0);
              //dtostrf(data, 6, 2, LDRTemp);
               // Read light sensor
              light = analogRead (lightPin);
              light = map (light, 0, 1023, 0, 100); // scaled from 100 - 0 (lower is darker)
              // You can delete the following Serial.print's, it's just for debugging purposes
              Serial.print("Humidity: ");
              Serial.print(h);
              /*
              Serial.print(" %\t Temperature: ");
              Serial.print(t);
              Serial.print(" *C ");
              Serial.print(f);
              Serial.print(" *F\t Heat index: ");
              Serial.print(hic);
              Serial.print(" *C ");
              Serial.print(hif);
              Serial.print(" *F");
              Serial.print("Humidity: ");
              Serial.print(h);
              Serial.print(" %\t Temperature: ");
              Serial.print(t);
              Serial.print(" *C ");
              Serial.print(f);
              Serial.print(" *F\t Heat index: ");
              Serial.print(hic);
              Serial.print(" *C ");
              Serial.print(hif);
              Serial.println(" *F");
              Serial.print(" LDR Sensor:");
              Serial.print(data);  */
              //-------------SSD 1306 Display-------------------//
                // Clear the buffer.
              display.clearDisplay();
              display.display();

              display.setTextSize(1);
              display.setTextColor(WHITE);
              display.setCursor(0,0);
              display.print("TemCel:");
              display.print(celsiusTemp);
              display.println(" *C ");
           
              display.setCursor(0,8);           
              display.print("TemFah:");
              display.print(fahrenheitTemp);
              display.println(" *F ");
           
              display.setCursor(0,16);           
              display.print("Humidity:");
              display.print(humidityTemp);
              display.println(" %");           
              //-------------SSD 1306 Display-------------------//
              display.setCursor(0,24);
              display.print("LDR Sensor:");
              //light = analogRead (lightPin);
              //light = map (l, 0, 1023, 0, 100); // scaled from 100 - 0 (lower is darker)
              display.print(light);
           
              display.setCursor(0,36);
              display.println("http://alex9ufo.blogspot.com/");
              display.display();
              //-------------SSD 1306 Display-------------------//

            }
            client.println("HTTP/1.1 200 OK");
            client.println("Content-Type: text/html");
            client.println("Connection: close");
            client.println();
            // your actual web page that displays temperature and humidity
            client.println("<!DOCTYPE HTML>");
            client.println("<html>");
            client.println("<head></head><body><h1>WeMos D1-Temperature and Humidity , LDR Sensor</h1><h3>Temperature in Celsius: ");
            client.println(celsiusTemp);
            client.println("*C</h3><h3>Temperature in Fahrenheit: ");
            client.println(fahrenheitTemp);
            client.println("*F</h3><h3>Humidity: ");
            client.println(humidityTemp);
            client.println("%</h3><h3>");
         
            client.println("</h3><h3>LDR Sensor: ");
            client.println(light);
            client.println("</h3><h3>");
         
            client.println("</body></html>");   
            break;
        }
        if (c == '\n') {
          // when starts reading a new line
          blank_line = true;
        }
        else if (c != '\r') {
          // when finds a character on the current line
          blank_line = false;
        }
      }
    }
    // closing the client connection
    delay(1);
    client.stop();
    Serial.println("Client disconnected.");
 
  }

if (!client_mqtt.connected()) {
    reconnect();
  }
  client_mqtt.loop();
  long now = millis();
  // read DHT11 sensor every 6 seconds
  if (now - lastMsg > 6000) {
     lastMsg = now;
     // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
     float h = dht.readHumidity();
     // Read temperature as Celsius (the default)
     float t = dht.readTemperature();
 
     // Read temperature as Fahrenheit (isFahrenheit = true)
     float f = dht.readTemperature(true);
     // Computes temperature values in Celsius + Fahrenheit and Humidity
     float hic = dht.computeHeatIndex(t, h, false);     
     light = analogRead (lightPin);
     light = map (light, 0, 1023, 0, 100); // scaled from 100 - 0 (lower is darker)
     if (isnan(h) || isnan(t) || isnan(f)) {
        Serial.println("Failed to read from DHT sensor!");
        strcpy(celsiusTemp,"Failed");
        strcpy(fahrenheitTemp, "Failed");
        strcpy(humidityTemp, "Failed");       
         }
      else{

     // Convert data to character array
     char tChar[10];
     char hChar[10];
     char hicChar[10];
     char lChar[10];
     dtostrf(t, 4, 2, tChar);
     dtostrf(h, 4, 2, hChar);
     dtostrf(hic, 4, 2, hicChar);
     dtostrf(light, 4, 2, lChar);

    // Publish data character array to MQTT topics
    client_mqtt.publish("alex9ufo/weather/humidity", hChar);
    client_mqtt.publish("alex9ufo/weather/temperature", tChar);
    client_mqtt.publish("alex9ufo/weather/heatindex", hicChar);
    client_mqtt.publish("alex9ufo/weather/light", lChar);

   
    // Convert data to JSON string
 
     String json =
    "{\"data\":{"
    "\"humidity\": \"" + String(h) + "\","
    "\"temperature\": \"" + String(t) + "\","
    "\"heatindex\": \"" + String(hic) + "\","
    "\"light\": \"" + String(light) + "\"}"
    "}";
   // Convert JSON string to character array
   char jsonChar[100];
   json.toCharArray(jsonChar, json.length()+1);

   // Publish JSON character array to MQTT topic
   client_mqtt.publish("alex9ufo/weather/json", jsonChar);
   /*******************
   // Print to Console
   ********************/

   Serial.println(" ");
   Serial.println("Data");
   Serial.println(json); 
   }  //esle
   
 }

} 
=================================================
node-red jason file

[{"id":"71b52fdc.d6182","type":"mongodb out","z":"59798b21.806fc4","mongodb":"da868d72.ad9c7","name":"mongodb save","collection":"weatherstation1","payonly":true,"upsert":true,"multi":false,"operation":"insert","x":700,"y":80,"wires":[]},{"id":"da13477b.a05df8","type":"mqtt in","z":"59798b21.806fc4","name":"alex9ufo/weather/#","topic":"alex9ufo/weather/#","qos":"2","broker":"57be2704.cd8468","x":127,"y":104,"wires":[["d5396705.c057b8","61b3ba26.16da44"]]},{"id":"61b3ba26.16da44","type":"debug","z":"59798b21.806fc4","name":"alex9ufo/weather/#","active":false,"tosidebar":false,"console":false,"tostatus":false,"complete":"payload","x":390,"y":100,"wires":[]},{"id":"d52320ec.ffc56","type":"mongodb in","z":"59798b21.806fc4","mongodb":"da868d72.ad9c7","name":"weatherstation","collection":"weatherstation1","operation":"find","x":300,"y":640,"wires":[["de2c61c1.dd6de","8484b45c.3c2848"]]},{"id":"da57953.16abe68","type":"mongodb in","z":"59798b21.806fc4","mongodb":"da868d72.ad9c7","name":"weatherstation","collection":"weatherstation1","operation":"find","x":320,"y":520,"wires":[["aca4e2e3.db875"]]},{"id":"aca4e2e3.db875","type":"http response","z":"59798b21.806fc4","name":"weather response","x":550,"y":520,"wires":[]},{"id":"4fe1e569.ca654c","type":"http in","z":"59798b21.806fc4","name":"[get] /showweather","url":"/showweather","method":"get","upload":false,"swaggerDoc":"","x":110,"y":520,"wires":[["da57953.16abe68"]]},{"id":"2cc35f3e.60356","type":"comment","z":"59798b21.806fc4","name":"Weather Station Data in HTML/JSON View","info":"","x":180,"y":480,"wires":[]},{"id":"4297471.8885eb8","type":"chart request","z":"59798b21.806fc4","charttype":"AnnotationChart","path":"/mqttchart2","refresh":"","formatx":"","formaty":"","attribs":[{"name":"date","type":"date"},{"name":"temperature","type":"number"},{"name":"humidity","type":"number"},{"name":"light","type":"number"}],"x":90,"y":640,"wires":[["d52320ec.ffc56"]]},{"id":"8484b45c.3c2848","type":"debug","z":"59798b21.806fc4","name":"chart debug","active":true,"tosidebar":false,"console":false,"tostatus":false,"complete":"payload","x":550,"y":660,"wires":[]},{"id":"de2c61c1.dd6de","type":"chart response","z":"59798b21.806fc4","x":560,"y":620,"wires":[]},{"id":"d5396705.c057b8","type":"switch","z":"59798b21.806fc4","name":"","property":"topic","propertyType":"msg","rules":[{"t":"eq","v":"alex9ufo/weather/json","vt":"str"},{"t":"eq","v":"alex9ufo/weather/temperature","vt":"str"},{"t":"eq","v":"alex9ufo/weather/humidity","vt":"str"},{"t":"eq","v":"alex9ufo/weather/light","vt":"str"}],"checkall":"true","repair":false,"outputs":4,"x":140,"y":207,"wires":[["b5c44f83.bff03","a01c90a8.d4903"],["667d550a.50b9ec","a67d22ee.10ac6","bd6599bf.b26738"],["1c1eaea3.676941","a08695cb.c030d8","ddf716b0.805318"],["3f3c5af6.b272a6","8d79880a.4811a8","7619479e.a3b758"]]},{"id":"b5c44f83.bff03","type":"debug","z":"59798b21.806fc4","name":"alex9ufo/weather/json","active":true,"tosidebar":false,"console":false,"tostatus":false,"complete":"payload","x":580,"y":200,"wires":[]},{"id":"667d550a.50b9ec","type":"debug","z":"59798b21.806fc4","name":"alex9ufo/weather/temperature","active":false,"tosidebar":false,"console":false,"tostatus":false,"complete":"payload","x":550,"y":240,"wires":[]},{"id":"1c1eaea3.676941","type":"debug","z":"59798b21.806fc4","name":"alex9ufo//weather/humidity","active":false,"tosidebar":false,"console":false,"tostatus":false,"complete":"payload","x":540,"y":360,"wires":[]},{"id":"3f3c5af6.b272a6","type":"debug","z":"59798b21.806fc4","name":"alex9ufo//weather/light","active":false,"tosidebar":false,"console":false,"tostatus":false,"complete":"payload","x":180,"y":340,"wires":[]},{"id":"c88131b0.6a9ba","type":"function","z":"59798b21.806fc4","name":"timestamp and format data","func":"msg.payload.data.date = new Date();\nmsg.payload = msg.payload.data;\nreturn msg;","outputs":1,"noerr":0,"x":476,"y":158,"wires":[["71b52fdc.d6182","1b790e76.e78d52"]]},{"id":"a01c90a8.d4903","type":"json","z":"59798b21.806fc4","name":"","property":"payload","action":"","pretty":false,"x":285,"y":158,"wires":[["c88131b0.6a9ba"]]},{"id":"1b790e76.e78d52","type":"debug","z":"59798b21.806fc4","name":"json debug","active":true,"tosidebar":false,"console":false,"tostatus":false,"complete":"payload","x":690,"y":160,"wires":[]},{"id":"7b0f5c00.3ee124","type":"comment","z":"59798b21.806fc4","name":"Weather Station in Google Chart view - /mqttchart","info":"","x":200,"y":600,"wires":[]},{"id":"2ee19861.28d7f8","type":"comment","z":"59798b21.806fc4","name":"Weather Station MQTT Flow","info":"","x":140,"y":63,"wires":[]},{"id":"a67d22ee.10ac6","type":"ui_gauge","z":"59798b21.806fc4","name":"","group":"3382b019.e1c8c","order":0,"width":0,"height":0,"gtype":"gage","title":"temperature","label":"units","format":"{{value}}°C","min":0,"max":"50","colors":["#00b500","#e6e600","#ca3838"],"seg1":"","seg2":"","x":510,"y":280,"wires":[]},{"id":"bd6599bf.b26738","type":"ui_chart","z":"59798b21.806fc4","name":"","group":"3382b019.e1c8c","order":0,"width":0,"height":0,"label":"temperature","chartType":"line","legend":"false","xformat":"HH:mm:ss","interpolate":"linear","nodata":"","dot":false,"ymin":"0","ymax":"50","removeOlder":1,"removeOlderPoints":"","removeOlderUnit":"86400","cutout":0,"useOneColor":false,"colors":["#1f77b4","#aec7e8","#ff7f0e","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5"],"useOldStyle":false,"x":510,"y":320,"wires":[[],[]]},{"id":"a08695cb.c030d8","type":"ui_gauge","z":"59798b21.806fc4","name":"","group":"ea29e7c5.92eb78","order":0,"width":0,"height":0,"gtype":"gage","title":"humidity","label":"units","format":"{{value}}%","min":0,"max":"100","colors":["#00b500","#e6e600","#ca3838"],"seg1":"","seg2":"","x":500,"y":400,"wires":[]},{"id":"ddf716b0.805318","type":"ui_chart","z":"59798b21.806fc4","name":"","group":"ea29e7c5.92eb78","order":0,"width":0,"height":0,"label":"humidity","chartType":"line","legend":"false","xformat":"HH:mm:ss","interpolate":"linear","nodata":"","dot":false,"ymin":"0","ymax":"100","removeOlder":1,"removeOlderPoints":"","removeOlderUnit":"86400","cutout":0,"useOneColor":false,"colors":["#1f77b4","#aec7e8","#ff7f0e","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5"],"useOldStyle":false,"x":500,"y":440,"wires":[[],[]]},{"id":"8d79880a.4811a8","type":"ui_gauge","z":"59798b21.806fc4","name":"","group":"f56a5ae1.4339b8","order":0,"width":0,"height":0,"gtype":"gage","title":"light","label":"units","format":"{{value}}%","min":0,"max":"100","colors":["#00b500","#e6e600","#ca3838"],"seg1":"","seg2":"","x":130,"y":380,"wires":[]},{"id":"7619479e.a3b758","type":"ui_chart","z":"59798b21.806fc4","name":"","group":"f56a5ae1.4339b8","order":0,"width":0,"height":0,"label":"light","chartType":"line","legend":"false","xformat":"HH:mm:ss","interpolate":"linear","nodata":"","dot":false,"ymin":"0","ymax":"100","removeOlder":1,"removeOlderPoints":"","removeOlderUnit":"86400","cutout":0,"useOneColor":false,"colors":["#1f77b4","#aec7e8","#ff7f0e","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5"],"useOldStyle":false,"x":130,"y":420,"wires":[[],[]]},{"id":"76c853f3.7fda2c","type":"comment","z":"59798b21.806fc4","name":"Weather Station in ThingSpeak","info":"","x":150,"y":720,"wires":[]},{"id":"4f9df87.9c86808","type":"mqtt in","z":"59798b21.806fc4","name":"alex9ufo/weather/#","topic":"alex9ufo/weather/#","qos":"2","broker":"57be2704.cd8468","x":110,"y":760,"wires":[["9fa327ca.a066d8"]]},{"id":"2ad1b8da.44eab8","type":"json","z":"59798b21.806fc4","name":"","property":"payload","action":"","pretty":false,"x":410,"y":760,"wires":[["52c99fd4.c2746"]]},{"id":"52c99fd4.c2746","type":"function","z":"59798b21.806fc4","name":"Create GET ThingSpeak URL","func":"var field1 = msg.payload.data.temperature;\nvar field2 = msg.payload.data.humidity;\nvar field3 = msg.payload.data.heatindex;\nvar field4 = msg.payload.data.light;\nmsg.url = \"https://thingspeak.com/update?api_key=FM1ULTRWCUYBBEZZ&field1=\" + field1 + \"&field2=\" + field2 + \"&field3=\" + field3 + \"&field4=\" + field4 ;\nreturn msg;","outputs":1,"noerr":0,"x":430,"y":860,"wires":[["4b3f160a.892798","aa4bee01.4f0c3"]]},{"id":"4b3f160a.892798","type":"debug","z":"59798b21.806fc4","name":"chart debug","active":true,"tosidebar":false,"console":false,"tostatus":false,"complete":"payload","x":650,"y":880,"wires":[]},{"id":"9fa327ca.a066d8","type":"switch","z":"59798b21.806fc4","name":"","property":"topic","propertyType":"msg","rules":[{"t":"eq","v":"alex9ufo/weather/json","vt":"str"},{"t":"eq","v":"alex9ufo/weather/temperature","vt":"str"},{"t":"eq","v":"alex9ufo/weather/humidity","vt":"str"},{"t":"eq","v":"alex9ufo/weather/light","vt":"str"}],"checkall":"true","repair":false,"outputs":4,"x":270,"y":780,"wires":[["2ad1b8da.44eab8"],[],[],[]]},{"id":"aa4bee01.4f0c3","type":"http request","z":"59798b21.806fc4","name":"","method":"GET","ret":"txt","url":"","x":670,"y":800,"wires":[[]]},{"id":"da868d72.ad9c7","type":"mongodb","z":"","hostname":"127.0.0.1","port":"27017","db":"test1","name":""},{"id":"57be2704.cd8468","type":"mqtt-broker","z":"59798b21.806fc4","name":"broker.mqtt-dashboard.com","broker":"broker.mqtt-dashboard.com","port":"1883","clientid":"","usetls":false,"verifyservercert":true,"compatmode":true,"keepalive":"15","cleansession":true,"birthTopic":"","birthQos":"0","birthRetain":"false","birthPayload":"","closeTopic":"","closePayload":"","willTopic":"","willQos":"0","willRetain":"false","willPayload":""},{"id":"3382b019.e1c8c","type":"ui_group","z":"","name":"temperature","tab":"12b04d40.cb16f3","order":1,"disp":true,"width":"6","collapse":false},{"id":"ea29e7c5.92eb78","type":"ui_group","z":"","name":"humidity","tab":"12b04d40.cb16f3","order":2,"disp":true,"width":"6","collapse":false},{"id":"f56a5ae1.4339b8","type":"ui_group","z":"","name":"light","tab":"12b04d40.cb16f3","order":3,"disp":true,"width":"6","collapse":false},{"id":"12b04d40.cb16f3","type":"ui_tab","z":"","name":"alex9ufo","icon":"dashboard","order":1}]

2018年7月4日 星期三

MongoDB 教程

MongoDB 教程

MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。
MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。


内容列表

NoSQL 简介
介绍NoSQL基础概念。
MongoDB 简介
介绍MongoDB基础概念。
window平台安装MongoDB
介绍如何在window平台上安装MongoDB。
Linux平台安装MongoDB
介绍如何在Linux平台上安装MongoDB。
MongoDB 连接
介绍 MongoDB 数据库,对象,集合应用。
PHP安装MongoDB扩展
介绍PHP安装MongoDB扩展的方法。
MongoDB 插入文档
介绍MongoDB 数据插入操作。
MongoDB 更新文档
介绍 MongoDB 更新数据操作。
MongoDB 删除文档
介绍 MongoDB 删除数据操作。
MongoDB 查询
介绍 MongoDB 数据查询操作。
MongoDB条件操作符
介绍MongoDB条件操作符的使用。
MongoDB $type 操作符
介绍 MongoDB 条件操作符$type的使用。

参考地址

MongoDB 官网地址:https://www.mongodb.com/
MongoDB 官方英文文档:https://docs.mongodb.com/manual/
MongoDB 各平台下载地址:https://www.mongodb.com/download-center#community

2018年7月3日 星期二

Node RED Programming Guide

Node RED Programming Guide

Programming the IoT
The node red guide is a series of lectures designed to get you started with Node-RED. Starting from the very basics, it introduces you to how Node-RED works and how to get the most out of its built in nodes. Each lecture consists of a series of hands-on examples that take you from basic to intermediate Node-RED programming in easy to follow steps.
  • Node-RED: Lecture 1 – A brief introduction to Node-RED This lecture will introduce you to some examples of Node-RED, both to give you a sense of its capabilities and to introduce its basic concepts. We’ll also discuss the history of Node-RED and its origins to give you an idea of what Node-RED is good for and of what types of tasks are best left to a more traditional programming language and environments.
  • Node-RED: Lecture 2 – Building your first flows This lecture will introduce you to the Node-RED visual tool and get you started building your first flow. You’ll learn how to create simple flows, use debug nodes to track messages through the flows and how to use the function node to write simple JavaScript code that tailors the node to your specific needs.
  • Node-RED: Lecture 3 – Basic nodes and flows In this lecture you will get to see a few of the more commonly used nodes and build on some of the things you learnt in previous lectures. You’ll start off with a series of examples based around the popular MQTT protocol that shows how to wire together a set of basic but very useful message processing nodes. Then you’ll briefly look at other ways to get messages into and out of your flows using protocols such as TCP, UDP and websockets.
  • Node-RED: Lecture 4 – A tour of the core nodes This lecture will take a look at the core set of nodes that Node-RED installs by default and then show you the extended set of nodes that the cloud-based Node-RED service – FRED – supports.
  • Node-RED: Lecture 5 – The Node-RED programming model In this lecture, you’ll take a more detailed look at Node-RED’s programming model and some of its key concepts and explore the details of the message flow model that underlies Node-RED. Then you’ll dive into how to program your own function nodes using JavaScript and create reusable sub flows to add your own functionality to the set of nodes supplied with Node-RED.
  • Node-RED: Lecture 6 – Intermediate flows This lecture will build on the ideas you saw in lecture 5 and focus on examples that explore some of the key concepts from that lecture. The examples in this lecture are a little more complex than previous examples – mainly in the sense that the function nodes are more complex – but are still kept as clean and simple as possible.
  • Node-RED: Lecture 7 – Dashboards and UI techniques.  In this lecture you will take a look a few techniques to allow you to visualize data passing through flows. We’ll focus on three approaches;
    • PART 1: the use of a third party dashboard tool – FreeBoard,
    • PART 2: using the standard Node-RED default UI nodes
    • PART 3: using a standard external JavaScript charting library (Morris.JS).
  • Node-RED: Lecture 8 – examples of advanced flows. This lecture is a collection of tutorials and blogs that we’ve written showing Node-RED used for more sophisticated applications. It includes usage of IBM watson for AI bots, some hard core MQTT and OPC for the IoT crowd etc
  • List of examples used in the lectures – a listing of all of the examples used in all lectures

About Sense Tecnic: Sense Tecnic Systems Inc have been building IoT applications and services since 2010. We provide these lectures, and FRED, cloud hosted Node-RED as a service to the community. We also offer a commercial version to our customers, as well as professional services. Learn more.

2018年6月29日 星期五

DHT11_SSD1306_Webserver



















//D1 --SSD1305 SCL
//D2 --SSD1306 SDA

// Including the ESP8266 WiFi library
#include <ESP8266WiFi.h>
#include "DHT.h"
#include  "Adafruit_Sensor.h"
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define OLED_RESET LED_BUILTIN  //4
Adafruit_SSD1306 display(OLED_RESET);

// Uncomment one of the lines below for whatever DHT sensor type you're using!
#define DHTTYPE DHT11   // DHT 11
//#define DHTTYPE DHT21   // DHT 21 (AM2301)
//#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321

// Replace with your network details
//const char* ssid = "YOUR_NETWORK_NAME";
//const char* password = "YOUR_NETWORK_PASSWORD";
const char* ssid = "74170287";
const char* password = "24063173";


// Web Server on port 80
WiFiServer server(80);

// DHT Sensor
const int DHTPin = D3;
// Initialize DHT sensor.
DHT dht(DHTPin, DHTTYPE);

// Temporary variables
static char celsiusTemp[7];
static char fahrenheitTemp[7];
static char humidityTemp[7];

// only runs once on boot
void setup() {
  // Initializing serial port for debugging purposes
  Serial.begin(115200);
  delay(10);
  dht.begin();

  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  // Clear the buffer.
  display.clearDisplay();
  display.display();

  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0,0);
  display.println("Hello from:");
  display.println("http://alex9ufo.blogspot.com/");
  display.display();
 
  // Connecting to 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");
 
  // Starting the web server
  server.begin();
  Serial.println("Web server running. Waiting for the ESP IP...");
  delay(10000);
 
  // Printing the ESP IP address
  Serial.println(WiFi.localIP());
}

// runs over and over again
void loop() {
  // Listenning for new clients
  WiFiClient client = server.available();
 
  if (client) {
    Serial.println("New client");
    // bolean to locate when the http request ends
    boolean blank_line = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
       
        if (c == '\n' && blank_line) {
            // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
            float h = dht.readHumidity();
            // Read temperature as Celsius (the default)
            float t = dht.readTemperature();
            // Read temperature as Fahrenheit (isFahrenheit = true)
            float f = dht.readTemperature(true);
            // Check if any reads failed and exit early (to try again).
            if (isnan(h) || isnan(t) || isnan(f)) {
              Serial.println("Failed to read from DHT sensor!");
              strcpy(celsiusTemp,"Failed");
              strcpy(fahrenheitTemp, "Failed");
              strcpy(humidityTemp, "Failed");       
            }
            else{
              /*
              // Compute heat index in Fahrenheit (the default)
              float hif = dht.computeHeatIndex(f, h);
              // Compute heat index in Celsius (isFahreheit = false)
              float hic = dht.computeHeatIndex(t, h, false); */
             
              // Computes temperature values in Celsius + Fahrenheit and Humidity
              float hic = dht.computeHeatIndex(t, h, false);     
              dtostrf(hic, 6, 2, celsiusTemp);           
              float hif = dht.computeHeatIndex(f, h);
             
              dtostrf(hif, 6, 2, fahrenheitTemp);       
              dtostrf(h, 6, 2, humidityTemp);
              // You can delete the following Serial.print's, it's just for debugging purposes
              Serial.print("Humidity: ");
              Serial.print(h);
              Serial.print(" %\t Temperature: ");
              Serial.print(t);
              Serial.print(" *C ");
              Serial.print(f);
              Serial.print(" *F\t Heat index: ");
              Serial.print(hic);
              Serial.print(" *C ");
              Serial.print(hif);
              Serial.print(" *F");
              Serial.print("Humidity: ");
              Serial.print(h);
              Serial.print(" %\t Temperature: ");
              Serial.print(t);
              Serial.print(" *C ");
              Serial.print(f);
              Serial.print(" *F\t Heat index: ");
              Serial.print(hic);
              Serial.print(" *C ");
              Serial.print(hif);
              Serial.println(" *F");
              //-------------SSD 1306 Display-------------------//
                // Clear the buffer.
              display.clearDisplay();
              display.display();

              display.setTextSize(1);
              display.setTextColor(WHITE);
              display.setCursor(0,0);
              display.print("TemCel:");
              display.print(celsiusTemp);
              display.println(" *C ");
             
              display.setCursor(0,8);           
              display.print("TemFah:");
              display.print(fahrenheitTemp);
              display.println(" *F ");
             
              display.setCursor(0,16);             
              display.print("Humidity:");
              display.print(humidityTemp);
              display.println(" %");           
              //-------------SSD 1306 Display-------------------//
              display.setCursor(0,24); 
              display.println("http://alex9ufo.blogspot.com/");
              display.display();
              //-------------SSD 1306 Display-------------------//
            }
            client.println("HTTP/1.1 200 OK");
            client.println("Content-Type: text/html");
            client.println("Connection: close");
            client.println();
            // your actual web page that displays temperature and humidity
            client.println("<!DOCTYPE HTML>");
            client.println("<html>");
            client.println("<head></head><body><h1>ESP8266 - Temperature and Humidity</h1><h3>Temperature in Celsius: ");
            client.println(celsiusTemp);
            client.println("*C</h3><h3>Temperature in Fahrenheit: ");
            client.println(fahrenheitTemp);
            client.println("*F</h3><h3>Humidity: ");
            client.println(humidityTemp);
            client.println("%</h3><h3>");
            client.println("</body></html>");   
            break;
        }
        if (c == '\n') {
          // when starts reading a new line
          blank_line = true;
        }
        else if (c != '\r') {
          // when finds a character on the current line
          blank_line = false;
        }
      }
    } 
    // closing the client connection
    delay(1);
    client.stop();
    Serial.println("Client disconnected.");
 
  }
} 

OLED SSD1306 Display







//D1 --SSD1305 SCL
//D2 --SSD1306 SDA

#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define OLED_RESET LED_BUILTIN  //4
Adafruit_SSD1306 display(OLED_RESET);

//#if (SSD1306_LCDHEIGHT != 64)
//#error("Height incorrect, please fix Adafruit_SSD1306.h!");
//#endif

void setup() {
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);

  // Clear the buffer.
  display.clearDisplay();
  display.display();

  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0,0);
  display.println("Hello from:");
  display.println("http://alex9ufo.blogspot.com/");
  display.display();

}

void loop() {
  // put your main code here, to run repeatedly:

}

2018年6月20日 星期三

NodeMCU Starter Kit - Neo










NodeMCU Starter Kit - Neo

NodeMCU Analog Input on Arduino IDE 

This tutorial of Robo India explains the basics of input and output programming in physical computing world. This tutorial teaches how to take analog input from NodeMCU.

NodeMCU Analog Output on Arduino IDE 

This tutorial of Robo India explains the basics of input and output programming in physical computing world. This tutorial teaches how to take analog output from NodeMCU.

NodeMCU Serial Monitor on Arduino IDE 

This tutorial of Robo India explains the basics of serial monitor of Arduino IDE for NodeMCU.

NodeMCU i2c Scanner on Arduino IDE 

This tutorial of Robo India explains how to get address of i2c device connected to a NodeMCU using Arduino IDE.

NodeMCU Weather Station on Arduino IDE 

This tutorial of Robo India is to make an online weather station on NodeMCU with Arduino IDE.

NodeMCU Temperature, Humidity data upload on Thingspeak on Arduino IDE 

This tutorial of Robo India explains how to store and upload the weather data of DHT11 temperature and humidity sensor on cloud ( ThingSpeak.com) using wifi modem NodeMCU.

NodeMCU on Arduino - Introduction 

This tutorial of Robo India explains how to use NodeMCU on Arduino IDE.

NodeMCU RGB LED on Arduino IDE 

This tutorial of Robo India explains how to use RGB LED on NodeMCU using Arduino IDE.

NodeMCU Switching Using Transistor on Arduino IDE 

This tutorial of Robo India explains how to a transistor as a switch on NodeMCU using Arduino IDE.

NodeMCU Seven Segment Display on Arduino IDE 

This tutorial of Robo India explains how to use a seven segment display on NodeMCU using Arudino IDE.

NodeMCU connecting to internet on Arduino IDE 

This tutorial of Robo India is a basic tutorial to connect a NodeMCU wifi module to the internet. This tutorial is based on Arduino IDE.

NodeMCU Digital Output - LED Blinking on Arduino IDE 

This tutorial of Robo India explains the basics of input and output programming in physical computing world. This tutorial teaches how to take digital output from NodeMCU on Arduion IDE. The output is taken on LED, It glows for a second and remain off for a second.

NodeMCU 16x2 LCD on Arduino IDE 

This tutorial explains how to use 16x2 LCD on NodeMCU wifi development board using Arduino IDE.

NodeMCU LDR on Arduino IDE 

This tutorial of Robo India explains how to use LDR on NodeMCU using Arduino IDE.

NodeMCU IR proximity & Color Detection on Arduino IDE 

This tutorial of Robo India explains how to use IR LED and photo diode as a color detection sensor and as a proximity detection sensor.

DHT11 Temperature & Humidity sensor on NodeMCU using Arduino IDE 

Robo India presents tutorial on how to read temperature and humidity data through DHT11 sensor using ESP8266 wifi module on NODEMCU LUA platform.

NodeMCU on Arduino IDE - Getting MAC address 

This tutorial of Robo India explains how to get MAC address of NodeMCU using Aruduino IDE.



NodeMCU Digital Input with Output Arduino IDE 

This tutorial of Robo India explains the basics of input and output programming in physical computing world. This tutorial teaches how to take digital input and show that as an output on NodeMCU on Arduion IDE. The input is taken through switch and the output is taken on LED, the LED glows when button is pressed.

  清除項目編譯快取 執行 flutter clean 重新取得套件依賴 執行 flutter pub get 完整重新編譯並執行 flutter run 1. 新增專案套件 (pubspec.yaml) 在 Flutter 專案根目錄下的 pubspec.yaml 中,新增 ...