SyMqtt usage example
This guide provides a comprehensive, medium-complexity SyMqtt usage example, with explanations included.
Flow:
- The application initializes the topic related topology and handlers, then establishes the connection with the MQTT broker.
Without specific setting, the client created under the hood will use the default v5 MQTT protocol version.
The initialization creates:- One
SyMqttSenderTopicHolder- used to send fire-and-forget messages to the remote device - One
SyMqttReceiverTopicHolder- used to listen for unsolicited messages from the remote device - One
SyMqttChannel- used to send a synchronous interrogation message and displays the response from the device.
- One
- The application sends a fire-and-forget message to the device/controller “Here’s the server. I’m online!”
- The application interrogates the remote device by executing a synchronous request.
- The application starts listening for any incoming unsolicited messages from the device and displays them.
// Define the topology and connect to the MQTT server try { var mqttBox = new SyMqttBox() { TopicsPrefix = "MyDevicesGroup", AutoReconnect = true }; var openConnectionResult = await mqttBox .AddTopic(new SyMqttSenderTopicHolder("ServerGreeting", "/aaa/bbb/ccc")) .AddTopic(new SyMqttReceiverTopicHolder("UnattendedMessages", "ddd/eee/fff") .AddReceivedMessageHandler( async (inPayload, messageInfo) => { Console.WriteLine($"(2) From handler of topic holder 'UnattendedMessages': {inPayload} on topic '{messageInfo.PublishTopic}', QOS = {messageInfo.Qos}, IsRetained = {messageInfo.IsRetained}"); } ) ) .AddChannel(new SyMqttChannel(mqttBox, "Channel_1", "the/mqtt/sender/topic", "the/mqtt/receiver/topic")) .Initialize(new SyMqttClientParameters() { CleanSession = true, ClientId = "SyMqtt_console_test", TcpServer = "test.mosquitto.org", TcpPort = 1883 } ) .OpenConnectionAsync();
if (!openConnectionResult.Success) { Console.WriteLine($"Connection to the broker failed: {openConnectionResult.ErrorDescription}"); return; } } catch(SyMqttException ex) { Console.WriteLine($"[SyMqttException] {ex.Message}"); return; } catch(Exception ex) { Console.WriteLine(ex.Message); return; }
// Send greeting message to the device var greetingResult = await mqttBox.PublishSerialMessageAsync("ServerGreeting", SerialMessage.NewMessage("Here's the server. I'm online!"), null); if (!greetingResult.Success) { Console.WriteLine($"Greeting failed: {greetingResult.ErrorDescription}"); }
// Interrogate the device by sending a synchronous message // Signature: channelId, serialMessage, timeoutMilliseconds, messageOptions var queryResult = await mqttBox.FetchAsync("Channel_1", SerialMessage.NewMessage("GET_TEMPERATURE"), 3000, null);
// Display the response if (queryResult.Success) { SerialMessage deviceResponse = queryResult.Value; if (deviceResponse.MessageSuccessCode == 0) { Console.WriteLine($"Response from the device: {queryResult.Value.MessageDetails}"); } else { Console.WriteLine($"The device reported an error: {deviceResponse.MessageSuccessCode}"); } } else { Console.WriteLine($"Device query error: {queryResult.ErrorDescription}"); }
// Wait as long as you like for incoming messages from devices, on the // receiver topic holder with id "UnattendedMessages" defined above. Console.ReadLine();
await mqttBox.CloseConnectionAsync(); // RecommendedTo keep the code clean and straightforward, this example does not showcase several advanced production features available in SyMqtt, such as:
- Secure network connections using TLS/SSL
- Client and server certificate authentication
- Dynamic routing via message options (
TargetTopicSuffix) - Built-in diagnostic and debug logging configuration