-
Notifications
You must be signed in to change notification settings - Fork 0
/
telemetryProto.js
73 lines (60 loc) · 2.29 KB
/
telemetryProto.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
const gbid = id => document.getElementById(id)
const colors = ['red', 'blue', 'green', 'orange', 'lightgreen', 'lightblue', 'silver', 'black', 'grey']
const rndColor = () => colors[Math.floor(Math.random() * colors.length)]
const resolveModel = proto => {
const repoBaseUrl = 'https://iotmodels.github.io/dmr/'
return `${repoBaseUrl}protos/${proto.toLowerCase().replace('.', '/')}.proto`
}
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 modelUrl = resolveModel(modelId)
const root = await protobuf.load(modelUrl)
Telemetries = root.lookupType('Telemetries')
const el = document.getElementById('chart')
const dataPoints = new Map()
const series = []
Object.keys(Telemetries.fields).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}/tel`)
})
let i =0
client.on('message', (topic, message) => {
//console.log(topic)
const segments = topic.split('/')
const what = segments[2]
if (what === 'tel') {
const now = Date.now() - startTime
const tel = Telemetries.decode(message)
Object.keys(Telemetries.fields).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