Rido.IoTHubClient 0.0.5

Suggested Alternatives

Rido.Mqtt.HubClient

Additional Details

This package is no longer maintained.

There is a newer version of this package available.
See the version list below for details.
dotnet add package Rido.IoTHubClient --version 0.0.5
NuGet\Install-Package Rido.IoTHubClient -Version 0.0.5
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="Rido.IoTHubClient" Version="0.0.5" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Rido.IoTHubClient --version 0.0.5
#r "nuget: Rido.IoTHubClient, 0.0.5"
#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.
// Install Rido.IoTHubClient as a Cake Addin
#addin nuget:?package=Rido.IoTHubClient&version=0.0.5

// Install Rido.IoTHubClient as a Cake Tool
#tool nuget:?package=Rido.IoTHubClient&version=0.0.5

Rido.IoTHubClient

Minimalistic device client to interact with Azure IoT Hub based on MQTTNet

Features

  • Device Auth for Devices and Modules, X509 + SaS with token refresh and configurable reconnect
  • V1 support in master (V2 available in the preview branch, enabling Pub/Sub to MQTT Broker)
  • DPS Client
  • Telemetry, Properties and Commands using reserved topics for v1 and v2
  • Single entry point for DPS, Hub and Central by using a common ConnectionSettings

Connect to IoTHub

Connect Device With SaS

var client = await HubMqttClient.CreateAsync(hostname, device, sasKey);

Connect Module With SaS

var client = await HubMqttClient.CreateAsync(hostname, device, module, sasKey);

Announce the model Id

var client = await HubMqttClient.CreateAsync(hostname, device, sasKey, modelId);

Connect Device or Module with X509

var client = await HubMqttClient.CreateWithClientCertsAsync(hostname, certificate);

Note: See connection settings reference

Disconnects

The client will trigger the event event EventHandler<MqttClientDisconnectedEventArgs> OnMqttClientDisconnected;

(also visible in diagnostics traces)

MQTT Extensions

You can also connect with the MQTTNet client by using the extension methods:

var connack = await mqttClient.ConnectWithSasAsync(hostname, deviceId, sasKey);
var connack = await mqttClient.ConnectWithX509Async(hostname, certificate);

DPS Support

var dpsRes = await DpsClient.ProvisionWithSasAsync("<IdScope>", "<deviceId>", "<deviceKey>");
Console.WriteLine(dpsRes.registrationState.assignedHub));
var dpsRes = await DpsClient.ProvisionWithCertAsync("<IdScope>", certificate);
Console.WriteLine(dpsRes.registrationState.assignedHub));

Reserved Topics Usage

Send Telemetry

await client.SendTelemetryAsync(new { temperature = 1 });

Read Twin

var twin = await client.GetTwinAsync();

Update Twin (Reported Properties)

var version = await client.UpdateTwinAsync(new { tool = "from Rido.IoTHubClient" }); 
Console.WriteLine("Twin PATCHED version: " + version));

Respond to Twin updates (Desired Properties)

client.OnPropertyChange = e =>
{
    Console.WriteLine($"Processing Desired Property {e.PropertyMessageJson}");
    return new PropertyAck()
    {
        Version = e.Version,
        Status = 200,
        Description = "testing acks",
        Value = e.PropertyMessageJson
    };
};

Respond to Commands

client.OnCommand = req => 
{
    System.Console.WriteLine($"<- Received Command {req.CommandName}");
    string payload = req.CommandPayload;
    System.Console.WriteLine(payload);
    return new CommandResponse
    {
        _status = 200,
        CommandResponsePayload = new { myResponse = "all good"}
    };
};

Connection Settings Reference

