Beispiel #1
0
        // Tests_SRS_DEVICECLIENT_33_004: [** It shall call DisableEventReceiveAsync when the last delegate has been removed. **]**
        public async Task ModuleClient_SetReceiveCallbackAsync_RemoveCallback()
        {
            ModuleClient moduleClient = ModuleClient.CreateFromConnectionString(fakeConnectionString, TransportType.Mqtt_Tcp_Only);
            var          innerHandler = Substitute.For <IDelegatingHandler>();

            moduleClient.InnerHandler = innerHandler;

            await moduleClient.SetInputMessageHandlerAsync("endpoint1", (message, context) => Task.FromResult(MessageResponse.Completed), "custom data");

            await moduleClient.SetInputMessageHandlerAsync("endpoint2", (message, context) => Task.FromResult(MessageResponse.Completed), "custom data");

            await innerHandler.Received(1).EnableEventReceiveAsync(Arg.Any <CancellationToken>());

            await innerHandler.DidNotReceiveWithAnyArgs().DisableEventReceiveAsync(Arg.Any <CancellationToken>());

            await moduleClient.SetInputMessageHandlerAsync("endpoint1", null, null);

            await innerHandler.Received(1).EnableEventReceiveAsync(Arg.Any <CancellationToken>());

            await innerHandler.DidNotReceiveWithAnyArgs().DisableEventReceiveAsync(Arg.Any <CancellationToken>());

            await moduleClient.SetInputMessageHandlerAsync("endpoint2", null, null);

            await innerHandler.Received(1).EnableEventReceiveAsync(Arg.Any <CancellationToken>());

            await innerHandler.Received(1).DisableEventReceiveAsync(Arg.Any <CancellationToken>());
        }
        public async Task ModuleTwin_Contains_ModelId()
        {
            // Setup

            // Create a module.
            TestModule testModule = await TestModule.GetTestModuleAsync(DevicePrefix, ModulePrefix, Logger).ConfigureAwait(false);

            // Send model ID with MQTT connect packet to make the module plug and play.
            var options = new ClientOptions
            {
                ModelId = TestModelId,
            };

            using var moduleClient = ModuleClient.CreateFromConnectionString(testModule.ConnectionString, Client.TransportType.Mqtt_Tcp_Only, options);
            await moduleClient.OpenAsync().ConfigureAwait(false);

            // Act

            // Get module twin.
            using var registryManager = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString);
            Twin twin = await registryManager.GetTwinAsync(testModule.DeviceId, testModule.Id).ConfigureAwait(false);

            // Assert
            twin.ModelId.Should().Be(TestModelId, "because the module was created as plug and play");

            // Cleanup
            await registryManager.RemoveDeviceAsync(testModule.DeviceId).ConfigureAwait(false);
        }
Beispiel #3
0
        public static async Task <TestModule> CreateAndConnect(string connectionString, ITransportSettings[] settings)
        {
            ModuleClient moduleClient = ModuleClient.CreateFromConnectionString(connectionString, settings);
            await moduleClient.OpenAsync();

            return(new TestModule(moduleClient));
        }
Beispiel #4
0
        // Tests_SRS_DEVICECLIENT_33_002: [** The OnReceiveEventMessageCalled shall invoke the specified delegate. **]**
        public async Task ModuleClient_OnReceiveEventMessageCalled_SpecifiedCallbackCalled()
        {
            ModuleClient moduleClient = ModuleClient.CreateFromConnectionString(fakeConnectionString, TransportType.Mqtt_Tcp_Only);
            var          innerHandler = Substitute.For <IDelegatingHandler>();

            moduleClient.InnerHandler = innerHandler;

            bool isDefaultCallbackCalled = false;
            await moduleClient.SetMessageHandlerAsync((message, context) =>
            {
                isDefaultCallbackCalled = true;
                return(Task.FromResult(MessageResponse.Completed));
            }, "custom data");

            bool isSpecificCallbackCalled = false;
            await moduleClient.SetInputMessageHandlerAsync("endpoint2", (message, context) =>
            {
                isSpecificCallbackCalled = true;
                return(Task.FromResult(MessageResponse.Completed));
            }, "custom data");

            Message testMessage = new Message();

            testMessage.LockToken = "AnyLockToken";

            await moduleClient.InternalClient.OnReceiveEventMessageCalled("endpoint2", testMessage);

            Assert.IsFalse(isDefaultCallbackCalled);
            Assert.IsTrue(isSpecificCallbackCalled);
        }
