ESP8266 HTTP POST with Time Stamp: Sending Data to a Server
/**
- PostHTTPClient.ino
- Created on: 21.11.2016 */ #include <NTPClient.h> #include <WiFiUdp.h>
#define NTP_OFFSET 60 * 60 // In seconds #define NTP_INTERVAL 60 * 1000 // In miliseconds #define NTP_ADDRESS 'europe.pool.ntp.org'
WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP, NTP_ADDRESS, NTP_OFFSET, NTP_INTERVAL); #include <ESP8266WiFi.h> #include <ESP8266HTTPClient.h>
/* this can be run with an emulated server on host: cd esp8266-core-root-dir cd tests/host make ../../libraries/ESP8266WebServer/examples/PostServer/PostServer bin/PostServer/PostServer then put your PC's IP address in SERVER_IP below, port 9080 (instead of default 80): */ //#define SERVER_IP '10.0.1.7:9080' // PC address with emulation on host #define SERVER_IP '192.168.0.107:3000'
#ifndef STASSID #define STASSID 'MERCURY_2289' #define STAPSK 'qqq111000' #endif
void setup() {
Serial.begin(115200); timeClient.begin(); Serial.println(); Serial.println(); Serial.println();
WiFi.begin(STASSID, STAPSK);
while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print('.'); } Serial.println(''); Serial.print('Connected! IP address: '); Serial.println(WiFi.localIP()); }
void loop() { // wait for WiFi connection String formattedTime = timeClient.getFormattedTime();
// Print formatted time to serial monitor Serial.println(formattedTime); if ((WiFi.status() == WL_CONNECTED)) {
WiFiClient client;
HTTPClient http;
Serial.print('[HTTP] begin...
'); // configure traged server and url http.begin(client, 'http://' SERVER_IP '/upload'); // HTTP http.addHeader('Content-Type', 'application/json');
Serial.print('[HTTP] POST...
'); // start connection and send HTTP header and body int httpCode = http.POST('{'data':'world','id':'world','name':'world','time':' + timeClient.getEpochTime() + '}'); Serial.print('{'data':'world','id':'world','name':'world','time':' + timeClient.getEpochTime() + '}'); // httpCode will be negative on error if (httpCode > 0) { // HTTP header has been send and Server response header has been handled Serial.printf('[HTTP] POST... code: %d\n', httpCode);
// file found at server
if (httpCode == HTTP_CODE_OK) {
const String& payload = http.getString();
Serial.println('received payload:\n<<');
Serial.println(payload);
Serial.println('>>');
}
} else {
Serial.printf('[HTTP] POST... failed, error: %s\n', http.errorToString(httpCode).c_str());
}
http.end();
}
delay(10000); }
原文地址: https://www.cveoy.top/t/topic/mGFW 著作权归作者所有。请勿转载和采集!