Exemplo n.º 1
0
        public async Task <IActionResult> Start()
        {
            var payload = JsonConvert.SerializeObject(settings);
            await ioTHubModuleClient.InvokeMethodAsync(deviceId, moduleUpstreamFromStorages, new MethodRequest("StartUpstream", Encoding.UTF8.GetBytes(payload)));

            return(RedirectToAction("BlobTemperature"));
        }
Exemplo n.º 2
0
        public async Task <string[]> ListFiles(string path)
        {
            ListFilesModel model = new ListFilesModel(path);

            byte[]         message  = GetMessage(model);
            string         jstring  = JsonConvert.SerializeObject(model);
            MethodRequest  request  = new MethodRequest("listFiles", Encoding.UTF8.GetBytes(jstring));
            MethodResponse response = await client.InvokeMethodAsync(deviceId, moduleId, request);

            if (response.Status != 200)
            {
                Console.WriteLine("DirectMethods Client listFiles failed");
                throw new Exception("DirectMethods client failed on listFiles");
            }
            else
            {
                string jsonResult = response.ResultAsJson;
                if (string.IsNullOrEmpty(jsonResult))
                {
                    return(null);
                }
                else
                {
                    return(JsonConvert.DeserializeObject <string[]>(jsonResult));
                }
            }
        }
Exemplo n.º 3
0
        private static async Task GetTimeMethod(ModuleClient moduleClient, CancellationTokenSource cts)
        {
            var cancellationToken = cts.Token;

            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    var begin    = DateTime.UtcNow;
                    var response = await moduleClient.InvokeMethodAsync(DeviceId, "producer", new MethodRequest("GetTimeMethod"), cancellationToken);

                    var end      = DateTime.UtcNow;
                    var payload  = JObject.Parse(response.ResultAsJson);
                    var produced = payload.Value <DateTime>("UtcTime");
                    LogTiming(begin, produced, end);
                }
                catch (IotHubCommunicationException cex)
                {
                    LogException(cex);
                    //This is fatal since we never recover once we see this message.
                    //Just cancel and hopefully we restart
                    if (cex.Message.Equals("Address already in use"))
                    {
                        cts.Cancel();
                    }
                }
                catch (Exception ex)
                {
                    LogException(ex);
                }
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Module behavior:
        ///        Call HelloWorld Direct Method every 5 seconds.
        /// </summary>
        /// <param name="moduleClient"></param>
        /// <param name="dmDelay"></param>
        /// <param name="targetModuleId"></param>
        /// <param name="cts"></param>
        /// <param name="targetDeviceId"></param>
        /// <returns></returns>
        static async Task CallDirectMethod(
            ModuleClient moduleClient,
            TimeSpan dmDelay,
            string targetDeviceId,
            string targetModuleId,
            CancellationTokenSource cts)
        {
            while (!cts.Token.IsCancellationRequested)
            {
                Console.WriteLine($"\t{DateTime.Now.ToLocalTime()}> Calling Direct Method on module.");

                // Create the request
                var request = new MethodRequest("HelloWorldMethod", Encoding.UTF8.GetBytes("{ \"Message\": \"Hello\" }"));

                try
                {
                    //Ignore Exception. Keep trying.
                    MethodResponse response = await moduleClient.InvokeMethodAsync(targetDeviceId, targetModuleId, request);

                    if (response.Status == (int)HttpStatusCode.OK)
                    {
                        await moduleClient.SendEventAsync("AnyOutput", new Message(Encoding.UTF8.GetBytes("Method Call succeeded.")));
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }


                await Task.Delay(dmDelay, cts.Token).ConfigureAwait(false);
            }
        }
Exemplo n.º 5
0
        static async Task CallDirectMethod(
            ModuleClient moduleClient,
            TimeSpan delay,
            string deviceId,
            string moduleId,
            CancellationTokenSource cts)
        {
            var request = new MethodRequest("HelloWorldMethod", Encoding.UTF8.GetBytes("{ \"Message\": \"Hello\" }"));

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

                try
                {
                    MethodResponse response = await moduleClient.InvokeMethodAsync(deviceId, moduleId, request);

                    if (response.Status == (int)HttpStatusCode.OK)
                    {
                        await moduleClient.SendEventAsync("AnyOutput", new Message(Encoding.UTF8.GetBytes("Direct Method Call succeeded.")));
                    }
                }
                catch (Exception e)
                {
                    Logger.LogError($"Exception caught: {e}");
                }

                await Task.Delay(delay, cts.Token);
            }
        }
