Exemplo n.º 1
0
        protected Details(
            string iothubConnectionString,
            string eventhubCompatibleEndpointWithEntityPath,
            string deviceId,
            string certificateFileName,
            string edgeHostName,
            bool useWebSockets
            )
        {
            this.iothubConnectionString = iothubConnectionString;
            this.eventhubCompatibleEndpointWithEntityPath = eventhubCompatibleEndpointWithEntityPath;
            this.deviceId            = deviceId;
            this.certificateFileName = certificateFileName;
            this.edgeHostName        = edgeHostName;

            if (useWebSockets)
            {
                this.serviceClientTransportType  = ServiceClientTransportType.Amqp_WebSocket_Only;
                this.eventHubClientTransportType = EventHubClientTransportType.AmqpWebSockets;
                this.deviceClientTransportType   = DeviceClientTransportType.Mqtt_WebSocket_Only;
            }
            else
            {
                this.serviceClientTransportType  = ServiceClientTransportType.Amqp;
                this.eventHubClientTransportType = EventHubClientTransportType.Amqp;
                this.deviceClientTransportType   = DeviceClientTransportType.Mqtt;
            }
        }
Exemplo n.º 2
0
        static async Task <int> MainAsync()
        {
            Logger.LogInformation("DirectMethodCloudSender Main() started.");

            IConfiguration configuration = new ConfigurationBuilder()
                                           .SetBasePath(Directory.GetCurrentDirectory())
                                           .AddJsonFile("config/appsettings.json", optional: true)
                                           .AddEnvironmentVariables()
                                           .Build();

            string serviceClientConnectionString = Preconditions.CheckNonWhiteSpace(configuration.GetValue <string>("ServiceClientConnectionString"), "ServiceClientConnectionString");
            // Get device id of this device, exposed as a system variable by the iot edge runtime
            string        targetDeviceId = configuration.GetValue <string>("IOTEDGE_DEVICEID");
            string        targetModuleId = configuration.GetValue("TargetModuleId", "DirectMethodReceiver");
            TransportType transportType  = configuration.GetValue("ClientTransportType", TransportType.Amqp_Tcp_Only);
            TimeSpan      dmDelay        = configuration.GetValue("DirectMethodDelay", TimeSpan.FromSeconds(5));

            (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), null);

            await CallDirectMethodFromCloud(serviceClientConnectionString, targetDeviceId, targetModuleId, transportType, dmDelay, cts);

            completed.Set();
            handler.ForEach(h => GC.KeepAlive(h));
            Logger.LogInformation("DirectMethodCloudSender Main() finished.");
            return(0);
        }
Exemplo n.º 3
0
        private static ITransportSettings CreateTransportSettingsFromName(Microsoft.Azure.Devices.Client.TransportType transportType, string proxyAddress)
        {
            switch (transportType)
            {
            case Microsoft.Azure.Devices.Client.TransportType.Http1:
                return(new Http1TransportSettings
                {
                    Proxy = proxyAddress == null ? null : new WebProxy(proxyAddress),
                });

            case Microsoft.Azure.Devices.Client.TransportType.Amqp:
            case Microsoft.Azure.Devices.Client.TransportType.Amqp_Tcp_Only:
                return(new AmqpTransportSettings(TransportType.Amqp_Tcp_Only));    // Overriding as per error message if using Amqp only

            case Microsoft.Azure.Devices.Client.TransportType.Amqp_WebSocket_Only:
                return(new AmqpTransportSettings(transportType)
                {
                    Proxy = proxyAddress == null ? null : new WebProxy(proxyAddress),
                });

            case Microsoft.Azure.Devices.Client.TransportType.Mqtt:
            case Microsoft.Azure.Devices.Client.TransportType.Mqtt_Tcp_Only:
                return(new MqttTransportSettings(TransportType.Mqtt_Tcp_Only));    // Overriding as per error message if using Mqtt only

            case Microsoft.Azure.Devices.Client.TransportType.Mqtt_WebSocket_Only:
                return(new MqttTransportSettings(transportType)
                {
                    Proxy = proxyAddress == null ? null : new WebProxy(proxyAddress),
                });
            }

            throw new NotSupportedException($"Unknown transport: '{transportType}'.");
        }