Beispiel #5
0
        static void Main(string[] args)
        {
            try
            {
                try
                {
                    ModuleClient moduleClient = ModuleClient.CreateFromConnectionString(ModuleConnectionString);
                    moduleClient.OpenAsync().Wait();
                    SendMessages(moduleClient).Wait();
                    Twin twin = moduleClient.GetTwinAsync().Result;
                    Console.WriteLine($"Module Twin Desired Properties: {twin.Properties.Desired.ToJson(Formatting.Indented)}");
                    Console.WriteLine($"Module Twin Tags: {twin.Tags.ToJson(Formatting.Indented)}");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }

                Console.WriteLine("Exited!\n");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error in sample: {0}", ex.Message);
            }
        }
Beispiel #6
0
        private async Task CreateTemporaryConnection()
        {
            var moduleConnectionString =
                GetModuleConnectionStringAsync(_iotHubConnectionString, _deviceId, _modules[0].Name)
                .Result;

            var tmpClient = ModuleClient.CreateFromConnectionString(moduleConnectionString,
                                                                    new ITransportSettings[]
            {
                new AmqpTransportSettings(TransportType.Amqp_Tcp_Only)
                {
                    RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true,
                    OpenTimeout = new TimeSpan(1)
                }
            }
                                                                    );

            try
            {
                await tmpClient.OpenAsync();
            }
            catch
            {
                // ignored
            }
        }
Beispiel #7
0
        private void InitializeClient()
        {
            // If the client reports Connected status, it is already in operational state.
            if (s_connectionStatus != ConnectionStatus.Connected &&
                _moduleConnectionStrings.Any())
            {
                lock (_initLock)
                {
                    _logger.LogDebug($"Attempting to initialize the client instance, current status={s_connectionStatus}");

                    // If the module client instance has been previously initialized, then dispose it.
                    // The s_wasEverConnected variable is required to store if the client ever reported Connected status.
                    if (s_wasEverConnected && s_connectionStatus == ConnectionStatus.Disconnected)
                    {
                        s_moduleClient?.Dispose();
                        s_wasEverConnected = false;
                    }

                    s_moduleClient = ModuleClient.CreateFromConnectionString(_moduleConnectionStrings.First(), _transportType);
                    s_moduleClient.SetConnectionStatusChangesHandler(ConnectionStatusChangeHandler);
                    s_moduleClient.OperationTimeoutInMilliseconds = (uint)s_operationTimeout.TotalMilliseconds;
                }

                try
                {
                    // Force connection now
                    s_moduleClient.OpenAsync().GetAwaiter().GetResult();
                    _logger.LogDebug($"Initialized the client instance.");
                }
                catch (UnauthorizedException)
                {
                    // Handled by the ConnectionStatusChangeHandler
                }
            }
        }
        /// <inheritdoc />
        public void ReInit(string connectionString, TransportType transportType)
        {
            var newClient = ModuleClient.CreateFromConnectionString(connectionString, transportType);

            _client.Dispose();
            _client = newClient;
        }
