Files
ESP8266lib/net/UDP.h
2022-07-17 14:47:21 +02:00

135 lines
2.6 KiB
C++

#ifndef UDP_H
#define UDP_H
extern "C" {
//#include "mem.h"
//#include "espconn.h"
#include "lwip/sockets.h"
#include "lwip/sys.h"
#include "lwip/err.h"
#include "lwip/udp.h"
}
//typedef void (*UDPCallback)(void* arg, char* data, unsigned short len);
typedef void (*UDPCallback)(void* arg, struct udp_pcb* pcb, struct pbuf* p, const ip_addr_t* addr, u16_t port);
#include "../Debug.h"
#include "IP.h"
class UDP {
private:
static constexpr const char* NAME = "UDP";
//espconn* con;
struct udp_pcb* udp;
public:
UDP() {
init();
}
/** dtor */
~UDP() {
cleanup();
}
/** bind the socket to the given local port */
void bind(const Port localPort) {
Log::addInfo(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);
ip_addr_t bindIP;
IP4_ADDR(&bindIP, 0,0,0,0);
udp_bind(udp, &bindIP, localPort);
}
bool send(const IP4 ip, const Port port, const void* data, const uint16_t dataLen) {
Log::addInfo(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);
//
// // send. TODO: check. 0=OK
// const int res = espconn_sent(con, (unsigned char*)data, dataLen);
// return (res == 0);
// allocate and fill transmit buffer
pbuf* buf = pbuf_alloc(PBUF_TRANSPORT, dataLen, PBUF_RAM);
memcpy(buf->payload, data, dataLen);
// transmit
udp_sendto(udp, buf, ip.getPtr(), port);
pbuf_free(buf);
return true;
}
/** set the callback to call whenever a packet is received */
void setRecvCallback(UDPCallback callback) {
Log::addInfo(NAME, "setRecvCallback()");
// espconn_regist_recvcb(con, callback);
udp_recv(udp, callback, this);
}
/** get the IP address of the most recent packet's sender */
// IP4 getSenderIP() {
// remot_info* rem;
// espconn_get_connection_info(con, &rem, 0);
// ip_addr_t* _ip = (ip_addr_t*) rem->remote_ip;
// return IP4(*_ip);
// }
private:
/** initialize the UDP "connection" */
void init() {
Log::addInfo(NAME, "init()");
// // allocate connection-objects
// con = (espconn*) os_zalloc(sizeof(espconn));
// ets_memset( con, 0, sizeof( espconn ) );
//
// // configure
// con->type = ESPCONN_UDP;
//
// con->proto.udp = (esp_udp*) os_zalloc(sizeof(esp_udp));
udp = udp_new();
}
/** cleanup everything */
void cleanup() {
Log::addInfo(NAME, "cleanup()");
// espconn_delete(con);
// os_free(con->proto.udp);
// os_free(con);
udp_remove(udp);
}
};
#endif // UDP_H