including tftp based shell and sockets from different project
This commit is contained in:
@@ -0,0 +1,196 @@
|
||||
/**
|
||||
* @file etherCommon.hpp
|
||||
* @author Gustice
|
||||
* @brief Helper Functions for Ethernet usage
|
||||
*
|
||||
* @copyright Copyright (c) 2024
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include "esp_log.h"
|
||||
#include "esp_netif.h"
|
||||
#include "lwip/err.h"
|
||||
#include "lwip/sockets.h"
|
||||
#include "lwip/sys.h"
|
||||
#include <array>
|
||||
#include <cstring>
|
||||
#include <lwip/netdb.h>
|
||||
#include <string>
|
||||
|
||||
#if defined(CONFIG_LWIP_NETBUF_RECVINFO)
|
||||
constexpr bool NETBUF_RECVINFO = true;
|
||||
#else
|
||||
constexpr bool NETBUF_RECVINFO = false;
|
||||
#endif
|
||||
#if defined(CONFIG_EXAMPLE_IPV4)
|
||||
constexpr bool USE_IPV4 = true;
|
||||
#else
|
||||
constexpr bool USE_IPV4 = false;
|
||||
#endif
|
||||
#if defined(CONFIG_EXAMPLE_IPV6)
|
||||
constexpr bool USE_IPV6 = true;
|
||||
#else
|
||||
constexpr bool USE_IPV6 = false;
|
||||
#endif
|
||||
|
||||
class Ip {
|
||||
public:
|
||||
Ip(uint32_t ipV4) {
|
||||
_address.word = ipV4;
|
||||
}
|
||||
Ip(esp_ip4_addr_t ipV4) {
|
||||
_address.word = ipV4.addr;
|
||||
}
|
||||
|
||||
Ip(uint8_t b0, uint8_t b1, uint8_t b2, uint8_t b3) {
|
||||
_address.bytes[0] = b0;
|
||||
_address.bytes[1] = b1;
|
||||
_address.bytes[2] = b2;
|
||||
_address.bytes[3] = b3;
|
||||
}
|
||||
|
||||
Ip(std::string ipStr) {
|
||||
_address.word = ipaddr_addr(ipStr.c_str());
|
||||
}
|
||||
|
||||
uint8_t operator[](int index) const { return _address.bytes[index]; };
|
||||
uint32_t asWord() const { return _address.word; }
|
||||
std::string asString() const { return inet_ntoa(_address.word); }
|
||||
|
||||
private:
|
||||
union {
|
||||
uint8_t bytes[4]; // IPv4 address
|
||||
uint32_t word;
|
||||
} _address;
|
||||
};
|
||||
|
||||
class Mac {
|
||||
public:
|
||||
Mac(uint8_t val[NETIF_MAX_HWADDR_LEN]) {
|
||||
std::memcpy(bytes.begin(), val, NETIF_MAX_HWADDR_LEN);
|
||||
}
|
||||
|
||||
uint8_t operator[](int index) const {
|
||||
return bytes[index];
|
||||
};
|
||||
|
||||
std::string asString() const {
|
||||
char buffer[64];
|
||||
sprintf(buffer, "%02x:%02x:%02x:%02x:%02x:%02x", bytes[0], bytes[1],
|
||||
bytes[2], bytes[3], bytes[4], bytes[5]);
|
||||
return {buffer};
|
||||
}
|
||||
|
||||
const std::array<uint8_t, NETIF_MAX_HWADDR_LEN> &asArray() const {
|
||||
return bytes;
|
||||
}
|
||||
|
||||
private:
|
||||
std::array<uint8_t, NETIF_MAX_HWADDR_LEN> bytes; // IPv4 address
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief IP-set class
|
||||
*/
|
||||
struct IpInfo {
|
||||
/// @brief IP address
|
||||
Ip address{0u};
|
||||
/// @brief IP subnet
|
||||
Ip subnet{0u};
|
||||
/// @brief Gateway IP
|
||||
Ip gateway{0u};
|
||||
/// @brief MAC-Address
|
||||
Mac macAddress;
|
||||
|
||||
/// @brief Get broadcast address from IP and subnet
|
||||
/// @return
|
||||
Ip getBradcastAddress() const {
|
||||
auto sn = address.asWord() | ~subnet.asWord();
|
||||
return Ip(sn);
|
||||
}
|
||||
};
|
||||
|
||||
struct IpAdr {
|
||||
public:
|
||||
IpAdr(std::string ipStr, uint16_t port);
|
||||
IpAdr(uint32_t ip, uint16_t port);
|
||||
IpAdr(uint16_t port);
|
||||
IpAdr(sockaddr_in ipV4data);
|
||||
|
||||
static constexpr int IpProtocol = IPPROTO_IP; // IPPROTO_IPV6 for version 6
|
||||
static constexpr int ProtocolFamily = AF_INET; // AF_INET6 for version 6
|
||||
/// @brief StackFamily e.g. AF_INET or AF_INET6
|
||||
sa_family_t getProtocolFamily() const { return addrStore.ss_family; }
|
||||
|
||||
std::string getIp() {
|
||||
struct sockaddr_in *ipV4 = (struct sockaddr_in *)&addrStore;
|
||||
return inet_ntoa(ipV4->sin_addr.s_addr);
|
||||
}
|
||||
uint16_t getPort() const {
|
||||
struct sockaddr_in *ipV4 = (struct sockaddr_in *)&addrStore;
|
||||
return ntohs(ipV4->sin_port);
|
||||
};
|
||||
struct sockaddr *asSockAddrPtr() const { return (struct sockaddr *)&addrStore; }
|
||||
|
||||
static constexpr int Size = sizeof(sockaddr_storage);
|
||||
private:
|
||||
struct sockaddr_storage addrStore;
|
||||
};
|
||||
|
||||
struct IpAdrV6 {
|
||||
public:
|
||||
IpAdrV6(std::string ipStr, uint16_t port);
|
||||
IpAdrV6(in6_addr ip, uint16_t port);
|
||||
IpAdrV6(uint16_t port);
|
||||
IpAdrV6(sockaddr_in6 ipV6data);
|
||||
|
||||
static constexpr int IpProtocol = IPPROTO_IPV6;
|
||||
static constexpr int ProtocolFamily = AF_INET6;
|
||||
/// @brief StackFamily e.g. AF_INET or AF_INET6
|
||||
sa_family_t getProtocolFamily() const { return addrStore.ss_family; }
|
||||
|
||||
std::string getIp() {
|
||||
struct sockaddr_in6 *ipV6 = (struct sockaddr_in6 *)&addrStore;
|
||||
return inet6_ntoa(ipV6->sin6_addr);
|
||||
|
||||
}
|
||||
uint16_t getPort() const {
|
||||
struct sockaddr_in6 *ipV6 = (struct sockaddr_in6 *)&addrStore;
|
||||
return ntohs(ipV6->sin6_port);
|
||||
};
|
||||
struct sockaddr *asSockAddrPtr() const { return (struct sockaddr *)&addrStore; }
|
||||
|
||||
static constexpr int Size = sizeof(sockaddr_storage);
|
||||
private:
|
||||
struct sockaddr_storage addrStore;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Simplified abstraction for sockets
|
||||
*/
|
||||
class SocketBase {
|
||||
public:
|
||||
/// @brief Get if stream is active
|
||||
/// @return true if active
|
||||
virtual bool isActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
IpInfo getIpInfo() {
|
||||
auto *netIf = esp_netif_get_default_netif();
|
||||
esp_netif_ip_info_t ip;
|
||||
uint8_t mac[NETIF_MAX_HWADDR_LEN];
|
||||
ESP_ERROR_CHECK(esp_netif_get_ip_info(netIf, &ip));
|
||||
ESP_ERROR_CHECK(esp_netif_get_mac(netIf, mac));
|
||||
|
||||
IpInfo ips{
|
||||
.address = Ip{ip.ip},
|
||||
.subnet = Ip(ip.netmask),
|
||||
.gateway = Ip(ip.netmask),
|
||||
.macAddress = Mac(mac)};
|
||||
return ips;
|
||||
}
|
||||
|
||||
protected:
|
||||
bool active;
|
||||
};
|
||||
@@ -0,0 +1,307 @@
|
||||
/**
|
||||
* @file tcpSockets.hpp
|
||||
* @author Gustice
|
||||
* @brief Function wrapper for ESP-IDF socket implementation
|
||||
*
|
||||
* @copyright Copyright (c) 2024
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "esp_log.h"
|
||||
#include "etherCommon.hpp"
|
||||
#include "utils.hpp"
|
||||
#include <functional>
|
||||
#include <iostream>
|
||||
|
||||
/**
|
||||
* @brief TCP-Socket wrapper for ESP-IDF socket implementation
|
||||
*/
|
||||
class TcpSocket {
|
||||
public:
|
||||
/// @brief Constructor
|
||||
/// @note Socket not active until call of attach method
|
||||
/// @param addr Server/Client address
|
||||
TcpSocket(const IpAdr &addr)
|
||||
: Local(addr) {
|
||||
_listenSockId = socket(addr.ProtocolFamily, SOCK_STREAM, addr.IpProtocol);
|
||||
if (_listenSockId < 0) {
|
||||
ESP_LOGE("TCP", "Unable to create socket: errno %d", errno);
|
||||
throw CoreException("Unable to create socket");
|
||||
}
|
||||
|
||||
if (addr.ProtocolFamily == IPPROTO_IP) {
|
||||
int opt = 1;
|
||||
setsockopt(_listenSockId, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
|
||||
}
|
||||
|
||||
if constexpr (USE_IPV4 && USE_IPV6) {
|
||||
int opt = 1;
|
||||
// Note that by default IPV6 binds to both protocols, it is must be disabled
|
||||
// if both protocols used at the same time (used in CI)
|
||||
setsockopt(_listenSockId, IPPROTO_IPV6, IPV6_V6ONLY, &opt, sizeof(opt));
|
||||
}
|
||||
|
||||
ESP_LOGI("TCP", "Socket created");
|
||||
}
|
||||
|
||||
/// @brief Destructor
|
||||
~TcpSocket() {
|
||||
close(_listenSockId);
|
||||
}
|
||||
|
||||
/// @brief Attach to configured socket
|
||||
/// @note Blocks until successful or failed
|
||||
/// @return true if successful
|
||||
bool bindTo() {
|
||||
int err = bind(_listenSockId, Local.asSockAddrPtr(), sizeof(sockaddr_storage));
|
||||
if (err != 0) {
|
||||
ESP_LOGE("TCP", "Socket unable to bind: errno %d", errno);
|
||||
ESP_LOGE("TCP", "IPPROTO: %d", Local.ProtocolFamily);
|
||||
throw CoreException("Socket unable to bind");
|
||||
}
|
||||
ESP_LOGI("TCP", "Socket bound, port %d", Local.getPort());
|
||||
|
||||
err = listen(_listenSockId, 1);
|
||||
if (err != 0) {
|
||||
ESP_LOGE("TCP", "Error occurred during listen: errno %d", errno);
|
||||
throw CoreException("Error occurred during listen");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// @brief Get socket id for stream-operations
|
||||
/// @return Id of socket
|
||||
int getSocketId() {
|
||||
return _listenSockId;
|
||||
}
|
||||
|
||||
/// @brief Address of this station (server perspective)
|
||||
const IpAdr &Local;
|
||||
|
||||
private:
|
||||
int _listenSockId;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief TCP session
|
||||
*/
|
||||
class TcpSession : public SocketBase, public CharStream {
|
||||
public:
|
||||
/**
|
||||
* @brief Configuration structure for Session
|
||||
*/
|
||||
struct Config {
|
||||
int keepAlive;
|
||||
int keepIdle;
|
||||
int keepInterval;
|
||||
int keepCount;
|
||||
};
|
||||
|
||||
/// @brief Constructor
|
||||
/// @note Constructor blocks
|
||||
/// @param config Configuration for session
|
||||
/// @param listener reference to socket
|
||||
TcpSession(Config &config, TcpSocket &listener) : _other(IPADDR_ANY, 0) {
|
||||
socklen_t addr_len = _other.Size;
|
||||
_socket = accept(listener.getSocketId(), _other.asSockAddrPtr(), &addr_len);
|
||||
if (_socket < 0) {
|
||||
ESP_LOGE("TCP", "Unable to accept connection: errno %d", errno);
|
||||
active = false;
|
||||
throw CoreException("Unable to accept connection");
|
||||
}
|
||||
|
||||
// Set tcp keepalive option
|
||||
setsockopt(_socket, SOL_SOCKET, SO_KEEPALIVE, &config.keepAlive, sizeof(int));
|
||||
setsockopt(_socket, IPPROTO_TCP, TCP_KEEPIDLE, &config.keepIdle, sizeof(int));
|
||||
setsockopt(_socket, IPPROTO_TCP, TCP_KEEPINTVL, &config.keepInterval, sizeof(int));
|
||||
setsockopt(_socket, IPPROTO_TCP, TCP_KEEPCNT, &config.keepCount, sizeof(int));
|
||||
|
||||
std::string addrStr;
|
||||
if (_other.ProtocolFamily == listener.Local.ProtocolFamily) {
|
||||
if (_other.getProtocolFamily() == PF_INET) {
|
||||
addrStr = _other.getIp();
|
||||
// } else if (_other.addrStore.ss_family == PF_INET6) {
|
||||
// inet6_ntoa_r(((struct sockaddr_in6 *)&_other.addrStore)->sin6_addr, addrStr, sizeof(addrStr) - 1);
|
||||
} else {
|
||||
throw CoreException("Unknown case");
|
||||
}
|
||||
} else {
|
||||
ESP_LOGW("TCP", "Wrong IP-version request");
|
||||
active = false;
|
||||
}
|
||||
|
||||
ESP_LOGI("TCP", "Socket accepted ip address: %s", addrStr.c_str());
|
||||
|
||||
active = true;
|
||||
}
|
||||
|
||||
/// @brief Destructor
|
||||
~TcpSession() {
|
||||
if (_socket < 0)
|
||||
return;
|
||||
|
||||
ESP_LOGD("TCP", "Tearing down socket");
|
||||
shutdown(_socket, 0);
|
||||
}
|
||||
|
||||
/// @brief Get IP of remote
|
||||
/// @return
|
||||
IpAdr getSource() {
|
||||
return _other;
|
||||
}
|
||||
|
||||
/// @brief Read string
|
||||
/// @note This call blocks until data is received
|
||||
/// @return read string
|
||||
std::string read() override {
|
||||
auto data = readRaw();
|
||||
if (data.size() == 0) {
|
||||
return "";
|
||||
}
|
||||
|
||||
std::string ret((const char *)&data.data()[0]);
|
||||
return ret;
|
||||
}
|
||||
|
||||
/// @brief Write character to socket
|
||||
/// @param b character to write
|
||||
void write(char c) override {
|
||||
if (!isActive()) {
|
||||
return;
|
||||
}
|
||||
|
||||
int written = send(_socket, &c, 1, 0);
|
||||
if (written < 0) {
|
||||
ESP_LOGE("TCP", "Error occurred during sending: errno %d", errno);
|
||||
}
|
||||
}
|
||||
|
||||
/// @brief Write string to specific socket
|
||||
/// @param message payload
|
||||
/// @param dest Destination for message
|
||||
void write(std::string message) override {
|
||||
if (!isActive()) {
|
||||
return;
|
||||
}
|
||||
|
||||
int written = send(_socket, message.c_str(), message.size(), 0);
|
||||
if (written < 0) {
|
||||
ESP_LOGE("TCP", "Error occurred during sending: errno %d", errno);
|
||||
}
|
||||
}
|
||||
|
||||
IpAdr getOther() {
|
||||
return _other;
|
||||
}
|
||||
|
||||
protected:
|
||||
int _socket = 0;
|
||||
IpAdr _other;
|
||||
|
||||
std::vector<uint8_t> readRaw() {
|
||||
uint8_t data[128];
|
||||
int len = recv(_socket, data, sizeof(data) - 1, 0);
|
||||
|
||||
if (len < 0) {
|
||||
ESP_LOGE("TCP", "Error occurred during receiving: errno %d", errno);
|
||||
active = false;
|
||||
return {};
|
||||
}
|
||||
|
||||
data[len] = 0;
|
||||
if (len == 0) {
|
||||
ESP_LOGW("TCP", "Connection closed");
|
||||
active = false;
|
||||
return {};
|
||||
}
|
||||
|
||||
ESP_LOGD("TCP", "Received %d bytes: %s", len, data);
|
||||
std::vector<uint8_t> vec(data, data + len + 1);
|
||||
return vec;
|
||||
}
|
||||
};
|
||||
|
||||
constexpr TcpSession::Config DefaultTcpConfig{
|
||||
.keepAlive = 1,
|
||||
.keepIdle = 5,
|
||||
.keepInterval = 5,
|
||||
.keepCount = 3,
|
||||
};
|
||||
|
||||
constexpr uint16_t TelnetPort = 23;
|
||||
|
||||
/**
|
||||
* @brief TCP-Socket for Telnet-Applications
|
||||
*/
|
||||
class TelnetServer {
|
||||
|
||||
/**
|
||||
* @brief Specialization of TCP-Session for Telnet
|
||||
*/
|
||||
class TelnetSession : public TcpSession {
|
||||
|
||||
public:
|
||||
// Constructor
|
||||
TelnetSession(Config &config, TcpSocket &listener) : TcpSession(config, listener) {
|
||||
}
|
||||
|
||||
/// @brief Read string
|
||||
/// @note This call blocks until data is received
|
||||
/// @return read string
|
||||
std::string read() override {
|
||||
auto data = readRaw();
|
||||
if (data.size() == 0) {
|
||||
return "";
|
||||
}
|
||||
|
||||
data.pop_back(); // 0-termination is not needed here
|
||||
|
||||
int i = 0;
|
||||
while (data[i] == 0xFF) { // while telnet command
|
||||
i += 3; // skip this command
|
||||
}
|
||||
|
||||
if (i == data.size()) { // only configuration
|
||||
send(_socket, data.data(), data.size(), 0);
|
||||
return "";
|
||||
}
|
||||
|
||||
std::string ret((const char *)&data[i]);
|
||||
return ret;
|
||||
}
|
||||
};
|
||||
|
||||
public:
|
||||
/// @brief Constructor
|
||||
/// @param addrFamily IPV4 or IPV6
|
||||
TelnetServer(int addrFamily)
|
||||
: Local(addrFamily == AF_INET ? IpAdr(INADDR_ANY, TelnetPort) : IpAdr(TelnetPort)),
|
||||
Config(DefaultTcpConfig) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Start server
|
||||
*
|
||||
* @param initCall Callback for shell init
|
||||
* @param cyclicCall Callback for cyclic polling
|
||||
*/
|
||||
void run(std::function<void(TcpSession &)> initCall, std::function<void(TcpSession &)> cyclicCall) {
|
||||
TcpSocket socket(Local);
|
||||
socket.bindTo();
|
||||
while (true) {
|
||||
// Run telnet-session as long socket is active else restart socket
|
||||
ESP_LOGI("Telnet", "Socket waiting for connect");
|
||||
TelnetSession session(Config, socket);
|
||||
|
||||
initCall(session);
|
||||
while (session.isActive()) {
|
||||
cyclicCall(session);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
IpAdr Local;
|
||||
TcpSession::Config Config;
|
||||
};
|
||||
@@ -0,0 +1,303 @@
|
||||
/**
|
||||
* @file udpSockets.hpp
|
||||
* @author Gustice
|
||||
* @brief UDP-Socket wrapper for ESP-IDF socket implementation
|
||||
*
|
||||
* @copyright Copyright (c) 2024
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include "Task.hpp"
|
||||
#include "esp_log.h"
|
||||
#include "etherCommon.hpp"
|
||||
#include "utils.hpp"
|
||||
#include <cstdarg>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
constexpr bool UDP_WITH_TIMEOUT = false;
|
||||
|
||||
/**
|
||||
* @brief UDP-Socket wrapper for ESP-IDF socket implementation
|
||||
*/
|
||||
class UdpSocket : public ByteStream, public SocketBase {
|
||||
public:
|
||||
/// @brief Constructor for UDP-Socket-Server
|
||||
/// @note Socket not active until call of attach method
|
||||
/// @param addr Server/Client address
|
||||
UdpSocket(const IpAdr &addr)
|
||||
: Local(addr), _other(INADDR_ANY, 0) {
|
||||
_listenSockId = socket(addr.ProtocolFamily, SOCK_DGRAM, addr.IpProtocol);
|
||||
if (_listenSockId < 0) {
|
||||
ESP_LOGE("UDP", "Unable to create socket: errno %d", errno);
|
||||
throw CoreException("Unable to create socket");
|
||||
}
|
||||
ESP_LOGD("UDP", "Socket created");
|
||||
|
||||
if constexpr (NETBUF_RECVINFO && !USE_IPV6) {
|
||||
int enable = 1;
|
||||
lwip_setsockopt(_listenSockId, IPPROTO_IP, IP_PKTINFO, &enable, sizeof(enable));
|
||||
}
|
||||
|
||||
if constexpr (USE_IPV4 && USE_IPV6) {
|
||||
if (addr.ProtocolFamily == AF_INET6) {
|
||||
// Note that by default IPV6 binds to both protocols, it is must be disabled
|
||||
// if both protocols used at the same time (used in CI)
|
||||
int opt = 1;
|
||||
setsockopt(_listenSockId, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
|
||||
setsockopt(_listenSockId, IPPROTO_IPV6, IPV6_V6ONLY, &opt, sizeof(opt));
|
||||
}
|
||||
}
|
||||
|
||||
if constexpr (UDP_WITH_TIMEOUT) { // Set timeout if desired
|
||||
struct timeval timeout {
|
||||
.tv_sec = 10,
|
||||
.tv_usec = 0,
|
||||
};
|
||||
setsockopt(_listenSockId, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
|
||||
}
|
||||
}
|
||||
|
||||
/// @brief Destructor
|
||||
~UdpSocket() {
|
||||
active = false;
|
||||
ESP_LOGD("UDP", "Shutting down socket and restarting...");
|
||||
shutdown(_listenSockId, 0);
|
||||
close(_listenSockId);
|
||||
}
|
||||
|
||||
/// @brief Attach to configured socket
|
||||
/// @note Blocks until successful or failed
|
||||
/// @return true if successful
|
||||
bool bindTo() {
|
||||
active = false;
|
||||
int err = bind(_listenSockId, Local.asSockAddrPtr(), sizeof(sockaddr_storage));
|
||||
if (err < 0) {
|
||||
ESP_LOGE("UDP", "Socket unable to bind: errno %d", errno);
|
||||
throw CoreException("Socket unable to bind");
|
||||
}
|
||||
ESP_LOGI("UDP", "Socket bound, port %d", Local.getPort());
|
||||
|
||||
if constexpr (NETBUF_RECVINFO && !USE_IPV6) {
|
||||
_iov.iov_base = _rxBuffer;
|
||||
_iov.iov_len = sizeof(_rxBuffer);
|
||||
_msg.msg_control = _cmsg_buf;
|
||||
_msg.msg_controllen = sizeof(_cmsg_buf);
|
||||
_msg.msg_flags = 0;
|
||||
_msg.msg_iov = &_iov;
|
||||
_msg.msg_iovlen = 1;
|
||||
_msg.msg_name = _other.asSockAddrPtr();
|
||||
_msg.msg_namelen = _other.Size;
|
||||
}
|
||||
|
||||
active = true;
|
||||
return active;
|
||||
}
|
||||
|
||||
/// @brief Read from socket
|
||||
/// @note This call blocks until data is received
|
||||
/// @return read bytes
|
||||
std::vector<uint8_t> read() override {
|
||||
char buffer[256];
|
||||
int len = 0;
|
||||
if constexpr (NETBUF_RECVINFO && !USE_IPV6) {
|
||||
len = recvmsg(_listenSockId, &_msg, 0);
|
||||
} else {
|
||||
socklen_t socklen = _other.Size;
|
||||
len = recvfrom(_listenSockId, buffer, sizeof(buffer) - 1, 0, _other.asSockAddrPtr(), &socklen);
|
||||
}
|
||||
if (len < 0) {
|
||||
ESP_LOGE("UDP", "recvfrom failed: errno %d", errno);
|
||||
return {};
|
||||
}
|
||||
|
||||
std::string addrStr;
|
||||
// Get the sender's ip address as string
|
||||
if (Local.ProtocolFamily == PF_INET) {
|
||||
addrStr = _other.getIp();
|
||||
|
||||
if constexpr (NETBUF_RECVINFO && !USE_IPV6) {
|
||||
struct cmsghdr *cmsgtmp;
|
||||
for (cmsgtmp = CMSG_FIRSTHDR(&_msg); cmsgtmp != NULL; cmsgtmp = CMSG_NXTHDR(&_msg, cmsgtmp)) {
|
||||
if (cmsgtmp->cmsg_level == IPPROTO_IP && cmsgtmp->cmsg_type == IP_PKTINFO) {
|
||||
struct in_pktinfo *pktinfo;
|
||||
pktinfo = (struct in_pktinfo *)CMSG_DATA(cmsgtmp);
|
||||
ESP_LOGI("UDP", "dest ip: %s", inet_ntoa(pktinfo->ipi_addr));
|
||||
}
|
||||
}
|
||||
}
|
||||
} // else if (Local.ProtocolFamily == PF_INET6) {
|
||||
// inet6_ntoa_r(((struct sockaddr_in6 *)&_other.addrStore)->sin6_addr, addrStr, sizeof(addrStr) - 1);
|
||||
// }
|
||||
|
||||
ESP_LOGD("UDP", "Received %d bytes from %s:", len, addrStr.c_str());
|
||||
std::vector<uint8_t> ret(buffer, buffer + len);
|
||||
return ret;
|
||||
}
|
||||
|
||||
/// @brief Write character to socket
|
||||
/// @param b character to write
|
||||
void write(uint8_t b) override {}
|
||||
|
||||
/// @brief Write bytes to socket
|
||||
/// @param data payload as series of bytes
|
||||
void write(std::vector<uint8_t> data) override {
|
||||
write(&data[0], data.size());
|
||||
}
|
||||
|
||||
/// @brief Write string to specific socket
|
||||
/// @param message payload
|
||||
/// @param dest Destination for message
|
||||
void write(std::string &message, IpAdr *dest = nullptr) {
|
||||
auto data = message.c_str();
|
||||
write((uint8_t *)data, message.size() + 1, dest);
|
||||
}
|
||||
|
||||
/// @brief Write string to specific socket or to last source
|
||||
/// @param data payload
|
||||
/// @param size size of data
|
||||
/// @param addr Destination for message (if nullptr it will be send to last source)
|
||||
void write(uint8_t *data, uint size, IpAdr *dest = nullptr) {
|
||||
int err;
|
||||
if (dest == nullptr) {
|
||||
err = sendto(_listenSockId, data, size, 0, _other.asSockAddrPtr(), sizeof(sockaddr_storage));
|
||||
} else {
|
||||
struct sockaddr_in *ipV4 = (struct sockaddr_in *)dest->asSockAddrPtr();
|
||||
// ESP_LOGI("UDP", "EthIP: %s", inet_ntoa(ipV4->sin_addr.s_addr));
|
||||
// ESP_LOGI("UDP", "PORT: %i", ntohs(ipV4->sin_port));
|
||||
err = sendto(_listenSockId, data, size, 0, dest->asSockAddrPtr(), sizeof(sockaddr_storage));
|
||||
}
|
||||
|
||||
if (err < 0) {
|
||||
ESP_LOGE("UDP", "Error occurred during sending: errno %d", errno);
|
||||
active = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// @brief Standard destination address
|
||||
const IpAdr &Local;
|
||||
|
||||
/// @brief query if stream is still active
|
||||
/// @return true if active
|
||||
bool isValid() {
|
||||
return _listenSockId >= 0;
|
||||
}
|
||||
|
||||
IpAdr getOther() {
|
||||
return _other;
|
||||
}
|
||||
|
||||
private:
|
||||
int _listenSockId; // os handle for socket
|
||||
IpAdr _other; // Remote Station
|
||||
char _rxBuffer[128];
|
||||
|
||||
// Only used if NETBUF_RECVINFO is active
|
||||
iovec _iov;
|
||||
msghdr _msg;
|
||||
u8_t _cmsg_buf[CMSG_SPACE(sizeof(struct in_pktinfo))];
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief
|
||||
* @details according to RFC-5424
|
||||
* https://datatracker.ietf.org/doc/html/rfc5424
|
||||
*/
|
||||
class Syslog {
|
||||
public:
|
||||
static constexpr uint16_t SyslogPort = 514;
|
||||
static constexpr std::string_view NilValue = "-";
|
||||
|
||||
enum class Severity {
|
||||
Emergency = 0,
|
||||
Alert = 1,
|
||||
Critical = 2,
|
||||
Error = 3,
|
||||
Warning = 4,
|
||||
Notice = 5,
|
||||
Informational = 6,
|
||||
Debug = 7,
|
||||
};
|
||||
static constexpr uint8_t SeverityMask = 0x000F;
|
||||
|
||||
enum class Facility {
|
||||
kern = 0 << 3,
|
||||
User = 1 << 3,
|
||||
Mail = 2 << 3,
|
||||
Daemon = 3 << 3,
|
||||
Auth = 4 << 3,
|
||||
Syslog = 5 << 3,
|
||||
Lpr = 6 << 3,
|
||||
News = 7 << 3,
|
||||
Uucp = 8 << 3,
|
||||
Cron = 9 << 3,
|
||||
Authpriv = 10 << 3,
|
||||
Ftp = 11 << 3,
|
||||
Ntp = 12 << 3,
|
||||
LogAudit = 13 << 3,
|
||||
LogAlert = 14 << 3,
|
||||
Clock = 15 << 3,
|
||||
Local0 = 16 << 3,
|
||||
Local1 = 17 << 3,
|
||||
Local2 = 18 << 3,
|
||||
Local3 = 19 << 3,
|
||||
Local4 = 20 << 3,
|
||||
Local5 = 21 << 3,
|
||||
Local6 = 22 << 3,
|
||||
Local7 = 23 << 3,
|
||||
};
|
||||
|
||||
static void log(Severity severity, std::string message) {
|
||||
if (_Socket == nullptr) {
|
||||
return;
|
||||
}
|
||||
|
||||
char buffer[512];
|
||||
// V T H A P M D Msg
|
||||
// alternatively with BOM flag UTF8 \xEF\xBB\xBF
|
||||
auto pos = sprintf(buffer, "<%i>1 - %s %s - - - %s",
|
||||
static_cast<int>(_Facility) | static_cast<int>(severity),
|
||||
_HostName.c_str(),
|
||||
_AppName.c_str(),
|
||||
message.c_str());
|
||||
_Socket->write((uint8_t *)buffer, pos, &_Target);
|
||||
}
|
||||
|
||||
template <typename...Params>
|
||||
static void logv(Severity severity, const char *fmt, Params&&... args) {
|
||||
if (_Socket == nullptr) {
|
||||
return;
|
||||
}
|
||||
|
||||
char buffer[512];
|
||||
// V T H A P M D Msg
|
||||
// alternatively with BOM flag UTF8 \xEF\xBB\xBF
|
||||
auto pos = sprintf(buffer, "<%i>1 - %s %s - - - ",
|
||||
static_cast<int>(_Facility) | static_cast<int>(severity),
|
||||
_HostName.c_str(),
|
||||
_AppName.c_str());
|
||||
pos += sprintf(&buffer[pos], fmt, std::forward<Params> (args)...);
|
||||
|
||||
_Socket->write((uint8_t *)buffer, pos, &_Target);
|
||||
}
|
||||
|
||||
static void setupTask(IpAdr target) {
|
||||
if (_Socket) {
|
||||
return;
|
||||
}
|
||||
_Facility = Facility::Syslog;
|
||||
_HostName = "ESP";
|
||||
_AppName = "App";
|
||||
_Target = IpAdr{target.getIp(), SyslogPort};
|
||||
|
||||
static fos::Task syslogTask(SyslogTask, "SysLog", 4096);
|
||||
}
|
||||
|
||||
private:
|
||||
static void SyslogTask();
|
||||
static Facility _Facility;
|
||||
static std::string _HostName;
|
||||
static std::string _AppName;
|
||||
static UdpSocket *_Socket;
|
||||
static IpAdr _Target;
|
||||
};
|
||||
Reference in New Issue
Block a user