Making a UDP class which doesn't block an ESP8

2019-09-21 03:11发布

问题:

I have a need in my Arduino compatible project to listen on an ESP8266 to a specific UDP port and respond when an appropriate message is received, whilst doing other application stuff in the main program loop.

I want to abstract the UDP stuff into its own class, and this is where my question comes.

How do I let my class continue to listen, read a UDP packet, and then call a send response method, without putting lots of code into the main program loop?

The interface for my class is:

#ifndef Discover_Me_h
#define Discover_Me_h

#include "Arduino.h"

class DiscoverMe
{
  public:
    DiscoverMe(); //Constructor
    listenForPacket();// listens for packet, if one arrives it calls respond()
    respond();//Responds to the host which sent the packet with some data
};

#endif

The main program has:

    #include "DiscoverMe.h"
include "Arduino.h"

DiscoverMe dm;

void setup() {
  // put your setup code here, to run once:
 pinMode(ledPin, OUTPUT);
  dm.listenForPacket();
}

void loop() {
  // I WANT MY DiscoverMe class to still work when my program gets here

  int switchVar = 1;
  digitalWrite(ledPin, switchVar);
    delay(200);
    if (switchVar == 1) {
      switchVar = 0;
    } else {
      switchVar = 1;
    }
}

If I initalise and call my DiscoverMe object , and call listenForPacket() I have 2 questions:

  1. How do I make the UDP.begin()(which will be in the listenForPacket() method) not block, allowing my program to reach its loop()?
  2. If my program reaches it's loop, will the DiscoverMe listener continue to listen infinitely, if no, how do I make it behave as such? I guess I am asking, once loop() is hit, are the classes behaviours ignored, or do they run in separate threads?

回答1:

The answer was as per @maximilian:

In the loop, you will have to check if a packet has arrived every time. That's how the UDP library works (if(Udp.parsePacket() > 0)).

Design-wise, it would be best to make a DiscoverMe::HandlePacket function which will check if a packet is available, then act on it, and is called in every loop iteration. In the setup function, you may only bind your UDP client to a specific port. Udp.begin() will not block anyways.

This was implemented and I can confirm it works.

Long story short, libraries seem to require a method which will be called . during the main program loop, to touch base with the class and see if it needs to do any work.