StemMqtt 0.9.4
dotnet add package StemMqtt --version 0.9.4
NuGet\Install-Package StemMqtt -Version 0.9.4
<PackageReference Include="StemMqtt" Version="0.9.4" />
<PackageVersion Include="StemMqtt" Version="0.9.4" />
<PackageReference Include="StemMqtt" />
paket add StemMqtt --version 0.9.4
#r "nuget: StemMqtt, 0.9.4"
#:package StemMqtt@0.9.4
#addin nuget:?package=StemMqtt&version=0.9.4
#tool nuget:?package=StemMqtt&version=0.9.4
C#
async/await bindings generated by uniffi-bindgen-cs:
records, Task-returning methods and interfaces for callbacks. One NuGet package holds the client and
the broker. Read the shared concepts first for the option records and semantics.
Install
dotnet add package StemMqtt
using uniffi.mqtt_broker;
using uniffi.mqtt_client;
Requirements
- .NET 8 or newer (the package targets
net8.0; later runtimes roll forward).AllowUnsafeBlocksis only needed to build the package, not to consume it. - The package carries the native libraries under
runtimes/<rid>/native/— for the platforms the release built (Linuxlinux-x64today). NuGet copies the right one next to your app automatically. Other platforms need a source build of the package.
Quick start
using uniffi.mqtt_broker;
using uniffi.mqtt_client;
// Both components define a QoS (the broker owns its own), so name them explicitly.
using BrokerQoS = uniffi.mqtt_broker.QoS;
using ClientQoS = uniffi.mqtt_client.QoS;
static ConnectOptions Options(ushort port, string id) => new(
Host: "127.0.0.1", Port: port, ClientId: id, Version: MqttVersion.V5, CleanStart: true,
KeepAliveSecs: 30, Username: null, Password: null, Will: null, ConnectTimeoutSecs: 10,
OperationTimeoutSecs: 5, AutoReconnect: false, ReconnectBackoffSecs: 0,
ReconnectMaxBackoffSecs: 0, Tls: null);
var broker = new MqttBroker(new MqttBrokerConfig(
BindAddress: "127.0.0.1", Port: 0, WsPort: null, AllowAnonymous: true, MaxClients: 0,
MaxQos: BrokerQoS.ExactlyOnce, MaxRetainedMessages: 100, MaxQueuedPerClient: 100,
RedeliveryIntervalSecs: 0, Tls: null));
await broker.Start();
var port = broker.BoundPort() ?? 0;
var inbox = new Inbox();
var sub = new MqttClient(Options(port, "cs-sub"));
sub.SetMessageListener(inbox);
await sub.Connect();
await sub.Subscribe("demo/#", ClientQoS.AtLeastOnce);
var pub = new MqttClient(Options(port, "cs-pub"));
await pub.Connect();
await pub.Publish("demo/hello", System.Text.Encoding.UTF8.GetBytes("hello"), ClientQoS.AtLeastOnce, false);
inbox.Received.Wait(TimeSpan.FromSeconds(5));
Console.WriteLine($"{inbox.Message!.Topic}: {System.Text.Encoding.UTF8.GetString(inbox.Message.Payload)}");
await pub.Disconnect();
await sub.Disconnect();
await broker.Stop();
class Inbox : MqttMessageListener
{
public readonly ManualResetEventSlim Received = new(false);
public MqttMessage? Message;
public void OnMessage(MqttMessage message) { Message = message; Received.Set(); }
public void OnDisconnected(string reason) { }
}
MaxPacketSize, MaxOutboundQueue, SessionExpirySecs, AuthMethod and AuthData have defaults and
can be omitted, as above.
Client
Connect(),Subscribe(filter, qos),Unsubscribe(filter),Publish(topic, byte[], qos, retain),Disconnect(),NextMessage(timeoutMs)returnTask/Task<T>.IsConnected(),SetMessageListener(),EnableMessageQueue(capacity),LastDisconnectReason()are synchronous.- Everything is PascalCase:
ConnectOptions.KeepAliveSecs,MqttVersion.V5,QoS.AtLeastOnce. Numbers are unsigned:ushortports,uinttimeouts. Optional values are nullable (string?). - Callbacks are interfaces you implement (
MqttMessageListener,MqttAuthProvider, …). They run on a native thread, so use thread-safe collections (ConcurrentBag,Channel<T>,ManualResetEventSlim). - Or pull:
client.EnableMessageQueue(16)thenawait client.NextMessage(5000)→MqttMessage?.
Broker
await Start() / await Stop(), IsRunning(), BoundPort(): ushort?, BoundWsPort(),
BoundTlsPort(), ClientCount().
class Events : MqttBrokerEventListener
{
public void OnClientConnected(string clientId) => Console.WriteLine($"+ {clientId}");
public void OnClientDisconnected(string clientId, string reason) => Console.WriteLine($"- {clientId}");
public void OnMessagePublished(string clientId, string topic, BrokerQoS qos) { }
}
broker.SetEventListener(new Events());
Pull-style: broker.EnableEventQueue(64), await broker.NextEvent(1000) → BrokerEvent?.
Authentication
class Auth : MqttAuthProvider
{
public bool Authenticate(string clientId, string? username, byte[]? password) =>
username == "demo" && password is not null;
}
broker.SetAuthProvider(new Auth());
A refused client makes await client.Connect() throw MqttException.ConnectionRefused. Enhanced
authentication: implement MqttEnhancedAuthProvider.Step(clientId, method, data, round) returning
new EnhancedAuthStep(EnhancedAuthOutcome.Continue, bytes) on the broker, and
MqttAuthHandler.Respond(method, challenge) on the client (with AuthMethod / AuthData set on the options).
TLS
var tls = new TlsOptions(
CaCertPem: File.ReadAllBytes("ca.pem"), ClientCertPem: null, ClientKeyPem: null,
InsecureSkipCertificateVerification: false);
// ConnectOptions(..., Tls: tls)
var brokerTls = new BrokerTlsConfig(Port: 8883, CertPem: File.ReadAllBytes("server.pem"),
KeyPem: File.ReadAllBytes("server.key"), ClientCaPem: null);
// MqttBrokerConfig(..., Tls: brokerTls)
Language notes
- Exceptions:
uniffi.mqtt_client.MqttException(ConnectionRefused,Timeout,Protocol, …) anduniffi.mqtt_broker.MqttBrokerException(AlreadyRunning,Io,Tls); both derive fromUniffiException. - Always alias the two
QoSenums (using BrokerQoS = …). - The generated types are
public(the package builds them withaccess_modifier = "public"), so they can be used from your own assemblies. - Top-level statements, as above, need C# 9+; in a classic
Mainthe same code works unchanged.
Building from source
dotnet tool install -g csharpier # optional: formats the generated code
nu scripts/install_bindgens.nu csharp
nu scripts/publish_packages.nu stage csharp # dist/csharp: sources + runtimes/
nu scripts/publish_packages.nu verify csharp # dotnet pack
The end-to-end test is tests/bindings/csharp/Program.cs.
Troubleshooting
DllNotFoundException: mqtt_client— no native library for your RID in the package; checkruntimes/<rid>/native/in the.nupkg, or build the package for your platform.CS0104: 'QoS' is an ambiguous reference— alias one or both enums.- Warnings about
CSharpierwhen generating — cosmetic; installcsharpierto format the output. BadImageFormatException— 32/64-bit or architecture mismatch between your process and the native library.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net8.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.