a saperlo prima evitavo traduttore!!Grazie, ora so anche che sei italiano come me. Proveró con un semplice sketch.
//#include <WiFi.h> // For ESP32
#include <ESP8266WiFi.h> // For ESP8266
const char* ssid = "your-ssid";
const char* pass = "your-pass";
const int SERVER_PORT = 11342;
WiFiServer server (SERVER_PORT);
void setup() {
Serial.begin (115200);
delay (2000);
// We start by connecting to a WiFi network
Serial.printf ("\n\nConnecting to %s\n", ssid);
WiFi.begin (ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay (500);
Serial.print (".");
}
Serial.println ("");
Serial.println ("WiFi connected.");
Serial.println ("IP address: ");
Serial.println (WiFi.localIP());
server.begin();
}
void loop() {
WiFiClient client = server.available(); // Listen for incoming clients
if (client) { // If you get a client
Serial.println ("Client connected"); // Print a message out the serial port
while (client.connected()) { // Loop while the client connected
yield(); // Required for ESP8266
}
Serial.println ("Client disconnected"); // Else client disconnected
}
}
Sub Class_Globals
Private Root As B4XView
Private xui As XUI
Private AST As AsyncStreams
Private Client As Socket
Private Connected As Boolean = False
' Private RemoteIP As String = "79.52.141.40" ' Public IP Address
Private RemoteIP As String = "192.168.178.36" ' Local IP Address
Private RemotePort As Int = 11342
Private btnConnect As Button
Private btnDisconnect As Button
End Sub
Public Sub Initialize
' B4XPages.GetManager.LogEvents = True
End Sub
'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
Root = Root1
Root.LoadLayout("MainPage")
End Sub
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
Private Sub btnConnect_Click
ConnectToServer(RemoteIP, RemotePort)
End Sub
Sub btnDisconnect_Click
CloseExistingConnection
End Sub
'''''''''''''''''''''''''''''''''''
Sub AST_Error
Connected = False
mLog("AST Error")
AST_Terminated
End Sub
Sub AST_Terminated
Connected = False
mLog("AST Terminated")
btnConnect.Enabled = True
btnDisconnect.Enabled = False
End Sub
Sub AST_NewData (Buffer() As Byte)
Dim s As String = BytesToString(Buffer, 0, Buffer.Length, "UTF-8")
Log("Received " & Buffer.Length & " Bytes: " & s)
End Sub
''''''''''''''''''''''''''''''''''
Sub CloseExistingConnection
If AST.IsInitialized Then AST.Close
If Client.IsInitialized Then Client.Close
Connected = False
Log("IP - Connection Closed")
btnConnect.Enabled = True
btnDisconnect.Enabled = False
End Sub
Private Sub ConnectToServer(Host As String, Port As Int)
If Connected = False Then
Log("Trying to connect to: " & Host & ":" & Port)
CloseExistingConnection
Dim Client As Socket
Client.Initialize("Client")
Client.Connect(Host, Port, 10000)
Wait For Client_Connected (Successful As Boolean)
If Successful Then
Connected = True
AST.Initialize(Client.InputStream, Client.OutputStream, "AST")
Log("IP - Successful Connect")
ToastMessageShow("IP - Successful Connect", True)
btnConnect.Enabled = False
btnDisconnect.Enabled = True
Else
Log("IP - Failed to connect: " & LastException)
ToastMessageShow("IP - Failed to connect: " & LastException, True)
End If
End If
End Sub
Sub mLog (s As String)
Log(s)
ToastMessageShow(s, True)
End Sub
void GetSocketNewConnections() {
// LogMessage ("GetSocketNewConnections", true, false);
uint8_t i;
// Find free/disconnected spot
for (i = 0; i < MAX_SRV_CLIENTS; i++) {
// if (i == 0) LogMessage (" ", true, false);
// LogMessage ("GET CLIENT " + String (i) + " -> " + String (serverClients[i].connected()), true, false);
if (serverClients[i].connected()) {
// LogMessage ("CLIENT CONNECTED " + String (i) + " -> " + String (mSocketConnected[i]), true, false);
if (!mSocketConnected[i] == true) {
Beep (BEEP_FREQ_1, 80);
mSocketConnected[i] = true;
LogMessage ("\nClient [" + String (i + 1) + "] Connected", true, false);
// ShowMessageOnLCD (" [" + String (i + 1) + "] Connected");
ShowMessageOnLCD (" [" + String (i + 1) + "] Connected", 1000);
// Azzera in caso di riconnessione
FileIsOpenForWrite = false;
WaitingInfos = false;
// Set socket parameters
serverClients[i].setNoDelay (true);
// Set and Get socket parameters
#if defined(ESP8266)
serverClients[i].setSync (true); // VEDERE LA CONTROPARTE PER ESP32
serverClients[i].setTimeout (120000);
bool nodelay = serverClients[i].getNoDelay();
Serial.printf ("TCP NODELAY: %s\n", nodelay ? "True" : "False");
bool issync = serverClients[i].getSync();
Serial.printf ("TCP SYNC: %s\n", issync ? "True" : "False");
bool keepalive = serverClients[i].isKeepAliveEnabled();
Serial.printf ("TCP_KEEPALIVE: %s\n", keepalive ? "True" : "False");
uint16_t keepaliveidle = serverClients[i].getKeepAliveIdle();
Serial.printf ("TCP KEEPALIVE IDLE: %d\n", keepaliveidle);
uint16_t keepaliveinterval = serverClients[i].getKeepAliveInterval();
Serial.printf ("TCP KEEPALIVE INTERVAL: %d\n", keepaliveinterval);
uint8_t keepalivecount = serverClients[i].getKeepAliveCount();
Serial.printf ("TCP KEEPALIVE COUNT: %d\n", keepalivecount);
#elif defined(ESP32)
serverClients[i].setTimeout (120); // Seconds on ESP32
int flag1 = 0;
serverClients[i].getOption (0x01, &flag1);
bool nodelay = flag1;
Serial.printf ("TCP NODELAY: %s\n", nodelay ? "True" : "False");
int keepalive = 0;
serverClients[i].getOption (0x01, &keepalive);
Serial.printf ("TCP KEEPALIVE: %d\n", keepalive);
#endif
////////////
// No free/disconnected spot so reject
// TEORICAMENTE LA SEGUENTE CONDIZIONE NON SI DOVREBBE MAI VERIFICARE PERCHÈ i NON PUÒ MAI ESSERE UGUALE A MAX_SRV_CLIENTS
// Hints: server.available() is a WiFiClient with short-term scope when out of scope, a WiFiClient will
// - flush() - all data will be sent
// - stop() - automatically too
if (i == MAX_SRV_CLIENTS) {
server.available().println ("Server is busy [Max clients reached]");
LogMessage ("Server is busy with " + String (MAX_SRV_CLIENTS) + " active connections\n", true, true);
Beep (1200, 100);
Beep (1400, 100);
Beep (1200, 100);
Beep (1400, 200);
ShowMessageOnLCD ("SERVER BUSY");
}
}
} else {
if (mSocketConnected[i] == true) {
Beep (BEEP_FREQ_1, 50);
mSocketConnected[i] = false;
LogMessage ("\nClient [" + String (i + 1) + "] Disconnected", true, false);
// ShowMessageOnLCD (" [" + String (i + 1) + "] Disconnected");
ShowMessageOnLCD (" [" + String (i + 1) + "] Disconnected", 1000);
// Azzera in caso di riconnessione
FileIsOpenForWrite = false;
WaitingInfos = false;
}
serverClients[i] = server.available();
}
}
}
Sub Class_Globals
Private Root As B4XView
Private xui As XUI
Private AST As AsyncStreams
Private Client As Socket
Private Connected As Boolean = False
' Private RemoteIP As String = "79.52.141.40" ' Public IP Address
Private RemoteIP As String = "192.168.178.66" ' Local IP Address
Private RemotePort As Int = 11342
Private btnConnect As Button
Private btnDisconnect As Button
Dim Timer1 As Timer
Dim t1 As Long
End Sub
Public Sub Initialize
' B4XPages.GetManager.LogEvents = True
End Sub
'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
Root = Root1
Root.LoadLayout("MainPage")
Timer1.Initialize("Timer1", 1000)
End Sub
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.
Private Sub btnConnect_Click
ConnectToServer(RemoteIP, RemotePort)
End Sub
Sub btnDisconnect_Click
CloseExistingConnection
End Sub
'''''''''''''''''''''''''''''''''''
Sub AST_Error
Connected = False
mLog("AST Error", True)
AST_Terminated
End Sub
Sub AST_Terminated
Connected = False
mLog("AST Terminated", True)
btnConnect.Enabled = True
btnDisconnect.Enabled = False
End Sub
Sub AST_NewData (Buffer() As Byte)
Dim s As String = BytesToString(Buffer, 0, Buffer.Length, "UTF-8")
Log("Received " & Buffer.Length & " Bytes: " & s)
If s = "ALIVE" Then t1 = DateTime.Now
End Sub
''''''''''''''''''''''''''''''''''
Sub CloseExistingConnection
If AST.IsInitialized Then AST.Close
If Client.IsInitialized Then Client.Close
Connected = False
Log("IP - Connection Closed")
btnConnect.Enabled = True
btnDisconnect.Enabled = False
End Sub
Private Sub ConnectToServer(Host As String, Port As Int)
If Connected = False Then
CloseExistingConnection
mLog("Trying to connect to: " & Host & ":" & Port, True)
Client.Initialize("Client")
Client.Connect(Host, Port, 10000)
Wait For Client_Connected (Successful As Boolean)
If Successful Then
AST.Initialize(Client.InputStream, Client.OutputStream, "AST")
ServerConnected(True)
Else
ServerConnected(False)
End If
End If
End Sub
Sub Timer1_Tick
' Log("TIMER TICK")
Dim t2 As Long = DateTime.now - t1
Log("T2: " & t2)
If Connected And t2 > 2000 Then ServerConnected(False)
End Sub
Sub ServerConnected(b As Boolean)
If b Then
mLog ("SERVER CONNECTED", False)
Connected = True
btnConnect.Enabled = False
btnDisconnect.Enabled = True
Timer1.Enabled = True
Else
mLog ("SERVER DISCONNECTED OR FAILED TO CONNECT: " & LastException.Message, True)
Connected = False
btnConnect.Enabled = True
btnDisconnect.Enabled = False
Timer1.Enabled = False
End If
End Sub
Sub mLog (s As String, b As Boolean)
Log(s)
ToastMessageShow(s, b)
End Sub
#include <WiFi.h> // For ESP32
//#include <ESP8266WiFi.h> // For ESP8266
const char* ssid = "your ssid";
const char* pass = "your pass";
const int SERVER_PORT = 11342;
WiFiServer server (SERVER_PORT);
void setup() {
Serial.begin (115200);
delay (2000);
// We start by connecting to a WiFi network
Serial.printf ("\n\nConnecting to %s\n", ssid);
WiFi.begin (ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay (500);
Serial.print (".");
}
Serial.println ("");
Serial.println ("WiFi connected.");
Serial.println ("IP address: ");
Serial.println (WiFi.localIP());
server.begin();
}
void loop() {
WiFiClient client = server.available(); // Listen for incoming clients
if (client) { // If you get a client,
Serial.println ("Client connected"); // Print a message out the serial port
while (client.connected()) { // Loop while the client connected
if(millis() % 1000 == 0) client.print("ALIVE");
yield(); // Required for ESP8266
}
Serial.println ("Client disconnected"); // Else client disconnected
}
}
I'm sorry that you have not found a solution,Please do you have some suggestions to impove it or make the code more clear ?
Do not matter, the C++ code is simple as you see.... to do it with B4R. Is just a simple TCP server that listen on, and send ALIVE every second.I'm sorry that you have not found a solution,
the tests that I was able to do in my knowledge I have done.
here there are 2 problems:
the return of the error when disconnecting the esp...
and the other significant problem is that the esp code is in c++,
here i really don't have knowledge of this language.
However I will do some testing of the code you posted.
but peoples do not help, may they are to the sea
By sea I meant holidays, I got the wrong word... I'm sorry....Non proprio "to the sea", io sono in montagna
I connect ESP32 with WiFi TCP Socket.Do you connect phone with ESP32 with wifi or with USB cable ?
void loop() {
WiFiClient client = server.available(); // Listen for incoming clients
if (client) { // If you get a client
Serial.println ("Client connected"); // Print a message out the serial port
while (client.connected()) { // Loop while the client connected
yield(); // Required for ESP8266
delay (2000);
client.write("Here all OK");// >>>> Send to Android
}
Serial.println ("Client disconnected"); // Else client disconnected
}
}
Because do you set 2 seconds ? This works for me with just one second. See my last code. The problem is that I cannot make it smaller time because B4A get false disconnections.only method I was able to do is to send a string every 2 seconds or more to android
in android AST_NewData (Buffer() As Byte) you should check this string,
since the esp disconnects android doesn't receive it anymore.
this is little but I don't know more
B4X:void loop() { WiFiClient client = server.available(); // Listen for incoming clients if (client) { // If you get a client Serial.println ("Client connected"); // Print a message out the serial port while (client.connected()) { // Loop while the client connected yield(); // Required for ESP8266 delay (2000); client.write("Here all OK");// >>>> Send to Android } Serial.println ("Client disconnected"); // Else client disconnected } }
Great, I will try it now to emulate ESP32 by code and post here to you.Ok, I can help you, but as I wrote I don't have an ESP32 board (but I have 2 phone), so ........
Make a little project in B4A that emulate ESP32 server so I can install it in phone server.
Then, another project for client phone
Client send message to server and server answer.
Then, I poweroff phone server (ok, don't need poweroff, I switch off wifi connection) and so I can test what happen on client phone
Warning: heartbeat system is that client send a "beat" to server and server answer, not as you wrote !!
Mmmmm chatGPT and Google Bard says that server send alive message to a client and client check if the message continue to arrive, if not it is disconnected.Warning: heartbeat system is that client send a "beat" to server and server answer, not as you wrote !!
Because in both cases, the TCP connections were cleaned up properly, with the client app/Android properly closing the connections. Try shutting down your device or disabling Wi-Fi/whatever network the phone is connected to on the device itself and see if the ESP notices the disconnect.If I connect my app (client) to ESP32 (server), when I disconnect or just close the app, ESP32 know a disconnection without problems.
No, because the "server" is just shut down, without really closing the connection (turning power off = no more program running to notify anyone of the shutdown). So yes, powering off the ESP32 will not notify the client of the shutdown (how?).This do not happen on client side, if I switch off ESP32 while client is connected, my app do not know that server goes offline.
Actually, the correct answer was already given to you in post #2. Implementing the keep-alive/heartbeat, if you encountered any issues, should then have been handled with another question.but peoples do not help, may they are to the sea
May it just get the disconnection if server side disconnect the client by software ?
Is different if I just switch off server side (ESP32) ?
I know it from start, Erel's answer was good to me, but I asked if it is possible to do it other ways:Actually, the correct answer was already given to you in post #2
but this seem to be an issue in certain cases so 'heartbeat' always should work, if you disconnect, if no network signal occour, if router switch off and so....I need to use a timer to continue ping the server to know it ? I want avoid to do this, there are other solutions ?
We use cookies and similar technologies for the following purposes:
Do you accept cookies and these technologies?
We use cookies and similar technologies for the following purposes:
Do you accept cookies and these technologies?