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.");
}