Beispiel #9
0
        private async Task ModuleClient_Gives_ConnectionStatus_DeviceDisabled_Base(
            Client.TransportType protocol, Func <RegistryManager, string, Task> registryManagerOperation)
        {
            AmqpTransportSettings amqpTransportSettings = new AmqpTransportSettings(protocol);

            ITransportSettings[] transportSettings = new ITransportSettings[] { amqpTransportSettings };

            TestModule testModule = await TestModule.GetTestModuleAsync(DevicePrefix + $"_{Guid.NewGuid()}", ModulePrefix).ConfigureAwait(false);

            ConnectionStatus?            status             = null;
            ConnectionStatusChangeReason?statusChangeReason = null;
            int deviceDisabledReceivedCount = 0;
            ConnectionStatusChangesHandler statusChangeHandler = (s, r) =>
            {
                if (r == ConnectionStatusChangeReason.Device_Disabled)
                {
                    status             = s;
                    statusChangeReason = r;
                    deviceDisabledReceivedCount++;
                }
            };

            using (ModuleClient moduleClient = ModuleClient.CreateFromConnectionString(testModule.ConnectionString, transportSettings))
            {
                moduleClient.SetConnectionStatusChangesHandler(statusChangeHandler);
                _log.WriteLine($"Created {nameof(DeviceClient)} ID={TestLogging.IdOf(moduleClient)}");

                Console.WriteLine("ModuleClient OpenAsync.");
                await moduleClient.OpenAsync().ConfigureAwait(false);

                // Receiving the module twin should succeed right now.
                Console.WriteLine("ModuleClient GetTwinAsync.");
                var twin = await moduleClient.GetTwinAsync().ConfigureAwait(false);

                Assert.IsNotNull(twin);

                // Delete/disable the device in IoT Hub.
                using (RegistryManager registryManager = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString))
                {
                    await registryManagerOperation(registryManager, testModule.DeviceId).ConfigureAwait(false);
                }

                // Artificial sleep waiting for the connection status change handler to get triggered.
                int sleepCount = 50;
                for (int i = 0; i < sleepCount; i++)
                {
                    await Task.Delay(TimeSpan.FromSeconds(10)).ConfigureAwait(false);

                    if (deviceDisabledReceivedCount == 1)
                    {
                        break;
                    }
                }

                Assert.AreEqual(1, deviceDisabledReceivedCount);
                Assert.AreEqual(ConnectionStatus.Disconnected, status);
                Assert.AreEqual(ConnectionStatusChangeReason.Device_Disabled, statusChangeReason);
            }
        }
Beispiel #10
0
        public void ModuleClient_CreateFromConnectionStringWithClientOptions_DoesNotThrow()
        {
            // setup
            var clientOptions = new ClientOptions
            {
                ModelId = "tempModuleId"
            };

            // act
            var moduleClient = ModuleClient.CreateFromConnectionString(FakeConnectionString, clientOptions);
        }
        private async Task SendSingleMessageModule(ITransportSettings[] transportSettings)
        {
            TestModule testModule = await TestModule.GetTestModuleAsync(DevicePrefix, ModulePrefix, Logger).ConfigureAwait(false);

            using var moduleClient = ModuleClient.CreateFromConnectionString(testModule.ConnectionString, transportSettings);

            await moduleClient.OpenAsync().ConfigureAwait(false);

            await SendSingleMessageModuleAsync(moduleClient, testModule.DeviceId).ConfigureAwait(false);

            await moduleClient.CloseAsync().ConfigureAwait(false);
        }
Beispiel #12
0
        private async Task SendSingleMessageModule(TestDeviceType type, ITransportSettings[] transportSettings)
        {
            TestModule testModule = await TestModule.GetTestModuleAsync(DevicePrefix, ModulePrefix).ConfigureAwait(false);

            using (ModuleClient moduleClient = ModuleClient.CreateFromConnectionString(testModule.ConnectionString, transportSettings))
            {
                await moduleClient.OpenAsync().ConfigureAwait(false);
                await SendSingleMessageModuleAndVerifyAsync(moduleClient, testModule.DeviceId).ConfigureAwait(false);

                await moduleClient.CloseAsync().ConfigureAwait(false);
            }
        }
Beispiel #13
0
 /// <summary>
 /// Helper to create module client
 /// </summary>
 /// <param name="cs"></param>
 /// <param name="transportSetting"></param>
 /// <returns></returns>
 private static async Task<ModuleClient> CreateAsync(IotHubConnectionStringBuilder cs,
     ITransportSettings transportSetting) {
     if (transportSetting == null) {
         if (cs == null) {
             return await ModuleClient.CreateFromEnvironmentAsync();
         }
         return ModuleClient.CreateFromConnectionString(cs.ToString());
     }
     var ts = new ITransportSettings[] { transportSetting };
     if (cs == null) {
         return await ModuleClient.CreateFromEnvironmentAsync(ts);
     }
     return ModuleClient.CreateFromConnectionString(cs.ToString(), ts);
 }
Beispiel #14
0
        public static async Task <TestModule> CreateAndConnect(string connectionString, ITransportSettings[] settings, int retryCount = int.MaxValue)
        {
            ModuleClient moduleClient         = ModuleClient.CreateFromConnectionString(connectionString, settings);
            IRetryPolicy defaultRetryStrategy = new ExponentialBackoff(
                retryCount: retryCount,
                minBackoff: TimeSpan.FromMilliseconds(100),
                maxBackoff: TimeSpan.FromSeconds(10),
                deltaBackoff: TimeSpan.FromMilliseconds(100));

            moduleClient.SetRetryPolicy(defaultRetryStrategy);
            await moduleClient.OpenAsync();

            return(new TestModule(moduleClient));
        }
