#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
WiFiClient client;
WiFiUDP port;
char packetBuffer[255];
unsigned int localPort = 9999;
IPAddress serverIP(192, 168, 1, 117);
void setup() {
Serial.begin(9600);
WiFi.begin("******", "********");
port.begin(9999);
pinMode(2, OUTPUT);
digitalWrite(2,LOW);
}
void loop() {
int packetSize = port.parsePacket();
Serial.println(packetSize);
if (packetSize) {
int len = port.read(packetBuffer, 255);
if (len > 0) packetBuffer[len] = 0;
Serial.println(packetBuffer);
handleMessage(String(packetBuffer));
}
delay(500);
}
void handleMessage(String data) {
if(data=="on"){
digitalWrite(2,HIGH);
Serial.println("ON");
sendMessage("light on");
}
if(data=="off"){
digitalWrite(2,LOW);
Serial.write("OFF");
sendMessage("light off");
}
}
void sendMessage(char data[]) {
port.beginPacket(serverIP,localPort);
port.write(data);
port.endPacket();
}
Moderator: igrr
robertnash30 wrote:I'm not entirely sure that this is a bug but I can't see any other explanation for the behavior.
+1
In other post I showed working examples for an UDP Server and another one for UDP Client.
But when I extend these examples to combination the UDP Client and Server in 1 sketch I get the same problems you get.
I also adapted this code, but to no avail.
http://arduino.cc/en/Tutorial/WiFiSendReceiveUDPString
Perhaps IGRR can have a look when he's got the time.
In order to try and get around this I have tried calling stop and then begin again after a transmission to restart the listening but to no avail.
int WiFiUDP::beginPacket(IPAddress ip, uint16_t port)
{
ip_addr_t addr;
addr.addr = ip;
if (_ctx)
_ctx->unref();
_ctx = new UdpContext;
return (_ctx->connect(addr, port)) ? 1 : 0;
}
i.e (plagiarized from mvdbro on GitHub)
void sendMessage(char data[]) {
WiFiUDP port2;
port2.beginPacket(serverIP,localPort);
port2.write(data);
port2.endPacket();
}