Exemplo n.º 4
0
        public static DeviceClient CreateSelfSignedDevice(TransportType transport, string deviceId)
        {
            Console.Write("Connecting to hub....  ");
            var registryManager = RegistryManager.CreateFromConnectionString(hubConnStr);

            Console.WriteLine("done");
            Console.Write("Creating device with self signed key....  ");

            var certificate = GetSelfSigned();
            var device      = new Microsoft.Azure.Devices.Device(deviceId)
            {
                Authentication = new AuthenticationMechanism
                {
                    X509Thumbprint = new X509Thumbprint
                    {
                        PrimaryThumbprint = certificate.Thumbprint
                    }
                }
            };

            var createdDevice = registryManager.AddDeviceAsync(device).Result;

            Console.WriteLine($"done. Id='{deviceId}', X509Thumbprint = '{createdDevice.Authentication.X509Thumbprint.PrimaryThumbprint}'");
            Console.Write("Connecting to device...  ");
            var auth   = new DeviceAuthenticationWithX509Certificate(deviceId, certificate);
            var client = DeviceClient.Create(hubUrl, auth, transport);

            Console.WriteLine("done");

            return(client);
        }
Exemplo n.º 5
0
        public static DeviceClient CreateClient(TransportType transport, string deviceId)
        {
            Console.WriteLine("Connecting to IoT Hub with certificate:");
            var certificate = GetSelfSigned();
            DeviceAuthenticationWithX509Certificate auth = new DeviceAuthenticationWithX509Certificate(deviceId, certificate);

            Console.WriteLine($"----------\n{auth.Certificate}----------");
            DeviceClient client = DeviceClient.Create(hubUrl, auth, transport);

            return(client);
        }
Exemplo n.º 6
0
        public async Task DisposeAsync()
        {
            string deviceConnectionString = Environment.GetEnvironmentVariable("IoTHubDeviceConnectionString");

            Microsoft.Azure.Devices.Client.TransportType transportType = Microsoft.Azure.Devices.Client.TransportType.Mqtt;
            using (DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, transportType))
            {
                // purge messaging services
                output.WriteLine("Purging Service Bus messages");
                PurgeServiceBusMessagesAsync(workOrderQueueClient, output);
                PurgeServiceBusMessagesAsync(createAlertErrorQueueClient, output);
                PurgeServiceBusMessagesAsync(createAlertTopicSubscriptionClient, output);
                output.WriteLine("Purging IoT Hub messages");
                await PurgeIoTHubMessagesAsync(deviceClient);

                // find the case (title property is equal to alertid)
                output.WriteLine("Deleting Dynamics entities");
                QueryExpression  caseQueryExpression       = FindEntityWithPropertyValue("incident", "title", uniqueFaultName);
                EntityCollection caseQueryExpressionResult = this.cdsServiceClient.RetrieveMultiple(caseQueryExpression);
                if (caseQueryExpressionResult != null && caseQueryExpressionResult.Entities.Count > 0)
                {
                    Entity retrievedCase = caseQueryExpressionResult.Entities[0];
                    this.cdsServiceClient.Delete("incident", retrievedCase.Id);
                    output.WriteLine($"Deleted incident entity with id {retrievedCase.Id}");
                }

                // find the work order (msdyn_workordersummary property is equal to alertid) associated with the alert
                QueryExpression  workOrderQueryExpression       = FindEntityWithPropertyValue("msdyn_workorder", "msdyn_workordersummary", uniqueFaultName, true);
                EntityCollection workOrderQueryExpressionResult = this.cdsServiceClient.RetrieveMultiple(workOrderQueryExpression);
                if (workOrderQueryExpressionResult != null && workOrderQueryExpressionResult.Entities.Count > 0)
                {
                    // find the resource requirement attached to work order
                    Entity           retrievedWorkOrder                  = workOrderQueryExpressionResult.Entities[0];
                    string           workOrderName                       = (string)retrievedWorkOrder["msdyn_name"];
                    QueryExpression  resourceRequirementExpression       = FindEntityWithPropertyValue("msdyn_resourcerequirement", "msdyn_name", workOrderName);
                    EntityCollection resourceRequirementExpressionResult = this.cdsServiceClient.RetrieveMultiple(resourceRequirementExpression);
                    if (resourceRequirementExpressionResult != null && resourceRequirementExpressionResult.Entities.Count > 0)
                    {
                        Entity retrievedResourceRequirement = resourceRequirementExpressionResult.Entities[0];
                        this.cdsServiceClient.Delete("msdyn_resourcerequirement", retrievedResourceRequirement.Id);
                        output.WriteLine($"Deleted msdyn_resourcerequirement entity with id {retrievedResourceRequirement.Id}");
                    }
                    this.cdsServiceClient.Delete("msdyn_workorder", retrievedWorkOrder.Id);
                    output.WriteLine($"Deleted msdyn_workorder entity with id {retrievedWorkOrder.Id}");
                }

                foreach (KeyValuePair <Guid, string> pair in entitiesToDelete)
                {
                    this.cdsServiceClient.Delete(pair.Value, pair.Key);
                    output.WriteLine($"Deleted {pair.Value} entity with id {pair.Key}");
                }
                entitiesToDelete.Clear();
            }
        }
