Test the internet by TCP connecting to Google

This commit is contained in:
Thijs Raymakers 2024-06-20 01:48:08 +02:00
parent e6c28f8ed9
commit 47892039b7
No known key found for this signature in database

View file

@ -1,36 +1,29 @@
#include <Arduino.h> #include <Arduino.h>
#include <ESP8266WiFi.h> #include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#define RELAY 4 // GPIO4 #define RELAY 4 // GPIO4
#define WIFI_NAME "TechInc" #define WIFI_NAME "TechInc"
#define WIFI_PASSWORD "itoldyoualready" #define WIFI_PASSWORD "itoldyoualready"
#define ROOT_DNS_IP "193.0.14.129" #define HTTP_HOST "google.com"
#define HTTP_PORT (80)
const IPAddress root_dns_ip(193, 0, 14, 129);
bool testDNS() {
WiFiUDP udp;
udp.beginPacket(root_dns_ip, 53);
return true;
}
bool testHTTP() { bool testHTTP() {
return true; WiFiClient client;
client.setNoDelay(true);
bool available = client.connect(HTTP_HOST, HTTP_PORT);
client.stop();
return available;
} }
// Returns true if Internet works // Returns true if Internet works
bool uplinkWorks() { bool uplinkWorks() { return testHTTP(); }
return testDNS() || testHTTP();
}
void setup() { void setup() {
WiFi.begin(WIFI_NAME, WIFI_PASSWORD); WiFi.begin(WIFI_NAME, WIFI_PASSWORD);
Serial.begin(9600); Serial.begin(9600);
Serial.print("Connecting to WiFi"); Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) while (WiFi.status() != WL_CONNECTED) {
{
delay(500); delay(500);
Serial.print("."); Serial.print(".");
} }
@ -44,7 +37,7 @@ void setup() {
} }
void loop() { void loop() {
if(uplinkWorks()) { if (uplinkWorks()) {
Serial.println("Network is up"); Serial.println("Network is up");
digitalWrite(LED_BUILTIN, HIGH); digitalWrite(LED_BUILTIN, HIGH);
digitalWrite(RELAY, HIGH); digitalWrite(RELAY, HIGH);
@ -53,5 +46,5 @@ void loop() {
digitalWrite(LED_BUILTIN, LOW); digitalWrite(LED_BUILTIN, LOW);
digitalWrite(RELAY, LOW); digitalWrite(RELAY, LOW);
} }
delay(1000); // TODO: cleaner interval between tests delay(5000); // TODO: cleaner interval between tests
} }