Beispiel #15
0
        /// <summary>
        /// Initializes the DeviceClient and sets up the callback to receive
        /// messages containing temperature information
        /// </summary>
        static async Task Init(string connectionString, bool bypassCertVerification = false)
        {
            Console.WriteLine("Connection String: {0}", connectionString);

            var mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);

            // During dev you might want to bypass the cert verification. It is highly recommended to verify certs systematically in production
            if (bypassCertVerification)
            {
                Console.WriteLine("Certificate verification is bypassed.");
                mqttSetting.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
            }
            ITransportSettings[] settings = { mqttSetting };

            // Open a connection to the Edge runtime
            //var ioTHubModuleClient = DeviceClient.CreateFromConnectionString(connectionString, settings); //Andrey Fedorov
            ModuleClient ioTHubModuleClient = null;                                           //Andrey Fedorov

            if (string.IsNullOrEmpty(connectionString))                                       //Andrey Fedorov
            {
                ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); //Andrey Fedorov
            }
            else //Andrey Fedorov
            {
                ioTHubModuleClient = ModuleClient.CreateFromConnectionString(connectionString, settings);
            }

            await ioTHubModuleClient.OpenAsync();

            Console.WriteLine("IoT Hub module client initialized.");

            var moduleTwin = await ioTHubModuleClient.GetTwinAsync();

            var moduleTwinCollection = moduleTwin.Properties.Desired;

            desiredPropertiesData = new DesiredPropertiesData(moduleTwinCollection);

            // callback for updating desired properties through the portal or rest api
            await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null);

            // this direct method will allow to reset the temperature sensor values back to their initial state
            await ioTHubModuleClient.SetMethodHandlerAsync("reset", ResetMethod, null);

            // we don't pass ioTHubModuleClient as we're not sending any messages out to the message bus
            // Register callback to be called when a message is received by the module
            await ioTHubModuleClient.SetInputMessageHandlerAsync("control", ControlMessageHandler, null);

            // as this runs in a loop we don't await
            SendSimulationData(ioTHubModuleClient);
        }
Beispiel #16
0
 public IClient Create(IIdentity identity, string connectionString, ITransportSettings[] transportSettings)
 {
     if (identity is IModuleIdentity)
     {
         ModuleClient moduleClient = ModuleClient.CreateFromConnectionString(connectionString, transportSettings);
         return(new ModuleClientWrapper(moduleClient));
     }
     else if (identity is IDeviceIdentity)
     {
         DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(connectionString, transportSettings);
         return(new DeviceClientWrapper(deviceClient));
     }
     throw new InvalidOperationException($"Invalid client identity type {identity.GetType()}");
 }
Beispiel #17
0
        public ModuleSimulationService(ModuleSettings settings, SimulationSettingsModule simulationSettings, ITelemetryMessageService telemetryMessagingService, IErrorMessageService errorMessagingService, ICommissioningMessageService commissioningMessagingService, ILoggerFactory loggerFactory)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

            if (simulationSettings == null)
            {
                throw new ArgumentNullException(nameof(simulationSettings));
            }

            if (telemetryMessagingService == null)
            {
                throw new ArgumentNullException(nameof(telemetryMessagingService));
            }

            if (errorMessagingService == null)
            {
                throw new ArgumentNullException(nameof(errorMessagingService));
            }

            if (commissioningMessagingService == null)
            {
                throw new ArgumentNullException(nameof(commissioningMessagingService));
            }

            if (loggerFactory == null)
            {
                throw new ArgumentNullException(nameof(loggerFactory));
            }

            string logPrefix = "system".BuildLogPrefix();

            ModuleSettings     = settings;
            SimulationSettings = simulationSettings;
            _logger            = loggerFactory.CreateLogger <ModuleSimulationService>();

            _telemetryMessagingService     = telemetryMessagingService;
            _errorMessagingService         = errorMessagingService;
            _commissioningMessagingService = commissioningMessagingService;

            _telemetryInterval = 10;
            _stopProcessing    = false;

            _moduleClient = ModuleClient.CreateFromConnectionString(ModuleSettings.ConnectionString, Microsoft.Azure.Devices.Client.TransportType.Mqtt);
            _logger.LogDebug($"{logPrefix}::{ModuleSettings.ArtifactId}::Logger created.");
            _logger.LogDebug($"{logPrefix}::{ModuleSettings.ArtifactId}::Module simulator created.");
        }
