ESP32: Send Broadcast into local network and receive it with an Android App

Viewed 600

I've written a little sketch, which makes the ESP set up his own network:

#include <WiFi.h>

void setup() {

  Serial.begin(115200);
 
  WiFi.softAP("MyWiFiSSID", "MyWifiPW");

  IPAddress IP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(IP);
}

Now I am trying to send just the String "test" each 5 seconds as a broadcast through this Network (on Port 55559):

#include <AsyncUDP.h>

AsyncUDP udp;

void loop() {
  String testString = "test";
  udp.broadcastTo(testString.c_str(), 55559);

  delay(5000);
}

Unfortunately this seems to not work properly.

To check, I wrote a Little Xamarin.Android-App (programming language: C# instead of Java and VisualStudio instead of AndroidStudio, but it's more or less the same), which just contains a <Button /> and a <TextView />, for being able to simply receive and print that broadcast:

BroadcastReceiver broadcastReceiver;
private void OnButtonClick(object sender, EventArgs e){
    broadcastReceiver = new BroadcastReceiver();
    broadcastReceiver.ConnectSocket();
    string ip = "";
    while (!broadcastReceiver.GetBroadcast(ref ip)){ }
    FindViewById<TextView>(Resource.Id.txt).Text = broadcastReceiver.BroadcastData;
}
class BroadcastReceiver{
    public string BroadcastData{
        get{
            if (broadcastdatastring == ""){
                return "";
            }
            return broadcastdatastring;
        }
    }

    private IPEndPoint ipe;
    private Socket socket;
    private byte[] Broadcastdata = new byte[110];
    private string broadcastdatastring;

    public void ConnectSocket(){
        ipe = new IPEndPoint(IPAddress.Any, 55559);
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp){
            ReceiveBufferSize = 100 * 110
        };
        socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 1000);
        socket.Bind(ipe);
        return;
    }
    public bool GetBroadcast(ref string ip){
        ip = "";
        broadcastdatastring = "";

        if (socket?.Available > 0){
            var ep = (EndPoint)ipe;
            int received = socket.ReceiveFrom(Broadcastdata, ref ep);

            broadcastdatastring = Encoding.ASCII.GetString(Broadcastdata);
            ip = ((IPEndPoint)ep).Address.ToString();
        }
        return ip != "";
    }
}

Can anyone maybe help or can tell me why I can't receive this broadcast? Is there something wrong in the ESP32 code? Or in my app code (but when giving another broadcast with C# into the net, the app displays it, no Problem)? Or what is the matter?

Would be really happy for every answer!

Best regards

0 Answers
Related