#ifndef UDP_H #define UDP_H extern "C" { #include "mem.h" #include "espconn.h" } typedef void (*UDPCallback)(void* arg, char* data, unsigned short len); #include "../Debug.h" #include "IP.h" class UDP { private: static constexpr const char* NAME = "UDP"; espconn* con; public: UDP() { init(); } /** dtor */ ~UDP() { cleanup(); } /** bind the socket to the given local port */ void bind(const Port localPort) { debugMod1(NAME, "binding to local port %d", localPort); // set the local port to listen on con->proto.udp->local_port = localPort; // todo: check? 0=OK const int res = espconn_create(con); os_printf("create: %d\r\n", res); } bool send(const IP ip, const Port port, const void* data, const uint16_t dataLen) { debugMod1(NAME, "sending packet to remote port %d", port); // set remote port and IP con->proto.udp->remote_port = port; os_memcpy(con->proto.udp->remote_ip, ip.getPtr(), 4); //os_printf("send %d bytes\r\n", dataLen); //os_printf("IP: %d.%d.%d.%d\n\r", con->proto.udp->remote_ip[0], con->proto.udp->remote_ip[1], con->proto.udp->remote_ip[2], con->proto.udp->remote_ip[3]); // send. TODO: check. 0=OK const int res = espconn_sent(con, (unsigned char*)data, dataLen); return (res == 0); } /** set the callback to call whenever a packet is received */ void setRecvCallback(UDPCallback callback) { espconn_regist_recvcb(con, callback); } private: /** initialize the UDP "connection" */ void init() { debugMod(NAME, "init()"); // allocate connection-objects con = (espconn*) os_zalloc(sizeof(espconn)); ets_memset( con, 0, sizeof( espconn ) ); // configure con->type = ESPCONN_UDP; //con->state = ESPCONN_NONE; con->proto.udp = (esp_udp*) os_zalloc(sizeof(esp_udp)); } /** cleanup everything */ void cleanup() { debugMod(NAME, "cleanup()"); espconn_delete(con); os_free(con->proto.udp); os_free(con); } }; #endif // UDP_H