Giter Site home page Giter Site logo

paho.mqtt.m2mqtt's Introduction

M2Mqtt

MQTT Client Library for .Net and WinRT

Project Description

M2Mqtt is a MQTT client available for all .Net platforms (.Net Framework, .Net Compact Framework and .Net Micro Framework) and WinRT platforms (Windows 8.1, Windows Phone 8.1 and Windows 10) for Internet of Things and M2M communication.

MQTT, short for Message Queue Telemetry Transport, is a light weight messaging protocol that enables embedded devices with limited resources to perform asynchronous communication on a constrained network.

MQTT protocol is based on publish/subscribe pattern so that a client can subscribe to one or more topics and receive messages that other clients publish on these topics.

This sample is a library contains an MQTT client that you can use to connect to any MQTT broker. It is developed in C# language and works on all the following .Net platforms :

  • .Net Framework (up to 4.5)
  • .Net Compact Framework 3.5 & 3.9 (for Windows Embedded Compact 7 / 2013)
  • .Net Micro Framework 4.2 & 4.3
  • Mono (for Linux O.S.)

There is also the support for WinRT platforms :

  • Windows 8.1
  • Windows Phone 8.1
  • Windows 10

It can be used on Windows O.S, Windows Embedded Compact 7 / 2013 and Linux O.S. (thanks to Mono Project).

The project has an official website here : https://m2mqtt.wordpress.com/

The binaries for all platforms are also available as package from Nuget web site https://www.nuget.org/packages/M2Mqtt/

For all information about MQTT protocol, please visit official web site http://mqtt.org/.

Follow the project on Twitter @m2mqtt and Facebook.

Building the source code

The library is available for the following solution and project files :

  • M2Mqtt.sln : solution for Visual Studio that contains projects file for .Net Framework, .Net Compact Framework 3.9, .Net Micro Framework 4.2, .Net Micro Framework 4.3 and WinRT (a portable class library) for Windows 8.1, Window Phone 8.1 and Windows 10 applications
  • M2MqttVS2008.sln : solution for Visual Studio 2008 that contains project file for .Net Compact Framework 3.5;

To build sample based on .Net Micro Framework (4.2 and 4.3) you need to download .Net Micro Framework SDK from the official CodePlex web site : https://netmf.codeplex.com/

To build sample based on .Net Compact Framework 3.9 you need to download Application Builder for Windows Embedded Compact 2013 from here : http://www.microsoft.com/en-us/download/details.aspx?id=38819

SSL/TLS support

For SSL/TLS feature, the definition of the symbol "SSL" is needed before compile the project. On the repository, this symbol is already defined and all assemblies (needed for SSL/TLS) are referenced (for Debug and Release configuration). If you want to disable SSL/TLS feature, so that you can reduce memory occupation, you can delete "SSL" symbol and remove all assemblies referenced for SSL/TLS. However, you can leave the default project configuration and set "secure" parameter to false and "cacert" to null for MqttClient constructor (these are already default if you don't specify any values).

ATTENTION : .Net Micro Framework supports up to TLSV1

Example

The M2Mqtt library provides a main class MqttClient that represents the MQTT client to connect to a broker. You can connect to the broker providing its IP address or host name and optionally some parameters related to MQTT protocol.

After connecting to the broker you can use Publish() method to publish a message to a topic and Subscribe() method to subscribe to a topic and receive message published on it. The MqttClient class is events based so that you receive an event when a message is published to a topic you subscribed to. You can receive event when a message publishing is complete, you have subscribed or unsubscribed to a topic.

Following an example of client subscriber to a topic :

... 
 
// create client instance 
MqttClient client = new MqttClient(IPAddress.Parse(MQTT_BROKER_ADDRESS)); 
 
// register to message received 
client.MqttMsgPublishReceived += client_MqttMsgPublishReceived; 
 
string clientId = Guid.NewGuid().ToString(); 
client.Connect(clientId); 
 
// subscribe to the topic "/home/temperature" with QoS 2 
client.Subscribe(new string[] { "/home/temperature" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE }); 
 
... 
 
static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e) 
{ 
// handle message received 
} 

Following an example of client publisher to a topic :

... 
 
// create client instance 
MqttClient client = new MqttClient(IPAddress.Parse(MQTT_BROKER_ADDRESS)); 
 
string clientId = Guid.NewGuid().ToString(); 
client.Connect(clientId); 
 
string strValue = Convert.ToString(value); 
 
// publish a message on "/home/temperature" topic with QoS 2 
client.Publish("/home/temperature", Encoding.UTF8.GetBytes(strValue), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false); 
 
...

paho.mqtt.m2mqtt's People

Contributors

bobmarco avatar icraggs avatar jh-isw avatar jpwsutton avatar ppatierno avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

paho.mqtt.m2mqtt's Issues

Investigate potential application hang on publish

An IBM user reported that his application hung on publish. I think the issue is the client does not notify the application when the server closes the connection. Also, the client should throw an exception instead of queuing the message while not connected (unless we implement auto reconnect).

To reproduce the problem, write a simple application which does connect and then publish messages in a loop. Use another client to connect with the same clientId.

Problems With SSL and ClientCert on Windows 10 IoT Core

Hello!

