Giter VIP home page Giter VIP logo

mqtt's Introduction

Introduction

Code name: Hermes (messenger of the Greek gods)

Build Status Client Downloads Server Downloads

MQTT is a Client Server publish/subscribe messaging transport protocol, designed to be lightweight, open and simple to use and implement. This makes it suitable for Internet of Things (IoT) messaging, machine to machine communication, mobile devices, etc.

System.Net.Mqtt is a lightweight and simple implementation of the MQTT protocol version 3.1.1, written entirely in C# and divided in two libraries: System.Net.Mqtt and System.Net.Mqtt.Server.

The foundation of the System.Net.Mqtt libraries is to provide an intuitive and very easy to use API, hiding most of the protocol concepts that don't need to be exposed, letting consumers just focus on the main protocol operations, which are: CONNECT, SUBSCRIBE, UNSUBSCRIBE, PUBLISH, DISCONNECT.

All the protocol packets acknowledgement happens under the hood in an asynchronous way, adding a level of simplicity reduced to just awaiting the client method calls in a native .net style without worring about low level protocol concepts.

Also, the reception of the subscribed messages is handled using an IObservable implementation, which makes the stream of messages to receive more natural and aligned to the concept of Publish/Subscribe on which the protocol already relies. Finally, this allows subscribers of the received messages to query and filter them using Reactive Extensions, which adds an extra level of flexibility and control over the messages processing.

Usage samples

  • Creating and connecting an MQTT client with default options:

      var configuration = new MqttConfiguration();	
      var client = await MqttClient.CreateAsync("192.168.1.10", configuration);
      var sessionState = await client.ConnectAsync (new `MqttClientCredentials`(clientId: "foo"));
    

    The ConnectAsync method returns once the CONNACK packet has been received from the Server.

    The session state value contains information about if the session has been re used or cleared

  • Creating and connecting an MQTT client specifying configuration and clean session:

      var configuration = new MqttConfiguration {
      	BufferSize = 128 * 1024,
      	Port = 55555,
      	KeepAliveSecs = 10,
      	WaitTimeoutSecs = 2,
      	MaximumQualityOfService = MqttQualityOfService.AtMostOnce,	
      	AllowWildcardsInTopicFilters = true };
      var client = await MqttClient.CreateAsync("192.168.1.10", configuration);
      var sessionState = await client.ConnectAsync (new `MqttClientCredentials`(clientId: "foo"), cleanSession: true);
    

    The ConnectAsync method returns once the CONNACK packet has been received from the Server

  • Subscribing and unsubscribing to topics:

      await client.SubscribeAsync("foo/bar/topic1", MqttQualityOfService.AtMostOnce); //QoS0
      await client.SubscribeAsync("foo/bar/topic2", MqttQualityOfService.AtLeastOnce); //QoS1
      await client.SubscribeAsync("foo/bar/topic3", MqttQualityOfService.ExactlyOnce); //QoS2
    

    The SubscribeAsync method returns once the SUBACK packet has been received from the Server

      await client.UnsubscribeAsync("foo/bar/topic1");
      await client.UnsubscribeAsync("foo/bar/topic2");
      await client.UnsubscribeAsync("foo/bar/topic3");
    

    The UnsubscribeAsync method returns once the UNSUBACK packet has been received from the Server

  • Reception of messages from the subscribed topics:

      client
      	.MessageStream
      	.Subscribe(msg => Console.WriteLine($"Message received in topic {msg.Topic}"));
      	
      client
      	.MessageStream
      	.Where(msg => msg.Topic == "foo/bar/topic2")
      	.Subscribe(msg => Console.WriteLine($"Message received in topic {msg.Topic}"));`
    
  • Publishing messages to topics:

      var message1 = new MqttApplicationMessage("foo/bar/topic1", Encoding.UTF8.GetBytes("Foo Message 1"));
      var message2 = new MqttApplicationMessage("foo/bar/topic2", Encoding.UTF8.GetBytes("Foo Message 2"));
      var message3 = new MqttApplicationMessage("foo/bar/topic3", Encoding.UTF8.GetBytes("Foo Message 3"));
    
      await client.PublishAsync(message1, MqttQualityOfService.AtMostOnce); //QoS0
      await client.PublishAsync(message2, MqttQualityOfService.AtLeastOnce); //QoS1
      await client.PublishAsync(message3, MqttQualityOfService.ExactlyOnce); //QoS2
    

    The PublishAsync method returns once the corresponding ACK packet has been received from the Server, based on the configured QoS

  • Disconnecting an MQTT client:

      await client.DisconnectAsync();
    

Installing

System.Net.Mqtt and System.Net.Mqtt.Server are distributed as [NuGet][1] packages and can be installed from Visual Studio by searching for the "System.Net.Mqtt" packages or by running the following commands from the Package Manager Console:

Client Package: Install-Package System.Net.Mqtt -Pre

Server Package: Install-Package System.Net.Mqtt.Server -Pre

Current package dependencies:

System.Diagnostics.Tracer (>= 2.0.4) System.Net.Sockets (>= 4.1.0) System.Reactive (>= 3.0.0) System.Runtime.Serialization.Primitives (>= 4.1.1)

More

For more specific information about the MQTT protocol, please see the latest Oasis spec.

mqtt's People

Contributors

adalon avatar dependabot[bot] avatar emaf avatar japarson avatar jhalbrecht avatar jknaudt21 avatar kzu avatar mariaghiondea avatar mauroa avatar mslukewest avatar msylvia avatar rolfbjarne avatar svetbonev avatar tondat 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

mqtt's Issues

Application crashes unexpectedly when createasync is called

Hi, I tried both of the following ways , but both ways crash my application. I'm unable to debug with breakpoints because the debugger also crashes.

Way 1

client = await new System.Net.Mqtt.Sdk.MqttClientFactory(ServerAddress).CreateClientAsync(new MqttConfiguration()
{
     Port = ServerPort
});

Way 2

client = await MqttClient.CreateAsync(ServerAddress, ServerPort);

I'm debugging using my real phone connected to visual studio using Xamarin Live Player. Your help will be much appreciated.

Connection Issue

Hi,

I have started playing around with MQTT lately and have come across your package which I quite like. However I'm currently getting the below error thrown. Can you assist me?

System.Net.Mqtt.MqttClientException: An error occurred while trying to connect the client Client123456 ---> System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Mqtt.Sdk.TaskRunner'.
at System.Net.Mqtt.Sdk.TaskRunner.Run(Func`1 func)
at System.Net.Mqtt.Sdk.MqttClientImpl.d__39.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Net.Mqtt.Sdk.MqttClientImpl.d__28.MoveNext()
--- End of inner exception stack trace ---
at System.Net.Mqtt.Sdk.MqttClientImpl.d__28.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at App1.Page1.d__1.MoveNext()
The thread 0x8f8 has exited with code 0 (0x0).
The thread 0x4b88 has exited with code 0 (0x0).
The thread 0x3d78 has exited with code 0 (0x0).
The program '[1432] App1.UWP.exe: Program Trace' has exited with code 0 (0x0).
The program '[1432] App1.UWP.exe' has exited with code 1 (0x1).