Exemplo n.º 7
0
        public async void RunE2ETest()
        {
            string deviceConnectionString                   = Environment.GetEnvironmentVariable("IoTHubDeviceConnectionString");
            string maxRetriesEnvironmentVariable            = Environment.GetEnvironmentVariable("VerificationMaxRetries");
            string retrySecondsEnvironmentVariable          = Environment.GetEnvironmentVariable("VerificationRetrySeconds");
            string shouldCreateWorkOrderEnvironmentVariable = Environment.GetEnvironmentVariable("ShouldCreateWorkOrder");
            int    maxRetries = maxRetriesEnvironmentVariable != null?int.Parse(maxRetriesEnvironmentVariable) : 10;

            int retrySeconds = retrySecondsEnvironmentVariable != null?int.Parse(retrySecondsEnvironmentVariable) : 5;

            bool shouldCreateWorkOrder = shouldCreateWorkOrderEnvironmentVariable != null?bool.Parse(shouldCreateWorkOrderEnvironmentVariable) : false;

            Microsoft.Azure.Devices.Client.TransportType transportType = Microsoft.Azure.Devices.Client.TransportType.Mqtt;
            using (DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, transportType))
            {
                // generate unique GUIDs
                string uniqueAssetName = Guid.NewGuid().ToString();
                string uniqueAssetPath = Guid.NewGuid().ToString();
                uniqueFaultName = Guid.NewGuid().ToString();
                output.WriteLine($"Generated unique AssetName - {uniqueAssetName}");
                output.WriteLine($"Generated unique AssetPath - {uniqueAssetPath}");
                output.WriteLine($"Generated unique FaultName - {uniqueFaultName}");

                // send message to IoTHub
                output.WriteLine("Sending message to IoT Hub");
                string currentISOTimeString = DateTime.UtcNow.ToString("o");
                await SendIconicsFaultDataToIoTHubAsync(deviceClient, uniqueAssetName, uniqueAssetPath, uniqueFaultName, "Active", currentISOTimeString);

                // verify Dynamics Alert and Asset
                output.WriteLine("Attempting Dynamics Alert and Asset verification");
                AssetAlertVerification assetAlertVerification = VerifyDynamicsAssetAndAlert(maxRetries, retrySeconds, uniqueAssetName, uniqueFaultName);

                // create WorkOrder if necessary
                if (shouldCreateWorkOrder)
                {
                    CreateWorkOrderIfNecessary(assetAlertVerification.verifiedAlertId);
                }

                EventHubConsumerClient consumer = new EventHubConsumerClient(EventHubConsumerClient.DefaultConsumerGroupName, Environment.GetEnvironmentVariable("IoTHubEventHubEndpoint"), Environment.GetEnvironmentVariable("IoTHubEventHubName"));

                // verify work order acknowledgement in IoTHub
                output.WriteLine("Attempting IoT Hub work order acknowledgement verification");
                bool iotHubMessageVerified = await VerifyWorkOrderAcknowledgementAsync(consumer, maxRetries, retrySeconds, uniqueAssetPath, uniqueFaultName);

                // assert
                Assert.True(assetAlertVerification.assetVerified);
                Assert.True(assetAlertVerification.alertVerified);
                Assert.True(iotHubMessageVerified);
            }
        }
