public async Task OnGetAsync() { // Read ConfigData ConfigData = await _configDataService.ReadAsync(); }
public async Task <string> SendAsync(int id) { // Get full item content Item item = await ReadAsync(id); // Obtain IoT Hub connection string and Azure Sphere device name ConfigData configData = await _configDataService.ReadAsync(); // Prepare device method call via Iot Hub string methodName = _config.GetValue <string>("AzureSphereDevice:directMethodName"); int methodTimeout = _config.GetValue <int>("AzureSphereDevice:directMethodCallTimeout"); var methodInvocation = new CloudToDeviceMethod(methodName) { ResponseTimeout = TimeSpan.FromSeconds(methodTimeout) }; methodInvocation.SetPayloadJson(JsonSerializer.Serialize(item)); ServiceClient serviceClient; CloudToDeviceMethodResult deviceResult; try { serviceClient = ServiceClient.CreateFromConnectionString(configData.IotHubService); using (serviceClient) { // Invoke the direct method asynchronously and get the response from IoT device. deviceResult = await serviceClient.InvokeDeviceMethodAsync(configData.AzureSphereDevice, methodInvocation); } } catch (FormatException fex) { if (fex.Message.Equals("Malformed Token")) { return("ERROR: Invalid Iot Hub Service Connection String"); } return("ERROR: Iot Hub Message Format Exception"); } catch (ArgumentException) { return("ERROR: Invalid Iot Hub Service Connection String"); } catch (DeviceNotFoundException dnfex) { if (dnfex.Message.Contains(":404001,")) { // errorCode 404001: Device not registered or incorrect name return("ERROR: Device not registered in IoT Hub"); } else if (dnfex.Message.Contains(":404103,")) { // errorCode 404103: Timeout return("ERROR: Timeout connecting device"); } return("ERROR: Device not found"); } // Azure Sphere returns status and message property bool success = true; string message; try { JsonDocument document = JsonDocument.Parse(deviceResult.GetPayloadAsJson()); message = document.RootElement.GetProperty("message").GetString(); success = document.RootElement.GetProperty("success").GetBoolean(); } catch (JsonException) { message = "ERROR: Response parsing failed"; } if (!success) { message += "ERROR: "; } return(message); }