I'm currently trying to run my code through VS 2017 using a UWP app,

Conflicted version with System.Reactive

Hi

I can't use System.MQTT with xamarin.ios and i get this error:

Can't resolve the reference 'System.Reactive.Subjects.SubjectBase`1', referenced from the method 'System.Void System.Net.Mqtt.Sdk.ClientPacketListener/d__23::MoveNext()' in 'System.Reactive.Linq, Version=3.0.0.0, Culture=neutral, PublicKeyToken=94bc3704cddfc263'. project C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Xamarin\iOS\Xamarin.iOS.Common.targets 804

I used the same code on Xamarin.Android and it works, but nothing with the ios version

Refactor IRepository to use Query objects instead of predicates and queryables

The current abstraction will be very hard to replicate in all environments without forcing enumeration of all rows to evaluate the predicate (whenever a sufficiently smart Linq provider isn't available). We'd much rather have an explicit Query object that limits the options, and have a Linq-based translation for Linq-based storages. This would allow other repository providers to implement the appropriate queries using plain SQL, indexes, what-not.

Especially since MQTT itself has very few requirements from a persistence provider.

Allow GUID to be used in Client-id parameter

When trying to connect with GUID "7e6efa94-50d6-4d3d-85ff-74663a6ef000", the library throws the below exception:
An error occurred while trying to connect the client "7e6efa94-50d6-4d3d-85ff-74663a6ef000"
at System.Net.Mqtt.Sdk.MqttClientImpl.d__28.MoveNext() in C:\Code\Xamarin\mqtt\src\Client\Sdk\MqttClientImpl.cs:line 130
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()

Also, the library doesn’t return an exact cause of connection failure. It throws a generic exception in all cases. There is no indicator to identify root cause or to take alternate action based on failure reason. Paho M2Mqtt library provides different error codes for connection failures.
The client "7e6efa94-50d6-4d3d-85ff-74663a6ef000" has been disconnected while trying to perform the connection
at System.Net.Mqtt.Sdk.MqttClientImpl.d__28.MoveNext() in C:\Code\Xamarin\mqtt\src\Client\Sdk\MqttClientImpl.cs:line 127
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()

Cannot create more than one client.

I have a system where I have an object representing each of my devices. Wanted to add a "listener" on each device listening to some generic control channel and its particular channel. To simplify message handling.

But I get and exception when I try to create the second client. Is that the expected behavior ?

Please update System.Reactive to latest version (4.1.0) (Tested)

Hi!

The package conflicts with other state of the art packages like Realm or Zeroconf because of the System.Reactive 3.0.0 reference. I cloned the repo and re-compiled with System.Reactive 4.1.0 and referenced the assembly in a .NET Standard library and then to a Xamarin iOS / Android app. The server seems to work fine. I hope you can update the Nuget and test.

Thanks.

Occasional Unhandled Exceptions

I am using the client in a Xamarin Forms project on an Android 8.0 device and about 70% of the time things run as expected. The other 30% of the times I launch the app it crashes immediately with an unhandled exception stating "An item with the same key has already been added. Key: System.Net.Mqtt.Sdk.Storage.RetainedMessage". I've tried try/catch on everything to do with the client object and it doesn't catch it.

The call stack is as following:
at System.ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException (System.Object key) [0x00006] in <f32579baafc1404fa37ba3ec1abdc0bd>:0 at System.Collections.Generic.Dictionary'2[TKey,TValue].TryInsert (TKey key, TValue value, System.Collections.Generic.InsertionBehavior behavior) [0x000ad] in <f32579baafc1404fa37ba3ec1abdc0bd>:0 at System.Collections.Generic.Dictionary'2[TKey,TValue].Add (TKey key, TValue value) [0x00000] in <f32579baafc1404fa37ba3ec1abdc0bd>:0 at System.Net.Mqtt.Sdk.Storage.InMemoryRepositoryProvider.GetRepository[T] () [0x0006a] in C:\Code\Xamarin\mqtt\src\Client\Sdk\Storage\InMemoryRepositoryProvider.cs:24 at System.Net.Mqtt.Sdk.Flows.ClientProtocolFlowProvider.InitializeFlows () [0x00012] in C:\Code\Xamarin\mqtt\src\Client\Sdk\Flows\ClientProtocolFlowProvider.cs:21 at System.Net.Mqtt.Sdk.Flows.ProtocolFlowProvider.GetFlows () [0x00008] in C:\Code\Xamarin\mqtt\src\Client\Sdk\Flows\ProtocolFlowProvider.cs:64 at System.Net.Mqtt.Sdk.Flows.ProtocolFlowProvider.GetFlow (System.Net.Mqtt.Sdk.Packets.MqttPacketType packetType) [0x0002a] in C:\Code\Xamarin\mqtt\src\Client\Sdk\Flows\ProtocolFlowProvider.cs:40 at System.Net.Mqtt.Sdk.ClientPacketListener+<DispatchPacketAsync>d__23.MoveNext () [0x0002a] in C:\Code\Xamarin\mqtt\src\Client\Sdk\ClientPacketListener.cs:194 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <f32579baafc1404fa37ba3ec1abdc0bd>:0 at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <f32579baafc1404fa37ba3ec1abdc0bd>:0 at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <f32579baafc1404fa37ba3ec1abdc0bd>:0 at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <f32579baafc1404fa37ba3ec1abdc0bd>:0 at System.Runtime.CompilerServices.ConfiguredTaskAwaitable+ConfiguredTaskAwaiter.GetResult () [0x00000] in <f32579baafc1404fa37ba3ec1abdc0bd>:0 at System.Net.Mqtt.Sdk.ClientPacketListener+<<ListenNextPackets>b__17_0>d.MoveNext () [0x0002c] in C:\Code\Xamarin\mqtt\src\Client\Sdk\ClientPacketListener.cs:108 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <f32579baafc1404fa37ba3ec1abdc0bd>:0 at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__6_1 (System.Object state) [0x00000] in <f32579baafc1404fa37ba3ec1abdc0bd>:0 at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context (System.Object state) [0x00007] in <f32579baafc1404fa37ba3ec1abdc0bd>:0 at System.Threading.ExecutionContext.RunInternal (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state, System.Boolean preserveSyncCtx) [0x00071] in <f32579baafc1404fa37ba3ec1abdc0bd>:0 at System.Threading.ExecutionContext.Run (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state, System.Boolean preserveSyncCtx) [0x00000] in <f32579baafc1404fa37ba3ec1abdc0bd>:0 at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem () [0x00021] in <f32579baafc1404fa37ba3ec1abdc0bd>:0 at System.Threading.ThreadPoolWorkQueue.Dispatch () [0x00074] in <f32579baafc1404fa37ba3ec1abdc0bd>:0 at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback () [0x00000] in <f32579baafc1404fa37ba3ec1abdc0bd>:0

Cheers,
Elco

Add basic event tracing

Following the approach of the VSX spike, add basic Event Tracing support that works on the Mac by just tracing to a TraceSource.

Story xamarin/XamarinVS#1888

What would be a good policy to maintain a healthy and stable connection between broker and client?

Hi all!

I am trying to make a rock solid connection between Android & iOS platforms. When the client and the broker are connected and I keep sending messages, everything runs with impressive performance.

My company have years of experience using Mqtt with hardware (Microchip, Raspberry, Arduino, C# & Xamarin now). As far as I have learned in field applications is that the low networking level needs to be constantly monitored, to trigger some retry policies, start or sending pings to have visibility of devices (all this in WiFi, and some in cabled Ethernet).

In my experience in field applications, any hardware or software that implements any TCP or UDP connection, when entering WiFi mode, mqtt is the only way to guarantee the delivery of the message in very high contaminated WiFI environment, however the maintenance of the connectivity is always an issue and needs to be very well reactive and observed.

Some things that I have observed with this library in my first experiments, is that the broker some times crashes with a System.Network level exception which I am not able to catch yet because I don't know in what part of the code is being thrown.

We are planning to write a policy and keep-alive connection layer, based in the Nuget Polly library, and your knowledge could provide a lot of help for us.

What are the main factors in your experience that makes the connections lost? By now I have discovered that sometimes, when I start the server, and it keeps time running, some times the client application can't connect to the broker one (iOS to Android and viceversa), so i need to start writing the layer described above.

Again, this is a great work, thanks a lot! :)

Why is message received over and over again?

By following you example, I have implemented subscriber as shown below:

this.m_MqttClient.MessageStream
.Where(msg => msg.Topic == this.m_RcvTopic)
.Subscribe(async msg => {
await msgReceiver?.Invoke(msg.Payload);

The message is sent by using this code:
await this.m_MqttClient.PublishAsync(new MqttApplicationMessage(this.m_SendTopic, message), MqttQualityOfService.ExactlyOnce);

The message is correctly sent and received, but receiving of the same message does not stop.
The message is received over and over again.
What is the correct way to reliably complete receiving of the message?

Thanks

MQTT Secure Connection

When attempting to connect to a MQTT using a secure connection on port 8883 the following exception is thrown:-
System.Net.Mqtt.MqttClientException: 'An error occurred while trying to connect the client '

IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

SocketException: An existing connection was forcibly closed by the remote host

Can't send more than 18 messages

When sending messages from my Xamarin.forms app to an mqtt-server the first 18 Messages are getting sent.
The 19. and all following messages are not.
There is no Exception thrown when this happens (neither on the app nor on the server) and the App is still receiving messages from the Server.

I tried to work around this by reconnecting after 17 messages but I had no luck.
Restarting the App does reset the "counter".

I changed the App to use this Library instead: https://github.com/mohaqeq/paho.mqtt.m2mqtt
and I can send as much messages as I want and the connection feels a bit more stable.

Is there maybe something I did wrong?

Automatic reconnect to MQTT broker ?

Is there any setting available in MQTT client, that provides an automatic reconnect to the MQTT server/broker in case of lost of connection ?

Looking for examples of how to set up the Server

This project really intrigues me. But I'd like to see an end-to-end example (via code or documentation) of how to set up a service to receive messages sent by a client that would be close to what I would need to implement if I were to use it. The tests are only getting me so far in my understanding of it. Any pointers to some other project that is using it?

Improve automated build

Use semanticgit for versioning, automatically generate nuget packages from builds, etc.

Story xamarin/XamarinVS#1888

Cannot subscribe to messages

I use a 3rd party broker app (because I'm unable to connect to the server here)
https://play.google.com/store/apps/details?id=server.com.mqtt&hl=es

I connect to the broker correctly from C#, and from a nodeMCU device running micropython. I can submit messages from both python and C# but I only receive them from python. The subscribe method never reacts.

Here a question in stack overflow I posted with slightly more detail:
https://stackoverflow.com/questions/54768813/xamarin-mqtt-not-subscriving-to-messages

Could not load file or assembly System.Net.Mqtt.resources.dll

Hi there,

I am trying to connect to my Mqtt server from my Xamarin Forms App. I made an implementation on iOS this way:

public async Task CreateClientAsync(string serverIp, string serverPort)
{
    client = await MqttClient.CreateAsync(serverIp, serverIp);
}

public async Task<bool> Connect(string clientId, string user, string password)
{            
    credentials = new MqttClientCredentials(clientId, user, password);
    await client.ConnectAsync(credentials);
    return client.IsConnected;
}

But i always get this exception when I call to the method ConnectAsync(credentials)

Exception:

System.IO.FileNotFoundException: Could not load file or assembly '/Users/ciani/Library/Developer/CoreSimulator/Devices/18F2ACE9-10B6-48F5-957D-38A72BE47BCF/data/Containers/Bundle/Application/434A0A8B-7CD0-4790-84EA-74516FCFFFBD/SmartTracker.iOS.app/en-US/System.Net.Mqtt.resources.dll' or one of its dependencies occurred

What I am doing wrong?

Evaluate incorporating common broker $SYS topics for admin

Reporting broker status via $SYS is pretty common in other brokers. We should evaluate and implement the most common and "standard" topics for reporting broker status.

See https://github.com/mqtt/mqtt.github.io/wiki/SYS-Topics

Take into account the suggestions on OASIS: https://issues.oasis-open.org/browse/MQTT-16 (in particular, the restriction that clients subscribing with wildcards should not receive $SYS messages.

This is apparently already part of the spec:

  1. Applications MUST not define any topic names that start with a leading $ character
  2. MQTT server implementations MAY define topic names that start with the the string "$SYS/"
  3. MQTT server implementations MUST NOT define any other topics whose names start with a leading $ character.

More context at https://groups.google.com/forum/#!topic/mqtt/ooRgMpe-Wa8, another broker implementing this at http://mosquitto.org/man/mosquitto-8.html

Story xamarin/XamarinVS#1888

Cannot connect to the server from nodeMCU with micropython

I tested with a 3rd party broker and it works so the problem does not rely in the net configuration.

I start the server like this :
var server = MqttServer.Create();
server.ClientConnected += Debug;
server.ClientDisconnected += Debug;
server.Stopped += (o, e) => Debug($"disconnection ! {e.Message} and {e.Reason} ");

server.Start();

Then I try to connect from the nodeMCU and I get this :

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "Utils.py", line 10, in __init__
File "Utils.py", line 16, in ConnectMQTT
File "umqtt/simple.py", line 99, in connect
MQTTException: 2

Checked what the MQTTException : 2 is and I found no documentation but the fragment of code that writes it down it this :

self.sock.write(premsg, i + 2)
       self.sock.write(msg)
       #print(hex(len(msg)), hexlify(msg, ":"))
       self._send_str(self.client_id)
       if self.lw_topic:
           self._send_str(self.lw_topic)
           self._send_str(self.lw_msg)
       if self.user is not None:
           self._send_str(self.user)
           self._send_str(self.pswd)
       resp = self.sock.read(4)
       assert resp[0] == 0x20 and resp[1] == 0x02
       if resp[3] != 0:
           raise MQTTException(resp[3])
       return resp[2] & 1

Any ideas ?

Message on Re connect: recive only offline message not all

I had try with MQTT.js to the same broke node.js and with publish/subscribe on QoS = 1, publish retain = false and connect cleanSession = false if

CLIENT A & CLIENT B ONLINE SUBSCRIBED TO THE SAME TOPIC
CLIENT A --> SEND MESSAGE 1/ MESSAGE 2/ MESSAGE 3--> CLIENT A/B REVICE MESSAGE 1/2/3
CLIENT B --> DISCONNECT
CLIENT A--> SEND MESSAGE 4/ MESSAGE 5--> CLIENT A REVICE MESSAGE 4/5
CLIENT B --> RE CONNECT --> CLIENT B RECIVE MESSAGE 4/5

With this xamarin client I recive ALL messages always on reconnect
CLIENT A & CLIENT B ONLINE SUBSCRIBED TO THE SAME TOPIC
CLIENT A --> SEND MESSAGE 1/ MESSAGE 2/ MESSAGE 3--> CLIENT A/B REVICE MESSAGE 1/2/3
CLIENT B --> DISCONNECT
CLIENT A--> SEND MESSAGE 4/ MESSAGE 5--> CLIENT A REVICE MESSAGE 4/5
CLIENT B --> RE CONNECT --> CLIENT B RECIVE MESSAGE 1/2/3/4/5

No session has been found for client

Hello,
i tried to connect to a mosquitto broker, on ConnectAsync i get "No session has been found for client" disconnect error, no matter if cleansession is true or false.

Any ideas if is a bug or some strict feature of mqtt? (i'm connected to this server with same credentials with other libraries).
Thanks

publishing from mosquitto_pub command

Hi,
I am trying to publish data using "mosquitto_pub" command.

C:\Users\Administrator>mosquitto_pub -d -t path -m "Hello from Terminal window 2!" -h <<ipaddress>> Client mosqpub/16196-WIN-LNKCV sending CONNECT Error: The connection was lost.

This the error message that I am getting; from C# code both server & client are working fine. Finally I want publish from Raspberry Pi using "c / c++" library. Can you help me to connect this from the device.

Currently I am using this library to connect from the device:
https://github.com/eclipse/mosquitto

C# Server Code:
`
class Program
{
private static IMqttServer server;
private static IMqttClient client;
private static MqttConfiguration Configuration { get; set; }

