Skip to content

Instantly share code, notes, and snippets.

@KeesCBakker
Last active February 15, 2024 12:10
Show Gist options
  • Save KeesCBakker/d8e093c237bf939004f830406cb35c09 to your computer and use it in GitHub Desktop.
Save KeesCBakker/d8e093c237bf939004f830406cb35c09 to your computer and use it in GitHub Desktop.
Settings to connect to MQTT using M2Mqtt (can be used with CloudMqtt)
using System.ComponentModel.DataAnnotations;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
var settings = AppSettingsProvider.Create<MqttSettings>();
var port = Convert.ToInt32(settings.Port);
MqttClient client = null;
if (settings.UseSecureConnection)
{
client = new MqttClient(settings.BrokerHostName, port, true, null, null, MqttSslProtocols.TLSv1_2);
}
else
{
client = new MqttClient(settings.BrokerHostName, port, false, null, null, MqttSslProtocols.None);
}
client.Connect(Guid.NewGuid().ToString(), settings.UserName, settings.Password);
client.Subscribe(new string[] { settings.Topic }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
class MqttSettings
{
[Required]
public string BrokerHostName { get; set; }
[Required]
public uint Port { get; set; }
[Required]
public bool UseSecureConnection { get; set; }
[Required]
public string UserName { get; set; }
[Required]
public string Password { get; set; }
[Required]
public string Topic { get; set; }
}
@cgtamayo
Copy link

Thanks!! it worked with hivemq!
URL: .s2.eu.hivemq.cloud
Port: 8883
new =MqttClient(brokerIpAddressVariable.Value,8883,true,null,null,MqttSslProtocols.TLSv1_2)

@YC-Michael
Copy link

Thanks!! it worked with hivemq! URL: .s2.eu.hivemq.cloud Port: 8883 new =MqttClient(brokerIpAddressVariable.Value,8883,true,null,null,MqttSslProtocols.TLSv1_2)

Hi, I'm unable to connect to hivemq cloud... did u simply parse in the URL?

@cgtamayo
Copy link

Thanks!! it worked with hivemq! URL: .s2.eu.hivemq.cloud Port: 8883 new =MqttClient(brokerIpAddressVariable.Value,8883,true,null,null,MqttSslProtocols.TLSv1_2)

Hi, I'm unable to connect to hivemq cloud... did u simply parse in the URL?

Yes, set the URL without port. Each console have an unique url you should access to your cluster and copy the one it's asigned to you.
https://console.hivemq.cloud/

MqttClient client = new MqttClient ("##########.s2.eu.hivemq.cloud");

@YC-Michael
Copy link

Thanks!! it worked with hivemq! URL: .s2.eu.hivemq.cloud Port: 8883 new =MqttClient(brokerIpAddressVariable.Value,8883,true,null,null,MqttSslProtocols.TLSv1_2)

Hi, I'm unable to connect to hivemq cloud... did u simply parse in the URL?

Yes, set the URL without port. Each console have an unique url you should access to your cluster and copy the one it's asigned to you. https://console.hivemq.cloud/

MqttClient client = new MqttClient ("##########.s2.eu.hivemq.cloud");

Oh, I have the url. I was referring to running M2Mqtt on Unity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment