Skip to main content

MQTT

Overview

PortDIC supports MQTT through the handler pattern. Each [MQTTHandler] class gets its own independent MQTT connection, and the operating mode (Client or Broker) is selected by calling SetMode in the [Preset] method.

ModeDescription
MqttMode.ClientConnect to an external MQTT broker (default)
MqttMode.BrokerStart an embedded MQTT broker inside the process

Quick Start

Client Mode (connect to a broker)

using Portdic;
using Portdic.MQTT;

[MQTTHandler]
public class SensorClient
{
[MQTTHandlerProp]
public IMQTTHandler handler { get; set; } = null!;

[Preset]
private void Preset()
{
handler.SetMode(MqttMode.Client);
handler.SetHost("192.168.1.50");
handler.SetPort(1883);
handler.SetClientId("sensor-client-01");
handler.SetUsername("user");
handler.SetPassword("pass");

handler.OnMessageReceived += OnMessage;
handler.OnEvent += OnEvent;
}

private void OnMessage(string name, string topic, string payload, int qos)
=> Console.WriteLine($"[{name}] {topic}: {payload} (QoS {qos})");

private void OnEvent(string name, string eventType, string description)
{
Console.WriteLine($"[{name}] {eventType}: {description}");
if (eventType == "CONNECTED")
{
handler.Subscribe("sensor/temperature/#");
handler.Subscribe("sensor/humidity", qos: 1);
}
}
}
Port.Add<SensorClient>("mqtt_sensor");
Port.Run();

Broker Mode (embedded broker)

[MQTTHandler]
public class EmbeddedBroker
{
[MQTTHandlerProp]
public IMQTTHandler handler { get; set; } = null!;

[Preset]
private void Preset()
{
handler.SetMode(MqttMode.Broker);
handler.SetBrokerAddress("0.0.0.0:1883");
handler.SetUsers("[{\"name\":\"admin\",\"password\":\"admin\"}]");
handler.SetAllowRemotes("192.168.1.0/24", "10.0.0.100");
handler.SetUseMqttProtocol(true); // true = native MQTT/TCP, false = WebSocket

handler.OnEvent += OnEvent;
}

private void OnEvent(string name, string eventType, string description)
=> Console.WriteLine($"[{name}] {eventType}: {description}");
}
Port.Add<EmbeddedBroker>("mqtt_broker");
Port.Run();

Multiple Connections

Each registration creates its own independent MQTT handler:

Port.Add<LocalBrokerClient>("mqtt_local");
Port.Add<CloudBrokerClient>("mqtt_cloud");
Port.Run();

Publish and Subscribe

// Subscribe to a topic
handler.Subscribe("equipment/status");
handler.Subscribe("sensor/#", qos: 1); // wildcard, QoS 1

// Publish a message
handler.Publish("equipment/status", "online");
handler.Publish("sensor/temp", "25.3", qos: 1, retain: true);

// Unsubscribe
handler.Unsubscribe("sensor/#");

// Disconnect
handler.Close();

QoS Levels

LevelGuaranteeDescription
QoS 0At most onceNo delivery guarantee; possible message loss
QoS 1At least onceGuaranteed delivery; possible duplication
QoS 2Exactly onceGuaranteed delivery without duplication

API Reference

Attributes

AttributeTargetDescription
[MQTTHandler]ClassMarks the class as an MQTT handler container
[MQTTHandlerProp]PropertyInjects the IMQTTHandler instance
[Preset]MethodCalled before Open() to configure the handler

Mode

MethodDescription
SetMode(MqttMode mode)Select Client (default) or Broker mode

Client Configuration

MethodDefaultDescription
SetHost(string host)"127.0.0.1"Broker address
SetPort(int port)1883Broker port
SetClientId(string clientId)registration keyMQTT client ID
SetUsername(string username)Broker authentication username
SetPassword(string password)Broker authentication password
SetKeepAlive(int seconds)60Keep-alive interval in seconds
SetCleanSession(bool)trueDiscard previous session state on connect

Broker Configuration

MethodDefaultDescription
SetBrokerAddress(string address)"127.0.0.1:1883"Listen address in host:port format
SetUsers(string usersJson)admin/adminAuthorized users as JSON array
SetAllowRemotes(params string[] remotes)["127.0.0.1"]Allowed IPs, hostnames, or CIDR ranges
SetUseMqttProtocol(bool)truetrue = native MQTT/TCP; false = WebSocket

SetUsers JSON Format

[{"name":"admin","password":"admin123"},{"name":"sensor01","password":"pass"}]

Transport Modes

SetUseMqttProtocolTransportTypical PortUse Case
trueNative MQTT over TCP1883 / 8883MQTT clients, edge devices
falseMQTT over WebSocket8080Browser-based clients, dashboards

Connection

MethodReturnsDescription
Open()ERROR_CODEConnect to the broker or start the embedded broker
Close()ERROR_CODEDisconnect or stop the embedded broker
IsConnectedbooltrue if currently connected (Client mode)

Publish / Subscribe

MethodReturnsDescription
Publish(topic, payload, qos, retain)intPublish a message. Returns 0 on success
Subscribe(topic, qos)intSubscribe to a topic filter. Returns 0 on success
Unsubscribe(topic)intUnsubscribe from a topic. Returns 0 on success

Logging

MethodDescription
SetLogger(string rootPath)Enable hourly-rotated log files. Format: mqtt_{name}_{date}_{hour}.log
WriteLog(string message)Write a custom entry to the log file

Events

OnMessageReceived

Fired when a message arrives on a subscribed topic (Client mode).

handler.OnMessageReceived += (string name, string topic, string payload, int qos) =>
{
Console.WriteLine($"[{name}] {topic}: {payload}");
};
ParameterDescription
nameClient registration key
topicTopic the message was published on
payloadMessage payload as a UTF-8 string
qosQoS level (0, 1, or 2)

OnEvent

Fired on connection state changes and errors.

handler.OnEvent += (string name, string eventType, string description) =>
{
Console.WriteLine($"[{name}] {eventType}: {description}");
};
eventTypeTriggered When
CONNECTEDConnected to the broker / broker started
DISCONNECTEDDisconnected / broker stopped
SUBSCRIBEDTopic subscription confirmed
UNSUBSCRIBEDTopic unsubscription confirmed
PUBLISHEDMessage published successfully
ERRORError occurred (description contains detail)

Error Codes

CodeValueMeaning
ERR_CODE_NO_ERROR1Success
ERR_CODE_OPEN-1Open/connect failed
ERR_CODE_DLL_NOT_LOADED-2portmqttclient.dll / portmqtt.dll not loaded
ERR_CODE_PORTNAME_EMPTY-3Name not set
ERR_CODE_DLL_FUNC_NOT_CONFIRM-4Required DLL function unavailable
ERR_CODE_CONNECT_FAILED-5Connection attempt failed

  • RTSP — Real-time video streaming
  • SECS/GEM — Semiconductor equipment protocol
  • TCP — Raw TCP client/server communication