    static void Main(string[] args)
    {
        usedPorts = new ConcurrentBag<int>();

        server = GetServerAsync();
        client = GetClientAsync();
        server.Start();

        var subscriber1 = GetClientAsync();

        var clientId1 = GetClientId();
        var clientId2 = GetClientId();

        subscriber1.ConnectAsync(new MqttClientCredentials(clientId1)).Wait();
        client.ConnectAsync(new MqttClientCredentials(clientId2)).Wait();

        subscriber1.SubscribeAsync("path", MqttQualityOfService.AtMostOnce)
            .ConfigureAwait(continueOnCapturedContext: false);

        subscriber1.MessageStream
            .Subscribe(m =>
            {
                Console.WriteLine(Serializer.Deserialize<string>(m.Payload));
            });

        var message = new MqttApplicationMessage("path", Serializer.Serialize(Guid.NewGuid().ToString() + " :: " + DateTime.Now.ToString()));

        server.ClientConnected += (object sender, string e) =>
        {
            Console.WriteLine(sender.ToString());
        };
        for (int i = 0; i < 100; i++)
        {
            message = new MqttApplicationMessage("path", Serializer.Serialize(Guid.NewGuid().ToString() + " :: " + DateTime.Now.ToString()));                
            Thread.Sleep(200);
            client.PublishAsync(message, MqttQualityOfService.AtLeastOnce).Wait();
        }


        Console.WriteLine("Ready");

        var topic = Guid.NewGuid().ToString();


        Console.Read();

        server.Stop();
        client.DisconnectAsync().Wait();
        server.Dispose();
    }

