cs-midi/MIDI_Interfaces/AppleMIDI/LwIPUDP.hpp

60 lines
1.3 KiB
C++

#pragma once
#include "vendor/shim/IPAddress.h"
#include "lwip/udp.h"
#include "lwip/pbuf.h"
// Arduino WiFiUDP-compatible wrapper around lwIP raw UDP API.
// Template parameter for AppleMIDISession<LwIPUDP>.
class LwIPUDP {
public:
LwIPUDP();
~LwIPUDP();
bool begin(uint16_t port);
void stop();
// Rx — packet-oriented read
int available();
int parsePacket();
int read(uint8_t *buf, size_t len);
int read();
IPAddress remoteIP();
uint16_t remotePort();
// Tx — packet-oriented write
int beginPacket(IPAddress ip, uint16_t port);
size_t write(const uint8_t *buf, size_t len);
int endPacket();
void flush() {} // no-op; UDP sends are immediate
private:
static constexpr uint8_t RX_QUEUE_SIZE = 4;
struct RxPacket {
ip_addr_t addr;
uint16_t port;
struct pbuf *p;
uint16_t offset;
};
struct udp_pcb *pcb_;
RxPacket rxQueue_[RX_QUEUE_SIZE];
volatile uint8_t rxHead_;
volatile uint8_t rxTail_;
// Current packet being read
RxPacket *current_;
void advanceRx();
// Outgoing
ip_addr_t txAddr_;
uint16_t txPort_;
struct pbuf *txBuf_;
static void recvCb(void *arg, struct udp_pcb *pcb,
struct pbuf *p, const ip_addr_t *addr, u16_t port);
};