StemMqtt 0.9.4

dotnet add package StemMqtt --version 0.9.4
                    
NuGet\Install-Package StemMqtt -Version 0.9.4
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="StemMqtt" Version="0.9.4" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="StemMqtt" Version="0.9.4" />
                    
Directory.Packages.props
<PackageReference Include="StemMqtt" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add StemMqtt --version 0.9.4
                    
#r "nuget: StemMqtt, 0.9.4"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package StemMqtt@0.9.4
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=StemMqtt&version=0.9.4
                    
Install as a Cake Addin
#tool nuget:?package=StemMqtt&version=0.9.4
                    
Install as a Cake Tool

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). AllowUnsafeBlocks is 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 (Linux linux-x64 today). 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) return Task / Task<T>. IsConnected(), SetMessageListener(), EnableMessageQueue(capacity), LastDisconnectReason() are synchronous.
  • Everything is PascalCase: ConnectOptions.KeepAliveSecs, MqttVersion.V5, QoS.AtLeastOnce. Numbers are unsigned: ushort ports, uint timeouts. 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) then await 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, …) and uniffi.mqtt_broker.MqttBrokerException (AlreadyRunning, Io, Tls); both derive from UniffiException.
  • Always alias the two QoS enums (using BrokerQoS = …).
  • The generated types are public (the package builds them with access_modifier = "public"), so they can be used from your own assemblies.
  • Top-level statements, as above, need C# 9+; in a classic Main the 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; check runtimes/<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 CSharpier when generating — cosmetic; install csharpier to format the output.
  • BadImageFormatException — 32/64-bit or architecture mismatch between your process and the native library.
Product 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • 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.

Version Downloads Last Updated
0.9.4 49 11/26/2026
0.9.2 55 11/26/2026
0.9.1 61 11/25/2026
0.9.0 103 11/16/2026