-
Notifications
You must be signed in to change notification settings - Fork 0
/
deviceProto.js
246 lines (237 loc) · 10.5 KB
/
deviceProto.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import mqtt from './mqttClient.js'
let client
const resolveModel = proto => {
const repoBaseUrl = 'https://iotmodels.github.io/dmr/'
return `${repoBaseUrl}protos/${proto.toLowerCase().replace('.', '/')}.proto`
}
const isBuffer = obj => {
return obj != null && obj.constructor != null &&
typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
}
const isObject = obj => Object.prototype.toString.call(obj) === '[object Object]'
const resolveSchema = s => {
if (!isObject(s) && s.startsWith('dtmi:')) {
console.error('not supported schema', s)
return null
} else if (isObject(s) && s['@type'] === 'Enum') {
return s.valueSchema
} else if (s === 'int32') {
return 'integer'
} else if (s === 'bool') {
return 'boolean'
} else {
return s
}
}
let root
let Telemetries
let Properties
let Commands
let PropertiesSetter
let ack
export default {
data: () => ({
device: {},
properties: [],
commands: [],
telemetries: [],
modelpath: '',
telemetryValues: {},
host: ''
}),
async created() {
client = mqtt.start()
this.host = mqtt.host
await this.initModel()
this.fetchData()
},
methods: {
async loadModel(modelId) {
const modelUrl = resolveModel(modelId)
root = await protobuf.load(modelUrl)
this.modelpath = modelUrl
Telemetries = root.lookupType('Telemetries')
Properties = root.lookupType('Properties')
PropertiesSetter = root.lookupService('PropertiesSetter')
Commands = root.lookupService('Commands')
ack = root.lookupType('ack')
Object.keys(Telemetries.fields).forEach( t => {
this.telemetries.push({name: Telemetries.fields[t].name})
})
Object.keys(Properties.fields).forEach( t => {
this.properties.push({name: Properties.fields[t].name, writable: false})
})
Object.keys(Commands.methodsArray).forEach(k => {
const method = Commands.methodsArray[k]
const req = root.lookupType(method.requestType)
const res = root.lookupType(method.responseType)
this.commands.push({
name: method.name,
request: {
name : req.name,
schema: ''
},
response: {
name : res.name,
schema: ''
}
})
const curCmd = this.commands.filter(c => c.name === method.name)[0]
Object.keys(req.fields)
.forEach(k => {
curCmd.request.schema += req.fields[k].type
})
Object.keys(res.fields)
.forEach(k => {
curCmd.response.schema += res.fields[k].type
})
})
Object.keys(PropertiesSetter.methodsArray).forEach(k => {
const method = PropertiesSetter.methodsArray[k]
const req = root.lookupType(method.requestType)
Object.keys(req.fields)
.filter(f => f === method.name.substring(4)) // only props by set_
.forEach(k => {
//console.log(' ' + req.fields[k].name + ': ' + req.fields[k].type)
const prop = this.properties.filter(p=>p.name===k)[0]
prop.writable = true
prop.schema = req.fields[k].type
})
const res = root.lookupType(method.responseType)
// Object.keys(res.fields)
// .forEach(k => console.log(' ' + res.fields[k].name + ': ' + res.fields[k].type))
})
},
async initModel() {
const qs = new URLSearchParams(window.location.search)
document.title = qs.get('id')
await this.loadModel(qs.get('model-id'))
this.device = {
deviceId: qs.get('id'),
modelId: qs.get('model-id'),
properties: {
reported: {},
desired: {}
}}
},
async fetchData() {
client.on('error', e => console.error(e))
client.on('connect', () => {
console.log('connected', client.connected)
client.subscribe(`registry/${this.device.deviceId}/status`)
client.subscribe(`device/${this.device.deviceId}/props`)
client.subscribe(`device/${this.device.deviceId}/props/+/ack`)
client.subscribe(`device/${this.device.deviceId}/props/+/set/#`)
client.subscribe(`device/${this.device.deviceId}/cmd/+/resp`)
})
client.on('message', (topic, message) => {
let msg = {}
if (isBuffer(message)) {
const s = message.toString()
if (s[0] == '{') {
msg = JSON.parse(message)
} else {
msg = s
}
}
const ts = topic.split('/')
const what = ts[2]
if (topic === `registry/${this.device.deviceId}/status`) {
this.device.connectionState = msg.status === 'online' ? 'Connected' : 'Disconnected'
this.device.lastActivityTime = msg.when
}
if (topic.startsWith(`device/${this.device.deviceId}/props`)) {
const propName = ts[3]
if (topic.indexOf('/set')>0) {
const wprop = Properties.decode(message)
this.device.properties.desired[propName] = wprop[propName]
}else if (topic.endsWith('/ack')) {
const ackMsg = ack.decode(message)
const ackValue = Properties.decode(ackMsg.value.value)
this.device.properties.reported[propName] = {ac: ackMsg.status, ad : ackMsg.description, av: ackMsg.version, value : ackValue[propName] }
//gbid('interval_ack').innerText = ackMsg.status + ackMsg.description
} else {
const prop = Properties.decode(message)
Object.keys(Properties.fields).forEach(k => {
const p = this.properties.filter(p => p.name === k)[0]
if (p.writable) {
if (this.device.properties.reported[k]) {
this.device.properties.reported[k].value = prop[k]
} else {
this.device.properties.reported[k] = {value: prop[k], ac:0, ad:''}
}
} else {
const field = Properties.fields[k]
if (field.type==='google.protobuf.Timestamp') {
this.device.properties.reported[k] = new Date(prop[k].seconds * 1000 + prop[k].nanos/1000)
} else {
this.device.properties.reported[k] =prop[k]
}
}
})
}
}
if (topic.startsWith(`device/${this.device.deviceId}/cmd`)) {
const cmdName = ts[3]
const cmd = this.commands.filter(c => c.name === cmdName)[0]
const resType = root.lookupType(cmd.response.name)
const resValue = resType.decode(message)
const resTypeSecond = Object.keys(resType.fields)[1] // not status
cmd.responseMsg = resValue[resTypeSecond]
}
})
},
async handlePropUpdate(name, val, schema) {
const resSchema = resolveSchema(schema)
//this.device.properties.desired[name] = ''
//this.device.properties.reported[name] = ''
const currentVersion = this.device.properties.reported[name].av || 0
const topicV = `device/${this.device.deviceId}/props/${name}/set/?$version=${currentVersion}`
client.publish(topicV,null, {qos:1, retain: true})
const version = currentVersion + 1
const topic = `device/${this.device.deviceId}/props/${name}/set/?$version=${version}`
let desiredValue = {}
switch (resSchema) {
case 'string':
desiredValue = val
break
case 'integer':
desiredValue = parseInt(val)
break
case 'boolean':
desiredValue = (val === 'true')
break
case 'double':
desiredValue = parseFloat(val)
break
default:
console.error('schema serializer not implemented', resSchema)
throw new Error('Schema serializer not implemented for' + Json.stringify(resSchema))
}
const prop = {}
prop[name] = desiredValue
const msg = Properties.create(prop)
const payload = Properties.encode(msg).finish()
client.publish(topic,payload, {qos:1, retain: true})
},
onCommand (cmdName, cmdReq) {
const topic = `device/${this.device.deviceId}/cmd/${cmdName}`
const cmd = this.commands.filter(c => c.name === cmdName)[0]
const reqType = root.lookupType(cmd.request.name)
const reqTypeFirst = Object.keys(reqType.fields)[0]
const req = {}
req[reqTypeFirst] = cmdReq
const msg = reqType.create(req)
const payload = reqType.encode(msg).finish()
client.publish(topic,payload, {qos:1, retain: false})
},
formatDate(d) {
if (d === '0001-01-01T00:00:00Z') return ''
return moment(d).fromNow()
},
gv(object, string, defaultValue = '') {
// https://stackoverflow.com/questions/70283134
return _.get(object, string, defaultValue)
}
}
}