本文整理汇总了C++中WiFiClient::readStringUntil方法的典型用法代码示例。如果您正苦于以下问题:C++ WiFiClient::readStringUntil方法的具体用法?C++ WiFiClient::readStringUntil怎么用?C++ WiFiClient::readStringUntil使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类WiFiClient
的用法示例。
在下文中一共展示了WiFiClient::readStringUntil方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: connect
/********************************************************************
connect establishes a connection to the Slack RTM API
********************************************************************/
bool ArduinoSlackBot::connect() {
// Step 1: Find WebSocket address via RTM API (https://api.slack.com/methods/rtm.start)
HTTPClient http;
String slackAddr = "https://slack.com/api/rtm.start?token=";
slackAddr = String(slackAddr + slackToken);
PRINTLN(slackAddr);
http.begin(slackAddr.c_str(), slackSSLFingerprint);
int httpCode = http.GET();
if (httpCode != HTTP_CODE_OK) {
PRINTF("HTTP GET failed with code %d\n", httpCode);
return false;
}
WiFiClient *client = http.getStreamPtr();
client->find("wss:\\/\\/");
String host = client->readStringUntil('\\');
String path = client->readStringUntil('"');
path.replace("\\/", "/");
// Step 2: Open WebSocket connection and register event handler
PRINTLN("WebSocket Host=" + host + " Path=" + path);
webSocket.beginSSL(host, 443, path, "", "");
webSocket.onEvent(webSocketEvent);
return true;
}
示例2: sendParameter
void EIoTCloudRestApi::sendParameter(const char * instaceParamId, String value)
{
WiFiClient client;
while(!client.connect(EIOT_CLOUD_ADDRESS, EIOT_CLOUD_PORT)) {
debug("connection failed");
wifiConnect();
}
String url = "";
// URL: /RestApi/SetParameter/[instance id]/[parameter id]/[value]
url += "/RestApi/SetParameter/" + String(instaceParamId) + "/" + value; // generate EasIoT cloud update parameter URL
debug("POST data to URL: ");
#ifdef DEBUG
char buff[300];
url.toCharArray(buff, 300);
debug(buff);
#endif
client.print(String("POST ") + url + " HTTP/1.1\r\n" +
"Host: " + String(EIOT_CLOUD_ADDRESS) + "\r\n" +
"Connection: close\r\n" +
"Content-Length: 0\r\n" +
"\r\n");
delay(100);
while(client.available()){
#ifdef DEBUG
String line = client.readStringUntil('\r');
line.toCharArray(buff, 300);
debug(buff);
#endif
}
}
示例3: loop
void loop() {
// NETWORKING
// TODO FIGURE OUT WHETHRE THIS IS BLOCKING
WiFiClient client = server.available();
if (!client) return; // TODO CONTINUE LOOPING
int timeout = COMM_TIMEOUT; // TODO LESS BUSY WAIT?
logMsg("New client");
while(!client.available() && --timeout>0) {
delay(1);
}
if (timeout <= 0) {
logMsg("TIMEOUT");
client.flush();
return;
}
// GET MSG
// TODO FIGURE OUT WHY DOESN'T WORK DIRECTLY
String str = client.readStringUntil(0);
client.flush();
logMsg(String("Got message [") + str + "]");
// SEND REPLY
client.print(processRequest(str).toString());
delay(1);
logMsg("Client disonnected");
}
示例4: updateTime
void TimeClient::updateTime() {
WiFiClient client;
const int httpPort = 80;
if (!client.connect("google.com", httpPort)) {
Serial.println("connection failed");
return;
}
// This will send the request to the server
client.print(String("GET / HTTP/1.1\r\n") +
String("Host: google.com\r\n") +
String("Connection: close\r\n\r\n"));
int repeatCounter = 0;
while(!client.available() && repeatCounter < 10) {
delay(1000);
Serial.println(".");
repeatCounter++;
}
String line;
int size = 0;
client.setNoDelay(false);
while(client.connected()) {
while((size = client.available()) > 0) {
line = client.readStringUntil('\n');
line.toUpperCase();
// example:
// date: Thu, 19 Nov 2015 20:25:40 GMT
if (line.startsWith("DATE: ")) {
Serial.println(line.substring(23, 25) + ":" + line.substring(26, 28) + ":" +line.substring(29, 31));
int parsedHours = line.substring(23, 25).toInt();
int parsedMinutes = line.substring(26, 28).toInt();
int parsedSeconds = line.substring(29, 31).toInt();
Serial.println(String(parsedHours) + ":" + String(parsedMinutes) + ":" + String(parsedSeconds));
localEpoc = (parsedHours * 60 * 60 + parsedMinutes * 60 + parsedSeconds);
Serial.println(localEpoc);
localMillisAtUpdate = millis();
}
}
}
}
示例5: HttpRequest
String DHwifi::HttpRequest( String req )
{
WiFiClient client;
char host[99];
m_remoteServer.toCharArray( host, 99);
const int httpPort = 80;
if (!client.connect(host, httpPort))
{
Serial.print( host );
Serial.println(" connection failed");
return "";
}
client.print(String("GET ") + req + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
delay(10);
String result;
// Read all the lines of the reply from server and print them to Serial
while (client.available())
{
result = client.readStringUntil('\r');
}
return result;
}
示例6:
/**
* Send the supplied message then read back the other node's response
* and pass that to the user-supplied handler.
*
* @target_ssid The name of the AP the other node has set up.
* @message The string to send to the node.
* @returns: True if the exchange was a succes, false otherwise.
*
*/
bool ESP8266WiFiMesh::exchangeInfo(String message, WiFiClient curr_client)
{
curr_client.println( message.c_str() );
if (!waitForClient(curr_client, 1000))
return false;
String response = curr_client.readStringUntil('\r');
curr_client.readStringUntil('\n');
if (response.length() <= 2)
return false;
/* Pass data to user callback */
_handler(response);
return true;
}
示例7: sync_led
void sync_led(WiFiClient client) {
int new_brightness = -1;
while (client.available()) {
String line = client.readStringUntil('\r');
int ix_magic_ld = line.indexOf("ld");
int ix_colon = line.indexOf(":");
if (ix_magic_ld != -1) {
// Sync the LEDs
int ix_led = line.substring(ix_magic_ld + 2, ix_colon).toInt();
// The RGB value are encoded in Base 10 (not base 16) with "zero" padding.
// LD<LED_INDEX>: FFFFFF
// | | | |
// 0 2 C 2
String hexval = line.substring(ix_colon + 2);
long value = strtol(hexval.c_str(), NULL, 16);
int led_r = value >> 16;
int led_g = value >> 8 & 0xFF;
int led_b = value & 0xFF;
pixels.setPixelColor(ix_led, pixels.Color(led_r, led_g, led_b));
pixels.show();
#if DEBUG
Serial.print("LED#");
Serial.print(ix_led);
Serial.print(" <rgb>:");
Serial.print(led_r);
Serial.print(',');
Serial.print(led_g);
Serial.print(',');
Serial.print(led_b);
Serial.print('\n');
#endif
}
int ix_magic_br = line.indexOf("brightness");
if (ix_magic_br != -1) {
// Update the Brightness Values
new_brightness = line.substring(ix_colon + 2).toInt();
}
}
示例8: APServer
void APServer(){
WiFiClient client = server.available(); // Check if a client has connected
if (!client) {
return;
}
Serial.println("");
Serial.println("New client");
// Wait for data from client to become available
while (client.connected() && !client.available()) {
delay(1);
}
// Read the first line of HTTP request
String req = client.readStringUntil('\r');
Serial.println(req);
String s;
String gsid;
String gpwd;
//if the form has been submitted
if(req.indexOf("ssid")!=-1){
//TODO Make this a POST request
//I'm basically hoping they're being nice
int x = req.indexOf("ssid")+5;
gsid = req.substring(x,req.indexOf("&",x));
x = req.indexOf("pwd")+4;
gpwd = req.substring(x,req.indexOf(" ",x));
s = gsid;
saveWifiConfig(gsid,gpwd);
Serial.print("Restarting");
client.print("Thanks! Restarting to new configuration");
client.flush();
ESP.restart();
}
else{
s = "<h1>Welcome to your ESP</h1><form action='/' method='get'><table><tr><td>SSID</td><td><input type='text' name='ssid'></td></tr><tr><td>Password</td><td><input type='text' name='pwd'></td><tr><td /><td><input type='submit' value='Submit'></td></tr></form>";
client.print(s);
}
client.flush();
delay(1);
//Serial.println("Client disonnected");
}
示例9: atoi
bool ESP8266WebServer::_parseRequest(WiFiClient& client) {
// Read the first line of HTTP request
String req = client.readStringUntil('\r');
client.readStringUntil('\n');
//reset header value
for (int i = 0; i < _headerKeysCount; ++i) {
_currentHeaders[i].value =String();
}
// First line of HTTP request looks like "GET /path HTTP/1.1"
// Retrieve the "/path" part by finding the spaces
int addr_start = req.indexOf(' ');
int addr_end = req.indexOf(' ', addr_start + 1);
if (addr_start == -1 || addr_end == -1) {
#ifdef DEBUG_ESP_HTTP_SERVER
DEBUG_OUTPUT.print("Invalid request: ");
DEBUG_OUTPUT.println(req);
#endif
return false;
}
String methodStr = req.substring(0, addr_start);
String url = req.substring(addr_start + 1, addr_end);
String versionEnd = req.substring(addr_end + 8);
_currentVersion = atoi(versionEnd.c_str());
String searchStr = "";
int hasSearch = url.indexOf('?');
if (hasSearch != -1){
searchStr = urlDecode(url.substring(hasSearch + 1));
url = url.substring(0, hasSearch);
}
_currentUri = url;
_chunked = false;
HTTPMethod method = HTTP_GET;
if (methodStr == "POST") {
method = HTTP_POST;
} else if (methodStr == "DELETE") {
method = HTTP_DELETE;
} else if (methodStr == "OPTIONS") {
method = HTTP_OPTIONS;
} else if (methodStr == "PUT") {
method = HTTP_PUT;
} else if (methodStr == "PATCH") {
method = HTTP_PATCH;
}
_currentMethod = method;
#ifdef DEBUG_ESP_HTTP_SERVER
DEBUG_OUTPUT.print("method: ");
DEBUG_OUTPUT.print(methodStr);
DEBUG_OUTPUT.print(" url: ");
DEBUG_OUTPUT.print(url);
DEBUG_OUTPUT.print(" search: ");
DEBUG_OUTPUT.println(searchStr);
#endif
//attach handler
RequestHandler* handler;
for (handler = _firstHandler; handler; handler = handler->next()) {
if (handler->canHandle(_currentMethod, _currentUri))
break;
}
_currentHandler = handler;
String formData;
// below is needed only when POST type request
if (method == HTTP_POST || method == HTTP_PUT || method == HTTP_PATCH || method == HTTP_DELETE){
String boundaryStr;
String headerName;
String headerValue;
bool isForm = false;
bool isEncoded = false;
uint32_t contentLength = 0;
//parse headers
while(1){
req = client.readStringUntil('\r');
client.readStringUntil('\n');
if (req == "") break;//no moar headers
int headerDiv = req.indexOf(':');
if (headerDiv == -1){
break;
}
headerName = req.substring(0, headerDiv);
headerValue = req.substring(headerDiv + 1);
headerValue.trim();
_collectHeader(headerName.c_str(),headerValue.c_str());
#ifdef DEBUG_ESP_HTTP_SERVER
DEBUG_OUTPUT.print("headerName: ");
DEBUG_OUTPUT.println(headerName);
DEBUG_OUTPUT.print("headerValue: ");
DEBUG_OUTPUT.println(headerValue);
#endif
if (headerName == "Content-Type"){
if (headerValue.startsWith("text/plain")){
isForm = false;
} else if (headerValue.startsWith("application/x-www-form-urlencoded")){
isForm = false;
//.........这里部分代码省略.........
示例10: while
bool ESP8266WebServer::_parseForm(WiFiClient& client, String boundary, uint32_t len){
#ifdef DEBUG_ESP_HTTP_SERVER
DEBUG_OUTPUT.print("Parse Form: Boundary: ");
DEBUG_OUTPUT.print(boundary);
DEBUG_OUTPUT.print(" Length: ");
DEBUG_OUTPUT.println(len);
#endif
String line;
int retry = 0;
do {
line = client.readStringUntil('\r');
++retry;
} while (line.length() == 0 && retry < 3);
client.readStringUntil('\n');
//start reading the form
if (line == ("--"+boundary)){
RequestArgument* postArgs = new RequestArgument[32];
int postArgsLen = 0;
while(1){
String argName;
String argValue;
String argType;
String argFilename;
bool argIsFile = false;
line = client.readStringUntil('\r');
client.readStringUntil('\n');
if (line.startsWith("Content-Disposition")){
int nameStart = line.indexOf('=');
if (nameStart != -1){
argName = line.substring(nameStart+2);
nameStart = argName.indexOf('=');
if (nameStart == -1){
argName = argName.substring(0, argName.length() - 1);
} else {
argFilename = argName.substring(nameStart+2, argName.length() - 1);
argName = argName.substring(0, argName.indexOf('"'));
argIsFile = true;
#ifdef DEBUG_ESP_HTTP_SERVER
DEBUG_OUTPUT.print("PostArg FileName: ");
DEBUG_OUTPUT.println(argFilename);
#endif
//use GET to set the filename if uploading using blob
if (argFilename == "blob" && hasArg("filename")) argFilename = arg("filename");
}
#ifdef DEBUG_ESP_HTTP_SERVER
DEBUG_OUTPUT.print("PostArg Name: ");
DEBUG_OUTPUT.println(argName);
#endif
argType = "text/plain";
line = client.readStringUntil('\r');
client.readStringUntil('\n');
if (line.startsWith("Content-Type")){
argType = line.substring(line.indexOf(':')+2);
//skip next line
client.readStringUntil('\r');
client.readStringUntil('\n');
}
#ifdef DEBUG_ESP_HTTP_SERVER
DEBUG_OUTPUT.print("PostArg Type: ");
DEBUG_OUTPUT.println(argType);
#endif
if (!argIsFile){
while(1){
line = client.readStringUntil('\r');
client.readStringUntil('\n');
if (line.startsWith("--"+boundary)) break;
if (argValue.length() > 0) argValue += "\n";
argValue += line;
}
#ifdef DEBUG_ESP_HTTP_SERVER
DEBUG_OUTPUT.print("PostArg Value: ");
DEBUG_OUTPUT.println(argValue);
DEBUG_OUTPUT.println();
#endif
RequestArgument& arg = postArgs[postArgsLen++];
arg.key = argName;
arg.value = argValue;
if (line == ("--"+boundary+"--")){
#ifdef DEBUG_ESP_HTTP_SERVER
DEBUG_OUTPUT.println("Done Parsing POST");
#endif
break;
}
} else {
_currentUpload.status = UPLOAD_FILE_START;
_currentUpload.name = argName;
_currentUpload.filename = argFilename;
_currentUpload.type = argType;
_currentUpload.totalSize = 0;
_currentUpload.currentSize = 0;
#ifdef DEBUG_ESP_HTTP_SERVER
DEBUG_OUTPUT.print("Start File: ");
DEBUG_OUTPUT.print(_currentUpload.filename);
DEBUG_OUTPUT.print(" Type: ");
DEBUG_OUTPUT.println(_currentUpload.type);
//.........这里部分代码省略.........
示例11: loop
void Humure::loop()
{
// Check if a client has connected
WiFiClient client = this->server.available();
if (!client) {
return;
}
Serial.println("");
Serial.println("New client");
// Wait for data from client to become available
while(client.connected() && !client.available()){
delay(1);
}
// Read the first line of HTTP request
String req = client.readStringUntil('\r');
// GET or POST?
bool req_get;
if ( req.startsWith("GET") ) {
req_get = true;
} else if ( req.startsWith("POST") ) {
req_get = false;
} else {
Serial.print("Invalid request: ");
Serial.println(req);
return;
}
// First line of HTTP request looks like "GET /path HTTP/1.1"
// Retrieve the "/path" part by finding the spaces
int addr_start = req.indexOf(' ');
int addr_end = req.indexOf(' ', addr_start + 1);
if (addr_start == -1 || addr_end == -1) {
Serial.print("Invalid request: ");
Serial.println(req);
return;
}
req = req.substring(addr_start + 1, addr_end);
Serial.print("Request ");
if (req_get)
{
Serial.print("GET");
} else {
Serial.print("POST");
}
Serial.print(" : ");
Serial.println(req);
client.flush();
if ( req_get ) {
if ( req == "/" ) {
readSensor();
sendFullPage(client);
} else
if ( req == "/lamp") {
jsonValue(client, String( ! led_status) );
} else
if ( req == "/temperatur") {
readSensor();
jsonValue(client, String( this->t) );
} else
if ( req == "/humidity") {
readSensor();
jsonValue(client, String( this->h) );
} else {
client.print("HTTP/1.1 404 Not Found\r\n\r\n");
}
} else {
if ( req == "/lamp/on" ) {
led_status = 0;
jsonValue(client, String( ! led_status) );
} else
if ( req =="/lamp/off" ) {
led_status = 1;
jsonValue(client, String( ! led_status) );
} else {
client.print("HTTP/1.1 404 Not Found\r\n\r\n");
}
digitalWrite(this->led, led_status);
}
Serial.println("Done with client");
}
示例12: if
void ESP8266WebServer::handleClient()
{
WiFiClient client = _server.available();
if (!client) {
return;
}
#ifdef DEBUG
Serial.println("New client");
#endif
// Wait for data from client to become available
while(client.connected() && !client.available()){
delay(1);
}
// Read the first line of HTTP request
String req = client.readStringUntil('\r');
client.readStringUntil('\n');
HTTPMethod method = HTTP_GET;
if (req.startsWith("POST")) {
method = HTTP_POST;
}
// First line of HTTP request looks like "GET /path HTTP/1.1"
// Retrieve the "/path" part by finding the spaces
int addr_start = req.indexOf(' ');
int addr_end = req.indexOf(' ', addr_start + 1);
if (addr_start == -1 || addr_end == -1) {
#ifdef DEBUG
Serial.print("Invalid request: ");
Serial.println(req);
#endif
return;
}
req = req.substring(addr_start + 1, addr_end);
String formData;
if (method == HTTP_POST) {
int contentLength = -1;
int headerCount = 0;
while(headerCount < 1024) { // there shouldn't be that much really
String line = client.readStringUntil('\r');
client.readStringUntil('\n');
if (line.length() > 0) { // this is a header
++headerCount;
if (contentLength < 0 && line.startsWith("Content-Length")) {
// get content length from the header
int valuePos = line.indexOf(' ', 14);
if (valuePos > 0) {
String valueStr = line.substring(valuePos+1);
contentLength = valueStr.toInt();
#ifdef DEBUG
Serial.print("Content-Length: ");
Serial.println(contentLength);
#endif
}
}
}
else {
break;
}
}
#ifdef DEBUG
Serial.print("headerCount=");
Serial.println(headerCount);
#endif
if (contentLength >= 0) {
formData = "";
int n = 0; // timeout counter
while (formData.length() < contentLength && ++n < 3)
formData += client.readString();
}
else {
formData = client.readStringUntil('\r'); // will return after timing out once
}
}
else if (method == HTTP_GET) {
int args_start = req.indexOf('?');
if (args_start != -1) {
formData = req.substring(args_start + 1);
req = req.substring(0, args_start);
}
}
client.flush();
#ifdef DEBUG
Serial.print("Request: ");
Serial.println(req);
Serial.print("Args: ");
Serial.println(formData);
#endif
_parseArguments(formData);
_handleRequest(client, req, method);
}
示例13: if
bool ESP8266WebServer::_parseRequest(WiFiClient& client) {
// Read the first line of HTTP request
String req = client.readStringUntil('\r');
client.readStringUntil('\n');
// First line of HTTP request looks like "GET /path HTTP/1.1"
// Retrieve the "/path" part by finding the spaces
int addr_start = req.indexOf(' ');
int addr_end = req.indexOf(' ', addr_start + 1);
if (addr_start == -1 || addr_end == -1) {
#ifdef DEBUG
DEBUG_OUTPUT.print("Invalid request: ");
DEBUG_OUTPUT.println(req);
#endif
return false;
}
String methodStr = req.substring(0, addr_start);
String url = req.substring(addr_start + 1, addr_end);
String searchStr = "";
int hasSearch = url.indexOf('?');
if (hasSearch != -1){
searchStr = url.substring(hasSearch + 1);
url = url.substring(0, hasSearch);
}
_currentUri = url;
HTTPMethod method = HTTP_GET;
if (methodStr == "POST") {
method = HTTP_POST;
} else if (methodStr == "DELETE") {
method = HTTP_DELETE;
} else if (methodStr == "PUT") {
method = HTTP_PUT;
} else if (methodStr == "PATCH") {
method = HTTP_PATCH;
}
_currentMethod = method;
#ifdef DEBUG
DEBUG_OUTPUT.print("method: ");
DEBUG_OUTPUT.print(methodStr);
DEBUG_OUTPUT.print(" url: ");
DEBUG_OUTPUT.print(url);
DEBUG_OUTPUT.print(" search: ");
DEBUG_OUTPUT.println(searchStr);
#endif
String formData;
// below is needed only when POST type request
if (method == HTTP_POST || method == HTTP_PUT || method == HTTP_PATCH || method == HTTP_DELETE){
String boundaryStr;
String headerName;
String headerValue;
bool isForm = false;
uint32_t contentLength = 0;
//parse headers
while(1){
req = client.readStringUntil('\r');
client.readStringUntil('\n');
if (req == "") break;//no moar headers
int headerDiv = req.indexOf(':');
if (headerDiv == -1){
break;
}
headerName = req.substring(0, headerDiv);
headerValue = req.substring(headerDiv + 2);
if (headerName == "Content-Type"){
if (headerValue.startsWith("text/plain")){
isForm = false;
} else if (headerValue.startsWith("multipart/form-data")){
boundaryStr = headerValue.substring(headerValue.indexOf('=')+1);
isForm = true;
}
} else if (headerName == "Content-Length"){
contentLength = headerValue.toInt();
}
}
if (!isForm){
if (searchStr != "") searchStr += '&';
//some clients send headers first and data after (like we do)
//give them a chance
int tries = 100;//100ms max wait
while(!client.available() && tries--)delay(1);
size_t plainLen = client.available();
char *plainBuf = (char*)malloc(plainLen+1);
client.readBytes(plainBuf, plainLen);
plainBuf[plainLen] = '\0';
#ifdef DEBUG
DEBUG_OUTPUT.print("Plain: ");
DEBUG_OUTPUT.println(plainBuf);
#endif
if(plainBuf[0] == '{' || plainBuf[0] == '[' || strstr(plainBuf, "=") == NULL){
//plain post json or other data
searchStr += "plain=";
searchStr += plainBuf;
} else {
searchStr += plainBuf;
}
//.........这里部分代码省略.........
示例14: _sendNextGpsData
void GPSUploader::_sendNextGpsData() {
int startTimeUploading = millis();
if(!this->_initialized) return;
Serial.printf("Upload: Pending messages: %d\n", this->_sdQueue.getCount());
Serial.println("Upload: preparation");
this->_sdQueue.flush();//avoid parallel flush() during server connection (too much mem)
if(this->_sdQueue.getCount()==0) {
Serial.println("Upload: no data to send");
return;
}
//connect to server and send various POST on the same connection
WiFiClient client;
// Serial.printf("Host=%s:%d\n", this->_configNode.getUploadServerHost().c_str(), this->_configNode.getUploadServerPort());
_watchdog.ping();
int startTime = millis();
if (!client.connect(this->_uploadServerHost.get(), this->_uploadServerPort.get())) {
this->_totalUploadCountError++;
this->_totalUploadTimeError+=(millis()-startTime);
Serial.println("Upload: server connection failed");
_watchdog.ping();
return;
}
_watchdog.ping();
//send
//If this takes more than 10s, abort and loop again so that Wifi and MQTT won't lose connection
for(int i=0; i<10 && ((millis()-startTimeUploading)<10000); i++) {
// int len = 0;
int sdRecordsCount = 0;
int sdRecordsOK = 0;
int sdRecordsError = 0;
strcpy(this->_gpsUploadBuffer, "");
// Serial.println("Upload: Preparing chunk");
while(this->_sdQueue.peek(this->_gpsRecord, sdRecordsCount++) && strlen(this->_gpsUploadBuffer) < 1150) {
//fill post with ~1200 bytes
if(GPSUtils::validateNmeaChecksum(this->_gpsRecord)) {
strcat(this->_gpsUploadBuffer, this->_gpsRecord);
strcat(this->_gpsUploadBuffer, "\n");
sdRecordsOK++;
} else {
Serial.printf("Upload: crc error %s\n", this->_gpsRecord);
sdRecordsError++;
}
yield();
}
if(strlen(this->_gpsUploadBuffer)>0) {
Serial.printf("Upload: records=%d err=%d\n", sdRecordsOK, sdRecordsError);
Serial.println("POST /" + String(this->_uploadServerUri.c_str()));
int startTime = millis();
client.printf("POST /%s HTTP/1.1\r\nHost: %s\r\nContent-Length: %d\r\nContent-Type: text/plain\r\n\r\n",
this->_uploadServerUri.c_str(),
"api.devices.stutzthings.com",
// this->_uploadServerHost.get(),
strlen(this->_gpsUploadBuffer)
);
client.print(this->_gpsUploadBuffer);
_watchdog.ping();
// Serial.println("SENT");
//wait for response available
int timeout = millis();
while (client.available() < 15) {
if (millis() - timeout > 5000) {
Serial.println("Upload: server response timeout");
client.stop();
this->_totalUploadBytesError += strlen(this->_gpsUploadBuffer);
this->_totalUploadCountError++;
this->_totalUploadTimeError+=(millis()-startTime);
return;
}
delay(50);
_watchdog.ping();
}
// Serial.println("RECEIVED RESPONSE");
//process response
bool success = false;
if(client.readStringUntil(GCHAR_SPACE).length()>0) {
String code = client.readStringUntil(GCHAR_SPACE);
_watchdog.ping();
if(code == "201") {
Serial.println("Upload: 201 Created");
success = true;
this->_totalUploadBytesSuccess += strlen(this->_gpsUploadBuffer);
this->_totalUploadCountSuccess++;
this->_totalUploadTimeSuccess+=(millis()-startTime);
this->_totalUploadRecordsSuccess+=sdRecordsOK;
this->_totalUploadRecordCRCError+=sdRecordsError;
this->_sdQueue.removeElements(sdRecordsCount);
// Serial.println("Upload: sent records removed from disk");
} else {
this->_totalUploadBytesError += strlen(this->_gpsUploadBuffer);
this->_totalUploadCountError++;
this->_totalUploadTimeError+=(millis()-startTime);
Serial.println("Upload: server error " + String(code));
//.........这里部分代码省略.........
示例15: serverLoop
int WiFiManager::serverLoop()
{
// Check for any mDNS queries and send responses
mdns.update();
String s;
WiFiClient client = server_s.available();
if (!client) {
return(WM_WAIT);
}
DEBUG_PRINT("New client");
// Wait for data from client to become available
while(client.connected() && !client.available()){
delay(1);
}
// Read the first line of HTTP request
String req = client.readStringUntil('\r');
// First line of HTTP request looks like "GET /path HTTP/1.1"
// Retrieve the "/path" part by finding the spaces
int addr_start = req.indexOf(' ');
int addr_end = req.indexOf(' ', addr_start + 1);
if (addr_start == -1 || addr_end == -1) {
DEBUG_PRINT("Invalid request: ");
DEBUG_PRINT(req);
return(WM_WAIT);
}
req = req.substring(addr_start + 1, addr_end);
DEBUG_PRINT("Request: ");
DEBUG_PRINT(req);
client.flush();
if (req == "/")
{
s = HTTP_200;
String head = HTTP_HEAD;
head.replace("{v}", "Config ESP");
s += head;
s += HTTP_SCRIPT;
s += HTTP_STYLE;
s += HTTP_HEAD_END;
int n = WiFi.scanNetworks();
DEBUG_PRINT("scan done");
if (n == 0) {
DEBUG_PRINT("no networks found");
s += "<div>No networks found. Refresh to scan again.</div>";
}
else {
for (int i = 0; i < n; ++i)
{
DEBUG_PRINT(WiFi.SSID(i));
DEBUG_PRINT(WiFi.RSSI(i));
String item = HTTP_ITEM;
item.replace("{v}", WiFi.SSID(i));
s += item;
delay(10);
}
}
s += HTTP_FORM;
s += HTTP_END;
DEBUG_PRINT("Sending config page");
}
else if ( req.startsWith("/s") ) {
String qssid;
qssid = urldecode(req.substring(8,req.indexOf('&')).c_str());
DEBUG_PRINT(qssid);
DEBUG_PRINT("");
req = req.substring( req.indexOf('&') + 1);
String qpass;
qpass = urldecode(req.substring(req.lastIndexOf('=')+1).c_str());
setEEPROMString(0, 32, qssid);
setEEPROMString(32, 64, qpass);
EEPROM.commit();
s = HTTP_200;
String head = HTTP_HEAD;
head.replace("{v}", "Saved config");
s += HTTP_STYLE;
s += HTTP_HEAD_END;
s += "saved to eeprom...<br/>resetting in 10 seconds";
s += HTTP_END;
client.print(s);
client.flush();
DEBUG_PRINT("Saved WiFiConfig...restarting.");
return WM_DONE;
}
else
{
s = HTTP_404;
DEBUG_PRINT("Sending 404");
}
//.........这里部分代码省略.........