Exemplo n.º 8
0
        private async void Button_Click_Device(object sender, RoutedEventArgs e)
        {
            string s_port = "22";// tbSvcTimeout2.Text;
            int    port   = int.Parse(s_port, CultureInfo.InvariantCulture);
            string s_deviceConnectionString = Azure_IoTHub_Connections.MyConnections.DeviceConnectionString;

            Microsoft.Azure.Devices.Client.TransportType s_transportType = Microsoft.Azure.Devices.Client.TransportType.Amqp;
            string s_deviceId = Azure_IoTHub_Connections.MyConnections.DeviceId;

            await Task.Run(() =>
            {
                try
                {
                    port = int.Parse(s_port, CultureInfo.InvariantCulture);

                    using (DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(s_deviceConnectionString, s_transportType))
                    {
                        if (deviceClient == null)
                        {
                            Console.WriteLine("Failed to create DeviceClient!");
                            return;
                        }

                        var sample = new DeviceStreamSample(deviceClient, "localhost", port, UpdateDeviceOutputText, OnDeviceStatusUpdate);
                        sample.RunSampleAsync(new CancellationTokenSource()).GetAwaiter().GetResult();
                    }
                    //if (DeviceBasicMode)
                    //    DeviceStream_Device.RunDevice(device_cs, OnDeviceRecvTextIO).GetAwaiter().GetResult();
                    //if (!DeviceUseCustomClass)
                    //    DeviceStream_Device.RunDevice(device_cs, OnDeviceRecvTextIO, OnDeviceStatusUpdate, ActionCommand, AppSettingsValues.Settings.KeepDeviceListening ).GetAwaiter().GetResult();
                    //else
                    //    DeviceStream_Device.RunDevice(device_cs, OnDeviceRecvTextIO, OnDeviceStatusUpdate, ActionCommand, AppSettingsValues.Settings.KeepDeviceListening, new DeviceSvcCurrentSettings_Example()).GetAwaiter().GetResult();
                }
                catch (TaskCanceledException)
                {
                    OnDeviceStatusUpdate("0 Error App.RunClient(): Task cancelled");
                }
                catch (OperationCanceledException)
                {
                    OnDeviceStatusUpdate("0 Error App.RunClient(): Operation cancelled");
                }
                catch (Exception ex)
                {
                    OnDeviceStatusUpdate("0 Error App.RunClient(): " + ex.Message);
                }
            });
        }
