me-no-dev / ESPAsyncUDP

Async UDP library for ESP8266

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Connection failed for Wifi client called from onPacket lambda

majklovec opened this issue · comments

When calling SyncClient::connect from loop() or setup() everything is fine, when called from udp.onPacket([](AsyncUDPPacket packet) I'm getting connection failed from SyncClient::connect (returns 0)

I'm I doing something wrong?

The example below is compilation of the two examples MultiCastServer(ESPAsyncUDP) and SyncClient(ESPAsyncTCP).

Arduino 1.6.10 staging

Thank you for the great libraries!!!

Code:

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include "ESPAsyncTCP.h"
#include "SyncClient.h"
#include <ESPAsyncUDP.h>

const char* ssid = "*********";
const char* password = "******";

AsyncUDP udp;
SyncClient client;

void go() {
  if (!client.connect("www.google.com", 80)) {
    Serial.println("Connect Failed");
    return ;
  }
  client.setTimeout(2);
  if (client.printf("GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n") > 0) {
    while (!client.available())
      delay(1);
    while (client.connected()) {
      while (client.connected() && client.available() == 0)
        delay(1);

      while (client.connected() && client.available()) {
        Serial.write(client.read());
      }
    }
  } else {
    client.stop();
    Serial.println("Send Failed");
    while (client.connected()) delay(0);
  }
}

void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.println();
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  if (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.printf("WiFi Failed!\n");
    return;
  }

  if (udp.listenMulticast(IPAddress(239, 1, 2, 3), 1234)) {
    Serial.print("UDP Listening on IP: ");
    Serial.println(WiFi.localIP());
    udp.onPacket([](AsyncUDPPacket packet) {
        go();  // <------------------------------------- DOESN'T WORK - Connection failed always

    });
    //Send multicast
    udp.print("Hello!");
  }

  go();  // <------------------------------------- HERE IT WORKS
}

void loop() {
  go();  // <------------------------------------- HERE IT WORKS
}

You can not call synchronous methods inside async callback ;) set a flag and do it from the loop instead

That's how i did it, I was just curious if there is another way.

Thank you for your time.