Visual Studio 2015 – M2Mqtt

Running MQTT subscriver on VS2015 with M2Mqtt lib.

1 – Create new “console application project”;

2 – Open “nuget package manager”, search “m2mqtt” and install

m2mqtt

Edit this code with your settings:

using System;
using System.Text;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;

namespace MqttSubscriver
{
 public class Program
 { 

 private const string IotEndpoint = "127.0.0.1";
 private const int BrokerPort = 1883; // no SSL 1883 or SSL 8883;
 private const string user = "user";
 private const string pw = "password";


 public static void Main(string[] args)
 {
 var subscriber = new Program();
 subscriber.Subscribe();
 }

 public void Subscribe()
 {
 //convert to pfx using openssl
 //you'll need to add these two files to the project and copy them to the output
 //var clientCert = new X509Certificate2("YOURPFXFILE.pfx", "YOURPFXFILEPASSWORD");
 //this is the AWS caroot.pem file that you get as part of the download
 //var caCert = X509Certificate.CreateFromSignedFile("root.pem"); // this doesn't have to be a new X509 type...
 //var client = new MqttClient(IotEndpoint, BrokerPort, true, caCert, clientCert, MqttSslProtocols.None);

 var client = new MqttClient(IotEndpoint, BrokerPort, false, null, null, MqttSslProtocols.None);

 //event handler for inbound messages
 client.MqttMsgPublishReceived += ClientMqttMsgPublishReceived;

 //client id here is totally arbitary, but I'm pretty sure you can't have more than one client named the same.
 client.Connect("listener",user,pw);
 

 // '#' is the wildcard to subscribe to anything under the 'root' topic
 // the QOS level here - I only partially understand why it has to be this level - it didn't seem to work at anything else.
 client.Subscribe(new[] { "test" }, new[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE });

 while (true)
 {
 //listen good!
 }

 }

 public static void ClientMqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
 {
 Console.WriteLine("We received a message...");
 Console.WriteLine(Encoding.UTF8.GetChars(e.Message));
 }
 }
}

run and test with your mqtt publisher

see more here

Anúncios

Deixe uma Resposta

Preencha os seus detalhes abaixo ou clique num ícone para iniciar sessão:

Logótipo da WordPress.com

Está a comentar usando a sua conta WordPress.com Terminar Sessão / Alterar )

Imagem do Twitter

Está a comentar usando a sua conta Twitter Terminar Sessão / Alterar )

Facebook photo

Está a comentar usando a sua conta Facebook Terminar Sessão / Alterar )

Google+ photo

Está a comentar usando a sua conta Google+ Terminar Sessão / Alterar )

Connecting to %s