Exemplo n.º 9
0
        public async Task <bool> Connect()
        {
            string endPointURI     = _APIURL + "device-api/DeviceAuth/" + _IoTDeviceID;
            string IoTDeviceString = await callAPIService("GET", endPointURI, null);

            dynamic IoTDeviceJSONObj = JObject.Parse(IoTDeviceString);

            _IoTHubName               = IoTDeviceJSONObj.IoTHubName;
            _IoTHubProtocol           = IoTDeviceJSONObj.IoTHubProtocol;
            _IoTHubAuthenticationType = IoTDeviceJSONObj.IoTHubAuthenticationType;
            _IoTDeviceKey             = IoTDeviceJSONObj.DeviceKey;
            _ContainerName            = IoTDeviceJSONObj.ContainerName;
            _CertificateFileName      = IoTDeviceJSONObj.CertificateFileName;
            _CertificatePassword      = IoTDeviceJSONObj.CertificatePassword;
            try
            {
                Microsoft.Azure.Devices.Client.TransportType protocol = Microsoft.Azure.Devices.Client.TransportType.Http1;
                //MessageBox.Show("HTTP1");
                switch (_IoTHubProtocol.ToLower())
                {
                case "amqp":
                    protocol = Microsoft.Azure.Devices.Client.TransportType.Amqp;
                    break;

                case "mqtt":
                    protocol = Microsoft.Azure.Devices.Client.TransportType.Mqtt;
                    break;

                case "https":
                    protocol = Microsoft.Azure.Devices.Client.TransportType.Http1;
                    break;
                }
                if (_CDSClient == null)
                {
                    _CDSClient = DeviceClient.Create(_IoTHubName, new DeviceAuthenticationWithRegistrySymmetricKey(_IoTDeviceID, _IoTDeviceKey), protocol);
                    _CDSClient.OperationTimeoutInMilliseconds = 86400000;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                //MessageBox.Show(ex.ToString());
            }
            return(true);
        }
Exemplo n.º 10
0
        // Example:
        // DeviceLoad.exe {OutputStorageConnectionString} {DeviceClientEndpoint} {DevicePerVm} {MessagePerMin} {DurationInMin} {BatchJobId} {DeviceIdPrefix} [MessageFormat]
        // OutputStorageConnectionString: DefaultEndpointsProtocol=https;AccountName={name};AccountKey={key};EndpointSuffix={core.windows.net}
        // DeviceClientEndpoint: HostName={http://xx.chinacloudapp.cn};SharedAccessKeyName=owner;SharedAccessKey={key}
        static void Main(string[] args)
        {
            setting = Setting.Parse(args);
            if (setting == null)
            {
                Environment.Exit(-1);
            }

            ServicePointManager.DefaultConnectionLimit = 200;

            if (!Enum.TryParse(setting.Transport, out transport))
            {
                transport = Microsoft.Azure.Devices.Client.TransportType.Mqtt;
            }

            wallclock = Stopwatch.StartNew();
            var devices = CreateDevices().Result;

            SendMessages(devices).Wait();
        }
Exemplo n.º 11
0
        public async void ValidateDynamicsInActiveAlert()
        {
            string deviceConnectionString                   = Environment.GetEnvironmentVariable("IoTHubDeviceConnectionString");
            string maxRetriesEnvironmentVariable            = Environment.GetEnvironmentVariable("VerificationMaxRetries");
            string retrySecondsEnvironmentVariable          = Environment.GetEnvironmentVariable("VerificationRetrySeconds");
            string shouldCreateWorkOrderEnvironmentVariable = Environment.GetEnvironmentVariable("ShouldCreateWorkOrder");
            int    maxRetries = maxRetriesEnvironmentVariable != null?int.Parse(maxRetriesEnvironmentVariable) : 10;

            int retrySeconds = retrySecondsEnvironmentVariable != null?int.Parse(retrySecondsEnvironmentVariable) : 5;

            Microsoft.Azure.Devices.Client.TransportType transportType = Microsoft.Azure.Devices.Client.TransportType.Mqtt;
            using (DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, transportType))
            {
                // generate unique GUIDs
                string uniqueAssetName = Guid.NewGuid().ToString();
                string uniqueAssetPath = Guid.NewGuid().ToString();
                uniqueFaultName = Guid.NewGuid().ToString();
                output.WriteLine($"Generated unique AssetName - {uniqueAssetName}");
                output.WriteLine($"Generated unique AssetPath - {uniqueAssetPath}");
                output.WriteLine($"Generated unique FaultName - {uniqueFaultName}");

                // send message to IoTHub
                output.WriteLine("Sending message to IoT Hub");
                string currentISOTimeString = DateTime.UtcNow.ToString("o");
                await SendIconicsFaultDataToIoTHubAsync(deviceClient, uniqueAssetName, uniqueAssetPath, uniqueFaultName, "Active", currentISOTimeString);

                // verify Dynamics Alert and Asset
                output.WriteLine("Attempting Dynamics Alert and Asset verification");
                AssetAlertVerification assetAlertVerification = VerifyDynamicsAssetAndAlert(maxRetries, retrySeconds, uniqueAssetName, uniqueFaultName);
                output.WriteLine("Sending message to IoT Hub with Fault State as InActive");
                await SendIconicsFaultDataToIoTHubAsync(deviceClient, uniqueAssetName, uniqueAssetPath, uniqueFaultName, "InActive", currentISOTimeString);

                bool inActiveAlertVerified = VerifyDynamicsInActiveAlert(maxRetries, retrySeconds, uniqueFaultName);

                // assert
                Assert.True(assetAlertVerification.assetVerified);
                Assert.True(assetAlertVerification.alertVerified);
                Assert.True(inActiveAlertVerified);
            }
        }