    private static string GetClientId()
    {
        return string.Concat("Client", Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 15));
    }

    static ConcurrentBag<int> usedPorts;
    static Random random = new Random();

    private static int GetPort()
    {
        var port = random.Next(minValue: 40000, maxValue: 65535);

        if (usedPorts.Any(p => p == port))
        {
            port = GetPort();
        }
        else
        {
            usedPorts.Add(port);
        }

        return port;
    }

    private static IMqttClient GetClientAsync()
    {
        if (Configuration == null)
        {
            LoadConfiguration();
        }

        //Configuration.Port = GetPort();

        return MqttClient.CreateAsync(IPAddress.Loopback.ToString(), Configuration).Result;

        //var binding = new TcpBinding();
        //var initializer =  new MqttClientFactory(IPAddress.Loopback.ToString(), binding);



        //return initializer.CreateClientAsync(Configuration).Result;
    }

    private static IMqttServer GetServerAsync(IMqttAuthenticationProvider authenticationProvider = null)
    {
        try
        {
            LoadConfiguration();

            var binding = new ServerTcpBinding();
            var initializer = new MqttServerFactory(binding, authenticationProvider);
            var server = initializer.CreateServer(Configuration);

            server.Start();

            return server;
        }
        catch (MqttException protocolEx)
        {
            if (protocolEx.InnerException is SocketException)
            {
                return GetServerAsync();
            }
            else
            {
                throw;
            }
        }
    }

    private static ushort keepAliveSecs = 0;
    private static bool allowWildcardsInTopicFilters = true;
    private static object lockObject = new object();

    private static void LoadConfiguration()
    {
        lock (lockObject)
        {
            Configuration = new MqttConfiguration
            {
                BufferSize = 128 * 1024,
                //Port = 8883,
                Port = 1883,
                KeepAliveSecs = keepAliveSecs,
                WaitTimeoutSecs = 5,
                MaximumQualityOfService = MqttQualityOfService.ExactlyOnce,
                AllowWildcardsInTopicFilters = allowWildcardsInTopicFilters
            };
        }
    }
}

