From 2b04572df668e537eb400d95790e69365637ef4e Mon Sep 17 00:00:00 2001 From: Juraj Andrassy Date: Wed, 20 Sep 2023 21:19:35 +0200 Subject: [PATCH] WiFiServer operator bool --- docs/api.md | 57 ++++++++++++++++++++++++++++++++++++++++++++++ src/WiFiServer.cpp | 3 +++ src/WiFiServer.h | 1 + 3 files changed, 61 insertions(+) diff --git a/docs/api.md b/docs/api.md index ff5ac52..8064415 100644 --- a/docs/api.md +++ b/docs/api.md @@ -2764,6 +2764,63 @@ void loop() { ``` +### `if(server)` + +#### Description +Indicates whether the server is listening for new clients. You can use this to detect whether server.begin() was successful. + + +#### Syntax + +``` +if (server) +if (!server) + +``` + +#### Parameters +none + +#### Returns +- whether the server is listening for new clients (bool). + +#### Example + +``` +#include + +char ssid[] = "Network"; // your network SSID (name) +char pass[] = "myPassword"; // your network password + +WiFiServer server(23); + +void setup() { + + Serial.begin(115200); + while (!Serial) {} + + int status = WiFi.begin(ssid, pass); + if ( status != WL_CONNECTED) { + Serial.println("Couldn't get a WiFi connection"); + while(true); + } + + server.begin(); + if (!server) { + Serial.println("Server failed to start."); + while(true); + } +} + +void loop() { + WiFiClient client = server.available(); + if (client) { + String s = client.readStringUntil('\n'); + server.println(s); + } +} +``` + ### `server.status()` #### Description diff --git a/src/WiFiServer.cpp b/src/WiFiServer.cpp index 3756a1c..66a7dbc 100644 --- a/src/WiFiServer.cpp +++ b/src/WiFiServer.cpp @@ -88,6 +88,9 @@ uint8_t WiFiServer::status() { } } +WiFiServer::operator bool() { + return (_sock != NO_SOCKET_AVAIL); +} size_t WiFiServer::write(uint8_t b) { diff --git a/src/WiFiServer.h b/src/WiFiServer.h index b01fa5e..98bda93 100644 --- a/src/WiFiServer.h +++ b/src/WiFiServer.h @@ -42,6 +42,7 @@ class WiFiServer : public Server { virtual size_t write(uint8_t); virtual size_t write(const uint8_t *buf, size_t size); uint8_t status(); + explicit operator bool(); using Print::write; };