[C] 纯文本查看 复制代码
/*
ESP8266 TCPcleint 连接到NET WORK ,
读取DHT11数据并上传云端,用手机或电脑可监控设备温湿度,实现远程监控实时温湿度!
基于yeelink 免费物联平台 www.yeelink.net
by yfrobot
http://www.yfrobot.com
*/
#include <ESP8266WiFi.h>
#include "DHT.h"
#define DHTPIN 4 // what digital pin we're connected to
#define DHTTYPE DHT11 // DHT 11 -- Uncomment whatever type you're using!
const char* ssid = "YFROBOT"; // XXXXXX -- 使用时请修改为当前你的 wifi ssid
const char* password = "xxxxx"; // XXXXXX -- 使用时请修改为当前你的 wifi 密码
const char* host = "www.yeelink.net";
const char* APIKEY = "xxxxxx"; //API KEY
int deviceId = 345667;
int sensorId_T = 387465;
int sensorId_H = 387466;
WiFiClient client;
const int tcpPort = 80;
char data[512] ;
int x = 0;
int dat = 0;
DHT dht(DHTPIN, DHTTYPE);
int postCount = 0;
void setup() {
WiFi.mode(WIFI_AP_STA); //set work mode: WIFI_AP /WIFI_STA /WIFI_AP_STA
Serial.begin(115200);
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.print("IP address: ");
Serial.println(WiFi.localIP());
dht.begin();
}
void loop() {
delay(2000);
// Reading temperature or humidity takes about 250 milliseconds!
// 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();
Serial.print(h);
Serial.println(t);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
if (!client.connect(host, tcpPort)) {
Serial.println("connection failed");
return;
}
//post value
if (postCount == 0) {
postData(deviceId, sensorId_T, t);
postCount++;
} else {
postData(deviceId, sensorId_H, h);
postCount = 0;
}
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 2000) {
Serial.println(">>> Client Timeout !");
client.stop();
return;
}
}
Serial.println("closing connection");
}
void postData(int dId, int sId, float val) {
// We now create a URI for the request
String url = "/v1.0/device/";
url += String(dId);
url += "/sensor/";
url += String(sId);
url += "/datapoints";
String str = String(val);
String data = "{\"value\":" + str + "}";
// This will send the request to the server
client.print(String("POST ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Accept: */*\r\n" +
"U-ApiKey:" + APIKEY + "\r\n" +
"Content-Length: " + String(str.length()+10) + "\r\n" + //发送数据长度
"Content-Type: application/x-www-form-urlencoded\r\n" +
"Connection: close\r\n\r\n" +
data
);
Serial.println(str);
Serial.println(String(str.length()));
}