Rido.IoTHubClient 0.0.7

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.7
NuGet\Install-Package Rido.IoTHubClient -Version 0.0.7
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.7" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Rido.IoTHubClient --version 0.0.7
#r "nuget: Rido.IoTHubClient, 0.0.7"
#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.7

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

Rido.IoTHubClient

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

master preview
.NET .NET
NuGet version (Rido.IoTHubClient) N/A

Features

  • Device Auth for Devices and Modules, X509 + SaS with token refresh and reconnects
  • ClassicHub support in master
  • Broker-Enabled Hub available in the preview branch, with custom pub/sub support)
  • DPS Client
  • Telemetry, Properties and Commands using reserved topics for classic and broker-enabled hubs
  • Single entry point for DPS, Hub and Central by using a common ConnectionSettings

Connect to IoT Hub

Authentication

  • X509 and SAS Authentication available as IMqttClient extension methods.
mqttClient = MqttFactory().CreateMqttClient();
connack = await mqttClient.ConnectWithSasAsync(hostname, deviceId, sasKey);
connack = await mqttClient.ConnectWithSasAsync(hostname, deviceId, moduleId, sasKey);
connack = await mqttClient.ConnectWithX509Async(hostname, certificate);

Note: To connect with module identity, certificates, PnP, or other connection option use the connection settings overload.

Connection Management

  • The HubMqttConnection class handles Sas Token refresh and Reconnects, configurable using the ConnectionSettings.
  • Disconnects trigger the event event EventHandler<MqttClientDisconnectedEventArgs> OnMqttClientDisconnected;
var connection = await HubMqttConnection.CreateAsync(
  ConnectionSettings.FromConnectionString(
    Environment.GetEnvironmentVariable("cs")));

DPS Support

When using a connection setting with IdSCope the HubMqttConnection class will provision and set the assigned hub to the connection setting.

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

Reserved topics to use Telemetry, Properties and Commands are implemented in the HubMqttClient.

var client = await HubMqttClient.CreateAsync(
  ConnectionSettings.FromConnectionString(
    Environment.GetEnvironmentVariable("cs")));
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 = async 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 = async 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, default to 60.
  • RetryInterval Wait before connection retries in seconds. 0 to disable automatic reconnects, default to 5.
  • MaxRetries Max number of retries in case of automatic reconnect. default to 10.

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

Using custom topics requires access tp an IoTHub enabled broker actually in provate preview. Instructions available here

The preview branch implements the Authentication scheme and reserved topics.

Using MQTTNet directly

var mqttClient = new MqttFactory().CreateMqttClient(); 
var dcs = ConnectionSettings.FromConnectionString(cs);
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 625 12/3/2021
0.0.12 1,204 12/1/2021
0.0.11 3,835 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 602 10/29/2021
0.0.2 556 10/21/2021
0.0.1 546 10/19/2021
0.0.1-pre001 297 10/5/2021
0.0.1-broker0 281 10/19/2021

0.0.7 Expose internal MqttClient in HubMqttConnection
0.0.6 Make the callbacks async compatible, split connection and client
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