Files
ESP8266lib/net/UDP.h
kazu 5cb02880b3 many updates..
new sensors.. display.. led.. drawing.. stuff..
2019-01-17 23:12:01 +01:00

116 lines
2.2 KiB
C++

#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 IP4 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) {
debugMod(NAME, "setRecvCallback()");
espconn_regist_recvcb(con, callback);
}
/** 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);
//const uint16_t port = rem->remote_port;
}
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