Exemplo n.º 12
0
        static async Task <DeviceBenchmarkEntry> StartClient(string IoTHub, string IoTDevicePrefix, int deviceNumber, string commonKey, int maxMessages, int messageSize, Microsoft.Azure.Devices.Client.TransportType transportType)
        {
            string   connectionString = "HostName=" + IoTHub + ";DeviceId=" + IoTDevicePrefix + deviceNumber + ";SharedAccessKey=" + commonKey;
            string   deviceName       = IoTDevicePrefix + deviceNumber;
            DateTime startTime        = DateTime.Now;

            try
            {
                DeviceClient device = DeviceClient.CreateFromConnectionString(connectionString, transportType);
                await device.OpenAsync();

                int mycounter = 1;
                Console.WriteLine($"Device {deviceName} started");

                DateTime startTimeWithoutConnect = DateTime.Now;
                while (mycounter <= maxMessages)
                {
                    var IoTMessage = new Microsoft.Azure.Devices.Client.Message(new byte[messageSize]);
                    await device.SendEventAsync(IoTMessage);

                    mycounter++;
                }
                DateTime endTimeWithoutConnect           = DateTime.Now;
                double   messagesPerSecondWithoutConnect = maxMessages / (endTimeWithoutConnect - startTimeWithoutConnect).TotalSeconds;
                Console.WriteLine($"Device {deviceName}: Messages Per Second Without Connect: { messagesPerSecondWithoutConnect}");

                await device.CloseAsync();

                DateTime endTime           = DateTime.Now;
                double   messagesPerSecond = maxMessages / (endTime - startTime).TotalSeconds;
                Console.WriteLine($"Device {deviceName}: Messages Per Second: { messagesPerSecond}");
                Console.WriteLine($"Device {deviceName} ended");

                DeviceBenchmarkEntry benchmarkEntry = new DeviceBenchmarkEntry()
                {
                    StartTime = startTime,
                    EndTime   = endTime,
                    StartTimeWithoutConnect = startTimeWithoutConnect,
                    EndTimeWithoutConnect   = endTimeWithoutConnect,
                    DeviceName       = deviceName,
                    MaxMessages      = maxMessages,
                    MessageSize      = messageSize,
                    MessagePerSecond = messagesPerSecond,
                    MessagePerSecondWithoutConnect = messagesPerSecondWithoutConnect
                };
                return(benchmarkEntry);
            }
            catch (Exception er)
            {
                Console.WriteLine($"Error starting device: {deviceName} error: {er.InnerException.Message}");
            }
            return(null);
        }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            CommandLine.Parser.Default.ParseArguments <Options>(args)
            .WithParsed <Options>(opts =>
            {
                string IoTHub = opts.IotHubConnectionString.Split(';')[0].Split('=')[1];
                Console.WriteLine("Creating Devices");
                CreateDevices(opts.DeviceCount, opts.IotHubConnectionString).Wait();
                // Messagesize
                if (opts.MessageSize > 262143)
                {
                    Console.WriteLine($"Setting MessageSize to maximum of {MAXMESSAGESIZE}");
                    MessageSize = MAXMESSAGESIZE;
                }
                else
                {
                    MessageSize = opts.MessageSize;
                }
                // Transporttype
                switch (opts.TransportType)
                {
                case "MQTT":
                    TransportType = Microsoft.Azure.Devices.Client.TransportType.Mqtt;
                    break;

                case "AMQP":
                    TransportType = Microsoft.Azure.Devices.Client.TransportType.Amqp;
                    break;

                case "HTTP":
                    TransportType = Microsoft.Azure.Devices.Client.TransportType.Http1;
                    break;

                default:
                    TransportType = Microsoft.Azure.Devices.Client.TransportType.Mqtt;
                    break;
                }
                Console.WriteLine($"Starting Devices: DeviceCount: {opts.DeviceCount} MaxMessages:{opts.MaxMessages} MessageSize:{MessageSize} TransportType:{TransportType}");
                DateTime startTime            = DateTime.Now;
                BenchmarkEntry benchmarkEntry = new BenchmarkEntry()
                {
                    StartTime        = startTime,
                    DeviceCount      = opts.DeviceCount,
                    MaxMessages      = opts.MaxMessages,
                    MessageSize      = MessageSize,
                    DeviceBenchmarks = new List <DeviceBenchmarkEntry>(),
                    TransportType    = opts.TransportType
                };
                Task[] tasks = new Task[opts.DeviceCount];
                for (int deviceNumber = 1; deviceNumber <= opts.DeviceCount; deviceNumber++)
                {
                    tasks[deviceNumber - 1] = StartClient(IoTHub, IoTDevicePrefix, deviceNumber, CommonKey, opts.MaxMessages, MessageSize, TransportType).ContinueWith(task =>
                    {
                        benchmarkEntry.DeviceBenchmarks.Add(task.Result);
                    });
                }
                Task.WaitAll(tasks);
                DateTime endTime                = DateTime.Now;
                double messagesPerSecond        = opts.DeviceCount * opts.MaxMessages / (endTime - startTime).TotalSeconds;
                benchmarkEntry.EndTime          = endTime;
                benchmarkEntry.MessagePerSecond = messagesPerSecond;
                WriteResultsToFile(benchmarkEntry, opts.BenchmarkFileNamePath).Wait();

                Console.WriteLine("All Messages are sent");
                Console.WriteLine($"Total Clients: {opts.DeviceCount}");
                Console.WriteLine($"Message Size: {opts.MessageSize}");
                Console.WriteLine($"Total Messages Sent: {opts.DeviceCount * opts.MaxMessages}");
                Console.WriteLine($"Total Execution Time: {(endTime - startTime).TotalSeconds} seconds");
                Console.WriteLine($"Messages Per Second: {messagesPerSecond}");
                Thread.Sleep(7000); // Wait before starting to delete devices
                DeleteDevices(opts.DeviceCount, opts.IotHubConnectionString).Wait();
            });
        }
