// See if port 80 is accessable. Try 8080 as well. boolean WiFiManager::attemptClient(const char *szUrl) { WiFiClient client; int i; Serial.print("Probe port 80"); for(i = 0; i < 5; i++) { if (client.connect(szUrl, httpPort)) { client.stop(); Serial.println("Port 80 success"); return true; } Serial.print("."); delay(20); } httpPort = 8080; Serial.println(""); Serial.print("Probe port 8080"); for(i = 0; i < 5; i++) { if (client.connect(szUrl, httpPort)) { client.stop(); Serial.println("Port 8080 success"); return true; } Serial.print("."); delay(20); } Serial.println(""); Serial.println("No joy"); return false; }
AJ_Status AJ_Net_Connect(AJ_BusAttachment* bus, const AJ_Service* service) { int ret; IPAddress ip(service->ipv4); if (!(service->addrTypes & AJ_ADDR_TCP4)) { AJ_ErrPrintf(("AJ_Net_Connect(): only IPV4 TCP supported\n", ret)); return AJ_ERR_CONNECT; } AJ_InfoPrintf(("AJ_Net_Connect(bus=0x%p, addrType=%d.)\n", bus, service->addrTypes)); ret = g_client.connect(ip, service->ipv4port); if (ret != 1) { AJ_ErrPrintf(("AJ_Net_Connect(): connect() failed: %d: status=AJ_ERR_CONNECT\n", ret)); return AJ_ERR_CONNECT; } else { AJ_IOBufInit(&bus->sock.rx, rxData, sizeof(rxData), AJ_IO_BUF_RX, (void*)&g_client); bus->sock.rx.recv = AJ_Net_Recv; AJ_IOBufInit(&bus->sock.tx, txData, sizeof(txData), AJ_IO_BUF_TX, (void*)&g_client); bus->sock.tx.send = AJ_Net_Send; AJ_ErrPrintf(("AJ_Net_Connect(): connect() success: status=AJ_OK\n")); return AJ_OK; } AJ_ErrPrintf(("AJ_Net_Connect(): connect() failed: %d: status=AJ_ERR_CONNECT\n", ret)); return AJ_ERR_CONNECT; }
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 } }
AJ_Status AJ_Net_Connect(AJ_NetSocket* netSock, uint16_t port, uint8_t addrType, const uint32_t* addr) { int ret; IPAddress ip(*addr); AJ_InfoPrintf(("AJ_Net_Connect(nexSock=0x%p, port=%d., addrType=%d., addr=0x%p)\n", netSock, port, addrType, addr)); AJ_InfoPrintf(("AJ_Net_Connect(): Connect to 0x%x:%u.\n", addr, port));; ret = g_client.connect(ip, port); #ifdef NOTDEF Serial.print("Connecting to: "); Serial.print(ip); Serial.print(':'); Serial.println(port); #endif if (ret == -1) { AJ_ErrPrintf(("AJ_Net_Connect(): connect() failed: %d: status=AJ_ERR_CONNECT\n", ret)); return AJ_ERR_CONNECT; } else { AJ_IOBufInit(&netSock->rx, rxData, sizeof(rxData), AJ_IO_BUF_RX, (void*)&g_client); netSock->rx.recv = AJ_Net_Recv; AJ_IOBufInit(&netSock->tx, txData, sizeof(txData), AJ_IO_BUF_TX, (void*)&g_client); netSock->tx.send = AJ_Net_Send; AJ_ErrPrintf(("AJ_Net_Connect(): connect() success: status=AJ_OK\n")); return AJ_OK; } AJ_ErrPrintf(("AJ_Net_Connect(): connect() failed: %d: status=AJ_ERR_CONNECT\n", ret)); return AJ_ERR_CONNECT; }
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; }
void Iotfy_postdata(String group_iotfy, String id_iotfy, String tag_iotfy, String value_iotfy) { debug("in postdata"); debug("setting id"); String X_IOTFY_ID="X-IOTFY-ID: "+IOTFY_ID; String X_IOTFY_CLIENT="X-IOTFY-CLIENT: "+IOTFY_CLIENT; debug(X_IOTFY_CLIENT); debug(X_IOTFY_ID); String data="\{\"group\":\""; data+=group_iotfy; data+="\", \"device\":\""; data+=id_iotfy; data+="\", \"data\":[{"; data+="\"tag\":\""; data+=tag_iotfy; data+="\""; data+=",\"text\":\""; data+=value_iotfy; data+="\"}]}"; debug("Trying to connect"); if (client.connect(server, 80)) { debug("connected and now sending post request"); client.println("POST /api/telemetry/v1/post_text_data HTTP/1.0"); //client.println("POST /api/telemetry/v1/post_text_data HTTP/1.1"); client.println("User-Agent: arduino-ESP"); client.println("Host: cloud.iotfy.co"); client.println(X_IOTFY_ID); client.println(X_IOTFY_CLIENT); client.println("Content-Type: application/json"); client.print("Content-Length: "); client.println(data.length()); client.println(); client.println(data); client.println("Connection: close"); if(DEBUG) { debug("connected"); debug("POST /api/telemetry/v1/post_text_data HTTP/1.0"); //debug("POST /api/telemetry/v1/post_text_data HTTP/1.1"); debug("User-Agent: arduino-ESP"); debug("Host: cloud.iotfy.co"); debug(X_IOTFY_ID); debug(X_IOTFY_CLIENT); debug("Content-Type: application/json"); debug("Content-Length: "); debug((String)data.length()); debug(""); debug(data); } } }
void Farmy::send( const char* device_id, int input_pins[], String api_key, WiFiClient client) { if(!client.connect(host, 80)) { Serial.println("connection failed"); return; } String data = collectData(input_pins); sendData(device_id, api_key, client, data); }
void ThingspeakClient::getLastChannelItem(String channelId, String readApiKey) { JsonStreamingParser parser; parser.setListener(this); WiFiClient client; // http://api.thingspeak.com/channels/CHANNEL_ID/feeds.json?results=2&api_key=API_KEY const char host[] = "api.thingspeak.com"; String url = "/channels/" + channelId +"/feeds.json?results=1&api_key=" + readApiKey; const int httpPort = 80; if (!client.connect(host, httpPort)) { Serial.println("connection failed"); return; } Serial.print("Requesting URL: "); Serial.println(url); // This will send the request to the server client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n"); int retryCounter = 0; while(!client.available()) { Serial.println("."); delay(1000); retryCounter++; if (retryCounter > 10) { return; } } int pos = 0; boolean isBody = false; char c; int size = 0; client.setNoDelay(false); while(client.connected()) { while((size = client.available()) > 0) { c = client.read(); if (c == '{' || c == '[') { isBody = true; } if (isBody) { parser.parse(c); } } } }
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(); } } } }
void WundergroundClient::doUpdate(String url) { JsonStreamingParser parser; parser.setListener(this); WiFiClient client; const int httpPort = 80; if (!client.connect("api.wunderground.com", httpPort)) { Serial.println("connection failed"); return; } Serial.print("Requesting URL: "); Serial.println(url); // This will send the request to the server client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: api.wunderground.com\r\n" + "Connection: close\r\n\r\n"); int retryCounter = 0; while(!client.available()) { delay(1000); retryCounter++; if (retryCounter > 10) { return; } } int pos = 0; boolean isBody = false; char c; int size = 0; client.setNoDelay(false); while(client.connected()) { while((size = client.available()) > 0) { c = client.read(); if (c == '{' || c == '[') { isBody = true; } if (isBody) { parser.parse(c); } } } }
void sendTeperatureTS(int temp1, int temp2, int temp3, int temp4) { WiFiClient client; if (client.connect(tsserver, 80)) { // use ip 184.106.153.149 or api.thingspeak.com Serial.println("WiFi Client connected_neu "); EEPROM.begin(512); delay(10); String apiKey = ""; for (int i = 81; i < 97; i++) { apiKey += char(EEPROM.read(i)); } EEPROM.end(); Serial.println("Thingspeak-API_neu: " + apiKey); String postStr = apiKey; postStr += "&field1="; postStr += String(temp1); postStr += "&field2="; postStr += String(temp2); postStr += "&field3="; postStr += String(temp3); postStr += "&field4="; postStr += String(temp4); postStr += "\r\n\r\n"; client.print("POST /update HTTP/1.1\n"); client.print("Host: api.thingspeak.com\n"); client.print("Connection: close\n"); client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n"); client.print("Content-Type: application/x-www-form-urlencoded\n"); client.print("Content-Length: "); client.print(postStr.length()); client.print("\n\n"); client.print(postStr); delay(1000); Serial.println("Daten an Thingspeak gesendet"); }//end if sent++; client.stop(); }//end send
void init() { Serial.begin(SERIAL_BAUD_RATE); // 115200 by default Serial.systemDebugOutput(true); // Enable debug output to serial pinMode(LED_PIN, OUTPUT);//LED WifiStation.enable(true); WifiStation.config(WIFI_SSID, WIFI_PWD); WifiAccessPoint.enable(false); delay(4000); // Connect to the websocket server if (client.connect("echo.websocket.org", 80)) { Serial.println("Connected"); } else { Serial.println("Connection failed."); while(1) { // Hang on failure digitalWrite(LED_PIN, 0x1);//LED ON delay(500); digitalWrite(LED_PIN, 0x0);//LED OFF } } // Handshake with the server webSocketClient.path = path; webSocketClient.host = host; if (webSocketClient.handshake(client)) { Serial.println("Handshake successful"); } else { Serial.println("Handshake failed."); while(1) { // Hang on failure digitalWrite(LED_PIN, 0x1);//LED ON delay(100); digitalWrite(LED_PIN, 0x0);//LED OFF } } ////loop every 10 msec procTimer.initializeMs(10, loop).start();//10 msec }
bool connectSensorAPI() { /* ToDo: Add SSL/TLS support */ uint16_t port; char hostname[NODE_EEPROM_API_HOSTNAME_MAX_LENGTH + 1]; if(WiFi.status() != WL_CONNECTED) { return false; } getAPIHostnameOrDefault(&hostname[0], NODE_EEPROM_API_HOSTNAME_MAX_LENGTH); hostname[NODE_EEPROM_API_HOSTNAME_MAX_LENGTH] = '\0'; port = getAPIPortOrDefault(); client.stop(); if(client.connect(hostname, port)) { return true; } return false; }
void httpRequest() { // close any connection before send a new request. // This will free the socket on the WiFi shield client.stop(); // if there's a successful connection: if (client.connect("www.hasthelargehadroncolliderdestroyedtheworldyet.com", 80)) { Serial5.println("connecting..."); // send the HTTP PUT request: client.println("GET / HTTP/1.1"); client.println("Host: www.hasthelargehadroncolliderdestroyedtheworldyet.com"); //client.println("User-Agent: ArduinoWiFi/1.1"); client.println("Connection: close"); client.println(); if( client.connected() ) { Serial5.println("\tClient connected"); while( client.available() == 0 ) { //Waiting for data if( !client.connected() ) { Serial5.println("\tClient disconnected !"); break; } } } else { Serial5.println("\tClient not connected"); } } else { // if you couldn't make a connection: Serial5.println("\tconnection failed"); } }
void setup() { //Initialize serial and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } // check for the presence of the shield: if (WiFi.status() == WL_NO_SHIELD) { Serial.println("WiFi shield not present"); // don't continue: while(true); } // attempt to connect to Wifi network: while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); // Connect to WPA/WPA2 network. Change this line if using open or WEP network: status = WiFi.begin(ssid, pass); // wait 10 seconds for connection: delay(10000); } Serial.println("Connected to wifi"); printWifiStatus(); Serial.println("\nStarting connection to server..."); // if you get a connection, report back via serial: if (client.connect(server, 80)) { Serial.println("connected to server"); // Make a HTTP request: client.println("GET /search?q=arduino HTTP/1.1"); client.println("Host:www.google.com"); client.println("Connection: close"); client.println(); } }
t_httpUpdate_return ESP8266HTTPUpdate::update(const char * host, uint16_t port, const char * url, const char * current_version) { t_httpUpdate_return ret = HTTP_UPDATE_FAILED; WiFiClient tcp; DEBUG_HTTP_UPDATE("[httpUpdate] connected to %s:%u %s .... ", host, port, url); if(!tcp.connect(host, port)) { DEBUG_HTTP_UPDATE("failed.\n"); return ret; } DEBUG_HTTP_UPDATE("ok.\n"); // set Timeout for readBytesUntil and readStringUntil tcp.setTimeout(2000); tcp.setNoDelay(true); String req = "GET "; req += url; req += " HTTP/1.1\r\n" "Host: "; req += host; req += "\r\n" "Connection: close\r\n" "User-Agent: ESP8266-http-Update\r\n" "x-ESP8266-STA-MAC: "; req += WiFi.macAddress(); req += "\r\n" "x-ESP8266-AP-MAC: "; req += WiFi.softAPmacAddress(); req += "\r\n" "x-ESP8266-free-space: "; req += ESP.getFreeSketchSpace(); req += "\r\n" "x-ESP8266-sketch-size: "; req += ESP.getSketchSize(); req += "\r\n" "x-ESP8266-chip-size: "; req += ESP.getFlashChipRealSize(); req += "\r\n" "x-ESP8266-sdk-version: "; req += ESP.getSdkVersion(); if(current_version[0] != 0x00) { req += "\r\n" "x-ESP8266-version: "; req += current_version; } req += "\r\n" "\r\n"; tcp.write(req.c_str(), req.length()); uint32_t code = 0; size_t len = 0; while(true) { String headerLine = tcp.readStringUntil('\n'); headerLine.trim(); // remove \r if(headerLine.length() > 0) { DEBUG_HTTP_UPDATE("[httpUpdate][Header] RX: %s\n", headerLine.c_str()); if(headerLine.startsWith("HTTP/1.")) { // 9 = lenght of "HTTP/1.x " code = headerLine.substring(9, headerLine.indexOf(' ', 9)).toInt(); } else if(headerLine.startsWith("Content-Length: ")) { // 16 = lenght of "Content-Length: " len = headerLine.substring(16).toInt(); } } else { break; } } DEBUG_HTTP_UPDATE("[httpUpdate] Header read fin.\n"); DEBUG_HTTP_UPDATE("[httpUpdate] Server header:\n"); DEBUG_HTTP_UPDATE("[httpUpdate] - code: %d\n", code); DEBUG_HTTP_UPDATE("[httpUpdate] - len: %d\n", len); DEBUG_HTTP_UPDATE("[httpUpdate] ESP8266 info:\n"); DEBUG_HTTP_UPDATE("[httpUpdate] - free Space: %d\n", ESP.getFreeSketchSpace()); DEBUG_HTTP_UPDATE("[httpUpdate] - current Sketch Size: %d\n", ESP.getSketchSize()); if(current_version[0] != 0x00) { DEBUG_HTTP_UPDATE("[httpUpdate] - current version: %s\n", current_version); } switch(code) { case 200: ///< OK (Start Update) if(len > 0) { if(len > ESP.getFreeSketchSpace()) { ret = HTTP_UPDATE_FAILED; DEBUG_HTTP_UPDATE("[httpUpdate] FreeSketchSpace to low (%d) needed: %d\n", ESP.getFreeSketchSpace(), len); } else { WiFiUDP::stopAll(); WiFiClient::stopAllExcept(&tcp); delay(100); if(ESP.updateSketch(tcp, len, false, false)) { ret = HTTP_UPDATE_OK; DEBUG_HTTP_UPDATE("[httpUpdate] Update ok\n"); tcp.stop(); ESP.restart(); } else { ret = HTTP_UPDATE_FAILED; DEBUG_HTTP_UPDATE("[httpUpdate] Update failed\n"); } } } else { ret = HTTP_UPDATE_FAILED; DEBUG_HTTP_UPDATE("[httpUpdate] Content-Length is 0?!\n"); } break; case 304: ///< Not Modified (No updates) ret = HTTP_UPDATE_NO_UPDATES; break; case 403: ///< Forbidden // todo handle login default: ret = HTTP_UPDATE_FAILED; DEBUG_HTTP_UPDATE("[httpUpdate] Code is (%d)\n", code); break; } return ret; }
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)); } } else { this->_totalUploadBytesError += strlen(this->_gpsUploadBuffer); this->_totalUploadCountError++; this->_totalUploadTimeError+=(millis()-startTime); Serial.println("Upload: invalid server response"); } //drain response data // Serial.println("RESPONSE DRAIN0"); _watchdog.ping(); while(client.available()>0) { client.read(); } // Serial.println("RESPONSE DRAIN1"); // Serial.println("Upload: post finished"); } else { Serial.println("Upload: no data pending"); if(sdRecordsError>0) { this->_sdQueue.removeElements(sdRecordsError); this->_totalUploadRecordCRCError+=sdRecordsError; } break; } _watchdog.ping(); yield(); _watchdog.ping(); // Serial.println("FINISHED POST"); } client.stop(); }
/** * @brief Arduino setup function. */ void WiFi_setup() { // Set Hostname. //hostname += String(ESP.getChipId(), HEX); WiFi.hostname(HOSTNAME); // Print hostname. //Serial.println("Hostname: " + hostname); Serial.println("Hostname: " + WiFi.hostname()); // Initialize file system. if (!SPIFFS.begin()) { Serial.println("Failed to mount file system"); return; } // Load wifi connection information. if (! loadConfig(&station_ssid, &station_psk)) { station_ssid = MY_ACCESSPOINT_SSID ; station_psk = MY_ACCESSPOINT_PSK ; Serial.println("No WiFi connection information available."); } // Check WiFi connection // ... check mode if (WiFi.getMode() != WIFI_STA) { WiFi.mode(WIFI_STA); delay(10); } // ... Compare file config with sdk config. if (WiFi.SSID() != station_ssid || WiFi.psk() != station_psk) { Serial.println("WiFi config changed."); // ... Try to connect to WiFi station. WiFi.begin(station_ssid.c_str(), station_psk.c_str()); // ... Pritn new SSID Serial.print("new SSID: "); Serial.println(WiFi.SSID()); // ... Uncomment this for debugging output. //WiFi.printDiag(Serial); } else { // ... Begin with sdk config. WiFi.begin(); } Serial.println("Wait for WiFi connection."); // ... Give ESP 10 seconds to connect to station. unsigned long startTime = millis(); while (WiFi.status() != WL_CONNECTED && millis() - startTime < 10000) { Serial.write('.'); //Serial.print(WiFi.status()); delay(500); } Serial.println(); // Check connection if(WiFi.status() == WL_CONNECTED) { // ... print IP Address Serial.print("IP address: "); Serial.println(WiFi.localIP()); #if CLOUD_MODE // close any connection before send a new request. // This will free the socket on the WiFi shield client.stop(); delay(1000); Serial.print("Connection to "); Serial.print(CLOUD_HOSTNAME); Serial.print(":"); Serial.print(CLOUD_PORT); Serial.print(" "); // if there's a successful connection: if (client.connect(CLOUD_HOSTNAME, CLOUD_PORT)) { Serial.println("succeed"); } else { // if you couldn't make a connection: Serial.println("failed"); } #endif } else { Serial.println("Can not connect to WiFi station. Go into AP mode."); // Go into software AP mode. WiFi.mode(WIFI_AP); delay(10); WiFi.softAP(ap_default_ssid, ap_default_psk); Serial.print("IP address: "); Serial.println(WiFi.softAPIP()); } }
//****************** Send data for ModBusMaster **************** void MgsModbus::Req(MB_FC FC, word Ref, word Count, word Pos) { MbmFC = FC; byte ServerIp[] = {192,168,2,8}; MbmByteArray[0] = 0; // ID high byte MbmByteArray[1] = 1; // ID low byte MbmByteArray[2] = 0; // protocol high byte MbmByteArray[3] = 0; // protocol low byte MbmByteArray[5] = 6; // Lenght low byte; MbmByteArray[4] = 0; // Lenght high byte MbmByteArray[6] = 1; // unit ID MbmByteArray[7] = FC; // function code MbmByteArray[8] = highByte(Ref); MbmByteArray[9] = lowByte(Ref); //****************** Read Coils (1) & Read Input discretes (2) ********************** if(FC == MB_FC_READ_COILS || FC == MB_FC_READ_DISCRETE_INPUT) { if (Count < 1) {Count = 1;} if (Count > 125) {Count = 2000;} MbmByteArray[10] = highByte(Count); MbmByteArray[11] = lowByte(Count); } //****************** Read Registers (3) & Read Input registers (4) ****************** if(FC == MB_FC_READ_REGISTERS || FC == MB_FC_READ_INPUT_REGISTER) { if (Count < 1) {Count = 1;} if (Count > 125) {Count = 125;} MbmByteArray[10] = highByte(Count); MbmByteArray[11] = lowByte(Count); } //****************** Write Coil (5) ********************** if(MbmFC == MB_FC_WRITE_COIL) { if (GetBit(Pos)) {MbmByteArray[10] = 0xFF;} else {MbmByteArray[10] = 0;} // 0xFF coil on 0x00 coil off MbmByteArray[11] = 0; // always zero } //****************** Write Register (6) ****************** if(MbmFC == MB_FC_WRITE_REGISTER) { MbmByteArray[10] = highByte(MbData[Pos]); MbmByteArray[11] = lowByte(MbData[Pos]); } //****************** Write Multiple Coils (15) ********************** // not fuly tested if(MbmFC == MB_FC_WRITE_MULTIPLE_COILS) { if (Count < 1) {Count = 1;} if (Count > 800) {Count = 800;} MbmByteArray[10] = highByte(Count); MbmByteArray[11] = lowByte(Count); MbmByteArray[12] = (Count + 7) /8; MbmByteArray[4] = highByte(MbmByteArray[12] + 7); // Lenght high byte MbmByteArray[5] = lowByte(MbmByteArray[12] + 7); // Lenght low byte; for (int i=0; i<Count; i++) { bitWrite(MbmByteArray[13+(i/8)],i-((i/8)*8),GetBit(Pos+i)); } } //****************** Write Multiple Registers (16) ****************** if(MbmFC == MB_FC_WRITE_MULTIPLE_REGISTERS) { if (Count < 1) {Count = 1;} if (Count > 100) {Count = 100;} MbmByteArray[10] = highByte(Count); MbmByteArray[11] = lowByte(Count); MbmByteArray[12] = (Count*2); MbmByteArray[4] = highByte(MbmByteArray[12] + 7); // Lenght high byte MbmByteArray[5] = lowByte(MbmByteArray[12] + 7); // Lenght low byte; for (int i=0; i<Count;i++) { MbmByteArray[(i*2)+13] = highByte (MbData[Pos + i]); MbmByteArray[(i*2)+14] = lowByte (MbData[Pos + i]); } } //****************** ?? ****************** if (MbmClient.connect(ServerIp,502)) { #ifdef DEBUG Serial.println("connected with modbus slave"); Serial.print("Master request: "); for(int i=0;i<MbmByteArray[5]+6;i++) { if(MbmByteArray[i] < 16){Serial.print("0");} Serial.print(MbmByteArray[i],HEX); if (i != MbmByteArray[5]+5) {Serial.print(".");} else {Serial.println();} } #endif // this for loop seems to cause a time delay or something that my modbus simulator does not like , for now we use 12 bytes // for(int i=0;i<MbmByteArray[5]+6;i++) { // MbmClient.write(MbmByteArray[i]); // } MbmClient.write((uint8_t*)MbmByteArray,12); MbmBitCount = Count; } else { #ifdef DEBUG Serial.println("connection with modbus master failed"); #endif MbmClient.stop(); } }
//////////////////////////////////// // Scrape UTC Time from server //////////////////////////////////// char* updateCurTime(void) { static int timeout_busy=0; int ipos; timeout_busy=0; //reset const char* timeServer = "aws.amazon.com"; // send a bad header on purpose, so we get a 400 with a DATE: timestamp const char* timeServerGet = "GET example.com/ HTTP/1.1"; String utctime; String GmtDate; static char dateStamp[20]; static char chBuf[200]; char utctimeraw[80]; char* dpos; WiFiClient client; if (client.connect(timeServer, 80)) { //Send Request client.println(timeServerGet); client.println(); while((!client.available())&&(timeout_busy++<5000)){ // Wait until the client sends some data delay(1); } // kill client if timeout if(timeout_busy>=5000) { client.flush(); client.stop(); Serial.println("timeout receiving timeserver data\n"); return dateStamp; } // read the http GET Response String req2 = client.readString(); // Serial.println(""); // Serial.println(""); // Serial.print(req2); // Serial.println(""); // Serial.println(""); // close connection delay(1); client.flush(); client.stop(); ipos = req2.indexOf("Date:"); if(ipos>0) { GmtDate = req2.substring(ipos,ipos+35); // Serial.println(GmtDate); utctime = GmtDate.substring(18,22) + getMonth(GmtDate.substring(14,17)) + GmtDate.substring(11,13) + GmtDate.substring(23,25) + GmtDate.substring(26,28) + GmtDate.substring(29,31); // Serial.println(utctime.substring(0,14)); utctime.substring(0,14).toCharArray(dateStamp, 20); } } else { Serial.println("did not connect to timeserver\n"); } timeout_busy=0; // reset timeout return dateStamp; // Return latest or last good dateStamp }
void ArduinoOTAClass::_runUpdate() { if (!Update.begin(_size, _cmd)) { #ifdef OTA_DEBUG OTA_DEBUG.println("Update Begin Error"); #endif if (_error_callback) { _error_callback(OTA_BEGIN_ERROR); } _udp_ota->listen(*IP_ADDR_ANY, _port); _state = OTA_IDLE; return; } Update.setMD5(_md5.c_str()); WiFiUDP::stopAll(); WiFiClient::stopAll(); if (_start_callback) { _start_callback(); } if (_progress_callback) { _progress_callback(0, _size); } WiFiClient client; if (!client.connect(_ota_ip, _ota_port)) { #ifdef OTA_DEBUG OTA_DEBUG.printf("Connect Failed\n"); #endif _udp_ota->listen(*IP_ADDR_ANY, _port); if (_error_callback) { _error_callback(OTA_CONNECT_ERROR); } _state = OTA_IDLE; } uint32_t written, total = 0; while (!Update.isFinished() && client.connected()) { int waited = 1000; while (!client.available() && waited--) delay(1); if (!waited){ #ifdef OTA_DEBUG OTA_DEBUG.printf("Receive Failed\n"); #endif _udp_ota->listen(*IP_ADDR_ANY, _port); if (_error_callback) { _error_callback(OTA_RECEIVE_ERROR); } _state = OTA_IDLE; } written = Update.write(client); if (written > 0) { client.print(written, DEC); total += written; if(_progress_callback) { _progress_callback(total, _size); } } } if (Update.end()) { client.print("OK"); client.stop(); delay(10); #ifdef OTA_DEBUG OTA_DEBUG.printf("Update Success\nRebooting...\n"); #endif if (_end_callback) { _end_callback(); } ESP.restart(); } else { _udp_ota->listen(*IP_ADDR_ANY, _port); if (_error_callback) { _error_callback(OTA_END_ERROR); } Update.printError(client); #ifdef OTA_DEBUG Update.printError(OTA_DEBUG); #endif _state = OTA_IDLE; } }