Exemplo n.º 6
0
        static async Task CallDirectMethodAsync()
        {
            try
            {
                var varEnvs = System.Environment.GetEnvironmentVariables();
                foreach (System.Collections.DictionaryEntry varEnv in varEnvs)
                {
                    Console.WriteLine($"Variable: key '{varEnv.Key}', value '{varEnv.Value}'");
                }

                var deviceId = System.Environment.GetEnvironmentVariable("IOTEDGE_DEVICEID");
                Console.WriteLine($"deviceId: {deviceId}");

                // MethodRequest request = new MethodRequest("MethodA", Encoding.UTF8.GetBytes("{ \"Message\": \"Hello\" }"));
                string        message = "{ \"TimeOut_mns\": " + timeOut_mns.ToString() + " }";
                MethodRequest request = new MethodRequest("NotifyTimeOut", Encoding.UTF8.GetBytes(message));

                MqttTransportSettings mqttSetting        = new MqttTransportSettings(Microsoft.Azure.Devices.Client.TransportType.Mqtt_Tcp_Only);
                ITransportSettings[]  settings           = { mqttSetting };
                ModuleClient          ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);

                await ioTHubModuleClient.OpenAsync();

                var response = await ioTHubModuleClient.InvokeMethodAsync(deviceId, "MQTTClientModule", request).ConfigureAwait(false);

                Console.WriteLine($"Received response with status {response.Status}");
            }
            catch (Exception ex)
            {
                Console.WriteLine();
                Console.WriteLine($"Error : {ex.Message}");
            }
        }
Exemplo n.º 7
0
        /// <inheritdoc />
        protected override async Task <(HttpStatusCode ResponseStatus, string ResponseString)> SendIotRequestAsync(string methodName, string requestString)
        {
            var directMethod         = new MethodRequest(methodName, Encoding.UTF8.GetBytes(requestString), _responseTimeout, _connectionTimeout);
            var directMethodResponse = await _moduleClient.InvokeMethodAsync(_deviceId, _moduleId, directMethod);

            return((HttpStatusCode)directMethodResponse.Status, directMethodResponse.ResultAsJson);
        }
Exemplo n.º 8
0
        public async Task UploadFile(string path, string filename, string blobPath, string blobFilename, string contentType, bool append = false, CancellationToken token = default(CancellationToken))
        {
            UploadFileModel model = new UploadFileModel(path, filename, blobPath, blobFilename, contentType, append);

            byte[]         message  = GetMessage(model);
            string         jstring  = JsonConvert.SerializeObject(model);
            MethodRequest  request  = new MethodRequest("uploadFile", Encoding.UTF8.GetBytes(jstring));
            MethodResponse response = await client.InvokeMethodAsync(deviceId, moduleId, request);

            if (response.Status != 200)
            {
                Console.WriteLine("DirectMethods Client UploadFile failed");
            }
        }
Exemplo n.º 9
0
        static async Task <string> CallModuleUsingModuleClient(string deviceId, string libraryModule, ModuleClient client)
        {
            Console.WriteLine($"Will call module method: {deviceId}, {libraryModule}");

            var payloadData   = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new { payload = "ABCDEF0987654321", fport = 1 }));
            var methodName    = random.Next(2) % 2 == 0 ? "test1" : "test2";
            var methodRequest = new MethodRequest(methodName, payloadData);

            var stopwatch = Stopwatch.StartNew();
            var response  = await client.InvokeMethodAsync(deviceId, libraryModule, methodRequest);

            stopwatch.Stop();

            var responseText = Encoding.UTF8.GetString(response.Result);

            Console.WriteLine($"Called module function: {responseText} in {stopwatch.ElapsedMilliseconds}ms");
            return(responseText);
        }
