protected async Task VerifyDirectMethodAsync() { // User Service SDK to invoke Direct Method on the device. ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(this.context.IotHubConnectionString, this.serviceClientTransportType); // Call a direct method using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(300))) { CloudToDeviceMethod cloudToDeviceMethod = new CloudToDeviceMethod("DirectMethod").SetPayloadJson("{\"TestKey\" : \"TestValue\"}"); CloudToDeviceMethodResult result = await serviceClient.InvokeDeviceMethodAsync( this.context.Device.Id, cloudToDeviceMethod, cts.Token); if (result.Status != 200) { throw new Exception("Could not invoke Direct Method on Device."); } if (!result.GetPayloadAsJson().Equals("{\"TestKey\":\"TestValue\"}", StringComparison.Ordinal)) { throw new Exception($"Payload doesn't match with Sent Payload. Received payload: {result.GetPayloadAsJson()}. Expected: {{\"TestKey\":\"TestValue\"}}"); } } }
public static async Task Run([CosmosDBTrigger("<database_name>", "<collection_name>", ConnectionStringSetting = "ConnetionString", LeaseCollectionName = "AnomalyLeases", CreateLeaseCollectionIfNotExists = true)] IReadOnlyList <Document> input, ILogger log) { if (input == null || input.Count <= 0) { return; } Initialize(); log.LogInformation($"Documents modified: {input.Count}"); log.LogInformation($"First document Id: {input[0].Id}"); string jsonMessage = GetJsonFormatObjectMessage(input); log.LogInformation(jsonMessage); try { CloudToDeviceMethodResult response = await SendMessageToDevice(jsonMessage); log.LogInformation($"result '{response.GetPayloadAsJson()}' status: '{response.Status}'"); } catch (Exception e) { log.LogInformation(e.Message); } }
protected async Task CallMethodAsync(CancellationToken ct) { _mMethod.ScheduleTime = null; _mMethod.OperationType = TelemetryMetrics.ServiceOperationMethodCall; _swMethod.Restart(); try { string deviceId = Configuration.Stress.GetDeviceNameById(_id, _authType); var methodCall = new CloudToDeviceMethod(TestMethodName); methodCall.SetPayloadJson(_methodPayload); Task <CloudToDeviceMethodResult> t = s_sc.InvokeDeviceMethodAsync(Configuration.Stress.GetDeviceNameById(_id, _authType), methodCall); _mMethod.ScheduleTime = _swMethod.ElapsedMilliseconds; _swMethod.Restart(); CloudToDeviceMethodResult result = await t.ConfigureAwait(false); // Check method result. if (result.Status != MethodPassStatus) { throw new InvalidOperationException($"IoTPerfClient: Status: {result.Status} Payload:{result.GetPayloadAsJson()}"); } } catch (Exception ex) { _mMethod.ErrorMessage = $"{ex.GetType().Name} - {ex.Message}"; throw; } finally { _mMethod.ExecuteTime = _swMethod.ElapsedMilliseconds; await _writer.WriteAsync(_mMethod).ConfigureAwait(false); } }
public async Task <string> InvokeDirectMethodAsync(string deviceId, string methodName, string payload) { try { var methodInvocation = new CloudToDeviceMethod(methodName) { ResponseTimeout = TimeSpan.FromSeconds((double)_settings.IoTHub?.DirectMethodTimeOut) }; methodInvocation.SetPayloadJson(payload); // Invoke the direct method asynchronously and get the response from the simulated device. CloudToDeviceMethodResult response = await _serviceClient.InvokeDeviceMethodAsync(deviceId, methodInvocation); if (response != null) { return(response.GetPayloadAsJson()); } else { return(null); } } catch (Exception ex) { //TODO: add trace return(null); } }
public async void Should_Reboot_SimulatedDevice() { //Arrange this.Try_Delete_Existing_Simulation(); var simulation = JObject.Parse(@"{ 'Enabled': true, 'DeviceModels': [ { 'Id': 'chiller-01', 'Count': 5 } ] }"); var request = new HttpRequest(Constants.DS_ADDRESS + "/simulations"); request.SetContent(simulation); var response = this.httpClient.PostAsync(request).Result; Assert.Equal(HttpStatusCode.OK, response.StatusCode); Thread.Sleep(Constants.WAIT_TIME); //Act ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(IOTHUB_CONNECTION_STRING); Task <CloudToDeviceMethodResult> rebootMethodResult = serviceClient.InvokeDeviceMethodAsync("chiller-01.0", new CloudToDeviceMethod("Reboot")); CloudToDeviceMethodResult rebootResponse = await rebootMethodResult.ConfigureAwait(false); //Assert Assert.Equal(200, rebootResponse.Status); //TODO //Currently, there is no property of the device that indicates a reboot happened. We have to handle this in the future. }
public async Task <int> CallMethodAsync(string action, string deviceId) { ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(_configuration.GetConnectionString("IOTHUB")); CloudToDeviceMethodResult c2dMethodRes = await serviceClient.InvokeDeviceMethodAsync(deviceId, new CloudToDeviceMethod(action)); return(c2dMethodRes.Status); }
private async Task InvokeGetMaxMinReportCommandAsync() { const string getMaxMinReportCommandName = "getMaxMinReport"; // Create command name to invoke for component var commandInvocation = new CloudToDeviceMethod(getMaxMinReportCommandName) { ResponseTimeout = TimeSpan.FromSeconds(30) }; // Set command payload DateTimeOffset since = DateTimeOffset.Now.Subtract(TimeSpan.FromMinutes(2)); string componentCommandPayload = JsonConvert.SerializeObject(since); commandInvocation.SetPayloadJson(componentCommandPayload); _logger.LogDebug($"Invoke the {getMaxMinReportCommandName} command on {_deviceId} device twin."); try { CloudToDeviceMethodResult result = await _serviceClient.InvokeDeviceMethodAsync(_deviceId, commandInvocation); _logger.LogDebug($"Command {getMaxMinReportCommandName} was invoked on device twin {_deviceId}." + $"\nDevice returned status: {result.Status}. \nReport: {result.GetPayloadAsJson()}"); } catch (DeviceNotFoundException) { _logger.LogWarning($"Unable to execute command {getMaxMinReportCommandName} on {_deviceId}." + $"\nMake sure that the device sample Thermostat located in " + $"https://github.com/Azure-Samples/azure-iot-samples-csharp/tree/master/iot-hub/Samples/device/PnpDeviceSamples/Thermostat " + $"is also running."); } }
/// <summary> /// Convert result to model /// </summary> /// <param name="result"></param> /// <returns></returns> public static MethodResultModel ToModel(this CloudToDeviceMethodResult result) { return(new MethodResultModel { JsonPayload = result.GetPayloadAsJson(), Status = result.Status }); }
async Task sendMethodAndRespond(Client.TransportType transport) { Tuple <string, string> deviceInfo = TestUtil.CreateDevice("E2E_Method_CSharp_", hostName, registryManager); string deviceResponseJson = "{\"name\":\"e2e_test\"}"; string serviceRequestJson = "{\"a\":123}"; string methodName = "MethodE2ETest"; var assertResult = new TaskCompletionSource <Tuple <bool, bool> >(); var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport); await deviceClient.SetMethodHandlerAsync(methodName, (request, context) => { assertResult.SetResult(new Tuple <bool, bool>(request.Name.Equals(methodName), request.DataAsJson.Equals(serviceRequestJson))); return(Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(deviceResponseJson), 200))); }, null); ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(hubConnectionString); Task <CloudToDeviceMethodResult> directResponseFuture = serviceClient.InvokeDeviceMethodAsync( deviceInfo.Item1, new CloudToDeviceMethod(methodName, TimeSpan.FromMinutes(5)).SetPayloadJson(serviceRequestJson) ); Assert.IsTrue(assertResult.Task.Result.Item1, "Method name is not matching with the send data"); Assert.IsTrue(assertResult.Task.Result.Item2, "Json data is not matching with the send data"); CloudToDeviceMethodResult response = await directResponseFuture; Assert.AreEqual(200, response.Status); Assert.AreEqual(deviceResponseJson, response.GetPayloadAsJson()); await deviceClient.CloseAsync(); TestUtil.RemoveDevice(deviceInfo.Item1, registryManager); }
private async Task InvokeGetMaxMinReportCommandAsync() { const string getMaxMinReportCommandName = "getMaxMinReport"; // Create command name to invoke for component. The command is formatted as <component name>*<command name> string commandToInvoke = $"{Thermostat1Component}*{getMaxMinReportCommandName}"; var commandInvocation = new CloudToDeviceMethod(commandToInvoke) { ResponseTimeout = TimeSpan.FromSeconds(30) }; // Set command payload DateTimeOffset since = DateTimeOffset.Now.Subtract(TimeSpan.FromMinutes(2)); string componentCommandPayload = JsonConvert.SerializeObject(since); commandInvocation.SetPayloadJson(componentCommandPayload); _logger.LogDebug($"Invoke the {getMaxMinReportCommandName} command on component {Thermostat1Component} " + $"in the {_digitalTwinId} digital twin."); try { CloudToDeviceMethodResult result = await _serviceClient.InvokeDeviceMethodAsync(_digitalTwinId, commandInvocation); _logger.LogDebug($"Command {getMaxMinReportCommandName} was invoked on component {Thermostat1Component}." + $"\nDevice returned status: {result.Status}. \nReport: {result.GetPayloadAsJson()}"); } catch (DeviceNotFoundException) { _logger.LogWarning($"Unable to execute command {getMaxMinReportCommandName} on component {Thermostat1Component}." + $"\nMake sure that the device sample TemperatureController located in {DeviceSampleLink} is also running."); } }
private async Task InvokeRebootCommandAsync() { // Create command name to invoke for component const string commandToInvoke = "reboot"; var commandInvocation = new CloudToDeviceMethod(commandToInvoke) { ResponseTimeout = TimeSpan.FromSeconds(30) }; // Set command payload string componentCommandPayload = JsonConvert.SerializeObject(3); commandInvocation.SetPayloadJson(componentCommandPayload); _logger.LogDebug($"Invoke the {commandToInvoke} command on the {_digitalTwinId} digital twin." + $"\nThis will set the \"targetTemperature\" on \"Thermostat\" component to 0."); try { CloudToDeviceMethodResult result = await _serviceClient.InvokeDeviceMethodAsync(_digitalTwinId, commandInvocation); _logger.LogDebug($"Command {commandToInvoke} was invoked on the {_digitalTwinId} digital twin." + $"\nDevice returned status: {result.Status}."); } catch (DeviceNotFoundException) { _logger.LogWarning($"Unable to execute command {commandToInvoke} on component {Thermostat1Component}." + $"\nMake sure that the device sample TemperatureController located in {DeviceSampleLink} is also running."); } }
public bool UnpublishAllConfiguredNodes(CancellationToken ct) { CloudToDeviceMethodResult result = null; List <NodeModel> nodes = new List <NodeModel>(); try { UnpublishAllNodesMethodRequestModel unpublishAllNodesMethodRequestModel = new UnpublishAllNodesMethodRequestModel(); _unpublishAllNodesMethod.SetPayloadJson(JsonConvert.SerializeObject(unpublishAllNodesMethodRequestModel)); if (string.IsNullOrEmpty(_publisherModuleName)) { result = _iotHubClient.InvokeDeviceMethodAsync(_publisherDeviceName, _unpublishAllNodesMethod, ct).Result; } else { result = _iotHubClient.InvokeDeviceMethodAsync(_publisherDeviceName, _publisherModuleName, _unpublishAllNodesMethod, ct).Result; } } catch (Exception e) { Logger.Fatal(e, $"UnpublishAllConfiguredNodes Exception"); } Logger.Debug($"UnpublishAllConfiguredNodes succeeded, result: {(HttpStatusCode)result.Status}"); return((HttpStatusCode)result.Status == HttpStatusCode.OK ? true : false); }
internal override async Task <int> InvokeDeviceMethodAsync(string deviceId, string targetModuleId, CancellationToken none) { CloudToDeviceMethod cloudToDeviceMethod = new CloudToDeviceMethod("HelloWorldMethod").SetPayloadJson("{ \"Message\": \"Hello\" }"); CloudToDeviceMethodResult result = await this.serviceClient.InvokeDeviceMethodAsync(deviceId, targetModuleId, cloudToDeviceMethod, CancellationToken.None); return(result.Status); }
public static async Task ServiceSendMethodAndVerifyResponseAsync( string deviceId, string moduleId, string methodName, string respJson, string reqJson, MsTestLogger logger, TimeSpan responseTimeout = default, ServiceClientTransportSettings serviceClientTransportSettings = default) { ServiceClient serviceClient = serviceClientTransportSettings == default ? ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString) : ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString, TransportType.Amqp, serviceClientTransportSettings); TimeSpan methodTimeout = responseTimeout == default ? s_defaultMethodTimeoutMinutes : responseTimeout; logger.Trace($"{nameof(ServiceSendMethodAndVerifyResponseAsync)}: Invoke method {methodName}."); CloudToDeviceMethodResult response = await serviceClient.InvokeDeviceMethodAsync( deviceId, moduleId, new CloudToDeviceMethod(methodName, responseTimeout).SetPayloadJson(reqJson)).ConfigureAwait(false); logger.Trace($"{nameof(ServiceSendMethodAndVerifyResponseAsync)}: Method status: {response.Status}."); Assert.AreEqual(200, response.Status, $"The expected response status should be 200 but was {response.Status}"); string payload = response.GetPayloadAsJson(); Assert.AreEqual(respJson, payload, $"The expected response payload should be {respJson} but was {payload}"); await serviceClient.CloseAsync().ConfigureAwait(false); serviceClient.Dispose(); }
public static async Task ServiceSendMethodAndVerifyNotReceivedAsync( string deviceId, string methodName, MsTestLogger logger, TimeSpan responseTimeout = default, ServiceClientTransportSettings serviceClientTransportSettings = default) { ServiceClient serviceClient = serviceClientTransportSettings == default ? ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString) : ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString, TransportType.Amqp, serviceClientTransportSettings); TimeSpan methodTimeout = responseTimeout == default ? s_defaultMethodTimeoutMinutes : responseTimeout; logger.Trace($"{nameof(ServiceSendMethodAndVerifyResponseAsync)}: Invoke method {methodName}."); try { CloudToDeviceMethodResult response = await serviceClient .InvokeDeviceMethodAsync( deviceId, new CloudToDeviceMethod(methodName, methodTimeout).SetPayloadJson(null)) .ConfigureAwait(false); } catch (DeviceNotFoundException) { } finally { await serviceClient.CloseAsync().ConfigureAwait(false); serviceClient.Dispose(); } }
public async Task <bool> UnpublishAllConfiguredNodesAsync(CancellationToken ct) { CloudToDeviceMethodResult methodResult = null; bool result = false; try { UnpublishAllNodesMethodRequestModel unpublishAllNodesMethodRequestModel = new UnpublishAllNodesMethodRequestModel(); _unpublishAllNodesMethod.SetPayloadJson(JsonConvert.SerializeObject(unpublishAllNodesMethodRequestModel)); if (string.IsNullOrEmpty(_publisherModuleName)) { methodResult = await _iotHubClient.InvokeDeviceMethodAsync(_publisherDeviceName, _unpublishAllNodesMethod, ct).ConfigureAwait(false); } else { methodResult = await _iotHubClient.InvokeDeviceMethodAsync(_publisherDeviceName, _publisherModuleName, _unpublishAllNodesMethod, ct).ConfigureAwait(false); } List <string> statusResponse = new List <string>(); if (!ct.IsCancellationRequested) { LogMethodResult(methodResult, _publishNodesMethod.MethodName); result = methodResult.Status == (int)HttpStatusCode.OK; } } catch (Exception e) { Logger.Error(e, $"Exception"); } return(result); }
protected override bool UnpublishAllConfiguredNodes(CancellationToken ct) { string logPrefix = $"{_logClassPrefix}:UnpublishAllConfiguredNodes:"; CloudToDeviceMethodResult result = null; try { UnpublishAllNodesMethodRequestModel unpublishAllNodesMethodRequestModel = new UnpublishAllNodesMethodRequestModel(); _unpublishAllNodesMethod.SetPayloadJson(JsonConvert.SerializeObject(unpublishAllNodesMethodRequestModel)); if (string.IsNullOrEmpty(_publisherModuleName)) { result = _iotHubClient.InvokeDeviceMethodAsync(_publisherDeviceName, _unpublishAllNodesMethod, ct).Result; } else { result = _iotHubClient.InvokeDeviceMethodAsync(_publisherDeviceName, _publisherModuleName, _unpublishAllNodesMethod, ct).Result; } if (result.Status == (int)HttpStatusCode.OK) { Logger.Debug($"{logPrefix} succeeded"); } else { Logger.Warning($"{logPrefix} failed"); } } catch (Exception e) { Logger.Fatal(e, $"{logPrefix} Exception"); } Logger.Debug($"{logPrefix} succeeded, result: {(HttpStatusCode)result.Status}"); return((HttpStatusCode)result.Status == HttpStatusCode.OK ? true : false); }
private async void SendFakeAmberAlert(string device, AmberAlertMSG payload) { string command = "amber_alert"; string output = JsonConvert.SerializeObject(payload); txtLogbox.AppendText("This will attempt to activate LightBeacons via the DisplayBeacon as a proxy." + Environment.NewLine); var remoteCommand = new CloudToDeviceMethod(command) { ResponseTimeout = TimeSpan.FromSeconds(30) }; remoteCommand.SetPayloadJson(output); CloudToDeviceMethodResult response = new CloudToDeviceMethodResult(); try { response = await serviceClient.InvokeDeviceMethodAsync(lstDevices.SelectedValue.ToString(), remoteCommand); } catch (Exception ex) { txtLogbox.AppendText(ex.Message + Environment.NewLine); } txtLogbox.AppendText(response.GetPayloadAsJson() + Environment.NewLine); }
static async Task <DateTime> RestartEdgeHubAsync( ServiceClient iotHubServiceClient, CancellationToken cancellationToken) { DateTime startAttemptTime = DateTime.UtcNow; CloudToDeviceMethod c2dMethod = new CloudToDeviceMethod("RestartModule"); string payloadSchema = "{{ \"SchemaVersion\": \"1.0\", \"Id\": \"{0}\" }}"; string payload = string.Format(payloadSchema, "edgeHub"); Logger.LogInformation("RestartModule Method Payload: {0}", payload); c2dMethod.SetPayloadJson(payload); while (true) { try { // TODO: Introduce the offline scenario to use docker command. CloudToDeviceMethodResult response = await iotHubServiceClient.InvokeDeviceMethodAsync(Settings.Current.DeviceId, "$edgeAgent", c2dMethod); if ((HttpStatusCode)response.Status != HttpStatusCode.OK) { Logger.LogError($"Calling EdgeHub restart failed with status code {response.Status} : {response.GetPayloadAsJson()}."); } else { Logger.LogInformation($"Calling EdgeHub restart succeeded with status code {response.Status}."); } return(DateTime.UtcNow); } catch (Exception e) { Logger.LogError($"Exception caught for payload {payload}: {e}"); if (Settings.Current.RestartPeriod < DateTime.UtcNow - startAttemptTime) { string errorMessage = $"Failed to restart EdgeHub from {startAttemptTime} to {DateTime.UtcNow}:\n\n{e}\n\nPayload: {payload}"; TestResultBase errorResult = new ErrorTestResult( Settings.Current.TrackingId, GetSource(), errorMessage, DateTime.UtcNow); var reportClient = new TestResultReportingClient { BaseUrl = Settings.Current.ReportingEndpointUrl.AbsoluteUri }; await ModuleUtil.ReportTestResultAsync( reportClient, Logger, errorResult, cancellationToken); throw; } } } }
private static async Task CheckAmberAlerts() { //Check @AmberAlert Twitter for new alerts string consumerKey = "NuJqfBKYAOGrGrq9VQgUAboQe"; string consumerSecret = "124ZakFjwjOzlhSrZfvyIwjwWCZ6HXSqo8bj9Gm3FBSyho63Iu"; string accessToken = "877373799343169536-EGA7XYg94hNmkLFoYQki2qbL2Z5XPZM"; string accessSecret = "tRjjrVF6VPPCi6wkD2fcy9GDiYAzmWrKzuOKOxM08BWVJ"; // Obtain keys by registering your app on https://dev.twitter.com/apps or https://apps.twitter.com/ var service = new TwitterService(consumerKey, consumerSecret); service.AuthenticateWith(accessToken, accessSecret); TwitterStatus result = service.ListTweetsOnUserTimeline(new ListTweetsOnUserTimelineOptions() { ScreenName = "AmberAlert", Count = 1 }).First(); var sendAmberAlert = new CloudToDeviceMethod("amber_alert") { ResponseTimeout = TimeSpan.FromSeconds(30) }; var clearAmberAlert = new CloudToDeviceMethod("clear_amber") { ResponseTimeout = TimeSpan.FromSeconds(30) }; //Determine if this a cancelled alert or not //Twitter text can mess with Json - ignore reTweets CloudToDeviceMethodResult response = new CloudToDeviceMethodResult(); if (result.TextDecoded.Contains("cancelled")) { //clearAmberAlert.SetPayloadJson("'{}'"); response = await serviceClient.InvokeDeviceMethodAsync("BeaconDisplay", clearAmberAlert); } else if (result.RetweetedStatus.Author.ScreenName != "AmberAlert") { //Handle ReTweets here } else if (result.Author.ScreenName == "AmberAlert") { var jsonPayload = "'{\"title\":\"Amber Alert!\",\"details\":\"" + result.TextDecoded.ToString() + "\"}'"; sendAmberAlert.SetPayloadJson(jsonPayload); response = await serviceClient.InvokeDeviceMethodAsync("BeaconDisplay", sendAmberAlert); } // SEND TO DISPLAY BEACONS Trace.TraceInformation("Response status: {0}, payload:", response.Status); Trace.TraceInformation(response.GetPayloadAsJson()); }
public static List <UserPublic> ScanMethod(string deviceId) { CloudToDeviceMethod method = new CloudToDeviceMethod("scan"); Task <CloudToDeviceMethodResult> resultTask = _serviceClient.InvokeDeviceMethodAsync(deviceId, method); CloudToDeviceMethodResult result = resultTask.Result; List <UserPublic> list = JsonConvert.DeserializeObject <List <UserPublic> >(result.GetPayloadAsJson()); return(list); }
private static async Task CallDirectMethod(ServiceClient serviceClient, string deviceId) { CloudToDeviceMethod method = new CloudToDeviceMethod("showMessage"); method.SetPayloadJson("'Hello from the band manager'"); CloudToDeviceMethodResult response = await serviceClient.InvokeDeviceMethodAsync(deviceId, method); Console.WriteLine($"Response status: {response.Status}, payload: {response.GetPayloadAsJson()}"); }
protected override bool PublishNodes(List <NodeIdInfo> nodeIdInfos, CancellationToken ct, string endpointUrl = null) { string logPrefix = $"{_logClassPrefix}:PublishNodes:"; bool result = true; int retryCount = MAX_RETRY_COUNT; try { PublishNodesMethodRequestModel publishNodesMethodRequestModel = new PublishNodesMethodRequestModel(endpointUrl ?? TestserverUrl); foreach (var nodeIdInfo in nodeIdInfos) { publishNodesMethodRequestModel.OpcNodes.Add(new OpcNodeOnEndpointModel(nodeIdInfo.Id)); } CloudToDeviceMethodResult methodResult = new CloudToDeviceMethodResult(); methodResult.Status = (int)HttpStatusCode.NotAcceptable; while (methodResult.Status == (int)HttpStatusCode.NotAcceptable && retryCount-- > 0) { _publishNodesMethod.SetPayloadJson(JsonConvert.SerializeObject(publishNodesMethodRequestModel)); if (string.IsNullOrEmpty(_publisherModuleName)) { methodResult = _iotHubClient.InvokeDeviceMethodAsync(_publisherDeviceName, _publishNodesMethod, ct).Result; } else { methodResult = _iotHubClient.InvokeDeviceMethodAsync(_publisherDeviceName, _publisherModuleName, _publishNodesMethod, ct).Result; } if (methodResult.Status == (int)HttpStatusCode.NotAcceptable) { Thread.Sleep(MaxShortWaitSec * 1000); } else { break; } } foreach (var nodeIdInfo in nodeIdInfos) { if (!nodeIdInfo.Published && methodResult.Status != (int)HttpStatusCode.OK && methodResult.Status != (int)HttpStatusCode.Accepted) { Logger.Warning($"{logPrefix} failed (nodeId: '{nodeIdInfo.Id}', statusCode: '{methodResult.Status}', publishedState: '{nodeIdInfo.Published}')"); result = false; } else { nodeIdInfo.Published = true; Logger.Debug($"{logPrefix} succeeded (nodeId: '{nodeIdInfo.Id}', statusCode: '{methodResult.Status}')"); } } } catch (Exception e) { Logger.Fatal(e, $"{logPrefix} Exception"); } return(result); }
public static async Task CloudCommand() { client = ServiceClient.CreateFromConnectionString(IotHubConnectionString); CloudToDeviceMethod method = new CloudToDeviceMethod("TestCommand"); method.ResponseTimeout = TimeSpan.FromSeconds(30); CloudToDeviceMethodResult result = await client.InvokeDeviceMethodAsync(deviceId, method); System.Diagnostics.Debug.WriteLine("Invoked cloud command update on device."); }
public static async Task StartReboot() { client = ServiceClient.CreateFromConnectionString(connString); CloudToDeviceMethod method = new CloudToDeviceMethod("reboot"); method.ResponseTimeout = TimeSpan.FromSeconds(30); CloudToDeviceMethodResult result = await client.InvokeDeviceMethodAsync(deviceId, method); Console.WriteLine("Invoked firmware update on device."); }
/// <summary> /// Restarts random modules periodically (with default restart occurrence once every 10 minutes). /// </summary> static async Task RestartModules(CancellationTokenSource cts) { if (Settings.Current.DesiredModulesToRestart.Count == 0) { Logger.LogInformation("No modules names found in input. Stopping."); return; } try { ServiceClient iotHubServiceClient = ServiceClient.CreateFromConnectionString(Settings.Current.ServiceClientConnectionString); CloudToDeviceMethod c2dMethod = new CloudToDeviceMethod("RestartModule"); Random random = new Random(); string payloadSchema = "{{ \"SchemaVersion\": \"1.0\", \"Id\": \"{0}\" }}"; List <string> moduleNames = Settings.Current.DesiredModulesToRestart; while (!cts.Token.IsCancellationRequested) { Logger.LogInformation($"Started delay for {Settings.Current.RestartInterval} till {DateTime.UtcNow.Add(Settings.Current.RestartInterval)}."); await Task.Delay(Settings.Current.RestartInterval, cts.Token); if (!cts.IsCancellationRequested) { string moduleToBeRestarted = moduleNames[random.Next(0, moduleNames.Count)]; string payload = string.Format(payloadSchema, moduleToBeRestarted); Logger.LogInformation("RestartModule Method Payload: {0}", payload); try { c2dMethod.SetPayloadJson(payload); CloudToDeviceMethodResult response = await iotHubServiceClient.InvokeDeviceMethodAsync(Settings.Current.DeviceId, "$edgeAgent", c2dMethod); Logger.LogInformation($"Successfully invoke direct method to restart module {moduleToBeRestarted}."); if (response.Status != (int)HttpStatusCode.OK) { Logger.LogError($"Calling Direct Method failed with status code {response.Status}."); } } catch (Exception e) { Logger.LogError($"Exception caught for payload {payload}: {e}"); } } } } catch (Exception e) { Logger.LogError($"Exception caught: {e}"); throw; } Logger.LogInformation("RestartModules finished."); }
static async Task ReportStatus(string moduleId, CloudToDeviceMethodResult result, AnalyzerClient analyzerClient) { try { await analyzerClient.ReportResultAsync(new TestOperationResult { Source = moduleId, Result = result.Status.ToString(), CreatedAt = DateTime.UtcNow, Type = "LegacyDirectMethod" }); } catch (Exception e) { Logger.LogError(e, "Failed call to report status to analyzer"); } }
static async Task CallAnalyzerToReportStatusAsync(string moduleId, CloudToDeviceMethodResult result, AnalyzerClient analyzerClient) { try { await analyzerClient.AddDirectMethodStatusAsync(new ResponseStatus { ModuleId = moduleId, StatusCode = result.Status.ToString(), EnqueuedDateTime = DateTime.UtcNow }); } catch (Exception e) { Logger.LogError($"Failed call to report status to analyzer: {e}"); } }
public static InvocationResult ToInvocationResult(this CloudToDeviceMethodResult result) { string payload = result.GetPayloadAsJson(); // if necessary, device result can be 'unstringified' to allow proper deserialization afterwards if (!string.IsNullOrEmpty(payload) && payload.StartsWith("\"")) { payload = JsonConvert.DeserializeObject <string>(payload); } return(new InvocationResult(result.Status, payload)); }
public static async Task StartReboot() { client = ServiceClient.CreateFromConnectionString(connString); CloudToDeviceMethod method = new CloudToDeviceMethod("reboot"); method.ResponseTimeout = TimeSpan.FromSeconds(30); //method.SetPayloadJson(JsonConvert.SerializeObject("null")); CloudToDeviceMethodResult result = await client.InvokeDeviceMethodAsync(targetDevice, method); Console.WriteLine("Invoked firmware update on device"); }