Beispiel #18
0
        // Initialize the device client instance over Mqtt protocol (TCP, with fallback over Websocket), setting the ModelId into ClientOptions.
        // This method also sets a connection status change callback, that will get triggered any time the device's connection status changes.
        private static void InitializeDeviceClientAsync()
        {
            var options = new ClientOptions
            {
                ModelId = ModelId,
            };

            s_deviceClient = ModuleClient.CreateFromConnectionString(s_deviceConnectionString, TransportType.Mqtt, options);

            //s_deviceClient = DeviceClient.CreateFromConnectionString(s_deviceConnectionString, TransportType.Mqtt, options);
            s_deviceClient.SetConnectionStatusChangesHandler((status, reason) =>
            {
                s_logger.LogDebug($"Connection status change registered - status={status}, reason={reason}.");
            });
        }
Beispiel #19
0
 private void Connect()
 {
     if (Client == null)
     {
         try
         {
             Client = ModuleClient.CreateFromConnectionString(_options.ModuleConnectionString, TransportType.Amqp);
         }
         catch (Exception e)
         {
             Client = null; // Set to null for reconection
             throw e;
         }
     }
 }
Beispiel #20
0
        public async Task <ConnectResponse> ConnectAsync(string transport, string connectionString, Certificate caCertificate)
        {
            Console.WriteLine("ConnectAsync for " + transport);
            var client = ModuleClient.CreateFromConnectionString(connectionString, GlueUtils.TransportNameToType(transport));
            await client.OpenAsync().ConfigureAwait(false);

            var connectionId = modulePrefix + Convert.ToString(++objectCount);

            Console.WriteLine("Connected successfully.  Connection Id = " + connectionId);
            objectMap[connectionId] = client;
            return(new ConnectResponse
            {
                ConnectionId = connectionId
            });
        }
        public async Task ModuleClient_SetDefaultReceiveCallbackAsync_SetCallback_Amqp()
        {
            var moduleClient = ModuleClient.CreateFromConnectionString(FakeConnectionString, TransportType.Amqp_Tcp_Only);
            IDelegatingHandler innerHandler = Substitute.For <IDelegatingHandler>();

            moduleClient.InnerHandler = innerHandler;

            await moduleClient.SetMessageHandlerAsync((message, context) => Task.FromResult(MessageResponse.Completed), "custom data").ConfigureAwait(false);

            await innerHandler.Received(1).EnableEventReceiveAsync(false, Arg.Any <CancellationToken>()).ConfigureAwait(false);

            await innerHandler.DidNotReceiveWithAnyArgs().EnableReceiveMessageAsync(Arg.Any <CancellationToken>()).ConfigureAwait(false);

            await innerHandler.DidNotReceiveWithAnyArgs().DisableEventReceiveAsync(false, Arg.Any <CancellationToken>()).ConfigureAwait(false);
        }
Beispiel #22
0
        //private static TransportType s_transportType = TransportType.Amqp_WebSocket_Only;
        //private static TransportType s_transportType = TransportType.Mqtt_WebSocket_Only;

        public static int Main(string[] args)
        {
            if (string.IsNullOrEmpty(s_deviceConnectionString) && args.Length > 0)
            {
                s_deviceConnectionString = args[0];
            }

            if (string.IsNullOrEmpty(s_deviceConnectionString))
            {
                Console.WriteLine("Please provide a device connection string");
                Console.WriteLine("Usage: DeviceClientC2DStreamingSample [iotHubDeviceConnString]");
                return(1);
            }

            if (s_deviceConnectionString.Contains("ModuleId="))
            {
                Console.WriteLine("Creating a module client using " + s_transportType);
                using (ModuleClient moduleClient = ModuleClient.CreateFromConnectionString(s_deviceConnectionString, s_transportType))
                {
                    if (moduleClient == null)
                    {
                        Console.WriteLine("Failed to create DeviceClient!");
                        return(1);
                    }

                    var sample = new DeviceStreamSample(null, moduleClient);
                    sample.RunSampleAsync().GetAwaiter().GetResult();
                }
            }
            else
            {
                Console.WriteLine("Creating a device client using " + s_transportType);
                using (DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(s_deviceConnectionString, s_transportType))
                {
                    if (deviceClient == null)
                    {
                        Console.WriteLine("Failed to create ModuleClient!");
                        return(1);
                    }

                    var sample = new DeviceStreamSample(deviceClient, null);
                    sample.RunSampleAsync().GetAwaiter().GetResult();
                }
            }

            Console.WriteLine("Done.\n");
            return(0);
        }