I actually left this as a reply to Paolos Article.. regarding using M2Mqtt for Windows 10 IoT Core. but I thought maybe this could be interesting for more people so I will ask this question here also.. Also, after some more investigation I think I better understand the problem and am rephrasing my question :)

I'm currently building a "Local Agent" for an Central IoT Solution using Raspberry and Windows 10 IoT Core. We already have a Mqtt Broker set up and it works great for several different clients including, iOS, Windows and ESP8266. To handle basic security we use SSL (TLS1.2 Protocol) with a bought certificate from a trusted certificate authoritym (Verisign) we have both a Server Cert and Client Cert and I guess its the latter that is the problem in this case because I can actually connect to the server but cant get the client to publish or subscribe to any topics..

When instantiating the MqttNetworkChannel on WinRT we dont even have the option of using clientcert.. We need this to get it to work with the Raspberry, can you tell me the reason why it is omitted from the WinRT options?

Is the X509Certificate objects not available for UWP applications? Yes I know! I should test it my self, but I currently do not have the possibility and really need your feedback.

Anyone have thoughts or a solution to this?

Best regards and Merry Christmas to all of you!
Torbjörn Nilsson

No documentation provided

I struggling to find some documentation for the methods, specially for the following Connect method

public byte Connect(string clientId, string username, string password, bool cleanSession, ushort keepAlivePeriod);

what is the cleanSession and keepAlivePeriod means ?
Is there any documentation for the this library or not, even the Wiki is very weak.

the only documentation I found for them is
/// param name="cleanSession" Clean sessione flag
/// param name="keepAlivePeriod" Keep alive period
which is not enough at all, for example what is the unit of the keepAlivePeriod, is it in hours, days, seconds and what is the default value for it?

Thank you in advanced.

Messages not published on Disconnect

Hi, I created a unit-test to publish a single message:

  • connect
  • publish
  • disconnect
    and I noticed that sometime the message is not published.
    It happens because the message queue doesn't get flushed during the disconnect, and if the client gets collected by the garbage-collector, the the messages which are still in the queue will get lost.

Cannot Unsubscribe or Disconnect

Program needs to have the ability to unsubscribe from topics and disconnect from broker entirely. Cannot seem to do either.

When doing the unsubscribe - nothing is done - I check the broker and the topics are still subscribed to by the client. Have the unsubscribe event registered in the connect but do not get anything back method so the client is not unsubscribing from the topic.

Method Code posted below - as well as the Client Disconnect exception thrown each time I try to disconnect.

public void disconnectFromMQTT(List Topics)
{

        foreach (string t in Topics)
        {
           
            try
            {
                myClient.Unsubscribe(new [] { t });
            }
            catch(Exception e)
            {
                System.Windows.MessageBox.Show(Convert.ToString(e));
            }
        }
        
        try
        {
            myClient.Disconnect();
        }
        catch(Exception e)
        {
            System.Windows.MessageBox.Show(Convert.ToString(e));
        }
        
    }

Exception Thrown -

