正如我在评论中提到的,Azure IoT Central 可以完全控制内部 IoT 中心面向服务的端点。但是,有一种方法,Azure IoT Central 允许对这个面向服务的端点进行有限访问,并使用 REST API 来处理设备孪生并在设备上调用直接方法。
以下是如何为 REST Api 调用所需的授权标头获取 sas 令牌的步骤:
从 Azure IoT Central 应用程序获取访问令牌。
格式为:
SharedAccessSignature sr=appId&sig=xxxxx&skn=myTokenName&se=1577730019340
请注意,appId显示的是 Azure IoT Central 应用程序的应用程序 ID
调用 REST POST 请求获取iothubTenantSasToken.sasToken
POST https://api.azureiotcentral.com/v1-beta/applications/{appId}/diagnostics/sasTokens
Authorization:SharedAccessSignature sr=appId&sig=xxxxx&skn=myTokenName&se=1577730019340
响应具有以下格式:
{
"iothubTenantSasToken": {
"sasToken": "SharedAccessSignature sr=saas-iothub-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azure-devices.net&sig=xxxxx&se=1546197703&skn=service"
},
"eventhubSasToken": {
"sasToken": "SharedAccessSignature sr=sb%3A%2F%2Fep-ns-saas-ep-15-262-xxxxxxxxxx.servicebus.windows.net%2Fep-ehub-saas-iothu-1044564-xxxxxxxxxx&sig=xxxxxx&se=1546197703&skn=service",
"entityPath": "ep-ehub-saas-iothu-1044564-xxxxxxxxxx",
"hostname": "sb://ep-ns-saas-ep-15-262-xxxxxxxxxx.servicebus.windows.net/"
},
"expiry": 1546197703
}
我们面向服务的端点调用的 sasToken 是:
SharedAccessSignature sr=saas-iothub-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azure-devices.net&sig=xxxxx&se=1546197703&skn=service
现在,我们可以使用一些 Azure IoT Hub REST API,基本上是在 uri 路径中使用双胞胎的调用,例如:
https://docs.microsoft.com/en-us/rest/api/iothub/service/gettwin
https://docs.microsoft.com/en-us/rest/api/iothub/service/updatetwin
https://docs.microsoft.com/en-us/rest/api/iothub/service/replacetwin
https://docs.microsoft.com/en-us/rest/api/iothub/service/invokedevicemethod
在设备 1 上调用直接方法的示例:
POST https://saas-iothub-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azure-devices.net/twins/device1/methods?api-version=2018-06-30
Authorization:SharedAccessSignature sr=saas-iothub-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azure-devices.net&sig=xxxxx&se=1546197703&skn=service
body:
{
"methodName": "writeLine",
"timeoutInSeconds": 20,
"payload": {
"input1": 12345,
"input2": "HelloDevice"
}
}
更新设备孪生标签属性的示例:
PATCH https://saas-iothub-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azure-devices.net/twins/device1?api-version=2018-06-30
Authorization:SharedAccessSignature sr=saas-iothub-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azure-devices.net&sig=xxxxx&se=1546197703&skn=service
body:
{
"tags": {
"test":12345
}
}
请注意,sasToken到期时间为 60 分钟。我确实建议缓存步骤 2 中的响应对象。并根据到期时间刷新。
更新:
以下是使用 IoT Central 访问令牌处理 azure 函数中的设备孪生和设备直接方法的步骤。
- 在 IoT Central 应用程序中生成访问令牌,请参阅以下屏幕片段:
将此访问令牌添加到您的函数应用程序设置中。在此示例中,应用设置名称使用AzureIoTCAccessToken。请注意,此访问令牌可以存储在 Azure Key Vault 中,请在此处查看更多详细信息。
在 Function App 中创建 HttpTrigger 函数。
将 run.csx 替换为以下代码:
#r "Newtonsoft.Json"
#r "Microsoft.Azure.WebJobs.Extensions.Http"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Linq;
using System.Text;
// reusable client proxy
static HttpClientHelper iothub = new HttpClientHelper(Environment.GetEnvironmentVariable("AzureIoTCAccessToken"));
public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
var atype = new { device = new { deviceId = "", properties = new JObject(), measurements = new JObject() } };
var iotcobj = JsonConvert.DeserializeAnonymousType(await req.ReadAsStringAsync(), atype);
// get deviceId, for test puspose use the device1
string deviceId = iotcobj?.device?.deviceId ?? "device1";
// get a device twins
var response = await iothub.Client.GetAsync($"/twins/{deviceId}?api-version=2018-06-30");
string jsontext = await response.Content.ReadAsStringAsync();
log.LogInformation($"DeviceTwin: {JsonConvert.DeserializeObject(jsontext)}");
// patch on desired property
var patch = JsonConvert.SerializeObject(new { properties = new { desired = new { ping = DateTime.UtcNow } } });
response = await iothub.Client.PatchAsync($"/twins/{deviceId}?api-version=2018-06-30", new StringContent(patch, Encoding.UTF8, "application/json"));
jsontext = await response.Content.ReadAsStringAsync();
log.LogInformation($"Patch: {JsonConvert.DeserializeObject(jsontext)}");
// invoke a device method
var method = new { methodName = "writeLine", timeoutInSeconds = 30, payload = new {input1 = 12345, input2 = "HelloDevice" } };
response = await iothub.Client.PostAsJsonAsync($"/twins/{deviceId}/methods?api-version=2018-06-30", method );
jsontext = await response.Content.ReadAsStringAsync();
log.LogInformation($"DirectMethod: {JsonConvert.DeserializeObject(jsontext)}");
return new OkObjectResult(jsontext);
}
class HttpClientHelper
{
HttpClient client;
string accessToken;
dynamic iothub;
long toleranceInSeconds = 60;
public HttpClientHelper(string accessToken)
{
this.accessToken = accessToken;
this.iothub = GetIoTHubTenant(accessToken);
string hostname = GetHostNameFromSaSToken(this.iothub.iothubTenantSasToken.sasToken);
client = new HttpClient() { BaseAddress = new Uri($"https://{hostname}") };
client.DefaultRequestHeaders.Add("Authorization", iothub.iothubTenantSasToken.sasToken);
}
public HttpClient Client
{
get
{
if((new DateTime(1970, 1, 1)).AddSeconds(this.iothub.expiry - toleranceInSeconds) < DateTime.UtcNow)
SetAuthorizationHeader();
return client;
}
}
private void SetAuthorizationHeader()
{
lock (client)
{
if ((new DateTime(1970, 1, 1)).AddSeconds(this.iothub.expiry - toleranceInSeconds) < DateTime.UtcNow)
{
if (client.DefaultRequestHeaders.Contains("Authorization"))
client.DefaultRequestHeaders.Remove("Authorization");
this.iothub = GetIoTHubTenant(this.accessToken);
client.DefaultRequestHeaders.Add("Authorization", this.iothub.iothubTenantSasToken.sasToken);
}
}
}
private string GetHostNameFromSaSToken(string sastoken)
{
var parts = sastoken.Replace("SharedAccessSignature", "").Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Split(new[] { '=' }, 2)).ToDictionary(x => x[0].Trim(), x => x[1].Trim());
return parts["sr"] ?? "";
}
private dynamic GetIoTHubTenant(string iotcAccessToken)
{
string appId = GetHostNameFromSaSToken(iotcAccessToken);
using (var hc = new HttpClient())
{
hc.DefaultRequestHeaders.Add("Authorization", accessToken);
string address = $"https://api.azureiotcentral.com/v1-beta/applications/{appId}/diagnostics/sasTokens";
var response = hc.PostAsync(address, new StringContent("{}", Encoding.UTF8, "application/json")).Result;
return JsonConvert.DeserializeAnonymousType(response.Content.ReadAsStringAsync().Result, new { iothubTenantSasToken = new { sasToken = "" }, expiry = 0L });
}
}
}
注意:上述实现基于 IoT Central 应用程序生成的访问令牌,就像它最近发布的一般可用性一样,请参见此处。在更改格式等的情况下,包含上述解决方案的所有客户端、测试人员等都将受到影响。