how to send an html variable through the serial port in Arduino IDE (ESP32-CAM) - serial-port

Good afternoon,
I am trying to develop an object detector with the ESP32-CAM that works without internet connection, i.e. locally, and for this purpose an SD card has been used to load the recognition model (cocosd). As can be seen in the code, the model is called from the web server (html) and the detection is performed there. However, under the conditions in which I am, I have to avoid having access to the video, so I want to send through the serial port the information that is in the objectCount variable since I am only interested in knowing the number of objects that are detected.
The project is being developed with the ESP32-CAM using the Arduino IDE; therefore, what I want to do is to send through the serial port the information that is stored in the objectCount variable in the html code.
Does anyone have any idea on how to send the objectCount variable through the serial port?
Thank you very much in advance and best regards.
Alex
code:
const char* ssid = ""; //network SSID
const char* password = ""; //network password
const char* apssid = "ESP32-CAM";
const char* appassword = "12345678";
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include "esp_camera.h"
#include "soc/soc.h"
#include "soc/rtc_cntl_reg.h"
#include "FS.h"
#include "SD_MMC.h"
String Feedback="";
String Command="",cmd="",P1="",P2="",P3="",P4="",P5="",P6="",P7="",P8="",P9="";
byte ReceiveState=0,cmdState=1,strState=1,questionstate=0,equalstate=0,semicolonstate=0;
#define PWDN_GPIO_NUM 32
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM 0
#define SIOD_GPIO_NUM 26
#define SIOC_GPIO_NUM 27
#define Y9_GPIO_NUM 35
#define Y8_GPIO_NUM 34
#define Y7_GPIO_NUM 39
#define Y6_GPIO_NUM 36
#define Y5_GPIO_NUM 21
#define Y4_GPIO_NUM 19
#define Y3_GPIO_NUM 18
#define Y2_GPIO_NUM 5
#define VSYNC_GPIO_NUM 25
#define HREF_GPIO_NUM 23
#define PCLK_GPIO_NUM 22
WiFiServer server(80);
void ExecuteCommand()
{
if (cmd!="getstill") {
Serial.println("cmd= "+cmd+" ,P1= "+P1+" ,P2= "+P2+" ,P3= "+P3+" ,P4= "+P4+" ,P5= "+P5+" ,P6= "+P6+" ,P7= "+P7+" ,P8= "+P8+" ,P9= "+P9);
Serial.println("");
}
if (cmd=="your cmd") {
}
else if (cmd=="ip") {
Feedback="AP IP: "+WiFi.softAPIP().toString();
Feedback+=", ";
Feedback+="STA IP: "+WiFi.localIP().toString();
}
else if (cmd=="mac") {
Feedback="STA MAC: "+WiFi.macAddress();
}
else if (cmd=="resetwifi") {
WiFi.begin(P1.c_str(), P2.c_str());
Serial.print("Connecting to ");
Serial.println(P1);
long int StartTime=millis();
while (WiFi.status() != WL_CONNECTED) {
delay(500);
if ((StartTime+5000) < millis()) break;
}
Serial.println("");
Serial.println("STAIP: "+WiFi.localIP().toString());
Feedback="STAIP: "+WiFi.localIP().toString();
}
else if (cmd=="restart") {
ESP.restart();
}
else if (cmd=="digitalwrite") {
ledcDetachPin(P1.toInt());
pinMode(P1.toInt(), OUTPUT);
digitalWrite(P1.toInt(), P2.toInt());
}
else if (cmd=="analogwrite") {
if (P1="4") {
ledcAttachPin(4, 4);
ledcSetup(4, 5000, 8);
ledcWrite(4,P2.toInt());
}
else {
ledcAttachPin(P1.toInt(), 5);
ledcSetup(5, 5000, 8);
ledcWrite(5,P2.toInt());
}
}
else if (cmd=="flash") {
ledcAttachPin(4, 4);
ledcSetup(4, 5000, 8);
int val = P1.toInt();
ledcWrite(4,val);
}
else if (cmd=="framesize") {
sensor_t * s = esp_camera_sensor_get();
if (P1=="QQVGA")
s->set_framesize(s, FRAMESIZE_QQVGA);
else if (P1=="HQVGA")
s->set_framesize(s, FRAMESIZE_HQVGA);
else if (P1=="QVGA")
s->set_framesize(s, FRAMESIZE_QVGA);
else if (P1=="CIF")
s->set_framesize(s, FRAMESIZE_CIF);
else if (P1=="VGA")
s->set_framesize(s, FRAMESIZE_VGA);
else if (P1=="SVGA")
s->set_framesize(s, FRAMESIZE_SVGA);
else if (P1=="XGA")
s->set_framesize(s, FRAMESIZE_XGA);
else if (P1=="SXGA")
s->set_framesize(s, FRAMESIZE_SXGA);
else if (P1=="UXGA")
s->set_framesize(s, FRAMESIZE_UXGA);
else
s->set_framesize(s, FRAMESIZE_QVGA);
}
else {
Feedback="Command is not defined.";
}
if (Feedback=="") Feedback=Command;
}
static const char PROGMEM INDEX_HTML[] = R"rawliteral(
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<script src="?getfile=/tf.min.js"> </script>
<script src="?getfile=/coco-ssd#2.1.0"> </script>
</head><body>
<img id="ShowImage" src="" style="display:none">
<canvas id="canvas" width="0" height="0"></canvas>
<table>
<tr>
<td><input type="button" id="restart" value="Restart"></td>
<td colspan="2"><input type="button" id="getStill" value="Start Detect" style="display:none"></td>
</tr>
<tr>
<td>Object</td>
<td colspan="2">
<select id="object" onchange="count.innerHTML='';">
<option value="person">person</option>
</select>
</td>
<td><span id="count" style="color:red"><span></td>
</tr>
<tr>
<td>ScoreLimit</td>
<td colspan="2">
<select id="score">
<option value="1.0">1</option>
<option value="0.9">0.9</option>
<option value="0.8">0.8</option>
<option value="0.7">0.7</option>
<option value="0.6">0.6</option>
<option value="0.5">0.5</option>
<option value="0.4">0.4</option>
<option value="0.3">0.3</option>
<option value="0.2">0.2</option>
<option value="0.1">0.1</option>
<option value="0" selected="selected">0</option>
</select>
</td>
</tr>
<tr>
<td>MirrorImage</td>
<td colspan="2">
<select id="mirrorimage">
<option value="1">yes</option>
<option value="0">no</option>
</select>
</td>
</tr>
<tr>
<td>Resolution</td>
<td colspan="2">
<select id="framesize">
<option value="UXGA">UXGA(1600x1200)</option>
<option value="SXGA">SXGA(1280x1024)</option>
<option value="XGA">XGA(1024x768)</option>
<option value="SVGA">SVGA(800x600)</option>
<option value="VGA">VGA(640x480)</option>
<option value="CIF">CIF(400x296)</option>
<option value="QVGA" selected="selected">QVGA(320x240)</option>
<option value="HQVGA">HQVGA(240x176)</option>
<option value="QQVGA">QQVGA(160x120)</option>
</select>
</td>
</tr>
<tr>
<td>Flash</td>
<td colspan="2"><input type="range" id="flash" min="0" max="255" value="0"></td>
</tr>
<tr>
<td>Quality</td>
<td colspan="2"><input type="range" id="quality" min="10" max="63" value="10"></td>
</tr>
<tr>
<td>Brightness</td>
<td colspan="2"><input type="range" id="brightness" min="-2" max="2" value="0"></td>
</tr>
<tr>
<td>Contrast</td>
<td colspan="2"><input type="range" id="contrast" min="-2" max="2" value="0"></td>
</tr>
<tr><td>Rotate</td>
<td align="left" colspan="2">
<select onchange="document.getElementById('canvas').style.transform='rotate('+this.value+')';">
<option value="0deg">0deg</option>
<option value="90deg">90deg</option>
<option value="180deg">180deg</option>
<option value="270deg">270deg</option>
</select>
</td>
</tr>
</table>
<div id="result" style="color:red"><div>
</body>
</html>
<script>
var getStill = document.getElementById('getStill');
var ShowImage = document.getElementById('ShowImage');
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var object = document.getElementById('object');
var score = document.getElementById("score");
var mirrorimage = document.getElementById("mirrorimage");
var count = document.getElementById('count');
var result = document.getElementById('result');
var flash = document.getElementById('flash');
var lastValue="";
var myTimer;
var restartCount=0;
var Model;
getStill.onclick = function (event) {
clearInterval(myTimer);
myTimer = setInterval(function(){error_handle();},5000);
ShowImage.src=location.origin+'/?getstill='+Math.random();
}
function error_handle() {
restartCount++;
clearInterval(myTimer);
if (restartCount<=2) {
result.innerHTML = "Get still error. <br>Restart ESP32-CAM "+restartCount+" times.";
myTimer = setInterval(function(){getStill.click();},10000);
}
else
result.innerHTML = "Get still error. <br>Please close the page and check ESP32-CAM.";
}
ShowImage.onload = function (event) {
clearInterval(myTimer);
restartCount=0;
canvas.setAttribute("width", ShowImage.width);
canvas.setAttribute("height", ShowImage.height);
if (mirrorimage.value==1) {
context.translate((canvas.width + ShowImage.width) / 2, 0);
context.scale(-1, 1);
context.drawImage(ShowImage, 0, 0, ShowImage.width, ShowImage.height);
context.setTransform(1, 0, 0, 1, 0, 0);
}
else
context.drawImage(ShowImage,0,0,ShowImage.width,ShowImage.height);
if (Model) {
DetectImage();
}
}
restart.onclick = function (event) {
fetch(location.origin+'/?restart=stop');
}
framesize.onclick = function (event) {
fetch(document.location.origin+'/?framesize='+this.value+';stop');
}
flash.onchange = function (event) {
fetch(location.origin+'/?flash='+this.value+';stop');
}
quality.onclick = function (event) {
fetch(document.location.origin+'/?quality='+this.value+';stop');
}
brightness.onclick = function (event) {
fetch(document.location.origin+'/?brightness='+this.value+';stop');
}
contrast.onclick = function (event) {
fetch(document.location.origin+'/?contrast='+this.value+';stop');
}
function ObjectDetect() {
result.innerHTML = "Please wait for loading model.";
cocoSsd.load().then(cocoSsd_Model => {
Model = cocoSsd_Model;
result.innerHTML = "";
getStill.style.display = "block";
});
}
function DetectImage() {
Model.detect(canvas).then(Predictions => {
var s = (canvas.width>canvas.height)?canvas.width:canvas.height;
var objectCount=0;
//console.log('Predictions: ', Predictions);
if (Predictions.length>0) {
result.innerHTML = "";
for (var i=0;i<Predictions.length;i++) {
const x = Predictions[i].bbox[0];
const y = Predictions[i].bbox[1];
const width = Predictions[i].bbox[2];
const height = Predictions[i].bbox[3];
context.lineWidth = Math.round(s/200);
context.strokeStyle = "#00FFFF";
context.beginPath();
context.rect(x, y, width, height);
context.stroke();
context.lineWidth = "2";
context.fillStyle = "red";
context.font = Math.round(s/30) + "px Arial";
context.fillText(Predictions[i].class, x, y);
//context.fillText(i, x, y);
result.innerHTML+= "[ "+i+" ] "+Predictions[i].class+", "+Math.round(Predictions[i].score*100)+"%, "+Math.round(x)+", "+Math.round(y)+", "+Math.round(width)+", "+Math.round(height)+"<br>";
if (Predictions[i].class==object.value&&Predictions[i].score>=score.value) {
objectCount++;
}
}
count.innerHTML = objectCount;
}
else {
result.innerHTML = "Unrecognizable";
count.innerHTML = "0";
}
try {
document.createEvent("TouchEvent");
setTimeout(function(){getStill.click();},250);
}
catch(e) {
setTimeout(function(){getStill.click();},150);
}
});
}
window.onload = function () { ObjectDetect(); }
</script>
)rawliteral";
void setup() {
WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0);
Serial.begin(115200);
Serial.setDebugOutput(true);
Serial.println();
camera_config_t config;
config.ledc_channel = LEDC_CHANNEL_0;
config.ledc_timer = LEDC_TIMER_0;
config.pin_d0 = Y2_GPIO_NUM;
config.pin_d1 = Y3_GPIO_NUM;
config.pin_d2 = Y4_GPIO_NUM;
config.pin_d3 = Y5_GPIO_NUM;
config.pin_d4 = Y6_GPIO_NUM;
config.pin_d5 = Y7_GPIO_NUM;
config.pin_d6 = Y8_GPIO_NUM;
config.pin_d7 = Y9_GPIO_NUM;
config.pin_xclk = XCLK_GPIO_NUM;
config.pin_pclk = PCLK_GPIO_NUM;
config.pin_vsync = VSYNC_GPIO_NUM;
config.pin_href = HREF_GPIO_NUM;
config.pin_sscb_sda = SIOD_GPIO_NUM;
config.pin_sscb_scl = SIOC_GPIO_NUM;
config.pin_pwdn = PWDN_GPIO_NUM;
config.pin_reset = RESET_GPIO_NUM;
config.xclk_freq_hz = 20000000;
config.pixel_format = PIXFORMAT_JPEG;
if(psramFound()){
config.frame_size = FRAMESIZE_UXGA;
config.jpeg_quality = 10;
config.fb_count = 2;
} else {
config.frame_size = FRAMESIZE_SVGA;
config.jpeg_quality = 12;
config.fb_count = 1;
}
esp_err_t err = esp_camera_init(&config);
if (err != ESP_OK) {
Serial.printf("Camera init failed with error 0x%x", err);
delay(1000);
ESP.restart();
}
sensor_t * s = esp_camera_sensor_get();
s->set_framesize(s, FRAMESIZE_QVGA);
if(!SD_MMC.begin()){
Serial.println("Card Mount Failed");
return;
}
uint8_t cardType = SD_MMC.cardType();
if(cardType == CARD_NONE){
Serial.println("No SD_MMC card attached");
SD_MMC.end();
return;
}
Serial.println("");
Serial.print("SD_MMC Card Type: ");
if(cardType == CARD_MMC){
Serial.println("MMC");
} else if(cardType == CARD_SD){
Serial.println("SDSC");
} else if(cardType == CARD_SDHC){
Serial.println("SDHC");
} else {
Serial.println("UNKNOWN");
}
Serial.printf("SD_MMC Card Size: %lluMB\n", SD_MMC.cardSize() / (1024 * 1024));
Serial.printf("Total space: %lluMB\n", SD_MMC.totalBytes() / (1024 * 1024));
Serial.printf("Used space: %lluMB\n", SD_MMC.usedBytes() / (1024 * 1024));
Serial.println();
SD_MMC.end();
ledcAttachPin(4, 4);
ledcSetup(4, 5000, 8);
WiFi.mode(WIFI_AP_STA);
WiFi.begin(ssid, password);
delay(1000);
Serial.println("");
Serial.print("Connecting to ");
Serial.println(ssid);
long int StartTime=millis();
while (WiFi.status() != WL_CONNECTED) {
delay(500);
if ((StartTime+10000) < millis()) break;
}
if (WiFi.status() == WL_CONNECTED) {
WiFi.softAP((WiFi.localIP().toString()+"_"+(String)apssid).c_str(), appassword);
Serial.println("");
Serial.println("STAIP address: ");
Serial.println(WiFi.localIP());
for (int i=0;i<5;i++) {
ledcWrite(4,10);
delay(200);
ledcWrite(4,0);
delay(200);
}
}
else {
WiFi.softAP((WiFi.softAPIP().toString()+"_"+(String)apssid).c_str(), appassword);
for (int i=0;i<2;i++) {
ledcWrite(4,10);
delay(1000);
ledcWrite(4,0);
delay(1000);
}
}
Serial.println("");
Serial.println("APIP address: ");
Serial.println(WiFi.softAPIP());
pinMode(4, OUTPUT);
digitalWrite(4, LOW);
server.begin();
}
void loop() {
Feedback="";Command="";cmd="";P1="";P2="";P3="";P4="";P5="";P6="";P7="";P8="";P9="";
ReceiveState=0,cmdState=1,strState=1,questionstate=0,equalstate=0,semicolonstate=0;
WiFiClient client = server.available();
if (client) {
String currentLine = "";
while (client.connected()) {
if (client.available()) {
char c = client.read();
getCommand(c);
if (c == '\n') {
if (currentLine.length() == 0) {
if (cmd=="getstill") {
camera_fb_t * fb = NULL;
fb = esp_camera_fb_get();
if(!fb) {
Serial.println("Camera capture failed");
delay(1000);
ESP.restart();
}
client.println("HTTP/1.1 200 OK");
client.println("Access-Control-Allow-Origin: *");
client.println("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
client.println("Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS");
client.println("Content-Type: image/jpeg");
client.println("Content-Disposition: form-data; name=\"imageFile\"; filename=\"picture.jpg\"");
client.println("Content-Length: " + String(fb->len));
client.println("Connection: close");
client.println();
uint8_t *fbBuf = fb->buf;
size_t fbLen = fb->len;
for (size_t n=0;n<fbLen;n=n+1024) {
if (n+1024<fbLen) {
client.write(fbBuf, 1024);
fbBuf += 1024;
}
else if (fbLen%1024>0) {
size_t remainder = fbLen%1024;
client.write(fbBuf, remainder);
}
}
client.println();
esp_camera_fb_return(fb);
pinMode(4, OUTPUT);
digitalWrite(4, LOW);
}
else if (cmd=="getfile") {
if(!SD_MMC.begin()){
Serial.println("Card Mount Failed");
}
fs::FS &fs = SD_MMC;
File file = fs.open(P1);
if(!file){
Serial.println("Failed to open file for reading");
SD_MMC.end();
}
else {
Serial.println("Read from file: "+P1);
Serial.println("file size: "+String(file.size()));
client.println("HTTP/1.1 200 OK");
client.println("Access-Control-Allow-Origin: *");
client.println("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
client.println("Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS");
client.println("Content-Type: text/html");
P1.replace("/","");
client.println("Content-Disposition: form-data; name=\"jsFile\"; filename=\""+P1+"\"");
client.println("Content-Length: " + String(file.size()));
client.println("Connection: close");
client.println();
byte buf[1024];
int i = -1;
while (file.available()) {
i++;
buf[i] = file.read();
if (i==(sizeof(buf)-1)) {
client.write((const uint8_t *)buf, sizeof(buf));
i = -1;
}
else if (!file.available())
client.write((const uint8_t *)buf, (i+1));
}
file.close();
SD_MMC.end();
}
pinMode(4, OUTPUT);
digitalWrite(4, LOW);
}
else if (cmd=="getimage") {
if(!SD_MMC.begin()){
Serial.println("Card Mount Failed");
}
fs::FS &fs = SD_MMC;
File file = fs.open(P1);
if(!file){
Serial.println("Failed to open file for reading");
SD_MMC.end();
}
else {
Serial.println("Read from file: "+P1);
Serial.println("file size: "+String(file.size()));
client.println("HTTP/1.1 200 OK");
client.println("Access-Control-Allow-Origin: *");
client.println("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
client.println("Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS");
client.println("Content-Type: image/jpeg");
P1.replace("/","");
client.println("Content-Disposition: form-data; name=\"imageFile\"; filename=\""+P1+"\"");
client.println("Content-Length: " + String(file.size()));
client.println("Connection: close");
client.println();
byte buf[1024];
int i = -1;
while (file.available()) {
i++;
buf[i] = file.read();
if (i==(sizeof(buf)-1)) {
client.write((const uint8_t *)buf, sizeof(buf));
i = -1;
}
else if (!file.available())
client.write((const uint8_t *)buf, (i+1));
}
file.close();
SD_MMC.end();
}
pinMode(4, OUTPUT);
digitalWrite(4, LOW);
}
else {
client.println("HTTP/1.1 200 OK");
client.println("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
client.println("Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS");
client.println("Content-Type: text/html; charset=utf-8");
client.println("Access-Control-Allow-Origin: *");
client.println("Connection: close");
client.println();
String Data="";
if (cmd!="")
Data = Feedback;
else {
Data = String((const char *)INDEX_HTML);
}
int Index;
for (Index = 0; Index < Data.length(); Index = Index+1000) {
client.print(Data.substring(Index, Index+1000));
}
client.println();
}
Feedback="";
break;
} else {
currentLine = "";
}
}
else if (c != '\r') {
currentLine += c;
}
if ((currentLine.indexOf("/?")!=-1)&&(currentLine.indexOf(" HTTP")!=-1)) {
if (Command.indexOf("stop")!=-1) {
client.println();
client.println();
client.stop();
}
currentLine="";
Feedback="";
ExecuteCommand();
}
}
}
delay(1);
client.stop();
}
}
void getCommand(char c)
{
if (c=='?') ReceiveState=1;
if ((c==' ')||(c=='\r')||(c=='\n')) ReceiveState=0;
if (ReceiveState==1)
{
Command=Command+String(c);
if (c=='=') cmdState=0;
if (c==';') strState++;
if ((cmdState==1)&&((c!='?')||(questionstate==1))) cmd=cmd+String(c);
if ((cmdState==0)&&(strState==1)&&((c!='=')||(equalstate==1))) P1=P1+String(c);
if ((cmdState==0)&&(strState==2)&&(c!=';')) P2=P2+String(c);
if ((cmdState==0)&&(strState==3)&&(c!=';')) P3=P3+String(c);
if ((cmdState==0)&&(strState==4)&&(c!=';')) P4=P4+String(c);
if ((cmdState==0)&&(strState==5)&&(c!=';')) P5=P5+String(c);
if ((cmdState==0)&&(strState==6)&&(c!=';')) P6=P6+String(c);
if ((cmdState==0)&&(strState==7)&&(c!=';')) P7=P7+String(c);
if ((cmdState==0)&&(strState==8)&&(c!=';')) P8=P8+String(c);
if ((cmdState==0)&&(strState>=9)&&((c!=';')||(semicolonstate==1))) P9=P9+String(c);
if (c=='?') questionstate=1;
if (c=='=') equalstate=1;
if ((strState>=9)&&(c==';')) semicolonstate=1;
}
}
I tried using GET and POST requests to send the variable, but as it is a synchronous server I can't get it to work.

Related

ESP8266 Wifi configuration

I had a Node MCU module as shown in the photo.
My nodemcu
I had this tutorial from this link:Tutorial link
I had a problem with WIFI Configuring which from the code I had online it should be working with the browser 192.168.4.1 as shown as below. But with my LoLin NodeMCU V3 I cant reach to the browser page and always show the connection has timed out. Can I know is it my NodeMCU module problem?
p.s.
The wifi connection work well with hardcoding but not WIFI configuration)
The Module i found there is slightly different from normal Nodemcu with a yellow component on it.
I used ARDUINO IDE to compile and upload.
proper result with the browser for wifi configuration
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>
//Variables
int i = 0;
int statusCode;
const char* ssid = "Default_SSID";
const char* passphrase = "Default_Password";
String st;
String content;
//Function Decalration
bool testWifi(void);
void launchWeb(void);
void setupAP(void);
//Establishing Local server at port 80 whenever required
ESP8266WebServer server(80);
void setup()
{
Serial.begin(115200); //Initialising if(DEBUG)Serial Monitor
Serial.println();
Serial.println("Disconnecting current wifi connection");
WiFi.disconnect();
EEPROM.begin(512); //Initialasing EEPROM
delay(10);
pinMode(LED_BUILTIN, OUTPUT);
Serial.println();
Serial.println();
Serial.println("Startup");
//---------------------------------------- Read eeprom for ssid and pass
Serial.println("Reading EEPROM ssid");
String esid;
for (int i = 0; i < 32; ++i)
{
esid += char(EEPROM.read(i));
}
Serial.println();
Serial.print("SSID: ");
Serial.println(esid);
Serial.println("Reading EEPROM pass");
String epass = "";
for (int i = 32; i < 96; ++i)
{
epass += char(EEPROM.read(i));
}
Serial.print("PASS: ");
Serial.println(epass);
WiFi.begin(esid.c_str(), epass.c_str());
if (testWifi())
{
Serial.println("Succesfully Connected!!!");
return;
}
else
{
Serial.println("Turning the HotSpot On");
launchWeb();
setupAP();// Setup HotSpot
}
Serial.println();
Serial.println("Waiting.");
while ((WiFi.status() != WL_CONNECTED))
{
Serial.print(".");
delay(100);
server.handleClient();
}
}
void loop() {
if ((WiFi.status() == WL_CONNECTED))
{
for (int i = 0; i < 10; i++)
{
digitalWrite(LED_BUILTIN, HIGH);
delay(1000);
digitalWrite(LED_BUILTIN, LOW);
delay(1000);
}
}
else
{
}
}
//----------------------------------------------- Fuctions used for WiFi credentials saving and connecting to it which you do not need to change
bool testWifi(void)
{
int c = 0;
Serial.println("Waiting for Wifi to connect");
while ( c < 20 ) {
if (WiFi.status() == WL_CONNECTED)
{
return true;
}
delay(500);
Serial.print("*");
c++;
}
Serial.println("");
Serial.println("Connect timed out, opening AP");
return false;
}
void launchWeb()
{
Serial.println("");
if (WiFi.status() == WL_CONNECTED)
Serial.println("WiFi connected");
Serial.print("Local IP: ");
Serial.println(WiFi.localIP());
Serial.print("SoftAP IP: ");
Serial.println(WiFi.softAPIP());
createWebServer();
// Start the server
server.begin();
Serial.println("Server started");
}
void setupAP(void)
{
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
int n = WiFi.scanNetworks();
Serial.println("scan done");
if (n == 0)
Serial.println("no networks found");
else
{
Serial.print(n);
Serial.println(" networks found");
for (int i = 0; i < n; ++i)
{
// Print SSID and RSSI for each network found
Serial.print(i + 1);
Serial.print(": ");
Serial.print(WiFi.SSID(i));
Serial.print(" (");
Serial.print(WiFi.RSSI(i));
Serial.print(")");
Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*");
delay(10);
}
}
Serial.println("");
st = "<ol>";
for (int i = 0; i < n; ++i)
{
// Print SSID and RSSI for each network found
st += "<li>";
st += WiFi.SSID(i);
st += " (";
st += WiFi.RSSI(i);
st += ")";
st += (WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*";
st += "</li>";
}
st += "</ol>";
delay(100);
WiFi.softAP("ElectronicsInnovation", "");
Serial.println("Initializing_softap_for_wifi credentials_modification");
launchWeb();
Serial.println("over");
}
void createWebServer()
{
{
server.on("/", []() {
IPAddress ip = WiFi.softAPIP();
String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
content = "<!DOCTYPE HTML>\r\n<html>Welcome to Wifi Credentials Update page";
content += "<form action=\"/scan\" method=\"POST\"><input type=\"submit\" value=\"scan\"></form>";
content += ipStr;
content += "<p>";
content += st;
content += "</p><form method='get' action='setting'><label>SSID: </label><input name='ssid' length=32><input name='pass' length=64><input type='submit'></form>";
content += "</html>";
server.send(200, "text/html", content);
});
server.on("/scan", []() {
//setupAP();
IPAddress ip = WiFi.softAPIP();
String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
content = "<!DOCTYPE HTML>\r\n<html>go back";
server.send(200, "text/html", content);
});
server.on("/setting", []() {
String qsid = server.arg("ssid");
String qpass = server.arg("pass");
if (qsid.length() > 0 && qpass.length() > 0) {
Serial.println("clearing eeprom");
for (int i = 0; i < 96; ++i) {
EEPROM.write(i, 0);
}
Serial.println(qsid);
Serial.println("");
Serial.println(qpass);
Serial.println("");
Serial.println("writing eeprom ssid:");
for (int i = 0; i < qsid.length(); ++i)
{
EEPROM.write(i, qsid[i]);
Serial.print("Wrote: ");
Serial.println(qsid[i]);
}
Serial.println("writing eeprom pass:");
for (int i = 0; i < qpass.length(); ++i)
{
EEPROM.write(32 + i, qpass[i]);
Serial.print("Wrote: ");
Serial.println(qpass[i]);
}
EEPROM.commit();
content = "{\"Success\":\"saved to eeprom... reset to boot into new wifi\"}";
statusCode = 200;
ESP.reset();
} else {
content = "{\"Error\":\"404 not found\"}";
statusCode = 404;
Serial.println("Sending 404");
}
server.sendHeader("Access-Control-Allow-Origin", "*");
server.send(statusCode, "application/json", content);
});
}
}
I had tried several times with the code provided online but same results came out with the browser couldnt work.
Be sure to first connect to AP ElectronnicsInnovation and type "http://192.168.4.1" in browser address.
(https - by default - don't works).
I try your code on esp8266 and it works fine.

Problem transferring data to firebase using Sim7600CE, http

I am using ESP32 integrated Sim7600CE module to transfer data to Firebase Realtime database using http and got 400 Bad Request, please help me to solve this.
13:36:48.693 -> Status code: 400
13:36:48.833 -> Response: <html>
13:36:48.833 -> <head><title>400 The plain HTTP request was sent to HTTPS port</title></head>
13:36:48.833 -> <body>
13:36:48.833 -> <center><h1>400 Bad Request</h1></center>
#define TINY_GSM_MODEM_SIM7600
#define TINY_GSM_RX_BUFFER 650
#include <ArduinoJson.h>
#include <TinyGsmClient.h>
#include <ArduinoHttpClient.h> //https://github.com/arduino-libraries/ArduinoHttpClient
#include "TinyGsmClient.h"
#define SIM_RESET_PIN 15
#define SIM_AT_BAUDRATE 115200
#define GSM_PIN ""
#define SIM_TX 17
#define SIM_RX 16
const char FIREBASE_HOST[] = "smartgrid1-930b0-default-rtdb.firebaseio.com";
const String FIREBASE_AUTH = "zezoyo69fX9eqPDpjaom6CJAyXhnW081GlJ4ah5c";
const String FIREBASE_PATH = "/";
const int SSL_PORT = 443;
char APN[] = "v-internet"; //
char USER[] = "";
char PASS[] = "";
TinyGsm modem(Serial2);
TinyGsmClient gsm_client_secure_modem(modem);
HttpClient http_client = HttpClient(gsm_client_secure_modem, FIREBASE_HOST, SSL_PORT);
unsigned long previousMillis = 0;
// Hàm dùng để thiết lập modem SIM tạo kết nối GPRS
bool connectToGPRS() {
// Unlock SIM (nếu có)
if (GSM_PIN && modem.getSimStatus() != 3)
modem.simUnlock(GSM_PIN);
Serial.println("Ket noi toi nha mang...");
while (!modem.waitForNetwork(60000L)) {
Serial.println("._.");
delay(5000);
}
// Nếu không thấy sóng từ nhà mạng thì thoát hàm
if (!modem.isNetworkConnected())
return false;
Serial.println("Ket noi GPRS");
if (!modem.gprsConnect(APN)) {// Hàm kết nối tới gprs trả về true/false cho biết có kết nối được hay chưa
Serial.print("Khong the ket noi GPRS - ");
Serial.println(APN);
return false;
}
// Kiểm tra lại lần nữa để chắc cú
if (modem.isGprsConnected()){
Serial.println("Da ket noi duoc GPRS!");
return true;
}
return false;
}
// Hàm khởi động module SIM
bool initModemSIM() {
Serial.println("Bat dau khoi dong module SIM");
// Đặt chân reset của module xuống LOW để chạy
pinMode(SIM_RESET_PIN, OUTPUT);
digitalWrite(SIM_RESET_PIN, LOW);
delay(5000);
Serial2.begin(SIM_AT_BAUDRATE);// Module SIM giao tiếp với ESP qua cổng Serial2 bằng AT cmds
if (!modem.restart()) {
Serial.println("Khong the khoi dong lai module SIM => Co loi");
return false;
}
return true;
}
void setup() {
Serial.begin(115200);
if (initModemSIM()){
while(!connectToGPRS()) delay(100);
}
if (modem.isGprsConnected()) {
Serial.print(F("Connecting to "));
Serial.println(APN);
if (!modem.gprsConnect(APN, USER, PASS))
{
Serial.println(" fail");
delay(1000);
return;
}
}
if (initModemSIM()){
while(!connectToGPRS()) delay(100);
}
modem.restart();
String modemInfo = modem.getModemInfo();
Serial.print("Modem: ");
Serial.println(modemInfo);
http_client.setHttpResponseTimeout(10 * 1000); //^0 secs timeout
}
void loop() {
Serial.print(F("Connecting to "));
Serial.println(APN);
if (!modem.gprsConnect(APN, USER, PASS))
{
Serial.println(" fail");
delay(1000);
return;
}
Serial.println(" OK");
http_client.connect(FIREBASE_HOST, SSL_PORT);
while (true) {
if (!http_client.connected())
{
Serial.println();
http_client.stop();// Shutdown
Serial.println("HTTP not connect");
break;
}
else
{
dht_loop();
}
}
}
void PostToFirebase(const char* method, const String & path , const String & data, HttpClient* http)
{
String response;
int statusCode = 0;
http->connectionKeepAlive(); // Currently, this is needed for HTTPS
String url;
if (path[0] != '/')
{
url = "/";
}
url += path + ".json";
url += "?auth=" + FIREBASE_AUTH;
Serial.print("POST:");
Serial.println(url);
Serial.print("Data:");
Serial.println(data);
String contentType = "application/json";
http->put(url, contentType, data);
statusCode = http->responseStatusCode();
Serial.print("Status code: ");
Serial.println(statusCode);
response = http->responseBody();
Serial.print("Response: ");
Serial.println(response);
// if (!http->connected())
// {
// Serial.println();
// http->stop();// Shutdown
// Serial.println("HTTP POST disconnected");
// }
}
void dht_loop()
{
String h = String(random(1,100));
delay(100);
Serial.print("h = ");
Serial.println(h);
String Data = "{";
Data += "\"Sim\":" + h + "";
Data += "}";
PostToFirebase("PATCH", FIREBASE_PATH, Data, &http_client);
}

Unable to connect in Ap_mode in esp32

I am making and auto connect code for esp32 in which i am trying to get wifi credential from the webpage when it is operated in ap-mode after getting credential it will connected to wifi whose credential are provided in webpage. But problem i am facing is that i am unable to connect my esp module when it is in ap mode here is my code.
#include "SPIFFS.h"
#include <FS.h>
#include <ArduinoJson.h>
#include "WiFi.h"
#include "ESPAsyncWebServer.h"
uint8_t pin_led = 2;
char* ssid = "YOUR_SSID"; //not used
char* password = "YOUR_AP_PASSWORD";
char* mySsid = "YOUR_AP_SSID";
AsyncWebServer server(80);
IPAddress local_ip(192,168,11,4);
IPAddress gateway(192,168,11,1);
IPAddress netmask(255,255,255,0);
char webpage[] PROGMEM = R"=====(
<html>
<head>
</head>
<body>
<form>
<fieldset>
<div>
<label for="ssid">SSID</label>
<input value="" id="ssid" placeholder="SSID">
</div>
<div>
<label for="password">PASSWORD</label>
<input type="password" value="" id="password" placeholder="PASSWORD">
</div>
<div>
<button class="primary" id="savebtn" type="button" onclick="myFunction()">SAVE</button>
</div>
</fieldset>
</form>
</body>
<script>
function myFunction()
{
console.log("button was clicked!");
var ssid = document.getElementById("ssid").value;
var password = document.getElementById("password").value;
var data = {ssid:ssid, password:password};
var xhr = new XMLHttpRequest();
var url = "/settings";
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
if(xhr.responseText != null){
console.log(xhr.responseText);
}
}
};
xhr.open("POST", url, true);
xhr.send(JSON.stringify(data));
};
</script>
</html>
)=====";
void setup()
{
pinMode(pin_led, OUTPUT);
Serial.begin(115200);
SPIFFS.begin();
wifiConnect();
server.on("/", HTTP_POST, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", webpage);
});
server.on("/toggle", HTTP_POST, [](AsyncWebServerRequest *request){
digitalWrite(pin_led,!digitalRead(pin_led));
request->send(204,"");
});
server.on("/settings", HTTP_POST, [](AsyncWebServerRequest *request){
if(request->hasArg("plain")){
String data = request->arg("plain");//("plain");
DynamicJsonDocument doc(1024);
serializeJson(doc, data);
// DynamicJsonBuffer jBuffer;
//JsonObject jObject = doc.as<JsonObject>();
File configFile = SPIFFS.open("/config.json", "w");
serializeJsonPretty(doc, configFile);
//jObject.printTo(configFile);
configFile.close();
request->send(200, "application/json", "{\"status\" : \"ok\"}");
delay(500);
wifiConnect();
}});
server.begin();
}
void loop()
{
}
void wifiConnect()
{
//reset networking
WiFi.softAPdisconnect(true);
WiFi.disconnect();
delay(1000);
//check for stored credentials
if(SPIFFS.exists("/config.json")){
const char * _ssid = "", *_pass = "";
File configFile = SPIFFS.open("/config.json", "r");
if(configFile){
size_t size = configFile.size();
std::unique_ptr<char[]> buf(new char[size]);
configFile.readBytes(buf.get(), size);
configFile.close();
DynamicJsonDocument doc(1024);
// DynamicJsonBuffer jsonBuffer;
DeserializationError error=deserializeJson(doc, buf.get());
//JsonObject& jObject = doc.as<JsonObject>();
if (error)
{
Serial.print("deserializeJson() failed: ");
Serial.println(error.c_str());
}
else{
_ssid = doc["ssid"];
_pass = doc["password"];
WiFi.mode(WIFI_STA);
WiFi.begin(_ssid, _pass);
unsigned long startTime = millis();
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
digitalWrite(pin_led,!digitalRead(pin_led));
if ((unsigned long)(millis() - startTime) >= 5000) break;
}
}
}
}
if (WiFi.status() == WL_CONNECTED)
{
digitalWrite(pin_led,HIGH);
} else
{
WiFi.mode(WIFI_AP);
WiFi.softAPConfig(local_ip, gateway, netmask);
WiFi.softAP(mySsid, password);
digitalWrite(pin_led,LOW);
}
Serial.println("");
WiFi.printDiag(Serial);
}
Please help me to figure it out
Putting the wifiConnect() as the last command in setup worked for my environment. This program works only under two important preconditions.1. No json on SPIFFS - so make sure during testing you always have a fresh formatted SPIFFS2. No open AP in range, because it will connect to it without pw and no AP_mode would be initiated. There are a lot of more or less working examples for captive portals especially for ESP32 around, but they all have their specific detection problems (e.g. always read the issues on github)

