Skip to content

Commit

Permalink
Add support for EdgeModules (#98)
Browse files Browse the repository at this point in the history
* support edge modules

* adding tests

---------

Co-authored-by: rido-min <[email protected]>
  • Loading branch information
ridomin and rido-min authored Mar 6, 2023
1 parent 610a3a4 commit 2500b79
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 12 deletions.
2 changes: 1 addition & 1 deletion samples/iothub-sample/Device.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public Device(ILogger<Device> logger, IConfiguration configuration)

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var connectionSettings = new ConnectionSettings(_configuration.GetConnectionString("cs"));
var connectionSettings = new ConnectionSettings(_configuration.GetConnectionString("csme"));
_logger.LogWarning("Connecting to: {connectionSettings}", connectionSettings);

var client = new HubMqttClient(await HubDpsFactory.CreateFromConnectionSettingsAsync(connectionSettings, stoppingToken));
Expand Down
20 changes: 15 additions & 5 deletions src/MQTTnet.Extensions.MultiCloud/Connections/SasAuth.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,18 @@ namespace MQTTnet.Extensions.MultiCloud.Connections;
internal class SasAuth
{
private const string apiversion_2020_09_30 = "2020-09-30";
internal static string GetUserName(string hostName, string deviceId, string modelId = "") =>
$"{hostName}/{deviceId}/?api-version={apiversion_2020_09_30}&model-id={modelId}";
internal static string GetUserName(string hostName, string deviceId, string modelId = "", string gatewayHostName = "")
{
if (string.IsNullOrEmpty(gatewayHostName))
{
return $"{hostName}/{deviceId}/?api-version={apiversion_2020_09_30}&model-id={modelId}";
}
else
{
return $"{gatewayHostName}/{deviceId}/?api-version={apiversion_2020_09_30}&model-id={modelId}";
}

}

internal static string Sign(string requestString, string key)
{
Expand All @@ -21,10 +31,10 @@ internal static string CreateSasToken(string resource, string sasKey, int minute
return $"SharedAccessSignature sr={resource}&sig={sig}&se={expiry}";
}

internal static (string username, string password) GenerateHubSasCredentials(string hostName, string deviceId, string sasKey, string audience, string modelId, int minutes = 60)
internal static (string username, string password) GenerateHubSasCredentials(string hostName, string deviceId, string sasKey, string audience, string modelId, int minutes = 60, string gatewayHostName = "")
{
string user = GetUserName(hostName, deviceId, modelId);
string pwd = CreateSasToken($"{audience}/devices/{deviceId}", sasKey, minutes);
string user = GetUserName(hostName, deviceId, modelId, gatewayHostName);
string pwd = CreateSasToken(audience, sasKey, minutes);
return (user, pwd);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,15 @@ internal static MqttClientOptionsBuilder WithAzureIoTHubCredentials(this MqttCli
string? hostName = cs!.HostName!;
if (!string.IsNullOrEmpty(cs.GatewayHostName))
{
hostName = cs.GatewayHostName;
//hostName = cs.GatewayHostName;
builder.WithTcpServer(cs.GatewayHostName, cs.TcpPort);
}
else
{
builder.WithTcpServer(hostName, cs.TcpPort);
}


builder.WithTcpServer(hostName, cs.TcpPort);
if (cs?.Auth == AuthType.Sas)
{
if (string.IsNullOrEmpty(cs.ModuleId))
Expand All @@ -27,7 +32,7 @@ internal static MqttClientOptionsBuilder WithAzureIoTHubCredentials(this MqttCli
}

builder.WithTlsSettings(cs);
return builder.WithAzureIoTHubCredentialsSas(hostName, cs.DeviceId!, cs.ModuleId!, cs.HostName!, cs.SharedAccessKey!, cs.ModelId!, cs.SasMinutes);
return builder.WithAzureIoTHubCredentialsSas(hostName, cs.DeviceId!, cs.ModuleId!, cs.HostName!, cs.SharedAccessKey!, cs.ModelId!, cs.SasMinutes, cs.GatewayHostName!);
}
else if (cs?.Auth == AuthType.X509)
{
Expand All @@ -54,14 +59,17 @@ internal static MqttClientOptionsBuilder WithAzureIoTHubCredentials(this MqttCli
}
}

public static MqttClientOptionsBuilder WithAzureIoTHubCredentialsSas(this MqttClientOptionsBuilder builder, string hostName, string deviceId, string moduleId, string audience, string sasKey, string modelId, int sasMinutes)
public static MqttClientOptionsBuilder WithAzureIoTHubCredentialsSas(this MqttClientOptionsBuilder builder, string hostName, string deviceId, string moduleId, string audience, string sasKey, string modelId, int sasMinutes, string gatewayHostName)
{
string target = deviceId;
if (!string.IsNullOrEmpty(moduleId))
{
target = $"{deviceId}/{moduleId}";
audience = $"{hostName}/devices/{deviceId}/modules/{moduleId}";
}
(string username, string password) = SasAuth.GenerateHubSasCredentials(hostName, target, sasKey, audience, modelId, sasMinutes);


(string username, string password) = SasAuth.GenerateHubSasCredentials(hostName, target, sasKey, audience, modelId, sasMinutes, gatewayHostName);
builder.WithCredentials(username, password);
return builder;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,5 +95,24 @@ public async Task ModuleCert()
Assert.True(client.IsConnected);
await client.DisconnectAsync();
}

[Fact(Skip ="Required edgeHub-local")]
public async Task ModuleSasUsingEdgeHub()
{
var cs = new ConnectionSettings()
{
HostName = "rido-edges.azure-devices.net",
DeviceId = "riduntu22",
ModuleId = "MyFilterModule",
SharedAccessKey = "xidAoWNigrri7dAV/NynNFvOCTTgyTjlUIGoHI6wxyk=",
GatewayHostName = "localhost"
};
var connAck = await client!.ConnectAsync(new MqttClientOptionsBuilder()
.WithConnectionSettings(cs)
.Build());
Assert.Equal(MqttClientConnectResultCode.Success, connAck.ResultCode);
Assert.True(client.IsConnected);
await client.DisconnectAsync();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public void CanDeserialize()
//var json = @"{""model-id"":""dtmi:rido:pnp:memmon;1"",""when"":""2022-09-11T16:28:38.1615346-07:00"",""status"":""offline""}";
var json = @"{""model-id"":""dtmi:rido:pnp:sensehat;1"",""when"":""2023-02-08T08:39:40.9008917+00:00"",""status"":""online""}";
BirthConvention.BirthMessage bm = Json.FromString<BirthConvention.BirthMessage>(json)!;
Assert.Equal(BirthConvention.ConnectionStatus.offline, bm.ConnectionStatus);
Assert.Equal(BirthConvention.ConnectionStatus.online, bm.ConnectionStatus);
}
}
}

0 comments on commit 2500b79

Please sign in to comment.