Exception thrown: 'uPLibrary.Networking.M2Mqtt.Exceptions.MqttCommunicationException' in M2Mqtt.Net.dll
uPLibrary.Networking.M2Mqtt.Exceptions.MqttCommunicationException ---> System.NullReferenceException: Object reference not set to an instance of an object.
at uPLibrary.Networking.M2Mqtt.MqttNetworkChannel.Send(Byte[] buffer) in c:\Users\ppatierno\Source\Repos\m2mqtt\M2Mqtt\Net\MqttNetworkChannel.cs:line 283
at uPLibrary.Networking.M2Mqtt.MqttClient.Send(Byte[] msgBytes) in c:\Users\ppatierno\Source\Repos\m2mqtt\M2Mqtt\MqttClient.cs:line 1002
--- End of inner exception stack trace ---
at uPLibrary.Networking.M2Mqtt.MqttClient.Send(Byte[] msgBytes) in c:\Users\ppatierno\Source\Repos\m2mqtt\M2Mqtt\MqttClient.cs:line 1015
at uPLibrary.Networking.M2Mqtt.MqttClient.Send(MqttMsgBase msg) in c:\Users\ppatierno\Source\Repos\m2mqtt\M2Mqtt\MqttClient.cs:line 1026
at uPLibrary.Networking.M2Mqtt.MqttClient.Disconnect() in c:\Users\ppatierno\Source\Repos\m2mqtt\M2Mqtt\MqttClient.cs:line 610
at MyHomeAuto.MQTT.disconnectFromMQTT(List`1 Topics) in G:\C#\Personal Programs\MyHomeAuto\MyHomeAuto\Classes\MQTT\MQTT.cs:line 86

Client certificate authentication

Hi,

How can i setup following configuration using M2MQTT in c#:
image
I'm trying to connect using client certificate and key file.

Thank you

Linux Mono 4.4.1: Build failed due to missing Tls11 and Tls12 definitions

Using Mono 4.4.1 the build fails.
Also please can you add a M2mqttMono.sln?

[andrea@laptop M2Mqtt]$ xbuild M2Mqtt.Mono.csproj
XBuild Engine Version 14.0
Mono, Version 4.4.1.0
Copyright (C) 2005-2013 Various Mono authors

Build started 9/18/2016 4:49:57 PM.


Project "/home/andrea/paho.mqtt.m2mqtt/M2Mqtt/M2Mqtt.Mono.csproj" (default target(s)):
Target PrepareForBuild:
Configuration: Debug Platform: AnyCPU
Target GenerateSatelliteAssemblies:
No input files were specified for target GenerateSatelliteAssemblies, skipping.
Target GenerateTargetFrameworkMonikerAttribute:
Skipping target "GenerateTargetFrameworkMonikerAttribute" because its outputs are up-to-date.
Target CoreCompile:
Tool /usr/lib/mono/4.5/mcs.exe execution started with arguments: /noconfig /debug:full /debug+ /optimize- /out:obj/Debug/M2Mqtt.Mono.dll Exceptions/MqttClientException.cs Exceptions/MqttCommunicationException.cs Exceptions/MqttConnectionException.cs Exceptions/MqttTimeoutException.cs IMqttNetworkChannel.cs Internal/InternalEvent.cs Internal/MsgInternalEvent.cs Internal/MsgPublishedInternalEvent.cs Messages/MqttMsgBase.cs Messages/MqttMsgConnack.cs Messages/MqttMsgConnect.cs Messages/MqttMsgConnectEventArgs.cs Messages/MqttMsgContext.cs Messages/MqttMsgDisconnect.cs Messages/MqttMsgPingReq.cs Messages/MqttMsgPingResp.cs Messages/MqttMsgPuback.cs Messages/MqttMsgPubcomp.cs Messages/MqttMsgPublish.cs Messages/MqttMsgPublishedEventArgs.cs Messages/MqttMsgPublishEventArgs.cs Messages/MqttMsgPubrec.cs Messages/MqttMsgPubrel.cs Messages/MqttMsgSuback.cs Messages/MqttMsgSubscribe.cs Messages/MqttMsgSubscribedEventArgs.cs Messages/MqttMsgSubscribeEventArgs.cs Messages/MqttMsgUnsuback.cs Messages/MqttMsgUnsubscribe.cs Messages/MqttMsgUnsubscribedEventArgs.cs Messages/MqttMsgUnsubscribeEventArgs.cs MqttClient.cs MqttSecurity.cs Net/Fx.cs Net/MqttNetworkChannel.cs MqttSettings.cs Properties/AssemblyInfo.cs Session/MqttBrokerSession.cs Session/MqttClientSession.cs Session/MqttSession.cs Utility/Trace.cs Utility/QueueExtension.cs /target:library /define:"DEBUG;SSL" /nostdlib /reference:/usr/lib/mono/4.0-api/System.dll /reference:/usr/lib/mono/4.0-api/System.Core.dll /reference:/usr/lib/mono/4.0-api/mscorlib.dll /warn:4
Messages/MqttMsgDisconnect.cs(53,17): warning CS0219: The variable remainingLength' is assigned but its value is never used Messages/MqttMsgPingReq.cs(69,17): warning CS0219: The variableremainingLength' is assigned but its value is never used
Messages/MqttMsgPingResp.cs(55,17): warning CS0219: The variable remainingLength' is assigned but its value is never used Messages/MqttMsgSubscribe.cs(111,17): warning CS0219: The variablereceived' is assigned but its value is never used
Messages/MqttMsgUnsubscribe.cs(98,17): warning CS0219: The variable received' is assigned but its value is never used MqttClient.cs(690,30): warning CS0168: The variablee' is declared but never used
MqttClient.cs(2482,47): warning CS0168: The variable e' is declared but never used Net/MqttNetworkChannel.cs(444,41): error CS0117:System.Security.Authentication.SslProtocols' does not contain a definition for Tls11' /usr/lib/mono/4.0-api/System.dll (Location of the symbol related to previous error) Net/MqttNetworkChannel.cs(446,41): error CS0117:System.Security.Authentication.SslProtocols' does not contain a definition for `Tls12'
/usr/lib/mono/4.0-api/System.dll (Location of the symbol related to previous error)
Task "Csc" execution -- FAILED
Done building target "CoreCompile" in project "/home/andrea/paho.mqtt.m2mqtt/M2Mqtt/M2Mqtt.Mono.csproj".-- FAILED
Done building project "/home/andrea/paho.mqtt.m2mqtt/M2Mqtt/M2Mqtt.Mono.csproj".-- FAILED

Build FAILED.

Warnings:

/home/andrea/paho.mqtt.m2mqtt/M2Mqtt/M2Mqtt.Mono.csproj (default targets) ->
/usr/lib/mono/4.5/Microsoft.CSharp.targets (CoreCompile target) ->

Messages/MqttMsgDisconnect.cs(53,17): warning CS0219: The variable `remainingLength' is assigned but its value is never used
Messages/MqttMsgPingReq.cs(69,17): warning CS0219: The variable `remainingLength' is assigned but its value is never used
Messages/MqttMsgPingResp.cs(55,17): warning CS0219: The variable `remainingLength' is assigned but its value is never used
Messages/MqttMsgSubscribe.cs(111,17): warning CS0219: The variable `received' is assigned but its value is never used
Messages/MqttMsgUnsubscribe.cs(98,17): warning CS0219: The variable `received' is assigned but its value is never used
MqttClient.cs(690,30): warning CS0168: The variable `e' is declared but never used
MqttClient.cs(2482,47): warning CS0168: The variable `e' is declared but never used

Errors:

/home/andrea/paho.mqtt.m2mqtt/M2Mqtt/M2Mqtt.Mono.csproj (default targets) ->
/usr/lib/mono/4.5/Microsoft.CSharp.targets (CoreCompile target) ->

Net/MqttNetworkChannel.cs(444,41): error CS0117: `System.Security.Authentication.SslProtocols' does not contain a definition for `Tls11'
Net/MqttNetworkChannel.cs(446,41): error CS0117: `System.Security.Authentication.SslProtocols' does not contain a definition for `Tls12'

 7 Warning(s)
 2 Error(s)

Time Elapsed 00:00:00.4237460

Unable to connect to MQTT broker: MqttCommunicationException

I'm getting a generic "Exception of type 'uPLibrary.Networking.M2Mqtt.Exceptions.MqttCommunicationException' was thrown." while trying to connect to an MQTT broker. I can connect to the broker just fine using MQTT.fx, and I can connect to another MQTT broker just fine using the M2MQTT libraries, so I'm thinking that the client isn't compatible with this particular broker for some reason.

Is there some way to get additional logging details or a deeper view into what's going wrong?

TLS (AWS IoT) support for Windows 10 IoT Core

I see that the Client constructor that includes the two x509 certs is missing when I nuget into a Visual Studio Windows Universal project. I don't think I can connect a Windows 10 IoT Core device to the AWS IoT service any other way (TLS is required). Is support on the dev roadmap? Is it a simple enough solution for me to implement in the source (and drop the use of nuget for now)?

Receive Thread hangs system in tight loop when server side drops connection

On a Windows client, the Receive thread can enter an infinite loop if the connection is closed first by the remote end. This loop consumes the CPU and other threads can not run.

When ReceiveThread() reads the socket, "read" then immediately returns 0, and the loop calls OnConnectionClosing which signals the Dispatch thread. The thread then loops back to the "read" and proceeds again to OnConnectionClosing. Since it already signalled the Dispatch thread, OnConnectionClosing has no effect. Once in this loop, the thread does not block and does not yield the CPU. Regardless of the client OS, ReceiveThread should not execute more than one iteration through this loop. After signalling the DispatchThread, it should block until DispatchThread has closed the local connection. A fix uses a ManualResetEvent to block ReceiveThread until it is released by the DispatchThread. Using a Manual rather than Auto ResetEvent allows the ReceiveThread to complete after the local close whether or not it has reached the blocking WaitOne().

SSL/TLS client authentication sample implementation

HI,

it seems m2mqtt now support SSL/TLS client authentication, but I haven't found any good implementation doc about it. Can anyone help me to get a good article or blog post where SSL/TLS client authentication described? Actually, I want to connect with mosquitto broker using SSL/TLS client authentication.

SSL/TLS for UWP?

I am working on a UWP app and it will use AWS mqtt. But my MqttClient is missing those ctors with X509Certificates.
Is there any workaround? I tried using a class library, but UWP app can only ref to UW libraries (which don't have those ctors as well) and portable library (which I can't even install M2Mqtt)

MqttClient.Connect willMessage parameter should be byte[], not string.

The LWT message is supposed to be for all intents and purposes just another normal mqtt message that just has special delivery conditions. Therefore the payload for this message should not be treated any differently than any other message. It makes no sense for the type for this payload to be a string, when the type for all other messages is byte[]

How to identify Reason for connection Failure

Hi I am using M2mqtt with unity . every thing works fine but when my connection fails i need the reason to be displayed on screen so that user can identify . As mqtt python client has a callback which gives return codes
0: Connection successful
1: Connection refused – incorrect protocol version
2: Connection refused – invalid client identifier
3: Connection refused – server unavailable
4: Connection refused – bad username or password
5: Connection refused – not authorised
6-255: Currently unused.
Is there any method in this m2mqtt through which we can identify the connect failure reason .

I have found that i can receive an byte code but even before that Exception is being thrown and i am unable to receive the connack code . How to solve this .

Here is the code
byte connack=client.Connect (client_id, userName, password,false,3);
Debug.Log ("Client Connection status..."+connack.ToString());

//Log is not getting printed;

How to build M2Mqtt with SSL function for .NET CF 3.5?

Hi, I have a question. I want to use M2Mqtt on my WinCE 7.0 device for connecting AWS or Azure, so I need the SSL/TLS function. But .NET CF 3.5 does not support System.Net.Security and System.Security.Authentication. How could I build M2Mqtt with the SSL function for .NET CF 3.5? Thanks.

broker on local pc - as string format unknown, or not accepted

I am trying out the client;

The code below will run, without a hitch, although it is deprecated.
When I try it with 'server' directly (as commented out below), it won't fly.

What is the format needed to indicate a host on the local network? (server.homenet also didn't take)

Tx

if (_mqttClient == null)
            {
               
                try
                {
                    //IPHostEntry entry = Dns.GetHostEntry(ipaddress);
                    IPAddress[] ip = Dns.GetHostAddresses("server");
                    IPAddress ipaddres = ip[2];
                    _mqttClient = new MqttClient(ipaddres);
                    //_mqttClient = new MqttClient("server");
                    _mqttClient.MqttMsgPublishReceived += _mqttClient_MqttMsgPublishReceived;
                    _mqttClient.Connect("TestClient");
                }
                catch (Exception ex)
                {
                    
                }
}

Bounds checking of the packet's remaining length

In https://github.com/eclipse/paho.mqtt.m2mqtt/blob/master/M2Mqtt/Messages/MqttMsgBase.cs the two methods encodeRemainingLength() and decodeRemainingLength() do not enforce the correct bound checking, which could lead to uncontrolled behaviour.

The specification http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718023 states:

The Remaining Length is encoded using a variable length encoding scheme which uses a single byte for values up to 127. Larger values are handled as follows. The least significant seven bits of each byte encode the data, and the most significant bit is used to indicate that there are following bytes in the representation. Thus each byte encodes 128 values and a "continuation bit". The maximum number of bytes in the Remaining Length field is four.

Connecting to azure using .Net Compact Framework 3.9 on WINCE2013

Hello, I have been using the .netcf3.9 for connecting to azure on WINCE2013. But my problem is that when I try to run the code it says that "The library is compiled without SSL Support". And as azure doesnt communicate without SSL support there is no connection established.It seems like the SSL symbol is not enabled as written in their README file(m2mqtt). If anyone has worked on WINCE2013 for azure connection please share some info..Thanks in Advance.

M2Mqtt dependency

I upgraded nuget to 2.12 and install M2MqttDotnetCore 1.0.3

I compile a small app and try run it on Ubuntu 16.04

I got an error:

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'M2Mqtt, Version=4.3.0.0, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.

at onewayticket_core_mqtt.Client..ctor()
at onewayticket_core_mqtt.Program.Main(String[] args) in /home/andrei/src/examples/core/onewayticket-core-mqtt/Program.cs:line 16

Please help me, how to reslove this.

CPU Leak if you specify Username/password

Hi,

Im using M2MQTT from https://www.nuget.org/packages/M2Mqtt/
IF i create a client and specify a user name the CPU usgae goes up by 25% and stays there even if the connection fails due to wrong credentials. And next call to connect will increment the CPU usage by 25%

So if you have multiple thread connecting to MQTT server, after a couple of calls the CPU reached 100% and crashes.
Following code can reproduce the issue, add it to a Console application .Net 4.5 or greater:

            Console.WriteLine("start?");
            Console.Read();
            Console.WriteLine("starting, please monitor the CPU usage.");
            List < MqttClient > l = new List<MqttClient>();
            for (int i = 0; i < 10; i++)
            {
                var client = new MqttClient(
                "test.mosquitto.org"
                , 1883
                , false
                , null
                , null
                , new MqttSslProtocols());
                client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
                try
                {
                    client.Connect(Guid.NewGuid().ToString(), "ss", null);//intentionally making it fail with wrong credentials
                }
                catch(Exception ex) { Console.WriteLine("Error");  }
                l.Add(client);
            }            

            Console.WriteLine("Exit?");
            Console.Read();```

Feature Request: Automatic Reconnect

Is it posssible to implement a reconnect since now if the client connection drops the client takeover is not happening and I think we get left with an half-open connection

Feature Request: Get "Subscription-Topic" in MqttMsgPublishReceived

In MqttMsgPublishReceived via MqttMsgPublishEventArgs you get the actual Topic for the message,
but you do not get the Subscription for the Topic.

So, if you subscribe to ALARM/# and NOTIFICATION/# with same client and you get a message via event,
and you have to know which subscription 'caused the message, you can just decide with some custom string comparing code...

It would be nice to get also the "Subscription" next to Topic via the EventArgs.

(Does MQTT send the subscription that 'triggered the message sending or only actual Topic is sent?)

Version for 3.5 missing in Nuget

I am trying to use m2mqtt in our unity-playground. Using nuget on the commandline (on mac) only produces versions for 3.9/4.2/4.3/4.5.
Is 3.5 not supported any more (at least the README says it is) ?

TopicsQosLevelsNotMatch exception in MqttMsgSubscribe not being raised at user code level

I made a mistake in trying some of the demo code, in that I was subscribing to two queues, but only passing in a single QOS level.

            string clientId = Guid.NewGuid().ToString();
            client.Connect(clientId);

            string[] topic = { "sensor/temp", "sensor/humidity" };

            byte[] qosLevels = { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE };

This caused an exception to be thrown:

uPLibrary.Networking.M2Mqtt.Exceptions.MqttClientException was unhandled
Message: An unhandled exception of type 'uPLibrary.Networking.M2Mqtt.Exceptions.MqttClientException' occurred in M2Mqtt.Net.dll

(I was using the NuGet 4.3.0 code for this.) I couldn't catch this exception and handle it, because the true exception does not make it to the user's level. Nor could I find out what the actual exception was.

When I compiled the m2mqtt code from GitHub, I debugged it and found that MqttMsgSubscribe.GetBytes() was throwing a TopicsQosLevelsNotMatch exception:

uPLibrary.Networking.M2Mqtt.Exceptions.MqttClientException occurred
  HResult=-2146233088
  Message=Exception of type 'uPLibrary.Networking.M2Mqtt.Exceptions.MqttClientException' was thrown.
  Source=M2Mqtt.Net
  StackTrace:
       at uPLibrary.Networking.M2Mqtt.Messages.MqttMsgSubscribe.GetBytes(Byte protocolVersion) in C:\Users\Patrick Gardella\Documents\Visual Studio 2015\Projects\paho.mqtt.m2mqtt\M2Mqtt\Messages\MqttMsgSubscribe.cs:line 187
  InnerException: 

It is the MqttClient.Send() that ignores the throw exceptions: M2Mqtt.Net.dll!uPLibrary.Networking.M2Mqtt.MqttClient.Send(uPLibrary.Networking.M2Mqtt.Messages.MqttMsgBase msg) Line 1029

Clearly I can avoid this now that I know what was wrong, but it would be good to either log the exception or raise it to the user's level.

Thanks for all your great work on this!

Patrick+

Full Xamarin support

Xamarin support of this MQTT client would be awesome. If you just add the NuGet package from nuget.org to a Xamarin project, your Xamarin project will not build anymore.

A workaround is to use the Mono implementation of this client:
In order to get the M2Mqtt.Mono.dll just open the Mono project that you can find in ./M2Mqtt/M2Mqtt.Mono.csproj. Now try to build the project in release. It may happen that you need to fix a little bit of the code. In our case it was just a broken enum which was an easy fix. When the build completed without errors, you will find the M2Mqtt.Mono.dll in ./M2Mqtt/obj/Release/M2Mqtt.Mono.dll.

However, some problems occur for iOS:
It seems to work at first but we encountered some problems when the app goes to background and lost its connection. It's easy to reproduce when you put the app to the background by clicking on the home button and then turn on the flight mode of your iOS device –> when the timeout is over (which should be around 30 seconds) the app will crash when you are trying to publish a message. The problem I got is that the we have a check just before we publish a message, if the client is still connected. This check returns always true in background, even when the timeout is over.

This is the exception:

Object name: 'System.Net.Sockets.NetworkStream'.
at System.Net.Sockets.NetworkStream.Write (System.Byte[] buffer, System.Int32 offset, System.Int32 size) [0x000e8] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/System/net/System/Net/Sockets/NetworkStream.cs:602
at Mono.Net.Security.MobileAuthenticatedStream.InnerFlush () [0x00011] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/System/Mono.Net.Security/MobileAuthenticatedStream.cs:561
at Mono.Net.Security.MobileAuthenticatedStream.InnerWrite () [0x00000] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/System/Mono.Net.Security/MobileAuthenticatedStream.cs:555
at Mono.Net.Security.AsyncProtocolRequest.ProcessOperation (Mono.Net.Security.AsyncOperationStatus status) [0x0006b] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/System/Mono.Net.Security/AsyncProtocolRequest.cs:267
at Mono.Net.Security.AsyncProtocolRequest.ProcessOperation () [0x0000d] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/System/Mono.Net.Security/AsyncProtocolRequest.cs:218
at Mono.Net.Security.AsyncProtocolRequest.StartOperation () [0x00000] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/System/Mono.Net.Security/AsyncProtocolRequest.cs:199
--- End of inner exception stack trace ---
at Mono.Net.Security.MobileAuthenticatedStream.StartOperation (Mono.Net.Security.AsyncProtocolRequest& nestedRequest, Mono.Net.Security.BufferOffsetSize2& internalBuffer, Mono.Net.Security.AsyncOperation operation, Mono.Net.Security.AsyncProtocolRequest asyncRequest, System.String name) [0x00047] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/System/Mono.Net.Security/MobileAuthenticatedStream.cs:369
at Mono.Net.Security.MobileAuthenticatedStream.Close () [0x00028] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/System/Mono.Net.Security/MobileAuthenticatedStream.cs:742
at System.IO.Stream.Dispose () [0x00000] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/io/stream.cs:260
at System.Net.Security.SslStream.Dispose (System.Boolean disposing) [0x00011] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/System/System.Net.Security/SslStream.cs:346
at System.IO.Stream.Close () [0x00000] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/io/stream.cs:248
at uPLibrary.Networking.M2Mqtt.MqttNetworkChannel.Close () [0x00016] in <9ef9813e67f247b6aa9565dfe6ded04e>:0
at uPLibrary.Networking.M2Mqtt.MqttClient.Close () [0x00079] in <9ef9813e67f247b6aa9565dfe6ded04e>:0
at uPLibrary.Networking.M2Mqtt.MqttClient.DispatchEventThread () [0x001b0] in <9ef9813e67f247b6aa9565dfe6ded04e>:0
at System.Threading.ThreadHelper.ThreadStart_Context (System.Object state) [0x00017] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/threading/thread.cs:68
at System.Threading.ExecutionContext.RunInternal (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state, System.Boolean preserveSyncCtx) [0x0008d] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/threading/executioncontext.cs:957
at System.Threading.ExecutionContext.Run (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state, System.Boolean preserveSyncCtx) [0x00000] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/threading/executioncontext.cs:904
at System.Threading.ExecutionContext.Run (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state) [0x00031] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/threading/executioncontext.cs:893
at System.Threading.ThreadHelper.ThreadStart () [0x0000b] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/threading/thread.cs:105

Infinite/endless loop in case of incorrect authententication -> burning THREAD/CORE

If Server is reachable, but for example password is incorrect,
then Connect() returns correctly 5 as unsuccessful connect,
but underlying MqttClient/MqttNetworkChannel remains in endless loop, burning the thread/core.

As I figured out ReceiveThread() calls OnConnectionClosing(),
but isRunning= false set only in Close() which is never called in this case from DispatchEventThread().
-->> endless loop burning one core, never ending.

(calling Disconnect in case of returning "5" not helps :( )

If I will have time, I try to understand more deeply to be enough brave to commit a fix.

NetMF TLS without client cert

When trying to connect when not using a client certificate in netmf v4.3.1 e.g.
MqttClient mqttc = new MqttClient(iotBrokerAddress, 8883, true, null, null, MqttSslProtocols.TLSv1_0);

An exception is thrown. This could be fixed by changing the server authentication code around line 245 in MqttNetworkChannel.cs to

// server authentication (SSL/TLS handshake)
#if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3)

                if (this.clientCert != null)
                {
                    this.sslStream.AuthenticateAsClient(this.remoteHostName,
                        this.clientCert,
                        new X509Certificate[] { this.caCert },
                        SslVerification.CertificateRequired,
                        MqttSslUtility.ToSslPlatformEnum(this.sslProtocol));
                }
                else
                {
                    this.sslStream.AuthenticateAsClient(this.remoteHostName, MqttSslUtility.ToSslPlatformEnum(this.sslProtocol));
                }
#else

Using M2MQTT with proxy

Hi guys,

I want to use the MQTT library for C# in my project. Unfortunately we have a HTTP-proxy between the MQTT-client and the broker.
Do we have any possibility to get this setup working?

Best regards
Dominik

Problem integrating into Unity3D, not a lot of help in the error message.

When trying to connect to a server using ssl certs the library throws a MqttCommunicationException with no other information.

I've tracked the location of the error to MqttClient.cs line 1100. It seems to be caused by a message being sent but the broker failing to respond before the timeout. The strange thing is that the broker never gets a message that a connection was attempted and certainly doesn't show it failed or was rebuffed.

Has anyone attempted to integrate this library in Unity3D AND used ssl to authenticate with an external broker?

Here is how the code looks to create the client and ask the client to connect:

Debug.Log("MQTTNetwork::Awake Decrypting SSL cert...");

 string caCertLoc = Application.streamingAssetsPath + "\\cacert.cer";

 string clientCertLoc = Application.streamingAssetsPath + "\\keycert.p12";

 X509Certificate2 caCert = new X509Certificate2(caCertLoc, "1313");

 X509Certificate2 clientCert = new X509Certificate2(clientCertLoc, "1313");

 m_client = new MqttClient("127.0.0.1", 8883, true, caCert, clientCert, MqttSslProtocols.TLSv1_0);

_client.Connect(clientId, "XXXXXXX", "XXXXXXX");```

If [brokerHostName] specified MqttNetworkChannel could cause Ex in constructor

If DNS specified in MqttClient constructor via brokerHostNames,
and IP cannot be looked up because machine is offline, DNS lookup is not available,
MqttClient constructor will fail.

(IPHostEntry hostEntry = Dns.GetHostEntry(remoteHostName); will fail in MqttNetworkChannel)

Sometimes you want to create the MqttClient, but connect later as machine comes online, etc.
This way instance cannot be created in advance with DNS name, just only with IP-address.

timeout on MQTTClient_waitfor()

Paho C MQTT APIs compiled with VisualStudio 2015
I want to send message to IoT Hub.
I have a timeout on Thread_wait_sem()
I use this configuration:
"DeviceAcoem"
, "\n"
, 100
, 0
, 0
, "xxx.azure-devices.net/DeviceAcoem"
, "SharedAccessSignature sr=xxx.azure-devices.net%2fdevices%2fDeviceAcoem&sig=3DO9XHIa0igyCYdYp%2bTd2VwPkROxiRvEAIQK3X9Uqg4%3d&se=1501234285"
, "xxx.azure-devices.net"
, "1883"
, 1

Thanks for your reply

Not detect when disconnect

Hi,

Library is not detect when disconnect.

Scenario: Library is connect to any mqtt server and internet is disconnect (or disable wifi). Now, Should be run Mqtt_ConnectionClosed event but not run.

Best regard.

Inflight thread in .NET MqttClient crashes (and the whole application) if exception is thrown inside the thread

The following code makes application crash. Problem is that when MqttMsgPublish.GetBytes() function makes check for wildcards inside the topic name while publishing message, it (reasonably) throws exception MqttClientException(MqttClientErrorCode.TopicWildcard) (line 107 of the file MqttMsgPublish.cs). This exception is NOT handled anywhere in inflight threads and makes the whole app crashing. I suggest to move this and other related checks from GetBytes() function to MqttClient.Publish() function or make some notification mechanism for errors in inflight thread.

static void Main(string[] args)
        {
            MqttClient mqtt = new MqttClient("servername");
            mqtt.Connect(Guid.NewGuid().ToString());
            string topic = "/h1/+"; // <--- INVALID TOPIC HERE (wildcards)
            mqtt.Publish(topic, Encoding.UTF8.GetBytes("Hello".ToCharArray()));

            Console.ReadLine();
        }

cannot connect to Mqtt broker on SSL

I have a MQTT broker exposing port 443, not the default 1883. I tried to connect to it with the following code, however always failed. (The code is based on .net core 1.1)

X509Certificate caCert = new X509Certificate(Directory.GetCurrentDirectory() + "/Certs/Production/Certificate.crt.cer");

X509Certificate clientCert = new X509Certificate(Directory.GetCurrentDirectory() + "/Certs/Production/CN_Certificate.crt.cer");

MqttClient client = new MqttClient(brokerHostName, 443, true, caCert, clientCert, MqttSslProtocols.TLSv1_2);

The stack trace is as below:

at uPLibrary.Networking.M2Mqtt.MqttClient.Connect(String clientId, String username, String password, Boolean willRetain, Byte willQosLevel, Boolean willFlag, String willTopic, String willMessage, Boolean cleanSession, UInt16 keepAlivePeriod)
at uPLibrary.Networking.M2Mqtt.MqttClient.Connect(String clientId, String username, String password)
at Test.Program.Main(String[] args) in /Users/xzhou/Projects/DysonChatbot/Test/Program.cs:line 50

By capturing the network trace, I can only see the client hello traffic, no server hello returned. But everything with the same setting works with JAVA paho MQTT client (test with MQTT.fx, where only client cert is required to set in the GUI, no server side cert is required). So, I guess there is some issue lying in this mqtt client implementation?

X509 Authentication with IoT Hub & C# not working

I'm trying the following code, but no messages are ever posted to IoT Hub

var deviceId = "2c8540ee-85df-4f1a-b35f-00124e1d3c4a";

var caCert = new X509Certificate2("c:\\certs\\iothub_ca.crt");   // From https://github.com/Azure/azure-iot-sdk-c/blob/master/certs/certs.c
var clientCert = new X509Certificate2("C:\\certs\\device.pfx");

var client = new MqttClient(
    "my-iot-hub.azure-devices.net", 
    MqttSettings.MQTT_BROKER_DEFAULT_SSL_PORT, true,
    caCert,
    clientCert,
    MqttSslProtocols.TLSv1_2);
    
client.Connect(deviceId);

client.Publish($"devices/{deviceId}/messages/events/", Encoding.UTF8.GetBytes("Hello"));

I've verified that my device.pfx file works with the IoT Hub Device SDK, but nothing I try with MqttClient is working.

Additionally, there appears to be some sort of resource leak because my cpu creeps up every time I call client.Publish, but never comes back down.

M2Mqtt auto reconnect

Hey, any info if you gonna work in the reconnect feature or any solution for that?
Thanks

Only one of two clients working

I'm writing a program that translates MQTT messages from one form into another form.
The platform is Windows IOT Core on Raspberry Pi 3, I'm writing an UWP application.
It seems that of the two clients that are connected to the same broker, only one of them is emitting messages. The Publish() action on the second client passes without complaining, but nothing arrives at the broker. Even though I'm using exactly the same Publish code on both clients.
Any thoughts/ideas on this ?

Installing M2MQTT for project that targets MonoAndroid, M2MQTT doesn't contain reference for that.

I am trying to install M2MQTT in Xamarin.Android project and getting this:

Could not install package 'M2Mqtt 4.3.0'. You are trying to install this package into a project that targets 'MonoAndroid,Version=v6.0', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

Is there any workaround/solution to this. I have checked with Nuget and everything else, its working fine.
Nuget 3.4, Visual Studio 2015.
Thanks in Advance.

Issue Receiving Messages

Using an EMQTT broker on my raspberry pi. From the broker's web interface I can see that I am connected, but subscriptions dont seem to work.

When using the iot.eclipse.org site I can subscribe perfectly (a bit too perfect when "#" ). So perhaps its not the failure to subscribe but failure to receive message from the broker?

Any ideas?

Disconnect() method throws exception in Mono when connected using SSL/TLS

I recently downloaded the M2Mqtt solution and built the M2Mqtt.Mono project for use with Xamarin.iOS. I originally wrote code to connect insecurely to an EMQTT broker running in the cloud. Later, I switched to an encrypted connection, and calling MqttClient.Disconnect() causes an unhandled exception thrown somewhere in unmanaged code. While I realize that there are many layers of things that could cause this to go wrong, the same code that works for an unencrypted client connection does not work for an encrypted connection. This leads me to believe that the issue is with the M2Mqtt library (at least when it is running in Mono).

This code will cause a crash:

MqttClient client = new MqttClient(hostname, 8883, true, certificate, null, MqttSslProtocols.TLSv1_2);
client.Connect("app", "username", "password", true, 10);
// subscribe to topics, etc....
client.Disconnect(); // causes crash

This code will not cause a crash:

MqttClient client = new MqttClient(hostname, 1883, false, null, null, MqttSslProtocols.None);
client.Connect("app", "username", "password", true, 10);
// subscribe to topics, etc....
client.Disconnect();

In both cases, everything connects to the broker and is able to publish/subscribe without an issue. The Disconnect() method is the only thing that I have noticed to be broken, and only when using SSL/TLS.

I am not willing to sacrifice the secure connection to be able to disconnect from the broker, and it is not mission-critical for me to do so. However, I would like to be able to close the connection in a situation like when app is backgrounded, etc., without crashing the application.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.