Getting Started with MQTT Broker


Requirements: IPWorks IoT

Introduction

MQTTBroker provides a lightweight, fully-featured MQTT broker implementation with support for version 3.1.1. The component supports plaintext and TLS-enabled connections over both standard TCP and WebSockets.

Configuring Listeners

The AddBrokerListener method adds a new listener to the Listeners collection. Any listeners must be configured before starting the broker.

The following protocols are supported:

  • Plaintext TCP
  • SSL/TLS over TCP
  • Plaintext WebSocket
  • SSL/TLS over WebSocket

Multiple protocols can be enabled (each on a different port): // Plaintext TCP mqttbroker.AddBrokerListener("127.0.0.1", PLAIN_PORT, (int)MQTTBrokerProtocols.mbpTCP, 0, null, null, null); // TCP with TLS mqttbroker.AddBrokerListener("127.0.0.1", SSL_PORT, (int)MQTTBrokerProtocols.mbpTLS, (int)CertStoreTypes.cstPFXFile, "test1.pfx", "test", "*"); // Plaintext WebSocket mqttbroker.AddBrokerListener("127.0.0.1", WS_PORT, (int)MQTTBrokerProtocols.mbpWS, 0, null, null, null); // WebSocket with TLS mqttbroker.AddBrokerListener("127.0.0.1", WSS_PORT, (int)MQTTBrokerProtocols.mbpWSS, (int)CertStoreTypes.cstPFXFile, "test2.pfx", "test", "*"); Once all listeners have been added, the broker can be started via the StartListening method.

Handling Sessions

When an MQTT client requests a session, the SessionRequest event will fire with session details. The UserName and Password parameters can be checked before setting Accept to True to accept the session request. Accept can be set to False to reject the session request.

broker.OnSessionRequest += (s,e) => { // Check e.UserName and e.Password if needed // Set Accept to true to accept the session request e.Accept = true; };

Handling Subscriptions

When an MQTT client requests to subscribe to a topic, the Subscribe event will fire.

The ClientId is used to identify this client in subsequent actions.

The TopicFilter is the requested topic the client wishes to subscribe to.

The RequestedQoS is the client's preferred QoS level.

ReturnCode is used to confirm the maximum QoS level granted for this subscription or indicate a failure. This can be less than the client's RequestedQoS.

broker.OnSubscribe += (s,e) => { // Respond with the desired ReturnCode to grant this subscription request // Or reject the subscription request with ReturnCode = 0x80 if (e.RequestedQoS == 0) { e.ReturnCode = 0x00 } if (e.RequestedQoS == 1) { e.ReturnCode = 0x01 } if (e.RequestedQoS == 2) { e.ReturnCode = 0x02 } else { e.ReturnCode = 0x80; } };

When a client requests to unsubscribe from a topic, the Unsubscribe event will fire, specifying which TopicFilter the client is unsubscribing from.

Handling Incoming Messages

The MQTTBroker component will automatically forward received messages to any subscribed clients. Events can be used to record the state of any incoming messages.

The MessageReceiving event fires when a message is initially received and contains message metadata.

The IncomingMessageStatus event fires each time an incoming message's state is updated.

The MessageReceived event fires when the message has completed the acknowledgement process with the client, depending on the QoS level.

Handling Outgoing Messages

The MQTTBroker component will automatically forward received messages to any subscribed clients. Events can be used to record the state of any incoming messages.

The MessageSending event fires when a message is initially sent to a client and contains message metadata.

The OutgoingMessageStatus event fires each time an outgoing message's state is updated.

The MessageSent event fires when the message has completed the acknowledgement process with the client, depending on the QoS level.

Saving and Loading Sessions

The SaveSession method saves the current state of a client session, including message queues and subscription data, for later retrieval.

SaveSession returns a JSON string representing the client's subscriptions and messages. This can later be loaded via LoadSession to restore the client's state.

The format should be a JSON string with the following parameters: string sessiondata = broker.SaveSession("Client1"); // sessiondata may contain a JSON string with information like this: { "ClientId":"Client1", "Subscriptions":[{ // A collection of the client's subscribed topics "Topic":"topic name", "QoS":2, }], "IncomingMessages": [{ // A collection of incoming messages "MessageId":1, // The incoming message's ID "Topic":"A", // The incoming message's topic "Payload":"54657374", // hexadecimal message payload "QoS":2, // The incoming message's QoS level "DUP":false, // Whether this message is a duplicate "Retain":false, // Whether this is a retained message "PacketId":1, // This message's packet id "State":3 // See IncomingMessageStatus event for State details }], "OutgoingMessages":[{ // A collection of outgoing messages "MessageId":2, "Topic":"A", "Payload":"54657374", "QoS":2, "DUP":false, "Retain":false, "PacketId":2, "State":3 // See OutgoingMessageStatus event for State details }] } // Later, the LoadSession method can be used to load the session data broker.LoadSession(sessiondata);

We appreciate your feedback. If you have any questions, comments, or suggestions about this article please contact our support team at support@nsoftware.com.