/* * ======== doCommand ======== * execute the command in buffer and send results to client */ static void doCommand(char *buffer, int len, WiFiClient client) { if (buffer[1] == '\n' || buffer[1] == '\r') { doWASD(buffer[0], client); } else { #if 0 long int addr = 0; int cnt = 0; char *ptr; /* get the address and count from the command */ getAddrCnt(buffer, len, &addr, &cnt); /* send client cnt bytes starting from addr */ ptr = (char *)addr; while (cnt-- > 0) { int status; if ((status = client.write(*ptr)) != 1) { return; } ptr++; } #else doWASD(' ', client); #endif } }
void Con::TCPhandler(){ if (this->curType&CON_TCP){ if (ConSrv.hasClient()){ if (ConTcp.connected()){ ConTcp.stop(); } ConTcp=ConSrv.available(); ConTcp.write("Hello\n",6); } } }
/* * ======== doWASD ======== */ static void doWASD(char wasd, WiFiClient client) { static char report[80]; /* set new motor command */ motorWASD = wasd; /* send current IMU data */ System_snprintf(report, sizeof(report), "A: %6d %6d %6d G: %6d %6d %6d M: %6d %6d %6d", imuCompass.a.x, imuCompass.a.y, imuCompass.a.z, imuGyro.g.x, imuGyro.g.y, imuGyro.g.z, imuCompass.m.x, imuCompass.m.y, imuCompass.m.z); if (client.write((unsigned char *)report, 72) != 72) { Serial.println("Error: reply failed, status != 72"); } }
/* * ======== doCommand ======== * execute the command in buffer and send results to client */ static void doCommand(char *buffer, int len, WiFiClient client) { long int addr = 0; int cnt = 0; char *ptr; /* get the address and count from the command */ getAddrCnt(buffer, len, &addr, &cnt); /* send client cnt bytes starting from addr */ ptr = (char *)addr; while (cnt-- > 0) { if (client.write(*ptr) != 1) { System_printf("doCommand write failure!"); } ptr++; } }
AJ_Status AJ_Net_Send(AJ_IOBuffer* buf) { uint32_t ret; uint32_t tx = AJ_IO_BUF_AVAIL(buf); AJ_InfoPrintf(("AJ_Net_Send(buf=0x%p)\n", buf)); if (tx > 0) { ret = g_client.write(buf->readPtr, tx); if (ret == 0) { AJ_ErrPrintf(("AJ_Net_Send(): send() failed. error=%d, status=AJ_ERR_WRITE\n", g_client.getWriteError())); return AJ_ERR_WRITE; } buf->readPtr += ret; } if (AJ_IO_BUF_AVAIL(buf) == 0) { AJ_IO_BUF_RESET(buf); } AJ_InfoPrintf(("AJ_Net_Send(): status=AJ_OK\n")); return AJ_OK; }
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; }
// Process HTTP requests -- just call it inside the loop() function void WebConfig::ProcessHTTP() { // Accept any new web connection WiFiClient httpClient = pHttpServer->available(); if (!httpClient) return; // Read the entire request String req = httpClient.readString(); httpClient.flush(); // after some time, do not open the web interface anymore. //if (millis() - startMillis > 2*60000) return; // response header String s; if (strlen(webLogin) > 0 || strlen(webPassword) > 0) { int authPos = req.indexOf("Authorization: Basic"); if (authPos == -1) { // request authentication s = "HTTP/1.0 401 Authorization Required\r\nWWW-Authenticate: Basic realm=\"" + String(apName) + "\"\r\n\r\n"; s += "<h1><b>ACCESS DENIED</b></h1>"; httpClient.write(s.c_str(), s.length()); httpClient.flush(); return; } // there is authentication info, check it String authInfo = req.substring(authPos + 21); int endLinePos = authInfo.indexOf("\r"); if (endLinePos == -1) { httpClient.print("Malformed request."); httpClient.stop(); return; } authInfo = authInfo.substring(0, endLinePos); if (strncmp(base64Auth, authInfo.c_str(), 64)) { s = "<h1><b>ACCESS DENIED</b></h1>"; httpClient.write(s.c_str(), s.length()); httpClient.flush(); return; } } byte mac[6]; WiFi.macAddress(mac); String m = String(mac[0],HEX) + ":" + String(mac[1],HEX) + ":" + String(mac[2],HEX) + ":" + String(mac[3],HEX) + ":" + String(mac[4],HEX) + ":" + String(mac[5],HEX); // // generate HTTP response // // authentication succeeded, proceed normally s = "HTTP/1.1 200 OK\r\n"; s += "Content-Type: text/html\r\n\r\n"; s += "<!DOCTYPE HTML>\r\n<html><body>\r\n"; // If there are parms, update variables and save settings bool updated = ProcessParms(req); if (updated) { s += "Parameters have been updated and microcontroller will restart.<br><br>\r\n"; } // javascript to save configuration s += "<script>\r\n"; s += "function save()\r\n"; s += "{\r\n"; s += "var webPort = document.getElementById('web_port').value;\r\n"; s += "var webLogin = document.getElementById('web_login').value;\r\n"; s += "var webPassword = document.getElementById('web_pass').value;\r\n"; s += "var webPassword2 = document.getElementById('web_pass2').value;\r\n"; s += "var modeap = document.getElementById('modeap').checked;\r\n"; s += "if (modeap) isAP = true; else isAP = false;\r\n"; s += "var apName = document.getElementById('ap_ssid').value;\r\n"; s += "var apPassword = document.getElementById('ap_pass').value;\r\n"; s += "var apPassword2 = document.getElementById('ap_pass2').value;\r\n"; s += "var apChannel = document.getElementById('apChannel').value;\r\n"; s += "var ssid = document.getElementById('ssid').value;\r\n"; s += "var password = document.getElementById('pass').value;\r\n"; s += "var password2 = document.getElementById('pass2').value;\r\n"; s += "var udpPort = document.getElementById('udpPort').value;\r\n"; s += "var tcpPort = document.getElementById('tcpPort').value;\r\n"; s += "if (webPassword != webPassword2) { alert('WEB passwords dont match'); return; }\r\n"; s += "if (apPassword != apPassword2) { alert('AP passwords dont match'); return; }\r\n"; s += "if (password != password2) { alert('Router passwords dont match'); return; }\r\n"; s += "window.location.search=webPort + '&' + webLogin + '&' + webPassword + '&' + btoa(webLogin+':'+webPassword) + '&' + (isAP?'1':'0') + '&' + apName + '&' + apPassword + '&' + apChannel + '&' + ssid + '&' + password + '&' + udpPort + '&' + tcpPort;\r\n"; s += "}\r\n"; s += "</script>\r\n"; // write first part of response httpClient.write(s.c_str(), s.length()); // title and mac address s = "<b>" + String(name) + "</b><br>\r\n"; s += "MAC: " + m + "<br>\r\n"; // web interface configuration s += "<table border=1>\r\n"; s += "<tr><td colspan=2 bgcolor=#E0E0E0><b>WEB INTERFACE</b></td></tr>\r\n"; s += "<tr><td>Port</td><td><input type=text id='web_port' value='" + String(webPort) + "'></td></tr>\r\n"; s += "<tr><td>Login</td><td><input type=text id='web_login' value='" + String(webLogin) + "'></td></tr>\r\n"; s += "<tr><td>Password</td><td><input type=password id='web_pass' value='" + String(webPassword) + "'></td></tr>\r\n"; s += "<tr><td>Pass Confirm</td><td><input type=password id='web_pass2' value='" + String(webPassword) + "'></td></tr>\r\n"; s += "</table>\r\n"; // ap configuration s += "<table border=1>\r\n"; s += "<tr><td colspan=2 bgcolor=#E0E0E0><b>ACCESS POINT</b></td></tr>\r\n"; s += "<tr><td>Mode</td><td><input type=radio id='modeap' name='mode' value='ap'" + (isAP?String(" checked"):String("")) + ">Access Point</td></tr>\r\n"; s += "<tr><td>Channel</td><td><select id='apChannel'>"; for (byte c=1; c<14; c++) s += "<option value='" + String(c) + "'" + (c==apChannel?String(" selected"):String("")) + ">" + String(c) + "</option>"; s += "</select></td></tr>\r\n"; s += "<tr><td>SSID</td><td><input type=text id='ap_ssid' value='" + String(apName) + "'></td></tr>\r\n"; s += "<tr><td>Password</td><td><input type=password id='ap_pass' value='" + String(apPassword) + "'></td></tr>\r\n"; s += "<tr><td>Pass Confirm</td><td><input type=password id='ap_pass2' value='" + String(apPassword) + "'></td></tr>\r\n"; s += "</table>\r\n"; // station configuration s += "<table border=1>\r\n"; s += "<tr><td colspan=2 bgcolor=#E0E0E0><b>STATION</b></td></tr>\r\n"; s += "<tr><td>Mode</td><td><input type=radio id='modest' name='mode' value='station'" + (isAP?String(""):String(" checked")) + ">Station</td></tr>\r\n"; s += "<tr><td>SSID</td><td><input type=text id='ssid' value='" + String(ssid) + "'></td></tr>\r\n"; s += "<tr><td>Password</td><td><input type=password id='pass' value='" + String(password) + "'></td></tr>\r\n"; s += "<tr><td>Pass Confirm</td><td><input type=password id='pass2' value='" + String(password) + "'></td></tr>\r\n"; s += "</table>\r\n"; // udp/tcp ports configuration s += "<table border=1>\r\n"; s += "<tr><td colspan=2 bgcolor=#E0E0E0><b>UDP|TCP LISTENERS</b></td></tr>\r\n"; s += "<tr><td>UDP Port</td><td><input type=text id='udpPort' value='" + String(udpPort) + "'></td></tr>\r\n"; s += "<tr><td>TCP Port</td><td><input type=text id='tcpPort' value='" + String(tcpPort) + "'></td></tr>\r\n"; s += "</table>\r\n"; // save button s += "<input type=button value='Save and Reset' onClick='save()'>\r\n"; // end of HTTP s += "</body></html>\r\n"; // write second part of response httpClient.write(s.c_str(), s.length()); httpClient.flush(); if (updated) { // give some time delay(2000); // reset the microcontroller Reset(); } }
//****************** Recieve data for ModBusSlave **************** void MgsModbus::MbsRun() { //****************** Read from socket **************** WiFiClient client = MbServer.available(); if(client.available()) { delay(10); int i = 0; while(client.available()) { MbsByteArray[i] = client.read(); i++; } MbsFC = SetFC(MbsByteArray[7]); //Byte 7 of request is FC } int Start, WordDataLength, ByteDataLength, CoilDataLength, MessageLength; //****************** Read Coils (1 & 2) ********************** if(MbsFC == MB_FC_READ_COILS || MbsFC == MB_FC_READ_DISCRETE_INPUT) { Start = word(MbsByteArray[8],MbsByteArray[9]); CoilDataLength = word(MbsByteArray[10],MbsByteArray[11]); ByteDataLength = CoilDataLength / 8; if(ByteDataLength * 8 < CoilDataLength) ByteDataLength++; CoilDataLength = ByteDataLength * 8; MbsByteArray[5] = ByteDataLength + 3; //Number of bytes after this one. MbsByteArray[8] = ByteDataLength; //Number of bytes after this one (or number of bytes of data). for(int i = 0; i < ByteDataLength ; i++) { MbsByteArray[9 + i] = 0; // To get all remaining not written bits zero for(int j = 0; j < 8; j++) { bitWrite(MbsByteArray[9 + i], j, GetBit(Start + i * 8 + j)); } } MessageLength = ByteDataLength + 9; client.write((uint8_t*)MbsByteArray, MessageLength); MbsFC = MB_FC_NONE; } //****************** Read Registers (3 & 4) ****************** if(MbsFC == MB_FC_READ_REGISTERS || MbsFC == MB_FC_READ_INPUT_REGISTER) { Start = word(MbsByteArray[8],MbsByteArray[9]); WordDataLength = word(MbsByteArray[10],MbsByteArray[11]); ByteDataLength = WordDataLength * 2; MbsByteArray[5] = ByteDataLength + 3; //Number of bytes after this one. MbsByteArray[8] = ByteDataLength; //Number of bytes after this one (or number of bytes of data). for(int i = 0; i < WordDataLength; i++) { MbsByteArray[ 9 + i * 2] = highByte(MbData[Start + i]); MbsByteArray[10 + i * 2] = lowByte(MbData[Start + i]); } MessageLength = ByteDataLength + 9; client.write((uint8_t*)MbsByteArray, MessageLength); MbsFC = MB_FC_NONE; } //****************** Write Coil (5) ********************** if(MbsFC == MB_FC_WRITE_COIL) { Start = word(MbsByteArray[8],MbsByteArray[9]); if (word(MbsByteArray[10],MbsByteArray[11]) == 0xFF00){SetBit(Start,true);} if (word(MbsByteArray[10],MbsByteArray[11]) == 0x0000){SetBit(Start,false);} MbsByteArray[5] = 2; //Number of bytes after this one. MessageLength = 8; client.write((uint8_t*)MbsByteArray, MessageLength); MbsFC = MB_FC_NONE; } //****************** Write Register (6) ****************** if(MbsFC == MB_FC_WRITE_REGISTER) { Start = word(MbsByteArray[8],MbsByteArray[9]); MbData[Start] = word(MbsByteArray[10],MbsByteArray[11]); MbsByteArray[5] = 6; //Number of bytes after this one. MessageLength = 12; client.write((uint8_t*)MbsByteArray, MessageLength); MbsFC = MB_FC_NONE; } //****************** Write Multiple Coils (15) ********************** if(MbsFC == MB_FC_WRITE_MULTIPLE_COILS) { Start = word(MbsByteArray[8],MbsByteArray[9]); CoilDataLength = word(MbsByteArray[10],MbsByteArray[11]); MbsByteArray[5] = 6; for(int i = 0; i < CoilDataLength; i++) { SetBit(Start + i,bitRead(MbsByteArray[13 + (i/8)],i-((i/8)*8))); } MessageLength = 12; client.write((uint8_t*)MbsByteArray, MessageLength); MbsFC = MB_FC_NONE; } //****************** Write Multiple Registers (16) ****************** if(MbsFC == MB_FC_WRITE_MULTIPLE_REGISTERS) { Start = word(MbsByteArray[8],MbsByteArray[9]); WordDataLength = word(MbsByteArray[10],MbsByteArray[11]); ByteDataLength = WordDataLength * 2; MbsByteArray[5] = 6; for(int i = 0; i < WordDataLength; i++) { MbData[Start + i] = word(MbsByteArray[ 13 + i * 2],MbsByteArray[14 + i * 2]); } MessageLength = 12; client.write((uint8_t*)MbsByteArray, MessageLength); MbsFC = MB_FC_NONE; } }
//****************** 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(); } }