Skip to content

Commit

Permalink
EthernetUDP: Refactor internal PCB creation
Browse files Browse the repository at this point in the history
  • Loading branch information
ssilverman committed Apr 16, 2024
1 parent dcfc0db commit e7ee84f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 15 deletions.
28 changes: 13 additions & 15 deletions src/QNEthernetUDP.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -138,18 +138,24 @@ bool EthernetUDP::beginWithReuse(uint16_t localPort) {
return begin(localPort, true);
}

void EthernetUDP::tryCreatePCB() {
if (pcb_ == nullptr) {
pcb_ = udp_new_ip_type(IPADDR_TYPE_ANY);
if (pcb_ == nullptr) {
Ethernet.loop(); // Allow the stack to move along
}
}
}

bool EthernetUDP::begin(uint16_t localPort, bool reuse) {
if (listening_) {
if (pcb_->local_port == localPort && listenReuse_ == reuse) {
return true;
}
stop();
}
tryCreatePCB();
if (pcb_ == nullptr) {
pcb_ = udp_new_ip_type(IPADDR_TYPE_ANY);
}
if (pcb_ == nullptr) {
Ethernet.loop(); // Allow the stack to move along
return false;
}

Expand Down Expand Up @@ -222,9 +228,7 @@ EthernetUDP::operator bool() const {
}

bool EthernetUDP::setDiffServ(uint8_t ds) {
if (pcb_ == nullptr) {
pcb_ = udp_new_ip_type(IPADDR_TYPE_ANY);
}
tryCreatePCB();
if (pcb_ == nullptr) {
return false;
}
Expand Down Expand Up @@ -373,11 +377,8 @@ int EthernetUDP::beginPacket(const char *host, uint16_t port) {
}

bool EthernetUDP::beginPacket(const ip_addr_t *ipaddr, uint16_t port) {
tryCreatePCB();
if (pcb_ == nullptr) {
pcb_ = udp_new_ip_type(IPADDR_TYPE_ANY);
}
if (pcb_ == nullptr) {
Ethernet.loop(); // Allow the stack to move along
return false;
}

Expand Down Expand Up @@ -463,11 +464,8 @@ bool EthernetUDP::send(const ip_addr_t *ipaddr, uint16_t port,
if (len > kMaxPossiblePayloadSize) {
return false;
}
tryCreatePCB();
if (pcb_ == nullptr) {
pcb_ = udp_new_ip_type(IPADDR_TYPE_ANY);
}
if (pcb_ == nullptr) {
Ethernet.loop(); // Allow the stack to move along
return false;
}

Expand Down
4 changes: 4 additions & 0 deletions src/QNEthernetUDP.h
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,10 @@ class EthernetUDP : public UDP {
static void recvFunc(void *arg, struct udp_pcb *pcb, struct pbuf *p,
const ip_addr_t *addr, u16_t port);

// Attempts to create the internal PCB if it's not already set. If
// unsuccessful, this calls Ethernet.loop().
void tryCreatePCB();

// Starts listening on a port and sets the SO_REUSEADDR socket option
// according to the `reuse` parameter. This returns whether the attempt
// was successful.
Expand Down

0 comments on commit e7ee84f

Please sign in to comment.