-
Notifications
You must be signed in to change notification settings - Fork 0
/
telemetryJson.js
74 lines (59 loc) · 2.38 KB
/
telemetryJson.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
const gbid = id => document.getElementById(id)
const repoBaseUrl = 'https://iotmodels.github.io/dmr/' // 'https://devicemodels.azure.com'
const dtmiToPath = function (dtmi) {
return `${dtmi.toLowerCase().replace(/:/g, '/').replace(';', '-')}.json`
}
const colors = ['red', 'blue', 'green', 'orange', 'lightgreen', 'lightblue', 'silver', 'black', 'grey']
const rndColor = () => colors[Math.floor(Math.random() * colors.length)]
let mqttCreds = JSON.parse(window.localStorage.getItem('mqttCreds'))
let client
let deviceId
let modelId
let Telemetries
const start = async () => {
const qs = new URLSearchParams(window.location.search)
deviceId = qs.get('id')
modelId = qs.get('modelId')
const modelpath = `${repoBaseUrl}${dtmiToPath(modelId)}`
const model = await (await window.fetch(modelpath)).json()
Telemetries = model.contents.filter(c => c['@type'].includes('Telemetry'))
const el = document.getElementById('chart')
const dataPoints = new Map()
const series = []
Telemetries.map(t => t.name).forEach( t => {
dataPoints[t] = []
series.push({ name: t, data: dataPoints[t], color: rndColor()})
})
let startTime = Date.now();
const chart = new TimeChart(el, {
series: series,
lineWidth: 5,
baseTime: startTime
});
client = mqtt.connect(`${mqttCreds.useTls ? 'wss' : 'ws'}://${mqttCreds.hostName}:${mqttCreds.port}/mqtt`, {
clientId: mqttCreds.clientId + 1, username: mqttCreds.userName, password: mqttCreds.password })
client.on('connect', () => {
client.subscribe(`device/${deviceId}/telemetry/#`)
})
client.on('message', (topic, message) => {
//console.log(topic)
const segments = topic.split('/')
const what = segments[2]
if (what === 'telemetry') {
let now = Date.now() - startTime
const tel = JSON.parse(message)
Telemetries.map(t => t.name).forEach(t => {
if (tel[t]) {
dataPoints[t].push({x: now, y: tel[t]})
}
})
Object.keys(dataPoints).forEach(k => {
if (dataPoints[k].length > 100) {
dataPoints[k].shift()
}
})
chart.update()
}
})
}
window.onload = start