-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDoorActionFunction.cs
100 lines (88 loc) · 4.38 KB
/
DoorActionFunction.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Net.Http;
using System.Text;
using Azure.Identity;
namespace IoTCentralTriggerFunctions
{
public static class DoorActionFunction
{
[FunctionName("DoorActionFunction")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
//Check if GET is used
if (req.Method != HttpMethod.Get.ToString())
{
//Send an Error if wrong HTTP method is used
return new BadRequestObjectResult("Bad Request");
}
//Define the variable which will be used to store the query parameter of the door being addressed
string door;
// parse query parameter
try
{
door = req.GetQueryParameterDictionary()["door"];
}
catch (Exception)
{
return new BadRequestObjectResult("Bad Request");
}
log.LogInformation("Received request to control door " + door);
//Get a AzureAD Token from Azure Default Credentials to be used for IoT Central API Call
var credential = new DefaultAzureCredential();
var token = credential.GetToken(new Azure.Core.TokenRequestContext(new[] { "https://apps.azureiotcentral.com/.default" }));
//Check for notification settings
string announcementTriggerUrl = Environment.GetEnvironmentVariable("Announcement_TriggerUrl");
string announcementToken = Environment.GetEnvironmentVariable("Announcement_Token");
string announcementFlowId = Environment.GetEnvironmentVariable("Announcement_FlowId");
if (!string.IsNullOrEmpty(announcementTriggerUrl)
&& !string.IsNullOrEmpty(announcementToken)
&& !string.IsNullOrEmpty(announcementFlowId))
{
log.LogInformation("Announcement API settings found. Triggering announcement");
//Trigger announcement of Door Action via Voice Monkey
using (var httpClient = new HttpClient())
{
var response = await httpClient.GetAsync($"{announcementTriggerUrl}?token={announcementToken}&flow={announcementFlowId}");
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
log.LogInformation("Announcement request successful. Response: " + responseBody);
}
else
{
log.LogWarning("Annoucement request failed. Status code: " + response.StatusCode);
}
}
}
//Send IoT Central API Call to open/close door
using (var client = new HttpClient())
{
string IoTAppName = Environment.GetEnvironmentVariable("IoTAppName");
string IoTDeviceName = Environment.GetEnvironmentVariable("IoTDeviceName");
string IoTComponentName = Environment.GetEnvironmentVariable("IoTComponentName");
string CommandName = Environment.GetEnvironmentVariable("CommandName");
//Build the API Call Url
var request = new HttpRequestMessage()
{
RequestUri = new Uri($"https://{IoTAppName}.azureiotcentral.com/api/devices/{IoTDeviceName}/commands/{CommandName}?api-version=2022-07-31"),
Method = HttpMethod.Post,
};
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token.Token);
request.Content = new StringContent("{\"request\": " + door + "}", Encoding.UTF8, "application/json");
//Send the request
var response = await client.SendAsync(request);
}
string responseMessage = "I sent the command to door: " + door;
return new OkObjectResult(responseMessage);
}
}
}