-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.iothub.js
83 lines (78 loc) · 2.96 KB
/
app.iothub.js
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
const hub = require('azure-iothub')
const dtService = require('azure-iot-digitaltwins-service')
const moment = require('moment')
function getDeviceList(connectionString, cb) {
const registry = hub.Registry.fromConnectionString(connectionString)
const queryText = `select deviceId,
lastActivityTime,
connectionState,
status,
properties.reported.[[$iotin:deviceinfo]].manufacturer.value as manufacturer
from devices
where capabilities.iotEdge != true`;
const query = registry.createQuery(queryText)
query.nextAsTwin((err, devices) => {
if (err) {
console.error(`Failed to query devices due to ${err}`);
} else {
const devicesInfo = devices.map((d) => {
const elapsed = moment(d.lastActivityTime)
return {
id: d.deviceId,
time: elapsed.isBefore('2019-01-01', 'year') ? '' : elapsed.fromNow(),
lastActivityTime: d.lastActivityTime,
state: d.connectionState,
status: d.status,
manufacturer: d.manufacturer
}
})
console.log(`Found ${devicesInfo.length} registered devices.`)
cb(devicesInfo)
}
})
}
async function getInterfaces(connectionString, deviceId) {
const credentials = new dtService.IoTHubTokenCredentials(connectionString)
const digitalTwinServiceClient = new dtService.DigitalTwinServiceClient(credentials)
let dt = null
try {
dt = await digitalTwinServiceClient.getDigitalTwin(deviceId)
} catch (err) {
console.log(err)
return
}
return dt
.interfaces
.urn_azureiot_ModelDiscovery_DigitalTwin
.properties
.modelInformation
.reported
.value
.interfaces
}
async function getInterfaceDetails(connectionString, urn) {
const credentials = new dtService.IoTHubTokenCredentials(connectionString)
const digitalTwinServiceClient = new dtService.DigitalTwinServiceClient(credentials)
let response
try {
response = await digitalTwinServiceClient.getModel(urn)
} catch (err) {
console.log(err)
return
}
return response.contents
}
async function runCommand(connectionString, deviceId, interfaceName, command, param) {
const credentials = new dtService.IoTHubTokenCredentials(connectionString)
const digitalTwinServiceClient = new dtService.DigitalTwinServiceClient(credentials)
const cmdParam = JSON.parse(param)
let response
try {
response = await digitalTwinServiceClient.invokeCommand(deviceId, interfaceName, command, cmdParam)
} catch (err) {
console.log(err)
return
}
return response.result
}
module.exports = { getDeviceList, getInterfaces, getInterfaceDetails, runCommand }