Exemplo n.º 14
0
 public Edge()
 {
     this.Transport = Microsoft.Azure.Devices.Client.TransportType.Mqtt;
 }
Exemplo n.º 15
0
        static async Task CallDirectMethodFromCloud(
            string serviceClientConnectionString,
            string deviceId,
            string moduleId,
            TransportType transportType,
            TimeSpan delay,
            CancellationTokenSource cts)
        {
            Logger.LogInformation("CallDirectMethodFromCloud started.");
            ModuleClient  moduleClient  = null;
            ServiceClient serviceClient = null;

            try
            {
                Guid batchId = Guid.NewGuid();
                int  count   = 1;

                IotHubConnectionStringBuilder iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(serviceClientConnectionString);
                Logger.LogInformation($"Prepare to call Direct Method from cloud ({iotHubConnectionStringBuilder.IotHubName}) on device [{deviceId}] module [{moduleId}]");

                serviceClient = ServiceClient.CreateFromConnectionString(serviceClientConnectionString, Microsoft.Azure.Devices.TransportType.Amqp);
                var cloudToDeviceMethod = new CloudToDeviceMethod("HelloWorldMethod").SetPayloadJson("{ \"Message\": \"Hello\" }");

                moduleClient = await ModuleUtil.CreateModuleClientAsync(
                    transportType,
                    ModuleUtil.DefaultTimeoutErrorDetectionStrategy,
                    ModuleUtil.DefaultTransientRetryStrategy,
                    Logger);

                while (!cts.Token.IsCancellationRequested)
                {
                    Logger.LogInformation($"Calling Direct Method from cloud ({iotHubConnectionStringBuilder.IotHubName}) on device [{deviceId}] module [{moduleId}] of count {count}.");

                    try
                    {
                        CloudToDeviceMethodResult result = await serviceClient.InvokeDeviceMethodAsync(deviceId, moduleId, cloudToDeviceMethod, CancellationToken.None);

                        if (result.Status == (int)HttpStatusCode.OK)
                        {
                            var eventMessage = new Message(Encoding.UTF8.GetBytes($"Direct Method [{transportType}] Call succeeded."));
                            eventMessage.Properties.Add("sequenceNumber", count.ToString());
                            eventMessage.Properties.Add("batchId", batchId.ToString());
                            Logger.LogInformation($"Calling Direct Method from cloud with count {count} succeeded.");
                            await moduleClient.SendEventAsync(RouteOutputName, eventMessage);
                        }
                        else
                        {
                            Logger.LogError($"Calling Direct Method from cloud with count {count} failed with status code {result.Status}.");
                        }

                        count++;
                    }
                    catch (Exception e)
                    {
                        Logger.LogError($"Exception caught with count {count}: {e}");
                    }

                    await Task.Delay(delay, cts.Token);
                }
            }
            catch (Exception e)
            {
                Logger.LogError($"Exception caught: {e}");
                throw;
            }
            finally
            {
                Logger.LogInformation("Close connection for service client and module client");
                if (serviceClient != null)
                {
                    await serviceClient.CloseAsync();
                }

                if (moduleClient != null)
                {
                    await moduleClient.CloseAsync();
                }
            }

            Logger.LogInformation("CallDirectMethodFromCloud finished.");
        }
Exemplo n.º 16
0
 public DeviceClient CreateDeviceClient(Device device, TransportType transportType)
 {
     return(DeviceClient.Create(configuration[ConfigurationKeys.IotHubUri], new DeviceAuthenticationWithRegistrySymmetricKey(device.Id, device.Authentication.SymmetricKey.PrimaryKey), transportType));
 }