Exemplo n.º 10
0
        static async Task CallDirectMethod(
            ModuleClient moduleClient,
            AnalyzerClient analyzerClient,
            TimeSpan delay,
            CancellationTokenSource cts)
        {
            var    request           = new MethodRequest("HelloWorldMethod", Encoding.UTF8.GetBytes("{ \"Message\": \"Hello\" }"));
            string deviceId          = Settings.Current.DeviceId;
            string targetModuleId    = Settings.Current.TargetModuleId;
            int    directMethodCount = 1;

            while (!cts.Token.IsCancellationRequested)
            {
                Logger.LogInformation($"Calling Direct Method on device {deviceId} targeting module {targetModuleId}.");

                try
                {
                    MethodResponse response = await moduleClient.InvokeMethodAsync(deviceId, targetModuleId, request);

                    string statusMessage = $"Calling Direct Method with count {directMethodCount} returned with status code {response.Status}";
                    if (response.Status == (int)HttpStatusCode.OK)
                    {
                        Logger.LogDebug(statusMessage);
                    }
                    else
                    {
                        Logger.LogError(statusMessage);
                    }

                    await ReportStatus(targetModuleId, response, analyzerClient);

                    directMethodCount++;
                }
                catch (Exception e)
                {
                    Logger.LogError(e, "Exception caught");
                }

                await Task.Delay(delay, cts.Token);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// This method will send message to leaf device by invoking leaf device direct method.
        /// </summary>
        static async Task SendMessageToLeafDevice(string deviceId, ModuleClient moduleClient)
        {
            try
            {
                string message       = $"{UtcDateTime} hello from edge!";
                string jString       = JsonConvert.SerializeObject(message);
                var    methodRequest = new MethodRequest("LeafDeviceDirectMethod", Encoding.UTF8.GetBytes(jString));
                var    response      = await moduleClient.InvokeMethodAsync(deviceId, methodRequest);

                if (response.Status == 200)
                {
                    Console.WriteLine($"{UtcDateTime} message {message} sent");
                }
                else
                {
                    Console.WriteLine($"Error occurred invoking LeafDeviceDirectMethod. error status code {response.Status}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"SendMessageToLeafDevice got exception {ex.Message}");
            }
        }
Exemplo n.º 12
0
        async Task <Tuple <DateTime, HttpStatusCode> > SendDirectMethodAsync(
            string deviceId,
            string targetModuleId,
            string directMethodName,
            DateTime runExpirationTime,
            CancellationToken cancellationToken)
        {
            ModuleClient moduleClient = await this.GetModuleClientAsync();

            while ((!cancellationToken.IsCancellationRequested) && (DateTime.UtcNow < runExpirationTime))
            {
                try
                {
                    // Direct Method sequence number is always increasing regardless of sending result.
                    this.directMethodCount++;
                    MethodRequest request = new MethodRequest(
                        directMethodName,
                        Encoding.UTF8.GetBytes($"{{ \"Message\": \"Hello\", \"DirectMethodCount\": \"{this.directMethodCount}\" }}"),
                        Settings.Current.SdkOperationTimeout,
                        Settings.Current.SdkOperationTimeout);
                    MethodResponse result = await moduleClient.InvokeMethodAsync(deviceId, targetModuleId, request);

                    this.logger.LogInformation($"[DirectMethodEdgeHubConnector] Invoke DirectMethod with count {this.directMethodCount}");

                    if ((HttpStatusCode)result.Status == HttpStatusCode.OK)
                    {
                        this.logger.LogDebug(result.ResultAsJson);
                    }
                    else
                    {
                        this.logger.LogError(result.ResultAsJson);
                    }

                    return(new Tuple <DateTime, HttpStatusCode>(DateTime.UtcNow, (HttpStatusCode)result.Status));
                }
                catch (Exception e)
                {
                    // Only handle the exception that relevant to our test case; otherwise, re-throw it.
                    if (this.IsEdgeHubDownDuringDirectMethodSend(e) || this.IsDirectMethodReceiverNotConnected(e))
                    {
                        // swallow exeception and retry until success
                        this.logger.LogDebug(e, $"[DirectMethodEdgeHubConnector] Exception caught with SequenceNumber {this.directMethodCount}");
                    }
                    else
                    {
                        // something is wrong, Log and send report to TRC
                        string errorMessage = $"[DirectMethodEdgeHubConnector] Exception caught with SequenceNumber {this.directMethodCount}";
                        this.logger.LogError(e, errorMessage);

                        TestResultBase errorResult = new ErrorTestResult(
                            Settings.Current.TrackingId,
                            this.GetSource(),
                            errorMessage,
                            DateTime.UtcNow);

                        await ModuleUtil.ReportTestResultAsync(
                            this.GetReportClient(),
                            this.logger,
                            errorResult,
                            cancellationToken);
                    }
                }
            }

            return(new Tuple <DateTime, HttpStatusCode>(DateTime.UtcNow, HttpStatusCode.InternalServerError));
        }