Beispiel #23
0
        private async Task SendMethodAndRespondAsync(Client.TransportType transport, Func <ModuleClient, string, MsTestLogger, Task <Task> > setDeviceReceiveMethod, TimeSpan responseTimeout = default, ServiceClientTransportSettings serviceClientTransportSettings = default)
        {
            TestModule testModule = await TestModule.GetTestModuleAsync(_devicePrefix, _modulePrefix, Logger).ConfigureAwait(false);

            using var moduleClient = ModuleClient.CreateFromConnectionString(testModule.ConnectionString, transport);

            Task methodReceivedTask = await setDeviceReceiveMethod(moduleClient, MethodName, Logger).ConfigureAwait(false);

            await Task
            .WhenAll(
                ServiceSendMethodAndVerifyResponseAsync(testModule.DeviceId, testModule.Id, MethodName, DeviceResponseJson, ServiceRequestJson, Logger, responseTimeout, serviceClientTransportSettings),
                methodReceivedTask)
            .ConfigureAwait(false);

            await moduleClient.CloseAsync().ConfigureAwait(false);
        }
Beispiel #24
0
        private async Task SendSingleMessageModule(TestDeviceType type, ITransportSettings[] transportSettings)
        {
            TestModule testModule = await TestModule.GetTestModuleAsync(DevicePrefix, ModulePrefix).ConfigureAwait(false);

            using (ModuleClient moduleClient = ModuleClient.CreateFromConnectionString(testModule.ConnectionString, transportSettings))
            {
                await moduleClient.OpenAsync().ConfigureAwait(false);

                string         payload;
                string         p1Value;
                Client.Message testMessage = ComposeD2CTestMessage(out payload, out p1Value);
                await moduleClient.SendEventAsync(testMessage).ConfigureAwait(false);

                await moduleClient.CloseAsync().ConfigureAwait(false);
            }
        }
Beispiel #25
0
        /// <summary>
        /// Initializes the ModuleClient and sets up the callback to receive
        /// messages containing temperature information
        /// </summary>
        static async Task Init()
        {
            MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);

            ITransportSettings[] settings = { mqttSetting };

            // Open a connection to the Edge runtime

            moduleClient = ModuleClient.CreateFromConnectionString("");
            moduleClient.SetConnectionStatusChangesHandler(OnConnectionStatusChanged);
            await moduleClient.OpenAsync();

            Console.WriteLine("IoT Hub module client initialized.");

            timer = new Timer(new TimerCallback(Program.SendEvent), null, 5000 /*dueTime*/, 5000 /*period*/);
        }
