Files
tracktime_beacon/main/Ethernet.cpp
Michal Courson b1e155d08b initial
2025-08-28 21:39:35 -04:00

115 lines
3.2 KiB
C++

#include "Ethernet.hpp"
#include "ETH.h"
#include "SPI.h"
#define ETH_PHY_TYPE ETH_PHY_W5500
#define ETH_PHY_ADDR 1
#define ETH_PHY_CS 8
#define ETH_PHY_IRQ 3
#define ETH_PHY_RST 5
#define ETH_SPI_SCK 11
#define ETH_SPI_MISO 10
#define ETH_SPI_MOSI 9
static bool eth_connected = false;
EthernetHandler eth;
void onEvent(arduino_event_id_t event, arduino_event_info_t info) {
switch (event) {
case ARDUINO_EVENT_ETH_START:
Serial.println("ETH Started");
// set eth hostname here
ETH.setHostname("esp32-eth0");
break;
case ARDUINO_EVENT_ETH_CONNECTED:
Serial.println("ETH Connected");
break;
case ARDUINO_EVENT_ETH_GOT_IP:
Serial.printf("ETH Got IP: '%s'\n", esp_netif_get_desc(info.got_ip.esp_netif));
Serial.println(ETH);
#if USE_TWO_ETH_PORTS
Serial.println(ETH1);
#endif
eth_connected = true;
break;
case ARDUINO_EVENT_ETH_LOST_IP:
Serial.println("ETH Lost IP");
eth_connected = false;
break;
case ARDUINO_EVENT_ETH_DISCONNECTED:
Serial.println("ETH Disconnected");
eth_connected = false;
break;
case ARDUINO_EVENT_ETH_STOP:
Serial.println("ETH Stopped");
eth_connected = false;
break;
default:
break;
}
}
void EthernetHandler::init() {
// Initialization code here
Network.onEvent(onEvent);
SPI.begin(ETH_SPI_SCK, ETH_SPI_MISO, ETH_SPI_MOSI);
ETH.begin(ETH_PHY_TYPE, ETH_PHY_ADDR, ETH_PHY_CS, ETH_PHY_IRQ, ETH_PHY_RST, SPI);
}
void EthernetHandler::begin() {
// Code to start Ethernet communication
}
void EthernetHandler::end() {
// Code to end Ethernet communication
}
String EthernetHandler::post(const String& url, const String& payload) {
if (!eth_connected) {
Serial.println("Ethernet not connected. Cannot perform POST request.");
return "";
}
HTTPClient http;
http.begin(url);
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST(payload);
String response;
if (httpResponseCode > 0) {
response = http.getString();
Serial.printf("POST Response code: %d\n", httpResponseCode);
Serial.println("Response: " + response);
} else {
Serial.printf("Error on sending POST: %s\n", http.errorToString(httpResponseCode).c_str());
}
http.end();
return response;
}
String EthernetHandler::get(const String& url) {
if (!eth_connected) {
Serial.println("Ethernet not connected. Cannot perform GET request.");
return "";
}
HTTPClient http;
http.begin(url);
int httpResponseCode = http.GET();
String response;
if (httpResponseCode > 0) {
response = http.getString();
Serial.printf("GET Response code: %d\n", httpResponseCode);
Serial.println("Response: " + response);
} else {
Serial.printf("Error on sending GET: %s\n", http.errorToString(httpResponseCode).c_str());
}
http.end();
return response;
}