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:
- How do I make the
UDP.begin()
(which will be in the listenForPacket() method) not block, allowing my program to reach itsloop()
? - 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, onceloop()
is hit, are the classes behaviours ignored, or do they run in separate threads?