Beispiel #26
0
        private async Task TestSecurityMessageModuleAsync(Client.TransportType transport)
        {
            TestModule testModule = await TestModule.GetTestModuleAsync(_devicePrefix, _modulePrefix, Logger).ConfigureAwait(false);

            using (var moduleClient = ModuleClient.CreateFromConnectionString(testModule.ConnectionString, transport))
            {
                try
                {
                    await SendSingleSecurityMessageModuleAsync(moduleClient, testModule.DeviceId, _logAnalyticsClient).ConfigureAwait(false);
                }
                finally
                {
                    await moduleClient.CloseAsync().ConfigureAwait(false);
                }
            }
        }
        public ModuleSimulationService(ModuleSettings settings, SimulationSettingsModule simulationSettings, IDTDLMessageService dtdlMessagingService, IDTDLCommandService dtdlCommandService, ILoggerFactory loggerFactory)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

            if (simulationSettings == null)
            {
                throw new ArgumentNullException(nameof(simulationSettings));
            }

            if (dtdlMessagingService == null)
            {
                throw new ArgumentNullException(nameof(dtdlMessagingService));
            }

            if (loggerFactory == null)
            {
                throw new ArgumentNullException(nameof(loggerFactory));
            }

            string logPrefix = "system".BuildLogPrefix();

            ModuleSettings     = settings;
            SimulationSettings = simulationSettings;
            _logger            = loggerFactory.CreateLogger <ModuleSimulationService>();

            _dtdlMessagingService = dtdlMessagingService;
            _dtdlCommandService   = dtdlCommandService;

            _telemetryInterval = 10;
            _stopProcessing    = false;

            _moduleClient = ModuleClient.CreateFromConnectionString(ModuleSettings.ConnectionString, Microsoft.Azure.Devices.Client.TransportType.Mqtt);
            _logger.LogDebug($"{logPrefix}::{ModuleSettings.ArtifactId}::Logger created.");
            _logger.LogDebug($"{logPrefix}::{ModuleSettings.ArtifactId}::Module simulator created.");

            //Default DTDL Model
            _defaultModel = ModuleSettings?.SupportedModels?.SingleOrDefault(i => i.ModelId == ModuleSettings.DefaultModelId);
            if (_defaultModel == null)
            {
                throw new Exception("No supported model corresponds to the default model Id.");
            }
        }
Beispiel #28
0
        public IClient Create(IIdentity identity, string connectionString, ITransportSettings[] transportSettings)
        {
            Preconditions.CheckNotNull(identity, nameof(identity));
            Preconditions.CheckNotNull(transportSettings, nameof(transportSettings));
            Preconditions.CheckNonWhiteSpace(connectionString, nameof(connectionString));

            if (identity is IModuleIdentity)
            {
                ModuleClient moduleClient = ModuleClient.CreateFromConnectionString(connectionString, transportSettings);
                return(new ModuleClientWrapper(moduleClient));
            }
            else if (identity is IDeviceIdentity)
            {
                DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(connectionString, transportSettings);
                return(new DeviceClientWrapper(deviceClient));
            }
            throw new InvalidOperationException($"Invalid client identity type {identity.GetType()}");
        }
        /// <summary>
        /// If a ModuleClient configuration is specified,
        /// creates a module client from the configuration,
        /// Otherwise creates a ModuleClientWrapper which delegates to the IoT sdk's ModuleClient.
        /// according to the LocalConfiguration.ClientConnectionString
        /// </summary>
        /// <returns>A new instance of IModuleClient</returns>
        private static IModuleClient CreateClient()
        {
            NameValueCollection agentConfig = (NameValueCollection)ConfigurationManager.GetSection("General");
            var moduleClientDll             = agentConfig["ModuleClientDll"];
            var moduleClientTypeName        = agentConfig["ModuleClientFullName"];

            if (!string.IsNullOrEmpty(moduleClientDll) && !string.IsNullOrEmpty(moduleClientTypeName))
            {
                Assembly assembly = Assembly.LoadFrom(Path.GetFullPath(moduleClientDll));
                Type     type     = assembly.GetType(moduleClientTypeName);

                return((IModuleClient)Activator.CreateInstance(type));
            }

            return(new ModuleClientWrapper(ModuleClient.CreateFromConnectionString(
                                               AuthenticationMethodProvider.GetModuleConnectionString(),
                                               LocalIoTHubConfiguration.IotInterface.TransportType)));
        }
Beispiel #30
0
        // Tests_SRS_DEVICECLIENT_33_001: [** If the given eventMessageInternal argument is null, fail silently **]**
        public async Task ModuleClient_OnReceiveEventMessageCalled_NullMessageRequest()
        {
            ModuleClient moduleClient = ModuleClient.CreateFromConnectionString(fakeConnectionString, TransportType.Mqtt_Tcp_Only);
            var          innerHandler = Substitute.For <IDelegatingHandler>();

            moduleClient.InnerHandler = innerHandler;

            bool isMessageHandlerCalled = false;
            await moduleClient.SetInputMessageHandlerAsync("endpoint1", (message, context) =>
            {
                isMessageHandlerCalled = true;
                return(Task.FromResult(MessageResponse.Completed));
            }, "custom data");

            await moduleClient.InternalClient.OnReceiveEventMessageCalled(null, null);

            Assert.IsFalse(isMessageHandlerCalled);
        }