`

Heartbeat monitoring

Hi,

Is it possible to monitor the client to broker connection? So that when it drops out I can sent an alert and/or reconnect?

Thanks.

KeepAlive in MqttConfiguration

I set the KeepAliveSecs parameter to (for instance) 10 (seconds) in the MqttConfiguration, when creating the MqttClient.
Then I physically removed the network cable for the connection to the mqtt broker.
The expected behaviour was to get the MqttClient "Disconnected" event triggered, but instead of that the application crashed with unexpected exception.
When just stopping the Mqtt broker (without removing the network cable), the MqttClient "Disconnected" event is triggered properly.

TLS / SSL connection

I am using Xamarin.Forms, when I try to connect to port 8883 I get a timeout error, any Platform (iOS, Android..)

Message:

A timeout occured while waiting for the client SICNH5TBUUK36SQ5P1WM connection confirmation

Stack trace:

  at System.Net.Mqtt.Sdk.MqttClientImpl+<ConnectAsync>d__28.MoveNext () [0x0022d] in C:\Code\Xamarin\mqtt\src\Client\Sdk\MqttClientImpl.cs:118 
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.36/src/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:151 
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00037] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.36/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187 
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.36/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156 
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.36/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128 
  at System.Runtime.CompilerServices.TaskAwaiter.GetResult () [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.36/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:113 
  at CloudMatic.Core.CCU+<<Init>b__71_0>d.MoveNext () [0x007ed] in /Users/eduard/Documents/Projects/CloudMatic/Shared/CloudMatic.Core/SmartHomeCentrals/CCU.cs:129 

The sever is okay and works with other libraries.
Any idea?
Could someone provide a sample how to correctly connect over TLS / SSL with this library?

Thanks in advance

// EDDY

Send an object

How I can send an object? I have my message class with (string user, string message, datetime now).
I can't find a method that convert object into Byte Array to send/receive with this library

ConnectAsync: problem with System.Net.Mqtt.Sdk.TaskRunner

var configuration = new MqttConfiguration { Port = 1883 };
            //Creation of the MQTT client
            var client = await MqttClient.CreateAsync("mqtt://myservernode.net", configuration);

await client.ConnectAsync(new MqttClientCredentials("userId"));

client.ConnectAsync(new MqttClientCredentials("userId")); give me this error

ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Mqtt.Sdk.TaskRunner'.

Header Flag 2 is invalid for SubscribeAck packet

Hi, I'm using the MQTT as a Client. When I communicate with a Mosquitto Broker I can do everything fine(Connect,Publish,Subscribe). But I need to communicate with a Broker that is implemented inside a ESP32 MicroController. The ESP32 broker works fine when it is with another clients , but when I put together the System.Net.Mqtt as Client and the ESP32 as broker I can Connect and Publish but I'm receiving this error from the SUBACK packet. I want to try to find which side is causing the error, the Client or the Broker. How can I debug from the client side to find more about the error?

System.Net.Mqtt.MqttClientException: An error occurred while trying to subscribe the client to topic CFG/TODEVICE/USER_1234/123456 ---> System.Net.Mqtt.MqttException: Header Flag 2 is invalid for SubscribeAck packet. Expected value: 0
at System.Net.Mqtt.Sdk.Formatters.Formatter1[T].ValidateHeaderFlag (System.Byte[] bytes, System.Func2[T,TResult] packetTypePredicate, System.Int32 expectedFlag) [0x0004b] in <2a97f540c561449a9767b58811eeab29>:0
at System.Net.Mqtt.Sdk.Formatters.SubscribeAckFormatter.Read (System.Byte[] bytes) [0x00000] in <2a97f540c561449a9767b58811eeab29>:0
at System.Net.Mqtt.Sdk.Formatters.Formatter1+<>c__DisplayClass4_0[T].<FormatAsync>b__0 () [0x00000] in <2a97f540c561449a9767b58811eeab29>:0 at System.Threading.Tasks.Task1[TResult].InnerInvoke () [0x0000f] in <43dbbdc147f2482093d8409abb04c233>:0
at System.Threading.Tasks.Task.Execute () [0x00010] in <43dbbdc147f2482093d8409abb04c233>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <43dbbdc147f2482093d8409abb04c233>:0
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <43dbbdc147f2482093d8409abb04c233>:0
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <43dbbdc147f2482093d8409abb04c233>:0
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in <43dbbdc147f2482093d8409abb04c233>:0 at System.Net.Mqtt.Sdk.Formatters.Formatter1+d__4[T].MoveNext () [0x000d4] in <2a97f540c561449a9767b58811eeab29>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <43dbbdc147f2482093d8409abb04c233>:0
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <43dbbdc147f2482093d8409abb04c233>:0
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <43dbbdc147f2482093d8409abb04c233>:0
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in <43dbbdc147f2482093d8409abb04c233>:0 at System.Net.Mqtt.Sdk.PacketManager+<GetPacketAsync>d__3.MoveNext () [0x000a7] in <2a97f540c561449a9767b58811eeab29>:0 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <43dbbdc147f2482093d8409abb04c233>:0 at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <43dbbdc147f2482093d8409abb04c233>:0 at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <43dbbdc147f2482093d8409abb04c233>:0 at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in <43dbbdc147f2482093d8409abb04c233>:0
at System.Net.Mqtt.Sdk.PacketChannel+<<-ctor>b__7_0>d.MoveNext () [0x0007a] in <2a97f540c561449a9767b58811eeab29>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Reactive.PlatformServices.ExceptionServicesImpl.Rethrow (System.Exception exception) [0x00006] in :0
at System.Reactive.ExceptionHelpers.ThrowIfNotNull (System.Exception exception) [0x0000d] in <89303124b9cf49c1966d01b97d1279d3>:0
at System.Reactive.Subjects.AsyncSubject`1[T].GetResult () [0x00039] in <35ac89e7c17f4eb4a976c11c44a435ed>:0
at System.Net.Mqtt.Sdk.MqttClientImpl+d__32.MoveNext () [0x0018e] in <2a97f540c561449a9767b58811eeab29>:0
--- End of inner exception stack trace ---
at System.Net.Mqtt.Sdk.MqttClientImpl+d__32.MoveNext () [0x00281] in <2a97f540c561449a9767b58811eeab29>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <43dbbdc147f2482093d8409abb04c233>:0
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <43dbbdc147f2482093d8409abb04c233>:0
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <43dbbdc147f2482093d8409abb04c233>:0
at System.Runtime.CompilerServices.TaskAwaiter.GetResult () [0x00000] in <43dbbdc147f2482093d8409abb04c233>:0
at AirSenseApp.ViewModel.MQTTViewModel+d__33.MoveNext () [0x00263] in D:\Lucas\Brise\Brise-App\AirSenseApp\AirSenseApp\ViewModel\MQTTViewModel.cs:117