This library implements a compatible connection string with Azure IoT SDK Device Client, and adds some new properties:

  • HostName Azure IoT Hub hostname (FQDN)
  • IdScope DPS IdScope
  • DeviceId Device Identity
  • SharedAccessKey Device Shared Access Key
  • X509Key <pathtopfx>|<pfxpassword>
  • ModelId DTDL Model ID in DTMI format to create PnP Devices
  • ModuleId Device Module Identity
  • Auth Device Authentication: [SAS, X509]
  • SasMinutes SasToken expire time in minutes
  • RetryInterval Wait before connection retries in seconds. 0 to disable automatic reconnects
  • MaxRetries Max number of retries in case of automatic reconnect

Sample Connection String

$"HostName=test.azure-devices.net;DeviceId=myDevice;ModuleId=myModule;SharedAccessKey=<moduleSasKey>;ModelId=dtmi:my:model;1";SasMinutes=120

Tracing

This library uses System.Diagnostics.Tracing

Trace.Listeners[0].Filter = new EventTypeFilter(SourceLevels.Information);
Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
Trace.Listeners[1].Filter = new EventTypeFilter(SourceLevels.Warning);

Custom Topics Usage

Custom topics require IoTHub V2, available in the preview branch

When connected to a MQTTBroker enabled hub, this library allows to pub/sub to topics defined in the hub topic-space.

Using MQTTNet directly

var mqttClient = new MqttFactory().CreateMqttClient(); 
var dcs = new ConnectionSettings
{
    HostName = "broker.azure-devices.net",
    DeviceId = "d4",
    SharedAccessKey = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(Guid.Empty.ToString("N")))
}; 
System.Console.WriteLine(dcs);

var connack = await mqttClient.ConnectWithSasAsync(dcs.HostName, dcs.DeviceId, dcs.SharedAccessKey);
Console.WriteLine($"{nameof(mqttClient.IsConnected)}:{mqttClient.IsConnected} . {connack.ResultCode}");

 var topic = $"vehicles";
var subAck = await mqttClient.SubscribeAsync(topic + $"/+/telemetry");
subAck.Items.ForEach(x => Console.WriteLine($"{x.TopicFilter}{x.ResultCode}"));

mqttClient.UseApplicationMessageReceivedHandler(e =>
{
    Console.Write($"<- {e.ApplicationMessage.Topic} {e.ApplicationMessage.Payload.Length} Bytes: ");
    Console.WriteLine(Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
    //Console.Write('.');
});

while (true)
{
    string pubtopic = $"{topic}/{dcs.DeviceId}/telemetry";
    var msg = Environment.TickCount64.ToString();
    var pubAck = await mqttClient.PublishAsync(pubtopic, msg);
    Console.WriteLine($"-> {pubtopic} {msg}. {pubAck.ReasonCode}");
    await Task.Delay(1000);
}

To create topic spaces, use

az iot hub topic-space create -n {iothub_name} --tsn publisher_ts --tst PublishOnly --template 'vehicles/${principal.deviceid}/GPS/#'
az iot hub topic-space create -n {iothub_name} --tsn subscriber_ts --tst LowFanout --template 'vehicles/#'

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  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. 
.NET Core netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.1 is compatible. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

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.0.13 619 12/3/2021
0.0.12 1,204 12/1/2021
0.0.11 3,834 11/25/2021
0.0.10 5,813 11/24/2021
0.0.9 516 11/18/2021
0.0.8 492 11/12/2021
0.0.7 555 11/5/2021
0.0.6 595 11/5/2021
0.0.5 544 11/3/2021
0.0.4 493 11/2/2021
0.0.3 601 10/29/2021
0.0.2 556 10/21/2021
0.0.1 546 10/19/2021
0.0.1-pre001 296 10/5/2021
0.0.1-broker0 281 10/19/2021

0.0.5 Update to MQTTNet 3.0.17
0.0.4 Use Func T for callbacks
Ack for desired properties
0.0.3 ConnectionSettings with IdScope
0.0.2 Expose Disconnect event,
Add component name to telemetry
Reconnects
0.0.1 - Support api-version 2020-09-30
Device/Module support
Sas Tokens Auth with Refresh
X509 Auth
DPS Client