Arduino Ethernet W5100 device stops responding after a few days

I am running a simple web server (static IP) based on the default web server example, which is occasionally interrupted by an external input (eg. RFID reader) which sends data as a client to another server in the local network and starting the server again. the device runs as intended for a few days but then stops responding to pin inputs, accessing the server page seems to get it back on line (not sure about this) otherwise I am forced to manually reset when this happens.
Could using Serial Print(used during the debugging stage) without connecting a serial monitor be the issue?
test code:
/*
This program will decode the wiegand data from a HID RFID Reader (or, theoretically,
any other device that outputs weigand data).
The Wiegand interface has two data lines, DATA0 and DATA1. These lines are normally held
high at 5V. When a 0 is sent, DATA0 drops to 0V for a few us. When a 1 is sent, DATA1 drops
to 0V for a few us. There is usually a few ms between the pulses.
Your reader should have at least 4 connections (some readers have more). Connect the Red wire
to 5V. Connect the black to ground. Connect the green wire (DATA0) to Digital Pin 2 (INT0).
Connect the white wire (DATA1) to Digital Pin 3 (INT1). That's it!
Operation is simple - each of the data lines are connected to hardware interrupt lines. When
one drops low, an interrupt routine is called and some bits are flipped. After some time of
of not receiving any bits, the Arduino will decode the data.
*/
#include <Ethernet.h>
#include <SPI.h>
#include <EEPROM.h>
#define MAX_BITS 100 // max number of bits
#define WEIGAND_WAIT_TIME 3000 // time to wait for another weigand pulse.
unsigned char databits[MAX_BITS]; // stores all of the data bits
unsigned char bitCount; // number of bits currently captured
unsigned char flagDone; // goes low when data is currently being captured
unsigned int weigand_counter; // countdown until we assume there are no more bits
unsigned long facilityCode = 0; // decoded facility code
unsigned long cardCode = 0; // decoded card code
byte tr = 0; //testing trigger
byte ship[4]; //Home Center IP
byte wsip[4]; //Web Server IP
int scene[100]; //scene ID storage
//byte ptr = 0; //log pointer
byte ld = 0; //latest updated log
byte bc[20]; //Wiegand bitCount log
unsigned long wd[20]; //Wiegand data log
String readString1; //IP buffer
String tempstr = "{\r\n\"value\":\"";
String PostData = "{\r\n\"value\":\"1\"\r\n}"; //JSON data to send
// interrupt that happens when INTO goes low (0 bit)-2
void ISR_INT0()
{
Serial.print("0"); // uncomment this line to display raw binary
bitCount++;
flagDone = 0;
weigand_counter = WEIGAND_WAIT_TIME;
tr = 1;
}
// interrupt that happens when INT1 goes low (1 bit)
void ISR_INT1()
{
Serial.print("1"); // uncomment this line to display raw binary
if(bitCount<MAX_BITS)
databits[bitCount] = 1;
bitCount++;
flagDone = 0;
weigand_counter = WEIGAND_WAIT_TIME;
}
byte mac[] = { 0x00, 0xAB, 0xCB, 0xCD, 0xDE, 0x05 };
// byte ip[] = {192,168,4,101};
IPAddress ip(192, 168, 5, 211);
// byte gateway[] = {192,168,4,254};
// byte gateway[] = {192, 168, 5, 1};
// byte subnet[] = {255, 255, 255, 0};
// IPAddress server(192,168,4,100);
IPAddress sh(192, 168, 5, 65);
EthernetServer server(80); //server port arduino server will use
EthernetClient client;
char cnt1 = 0, cnt2 = 0;
void setup()
{
//pinMode(13, OUTPUT); // LED
pinMode(2, INPUT_PULLUP); // DATA0 (INT0)
pinMode(3, INPUT_PULLUP); // DATA1 (INT1)
Serial.begin(9600);
Serial.println("BioLite Net");
attachInterrupt(0, ISR_INT0, FALLING);
attachInterrupt(1, ISR_INT1, FALLING);
// binds the ISR functions to the falling edge of INTO and INT1
EEPROM.get(15, wsip);
IPAddress ip(wsip[0], wsip[1], wsip[2], wsip[3]);
net();
delay(10);
server.begin();
Serial.print(F("Web server is at "));
Serial.println(ip);
// Serial.print(F("server is at "));
// Serial.println(Ethernet.localIP());
EEPROM.get(10, ship);
IPAddress sh(ship[0], ship[1], ship[2], ship[3]);
Serial.print(F("Home Center is at "));
Serial.println(sh);
Serial.println(F("stored scenes are :"));
EEPROM.get(20, scene);
for (byte i = 0; i < 10 ; i++)
{
for (byte j = 0; j < 10 ; j++)
{
Serial.print((10 * i) + j);
Serial.print(" : ");
Serial.print(scene[(10 * i) + j]);
Serial.print(" ; ");
}
Serial.println();
}
EEPROM.get(310, bc);
EEPROM.get(330, wd);
EEPROM.get(305, ld);
byte temp = ld;
Serial.println(temp);
for (byte i = 0; i < 10 ; i++)
{
for (byte j = 0; j < 2 ; j++)
{
Serial.print(bc[temp]);
Serial.print(" : ");
Serial.print(wd[temp], BIN);
Serial.print(" ; ");
if (temp == 0)
temp = 20;
temp--;
}
Serial.println();
}
Serial.println();
/* temp = 19;
for (byte i = 0; i < 10 ; i++)
{
for (byte j = 0; j < 2 ; j++)
{
Serial.print(bc[temp]);
Serial.print(" : ");
Serial.print(wd[temp], BIN);
Serial.print(" ; ");
temp--;
if (temp < 0)
temp = 19;
}
Serial.println();
}*/
weigand_counter = WEIGAND_WAIT_TIME;
}
void loop()
{
// This waits to make sure that there have been no more data pulses before processing data
if (!flagDone) {
if (--weigand_counter == 0)
flagDone = 1;
}
// if we have bits and we the weigand counter went out
if (bitCount > 0 && flagDone) {
//if (tr == 1) {
tr == 0; delay(3000);
unsigned char i;
Serial.println();
if(bitCount>255) bitCount=255;
EEPROM.get(305, ld);
EEPROM.get(310, bc);
EEPROM.get(330, wd);
ld++;
if (ld > 19)
ld = 0;
Serial.println(ld);
// ptr += 5;
// ld = (ptr - 310) / 5;
bc[ld] = bitCount;
wd[ld] = 0;
for (i = 0; i < bitCount; i++)
{
Serial.print(databits[i]);
wd[ld] <<= 1;
wd[ld] |= databits[i];
}
EEPROM.put(305, ld);
EEPROM.put(310, bc);
EEPROM.put(330, wd);
Serial.println();
Serial.print("Read ");
Serial.print(bitCount);
Serial.print(" bits. ");
// we will decode the bits differently depending on how many bits we have
// see www.pagemac.com/azure/data_formats.php for mor info
if (bitCount == 35)
{
// 35 bit HID Corporate 1000 format
// facility code = bits 2 to 14
for (i = 2; i < 14; i++)
{
facilityCode <<= 1;
facilityCode |= databits[i];
}
// card code = bits 15 to 34
for (i = 14; i < 34; i++)
{
cardCode <<= 1;
cardCode |= databits[i];
}
printBits();
}
else if (bitCount == 37)
{
// HID 37 bit format H10304
// facility code = bits 2 to 17
for (i = 1; i < 17; i++)
{
facilityCode <<= 1;
facilityCode |= databits[i];
}
// card code = bits 18 to 36
for (i = 17; i < 36; i++)
{
cardCode <<= 1;
cardCode |= databits[i];
}
printBits();
}
else if (bitCount == 34)
{
// HID 34 bit format N1002
// facility code = bits 2 to 17
for (i = 1; i < 17; i++)
{
facilityCode <<= 1;
facilityCode |= databits[i];
}
// card code = bits 18 to 33
for (i = 17; i < 33; i++)
{
cardCode <<= 1;
cardCode |= databits[i];
}
printBits();
}
else if (bitCount == 26)
{
// standard 26 bit format H10301
// facility code = bits 2 to 9
for (i = 1; i < 9; i++)
{
facilityCode <<= 1;
facilityCode |= databits[i];
}
// card code = bits 10 to 25
for (i = 9; i < 25; i++)
{
cardCode <<= 1;
cardCode |= databits[i];
}
printBits();
}
else if (bitCount == 11)
{
// older Magstripe 11 bit format
// facility code = bits 6 to 9
for (i = 5; i < 9; i++)
{
facilityCode <<= 1;
facilityCode |= databits[i];
}
// card code = bits 1 to 5
for (i = 0; i < 5; i++)
{
cardCode <<= 1;
cardCode |= databits[i];
}
printBits();
}
else {
// you can add other formats if you want!
Serial.println("Unable to decode.");
}
EEPROM.get(10, ship);
IPAddress sh(ship[0], ship[1], ship[2], ship[3]);
EEPROM.get(20, scene);
String tempstr = "{\r\n\"value\":\"";
String PostData = "{\r\n\"value\":\"1\",\"invokeScenes\":true\r\n}"; //JSON data to send
tempstr = tempstr + cardCode;
PostData = tempstr + "\",\"invokeScenes\":true\r\n}";
if (client.connect(sh, 80)) {
client.print("GET /api/sceneControl?id=");
client.print(scene[cardCode]);
client.println("&action=start HTTP/1.1");
auth(sh);
Serial.print("Scene ");
Serial.print(scene[cardCode]);
Serial.println(" treggered");
/* }
if (Ethernet.begin(mac) == 0) {
Serial.println(F("Failed to configure Ethernet using DHCP"));
delay(3000);
Ethernet.begin(mac, ip);
if (Ethernet.localIP() != ip)
{
Serial.println(F("Failed to configure Ethernet using static IP"));
for (;;)
;
}
}
if (!client.connected())client.stop();
delay(1);
if (client.connect(sh, 80)) {*/
client.println("PUT /api/globalVariables/UID HTTP/1.1");
auth(sh);
Serial.print(cardCode);
Serial.println(" registered");
}
//if (!client.connected())client.stop();
while (client.available()) {
char c = client.read();
Serial.print(c);
}
// if the server's disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
// do nothing forevermore:
//while (true);
}
// cleanup and get ready for the next card
bitCount = 0;
facilityCode = 0;
cardCode = 0;
for (i = 0; i < MAX_BITS; i++)
{
databits[i] = 0;
}
delay(10);
net();
delay(10);
server.begin();
}
// Create a client connection
EthernetClient nclient = server.available();
if (nclient) {
Serial.println(F("new client"));
while (nclient.connected()) {
if (nclient.available()) {
/* char c = client.read();
Serial.write(c);
//read char by char HTTP request
if (readString1.length() < 100) {
//store characters to string
readString1 += c;
}*/
readString1 = nclient.readStringUntil('\n');
Serial.println(readString1);
//if HTTP request has ended– 0x0D is Carriage Return \n ASCII
// if (c == 0x0D) {
nclient.println("HTTP/1.1 200 OK"); //send new page
nclient.println("Content-Type: text/html");
nclient.println();
nclient.println(F("<HTML>"));
nclient.println(F("<HEAD>"));
nclient.println(F("<TITLE> Wegand to Home Center Configurator</TITLE>"));
nclient.println(F("</HEAD>"));
nclient.println(F("<BODY style=\"background-color:#F0F0FF; text-align: center;\">"));
nclient.println(F("<br>"));
nclient.println(F("<H1 style=\"color:LimeGreen;\">Wegand<span style=\"color:Teal;\">2</span><span style=\"color:Blue;\">HC</span></H1>"));
// client.println(F("<hr>"));
nclient.println(F("<br>"));
//nclient.println(F("<a style=\"color:SteelBlue;background-color:White;padding: 5px;\" href=\"/?TEST\"\">TEST</a><br /><br />"));
nclient.println(F("<form id=\"txt_form\" name=\"frmText\">"));
nclient.println(F("<H2 style=\"color:Crimson;\"><b>Configurator</b></H2>"));
nclient.println(F("<label style=\"color:DodgerBlue;\" for=\"code\">code : <input type=\"password\" id=\"code\" size=\"4\" maxlength=\"4\" value=\"0000\" /></label><br /><br />"));
nclient.println(F("<label style=\"color:DodgerBlue;\" for=\"hcip\">Home Center IP : <input type=\"text\" id=\"hcip\" size=\"15\" minlength=\"15\" maxlength=\"15\" value=\""));
if (ship[0] < 10)
{
nclient.print("00");
}
else if (ship[0] < 100)
{
nclient.print("0");
}
nclient.print(ship[0]);
nclient.print(F("."));
if (ship[1] < 10)
{
nclient.print("00");
}
else if (ship[1] < 100)
{
nclient.print("0");
}
nclient.print(ship[1]);
nclient.print(F("."));
if (ship[2] < 10)
{
nclient.print("00");
}
else if (ship[2] < 100)
{
nclient.print("0");
}
nclient.print(ship[2]);
nclient.print(F("."));
if (ship[3] < 10)
{
nclient.print("00");
}
else if (ship[3] < 100)
{
nclient.print("0");
}
nclient.print(ship[3]);
nclient.println(F("\" required></label><br /><br />"));
nclient.println(F("<label style=\"color:DodgerBlue;\" for=\"sip\">Web Server IP : <input type=\"text\" id=\"sip\" size=\"15\" minlength=\"15\" maxlength=\"15\" value=\""));
if (wsip[0] < 10)
{
nclient.print("00");
}
else if (wsip[0] < 100)
{
nclient.print("0");
}
nclient.print(wsip[0]);
nclient.print(F("."));
if (wsip[1] < 10)
{
nclient.print("00");
}
else if (wsip[1] < 100)
{
nclient.print("0");
}
nclient.print(wsip[1]);
nclient.print(F("."));
if (wsip[2] < 10)
{
nclient.print("00");
}
else if (wsip[2] < 100)
{
nclient.print("0");
}
nclient.print(wsip[2]);
nclient.print(F("."));
if (wsip[3] < 10)
{
nclient.print("00");
}
else if (wsip[3] < 100)
{
nclient.print("0");
}
nclient.print(wsip[3]);
nclient.println(F("\" readonly></label><br /><br />"));
nclient.println(F("<label style=\"color:DodgerBlue;\" for=\"uid\">User ID : <input type=\"text\" id=\"uid\" size=\"2\" maxlength=\"2\" autocomplete=\"on\" value=\"00\" /></label><br /><br />"));
nclient.println(F("<label style=\"color:DodgerBlue;\" for=\"sid\">Scene ID : <input type=\"text\" id=\"sid\" size=\"4\" maxlength=\"4\" autocomplete=\"on\" value=\"0000\" /></label><br /><br />"));
nclient.println(F("<a style=\"color:SteelBlue;background-color:White;padding: 5px;\" href=\"\" onclick=\"this.href='/?'+document.getElementById('code').value+document.getElementById('uid').value+document.getElementById('sid').value+document.getElementById('hcip').value+document.getElementById('sip').value\" >EDIT</a>"));
nclient.println(F("</form>"));
nclient.println(F("</BODY>"));
nclient.println(F("</HTML>"));
delay(10);
//stopping client
nclient.stop();
Serial.println(F("client disconnected"));
if (readString1.indexOf("?1729") == 5 && readString1.indexOf("HTTP/1.1") == 47) //checks code
{
Serial.println(F("pwd match"));
// readString1.toCharArray(url, 25);
Serial.println(readString1);
byte ad = readString1.substring(10, 12).toInt();
Serial.println(ad);
if (ad > 0 && ad < 100) {
scene[ad] = readString1.substring(12, 16).toInt();
Serial.println(scene[ad]);
}
else
Serial.println(F("invalid UID"));
byte p = 16;
for (byte i = 0; i < 4; i++) {
ship[i] = readString1.substring(p, p + 3).toInt();
p = p + 4;
}
p--;
for (byte i = 0; i < 4; i++) {
wsip[i] = readString1.substring(p, p + 3).toInt();
p = p + 4;
}
EEPROM.put(10, ship);
EEPROM.put(15, wsip);
EEPROM.put(20, scene);
delay(1500);
EEPROM.get(10, ship);
EEPROM.get(15, wsip);
EEPROM.get(20, scene);
//digitalWrite(5, HIGH);
//delay(1500);
//digitalWrite(5, LOW);
Serial.println(F("Edited"));
}
//clearing string for next read
readString1 = "";
// }
}
}
}
switch (Ethernet.maintain())
{
case 1:
//renewed fail
Serial.println(F("Error: renewed fail"));
break;
case 2:
//renewed success
Serial.println(F("Renewed success"));
//print your local IP address:
Serial.print(F("server is at "));
Serial.println(Ethernet.localIP());
break;
case 3:
//rebind fail
Serial.println(F("Error: rebind fail"));
break;
case 4:
//rebind success
Serial.println(F("Rebind success"));
//print your local IP address:
Serial.print(F("server is at "));
Serial.println(Ethernet.localIP());
break;
default:
//nothing happened
break;
}
}
void printBits()
{
// I really hope you can figure out what this function does
Serial.println();
Serial.print("FC = ");
Serial.print(facilityCode);
Serial.print(", CC = ");
Serial.println(cardCode);
}
void net()
{
if (Ethernet.begin(mac) == 0) {
Serial.println(F("Failed to configure Ethernet using DHCP"));
// if (Ethernet.hardwareStatus() == EthernetNoHardware) {
// Serial.println(F("Ethernet shield was not found. Sorry, can't run without hardware. :("));
// } else if (Ethernet.linkStatus() == LinkOFF) {
// Serial.println(F("Ethernet cable is not connected."));
// } else {
// Serial.println(F("No idea why"));
// }
delay(3000);
Ethernet.begin(mac, ip);
if (Ethernet.localIP() != ip)
{
Serial.println(F("Failed to configure Ethernet using static IP"));
for (;;)
;
}
}
Serial.print(F("server is at "));
Serial.println(Ethernet.localIP());
ip = Ethernet.localIP();
for (byte i = 0; i < 4; i++) {
wsip[i] = ip[i];
}
EEPROM.put(15, wsip);
}
void auth(IPAddress sh)
{
Serial.println(sh);
client.print("Host: ");
client.println(sh);
client.println("Authorization: Basic YmVuc2U6Qmlnc"); //need to insert base 64 user:password
client.print("Content-Length: ");
client.println(PostData.length());
client.println();
client.println(PostData);
}

