Marijn78

Untitled

Jul 7th, 2020
108
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.     This sketch shows the Ethernet event usage
  3. */
  4.  
  5. #include <ETH.h>
  6.  
  7. static bool eth_connected = false;
  8.  
  9. void WiFiEvent(WiFiEvent_t event)
  10. {
  11.   switch (event) {
  12.     case SYSTEM_EVENT_ETH_START:
  13.       Serial.println("ETH Started");
  14.       //set eth hostname here
  15.       ETH.setHostname("esp32-ethernet");
  16.       break;
  17.     case SYSTEM_EVENT_ETH_CONNECTED:
  18.       Serial.println("ETH Connected");
  19.       break;
  20.     case SYSTEM_EVENT_ETH_GOT_IP:
  21.       Serial.print("ETH MAC: ");
  22.       Serial.print(ETH.macAddress());
  23.       Serial.print(", IPv4: ");
  24.       Serial.print(ETH.localIP());
  25.       if (ETH.fullDuplex()) {
  26.         Serial.print(", FULL_DUPLEX");
  27.       }
  28.       Serial.print(", ");
  29.       Serial.print(ETH.linkSpeed());
  30.       Serial.println("Mbps");
  31.       eth_connected = true;
  32.       break;
  33.     case SYSTEM_EVENT_ETH_DISCONNECTED:
  34.       Serial.println("ETH Disconnected");
  35.       eth_connected = false;
  36.       break;
  37.     case SYSTEM_EVENT_ETH_STOP:
  38.       Serial.println("ETH Stopped");
  39.       eth_connected = false;
  40.       break;
  41.     default:
  42.       break;
  43.   }
  44. }
  45.  
  46. void testClient(const char * host, uint16_t port)
  47. {
  48.   Serial.print("\nconnecting to ");
  49.   Serial.println(host);
  50.  
  51.   WiFiClient client;
  52.   if (!client.connect(host, port)) {
  53.     Serial.println("connection failed");
  54.     return;
  55.   }
  56.   client.printf("GET / HTTP/1.1\r\nHost: %s\r\n\r\n", host);
  57.   while (client.connected() && !client.available());
  58.   while (client.available()) {
  59.     Serial.write(client.read());
  60.   }
  61.  
  62.   Serial.println("closing connection\n");
  63.   client.stop();
  64. }
  65.  
  66. void setup()
  67. {
  68.   Serial.begin(115200);
  69.   WiFi.onEvent(WiFiEvent);
  70.   ETH.begin();
  71. }
  72.  
  73.  
  74. void loop()
  75. {
  76.   if (eth_connected) {
  77.     //testClient("google.com", 80); // 301 Moved Permanently
  78.     //testClient("http://postman-echo.com/get?foo1=bar1&foo2=bar2", 80); //connection failed
  79.     testClient("http://postman-echo.com", 80); //connection failed
  80.     delay(10000);
  81.   }
  82. }
RAW Paste Data