Last Will should have binary payload

According to the spec the last will message is no different than all other published messages: it contains a topic and a byte[] payload.

We unfortunately define it as a string which is later on converted to a byte[] when publishing by the server.

This should not be the case. To maintain some degree of backs compat, I'd flag this constructor and string property as obsolete with a warning (no error), hide it from intellisense with EditorBrowsable and provide a ctor overload receiving the byte[] payload instead. The legacy ctor would do the UTF8.GetBytes on the string so the backwards compat behavior is preserved.

Troubleshooting when connection lost

Hi,
I use the last available nuget package and I have issues. First, if I have no internet connection when I try to initialize the MQTT connection, the app crashes. If I add a try/catch statement, the app crashes too!

Secondly, if the connection is done and I lost my internet connection I have the same issue.

Finally, I have the same issue when I try to call the DisconnectAsync method or the IMqttClient Dispose method.

EDIT

I tested my code on Android 6.0.
I downloaded the repository and added the Client project to my VS solution and I referenced it in my project instead of the nuget package. Now, I have no problem when I try to connect to the broker without internet connection (it works with a try/catch statement). But I still have the two other problems described above.

System.IO.FileNotFoundException

I install the packages and i got this error.

Error Exception while loading assemblies: System.IO.FileNotFoundException: Could not load assembly 'System.Reactive.Linq, Version=3.0.0.0, Culture=neutral, PublicKeyToken=94bc3704cddfc263'. Perhaps it doesn't exist in the Mono for Android profile?
File name: 'System.Reactive.Linq.dll'
at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(AssemblyNameReference reference, ReaderParameters parameters)
at Xamarin.Android.Tasks.ResolveAssemblies.AddAssemblyReferences(DirectoryAssemblyResolver resolver, ICollection`1 assemblies, AssemblyDefinition assembly, Boolean topLevel)
at Xamarin.Android.Tasks.ResolveAssemblies.Execute(DirectoryAssemblyResolver resolver) mqttTest2

Add link to Wiki from README.md

I added some samples to the Wiki. Perhaps a link to the project README.md could be added?

Are maintainers aware of any other examples?

Some Examples

System.Net.Mqtt client sample A gist from @mauroa
xamarin-iot-samples/Hermes.Mqtt/ found in the xamarin/xamarin-iot-samples
Any others? Spicoli? Bueller?

Retrive CONNACK : how?

 var config = new MqttConfiguration{
                Port = 1883,
            };

            emitter = await MqttClient.CreateAsync("broker.net", config);
            emitter.ConnectAsync(new MqttClientCredentials("Mickey Mouse"), null, false);

How can retrive Connection ACK from ConnectAsync?

The target "GitVersion" does not exist in the project.

I'm attempting to evaluate "Hermes" mqtt for Xamarin.Forms.

I get error The target "GitVersion" does not exist in the project. on line 26 of "Directory.Build.targets" <Target Name="SetVersions" BeforeTargets="GetAssemblyVersion" DependsOnTargets="GitVersion" Returns="$(Version)">

I cloned and then attempted to build using

Microsoft Visual Studio Professional 2017  (VS2017rc)
Version 15.4.1
VisualStudio.15.Release/15.4.1+27004.2005
Microsoft .NET Framework
Version 4.7.02556

Installed Version: Professional
[...]
Xamarin   4.7.10.22 (fe36bec)
Visual Studio extension to enable development for Xamarin.iOS and Xamarin.Android.

Xamarin.Android SDK   8.0.0.33 (HEAD/7a6a056e8)
Xamarin.Android Reference Assemblies and MSBuild support.

Xamarin.iOS and Xamarin.Mac SDK   11.2.0.8 (9a9f054)
Xamarin.iOS and Xamarin.Mac Reference Assemblies and MSBuild support.

Is Flespi supposed to work?

Sorry about the vague question but I'm new with MQTT I can't find a working example with C# and Flespi.

I created the simplest sample from the README file and added my data:

try
{
	var configuration = new MqttConfiguration
	{
		Port = 31457
	};
	var client = MqttClient.CreateAsync("193.193.165.37", configuration).Result;
	var sessionState = client.ConnectAsync(new MqttClientCredentials(clientId: "test")).Result;
}
catch (Exception ex)
{
	while (ex != null)
	{
		Console.WriteLine(ex.Message);
		ex = ex.InnerException;
	}
}

and here's the error I get...
Header Flag 7 is invalid for PublishReceived packet. Expected value: 0

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.