Arduino Ethernet Client Server communication problem

This is my code:
#include <Keypad.h>
#include <LiquidCrystal.h>
#include <Ethernet.h>
#include <SPI.h>
bool hands = false;
bool result = true;
char Key;
unsigned int Number=0;
String weight;
String path;
bool alreadyConnected = false; // whether or not the client was connected previously
int cnt=0;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
byte ip[] = { 192, 168, 1, 2 }; // ip in lan
byte gateway[] = { 192, 168, 1, 1 }; // internet access via router
byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
LiquidCrystal lcd(35, 34, 33, 32, 31, 30);
EthernetServer server(9639); //server port
EthernetClient client;
char keys[4][4] = {
{'1', '2', '3','A'},
{'4', '5', '6','B'},
{'7', '8', '9','C'},
{'*', '0', '#','D'},
};
byte rowpins[4] = {22, 23, 24, 25};
byte colpins[4] = {26, 27, 28, 29};
Keypad mykeypad = Keypad(makeKeymap(keys), rowpins, colpins, 4, 4);
String readString;
void setup()
{
lcd.begin(20, 4);
Ethernet.begin(mac, ip, gateway, subnet);
if (Ethernet.linkStatus() == LinkOFF) {
lcd.setCursor(0, 0);
lcd.print(" :Error: ");
lcd.setCursor(0, 1);
lcd.print("Ethernet Cable");
lcd.setCursor(0, 2);
lcd.print("Not Connected!");
Serial.println("Ethernet cable is not connected.");
while(true);
}
Serial.begin(19200);
Serial1.begin(19200);
EthernetClient client = server.available();
lcd.setCursor(0, 1);
lcd.print(" Connecting... ");
delay(5000);
if (client.connect(gateway, 9639))
{
client.print("A");
Serial.println("Connecting MilkyWeigh Server...");
}
else
{ lcd.clear();
lcd.setCursor(0, 1);
lcd.print("1.Check LAN Cable");
lcd.setCursor(0, 2);
lcd.print(" --Reset MilkoSol-- ");
while (true);
}
server.begin();
while (true) {
client = server.available(); // wait for a new client:
if (client)
{
while (client.connected())
{
if (client.available())
{
char b = client.read();
if (b == 'B')
{
lcd.setCursor(0, 2);
lcd.print(" Connected! ");
Serial.println("Successfully Connected!");
delay(1500);
hands = true;
b = "";
} //if B comes, handshaking done
} // if client available
} //while client connected
} //if (client)
if (hands == true)
{
lcd.clear();
client.stop();
break;
}
} //while true
lcd.setCursor(0, 0);
lcd.print ("Input Code: ");
lcd.print (Number);
} // void setup
void loop()
{
while (Key == NO_KEY){
Key = mykeypad.getKey();
}
DetectButtons();
if (Key == '4')
{
SaveToServer();
delay(200);
SaveToServer();
}
if (Key == '#')
{
if (Number > 0)
{
GetName();
}
Getweight();
}
Key=NO_KEY;
}
void Getweight(){
while (Serial1.available()>0)
{
weight = Serial1.readStringUntil('\r');
Serial1.flush();
}
Serial.print(weight);
}
void SaveToServer()
{
if (client.connect(gateway, 9639))
{
client.print('#'+String(Number)+','+weight);
//client.stop();
}
else
{ lcd.clear();
lcd.setCursor(0, 2);
lcd.print(" Save Error ");
Serial.println("Try again!");
Number=0;
readString="";
// weight="";
alreadyConnected=false;
return 0;
}
server.begin();
EthernetClient client = server.available(); // Listening for client (i.e. server) response
if (client)
{
if (!alreadyConnected)
{
// clear out the input buffer:
client.flush();
alreadyConnected = true;
}
while (client.connected())
{
if (client.available())
{
if (client.available()>0)
{
char z = client.read();
if (z == 'K')
{
Serial.print("Success: Data Saved!");
lcd.clear();
lcd.setCursor(6, 2);
lcd.print("Success!");
delay(1500);
Number=0;
weight="";
readString="";
DisplayResult();
}
client.flush();
client.stop();
}
}
}
} // if client
}// SaveToServer
void GetName()
{
if (client.connect(gateway, 9639))
{
client.print(Number);
//client.stop();
}
else
{ lcd.clear();
lcd.setCursor(0, 2);
lcd.print(" Connection Failed! ");
Serial.println("Connection Failed!");
Number=0;
readString="";
// weight="";
alreadyConnected=false;
return 0;
}
server.begin();
EthernetClient client = server.available(); // Listening for client (i.e. server) response
if (client)
{
if (!alreadyConnected)
{
// clear out the input buffer:
client.flush();
alreadyConnected = true;
}
while (client.connected())
{
if (client.available())
{
readString="";
while (client.available()>0)
{
//client.readStringUntil('?');
readString = client.readStringUntil('?');
client.flush();
client.stop();
}
}
}
if (readString == "err")
{
lcd.clear();
lcd.setCursor(0, 2);
lcd.print("Not found,Try again!");
Serial.println("Not found,Try again!");
delay(1500);
Number=0;
readString="";
hands = true;
DisplayResult();
}
else
{
lcd.clear();
DisplayResult();
Serial.println(readString);
hands = true;
}
} // if client
}// GetName
void DetectButtons()
{
// path = path + "DetectButtons";
//Serial.println(path);
if (Key == '*') //If cancel Button is pressed
{
Serial.println ("Button Cancel");
Number = 0;
weight = "";
readString="";
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Input Code: ");
lcd.setCursor(0, 1);
lcd.print(" ");
lcd.setCursor(0, 2);
lcd.print(" ");
lcd.setCursor(0, 3);
lcd.print(" ");
}
if (Key == '1') //If Button 1 is pressed
{ Serial.println ("Button 1");
if (Number == 0)
Number = 1;
else
Number = (Number * 10) + 1; //Pressed twice
}
/*
if (Key == '4') //If Button 4 is pressed
{ Serial.println ("Button 4");
if (Number == 0)
Number = 4;
else
Number = (Number * 10) + 4; //Pressed twice
}
*/
if (Key == '7') //If Button 7 is pressed
{ Serial.println ("Button 7");
if (Number == 0)
Number = 7;
else
Number = (Number * 10) + 7; //Pressed twice
}
if (Key == '0')
{ Serial.println ("Button 0"); //Button 0 is Pressed
if (Number == 0)
Number = 0;
else
Number = (Number * 10) + 0; //Pressed twice
}
if (Key == '2') //Button 2 is Pressed
{ Serial.println ("Button 2");
if (Number == 0)
Number = 2;
else
Number = (Number * 10) + 2; //Pressed twice
}
if (Key == '5')
{ Serial.println ("Button 5");
if (Number == 0)
Number = 5;
else
Number = (Number * 10) + 5; //Pressed twice
}
if (Key == '8')
{ Serial.println ("Button 8");
if (Number == 0)
Number = 8;
else
Number = (Number * 10) + 8; //Pressed twice
}
if (Key == '3')
{ Serial.println ("Button 3");
if (Number == 0)
Number = 3;
else
Number = (Number * 10) + 3; //Pressed twice
}
if (Key == '6')
{ Serial.println ("Button 6");
if (Number == 0)
Number = 6;
else
Number = (Number * 10) + 6; //Pressed twice
}
if (Key == '9')
{ Serial.println ("Button 9");
if (Number == 0)
Number = 9;
else
Number = (Number * 10) + 9; //Pressed twice
}
DisplayResult();
} // end of detect buttons function
void DisplayResult()
{
lcd.clear();
lcd.setCursor(0, 0);
lcd.print ("Input Code: ");
lcd.print (Number);
lcd.setCursor(0, 1);
lcd.print (readString);
lcd.setCursor(0, 2);
lcd.print ("Weight :");
lcd.print (weight);
lcd.setCursor(0, 3);
lcd.print ("*=Cncl,#=Wght,A=Save");
}
The problem is when '#' key is pressed first time with input_code =111, client.read somehow miss or skip the response (name) from server and shows blank. But when i press '#' key second time with input_code = 222, it shows previous response (name) from server.
The EthernetClient can be used to connect to remote server as in WebClient example or it is used by the EthernetServer as a peer for remote client as in ChatServer example.
If you use both, use different names. Now your client 'client' is global and clients returned from server are local but with the same name. And you can make the global client variable local too.
The variable alreadyConnected is used with local client and with server's client.
You don't stop the local client.
You have redundant while/if (client.available()) to test the request (server's client).
Why while (client.available() > 0) around readStringUntil('?')?
EthernetServer should by started with begin only once in setup().

Resources