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
| "use strict";
|
| const axios = require("axios");
| const qs = require("qs");
|
| async function requestTuple({ baseUrl, path: apiPath, autoRegister, deviceNo, logger }) {
| const url = `${baseUrl}${apiPath}`;
|
| logger.upload("aliyun", "tuple", deviceNo,
| `请求三元组 ${url} isAutoRegister=${autoRegister ? 1 : 0} deviceName=${deviceNo}`);
|
| let response;
| try {
| response = await axios({
| method: "post",
| baseURL: baseUrl,
| url: apiPath,
| headers: { "Content-Type": "application/x-www-form-urlencoded" },
| data: qs.stringify({
| isAutoRegister: autoRegister ? 1 : 0,
| deviceName: deviceNo,
| }),
| timeout: 10000,
| });
| } catch (err) {
| const msg = err.response
| ? `HTTP ${err.response.status}`
| : err.message;
| logger.upload("aliyun", "tuple", deviceNo, `三元组请求失败: ${msg}`);
| return { ok: false, code: "ALIYUN_TUPLE_FAIL", reason: msg };
| }
|
| const body = response.data;
| const data = body && body.data;
|
| if (!data || !data.productKey || !data.deviceName || !data.deviceSecret) {
| const reason = "三元组返回字段缺失: " + JSON.stringify(body);
| logger.upload("aliyun", "tuple", deviceNo, reason);
| return { ok: false, code: "ALIYUN_TUPLE_NOT_FOUND", reason };
| }
|
| logger.upload("aliyun", "tuple", deviceNo,
| `三元组获取成功 productKey=${data.productKey}`);
|
| return {
| ok: true,
| code: "ALIYUN_TUPLE_OK",
| data: {
| productKey: data.productKey,
| deviceName: data.deviceName,
| deviceSecret: data.deviceSecret,
| },
| };
| }
|
| module.exports = { requestTuple };
|
|