private async Task ConnectIoTEdgeDeviceClient(CancellationToken stopToken) { upstreamClient = factory.CreateMqttClient(); logger.LogInformation($"HostName: {upstreamClientCredentials.HostName} : SasKey: {upstreamClientCredentials.SaSKey}"); var sig = EdgeTools.GenerateSasToken(upstreamClientCredentials.HostName, upstreamClientCredentials.DeviceId, upstreamClientCredentials.SaSKey, TimeSpan.FromDays(365 * 1000)); logger.LogInformation($"Device {upstreamClientCredentials.DeviceId} Shared Sig : {sig}"); var upstreamOptions = new MqttClientOptionsBuilder() .WithTcpServer(upstreamClientCredentials.HostName, 8883) .WithClientId(upstreamClientCredentials.DeviceId) .WithCredentials(upstreamClientCredentials.MqttDeviceUserName, sig) .WithProtocolVersion(MqttProtocolVersion.V311) .WithTls(new MqttClientOptionsBuilderTlsParameters() { UseTls = true }) .Build(); try { logger.LogInformation($"Connecting upstream client {device.IothubDeviceId}"); upstreamClient.UseConnectedHandler(async e => { logger.LogInformation($"Device {upstreamClientCredentials.DeviceId} connected"); // Subscribe to cloud to device messages var topic = $"devices/{upstreamClientCredentials.DeviceId}/messages/devicebound/#"; await upstreamClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic(topic).Build()); // Initialise twin handling //TwinStateLifecycle twinState = new TwinStateLifecycle(clock, upstreamClient); await Task.CompletedTask; }); upstreamClient.UseDisconnectedHandler(async e => { logger.LogInformation($"Device {upstreamClientCredentials.DeviceId} disconnected"); await Task.CompletedTask; }); upstreamClient.UseApplicationMessageReceivedHandler(async e => { await iotEdgeClient.HandleMessage(e, stopToken); }); await upstreamClient.ConnectAsync(upstreamOptions, stopToken); } catch (Exception ex) { logger.LogError($"{ex}"); } }
public static CompositeDeviceClient CreateInModule(IConfiguration config, CompositeDeviceConfiguration.Device device, Messaging.MessageHandler upstreamToDownstream, Messaging.MessageHandler downstreamToUpstream, IClock clock, ILoggerFactory loggerFactory) { var moduleConnectionString = config.GetValue <string>("EdgeHubConnectionString"); var upstreamClientCredentials = EdgeTools.GetDeviceCredentialsFromModule(moduleConnectionString, device.IothubDeviceId, device.SasKey); var downstreamClientCredentials = EdgeTools.GetMqttDeviceCredentials(device); return(new CompositeDeviceClient(device, upstreamClientCredentials, downstreamClientCredentials, upstreamToDownstream, downstreamToUpstream, clock, loggerFactory)); }