Meadow & MQTT - Can't connect to broker

Hi,

I’m trying to get my Meadow connecting to a MQTT broker using MQTTNet. However I can’t get it to connect.
“Error while connecting to host”

Has anyone been able to successfully get MQTT working on the Meadow?

 private string MQTTUrl = "IPADDRESS";
    private string ClientId = "";
    IManagedMqttClient _mqttClient;

    public MQTTHandler()
    {
        Connect();
    }

    private async void Connect()
    {
        ClientId = "MQTTClientName";
        Console.WriteLine(ClientId);

        MqttClientOptionsBuilder builder = new MqttClientOptionsBuilder().WithClientId(ClientId).WithTcpServer(MQTTUrl, 1883);
        ManagedMqttClientOptions options = new ManagedMqttClientOptionsBuilder()
                    .WithAutoReconnectDelay(TimeSpan.FromSeconds(60))
                    .WithClientOptions(builder.Build())
                    .Build();

        // Creates the client object
        _mqttClient = new MqttFactory().CreateManagedMqttClient();

        // Set up handlers

        _mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnConnected);
        _mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnDisconnected);
        _mqttClient.ConnectingFailedHandler = new ConnectingFailedHandlerDelegate(OnConnectingFailed);

        // Starts a connection with the Broker
        _mqttClient.StartAsync(options).Wait();
    }
    public bool IsConnected()
    {
        return _mqttClient.IsConnected;
    }

    public static void OnConnected(MqttClientConnectedEventArgs obj)
    {
        Console.WriteLine("Successfully connected.");
    }

    public static void OnConnectingFailed(ManagedProcessFailedEventArgs obj)
    {
        Console.WriteLine($"Couldn't connect to broker. {obj.Exception.Message}");
    }

    public static void OnDisconnected(MqttClientDisconnectedEventArgs obj)
    {
        Console.WriteLine("Successfully disconnected.");
    }

…do you have a way to verify the MQTT IP address you’re using is working properly outside the Meadow? I’m assuming the “IPADDRESS” constant in your code is replaced with the actual address to which you’re trying to connect…

Hi,

Yes. I have used the exact same code running in a console app on the PC debugging the meadow (same network) and it works fine. Yes, IPADDRESS is a constant thats replaced with the actual IP address.

Appreciate the response.

I’ve managed to get it to connect!

For anyone else that might have issues, what i did is below.

I then changed _socket = new Socket(SocketType.Stream, ProtocolType.Tcp); this to _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); in /Source/MQTTnet/Implementations/CrossPlatformSocket.cs in the constructor. See this branch Comparing dotnet:master...WildernessLabs:master · dotnet/MQTTnet · GitHub.

Build the MQTTnet libraries and added them as a dependency instead of the NUGET package and it should start working.

1 Like