可以由Node-RED 與MQTT-BOX 送出信號控制NodeMCU
/*********
Rui Santos
Complete project details at http://randomnerdtutorials.com
*********/
// Including the ESP8266 WiFi library
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"
// 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 = "PTS-2F";
const char* password = "";
const char* mqtt_server = "broker.mqtt-dashboard.com";
//const char* mqtt_server = "iot.eclipse.org";
WiFiClient espClient;
PubSubClient client1(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
// 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];
void callback(char* topic, byte* payload, unsigned int length)
{
Serial.print("Command is : [");
Serial.print(topic);
int p =(char)payload[0]-'0';
// if MQTT comes a 0 message, show humidity
if(p==0)
{
Serial.println("to show humidity!]");
Serial.print(" Humidity is: " );
Serial.print(dht.readHumidity(), 1);
Serial.println('%');
}
// if MQTT comes a 1 message, show temperature
if(p==1)
{
// digitalWrite(BUILTIN_LED, HIGH);
Serial.println(" is to show temperature!] ");
Serial.print(" Temp is: " );
Serial.print(dht.readTemperature(), 1);
Serial.println(' C');
}
Serial.println();
} //end callback
void reconnect() {
// Loop until we're reconnected
while (!client1.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 (client1.connect(clientId.c_str()))
{
Serial.println("connected");
//once connected to MQTT broker, subscribe command if any
client1.subscribe("alex9ufo_Command");
} else {
Serial.print("failed, rc=");
Serial.print(client1.state());
Serial.println(" try again in 5 seconds");
// Wait 6 seconds before retrying
delay(6000);
}
}
} //end reconnect()
// only runs once on boot
void setup() {
// Initializing serial port for debugging purposes
Serial.begin(115200);
delay(10);
dht.begin();
// 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());
client1.setServer(mqtt_server, 1883);
client1.setCallback(callback);
Serial.print(" Starting Humidity: " );
Serial.print(dht.readHumidity(), 2);
Serial.println('%');
Serial.print(" Starting Temparature ");
Serial.print(dht.readTemperature(), 2);
Serial.print('*C');
Serial.print(dht.readTemperature(true), 2);
Serial.println('*F');
}
//=================================================================================
// 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{
// 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");
}
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.");
}
if (!client1.connected()) {
reconnect();
}
client1.loop();
long now = millis();
// read DHT11 sensor every 6 seconds
if (now - lastMsg > 6000) {
lastMsg = now;
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);
String msg="Temperature: ";
msg= msg+ String(dht.computeHeatIndex(t, h, false),2);
msg = msg+" *C ;" ;
msg= msg+ String(dht.computeHeatIndex(f, h),2);
msg = msg+" *F ; Humidity: " ;
msg=msg+ String(dht.readHumidity(),2);
msg=msg+"%";
char message[58];
msg.toCharArray(message,58);
Serial.println(message);
//publish sensor data to MQTT broker
client1.publish("alex9ufo_Data", message);
}
}