Skip to content

Commit ded5ea7

Browse files
authored
Merge pull request #12 from FlowFuse/update-schema-detection
Use is-utf to validate string payload
2 parents 32959d1 + 1a37e6d commit ded5ea7

File tree

4 files changed

+25
-16
lines changed

4 files changed

+25
-16
lines changed

index.js

+1
Original file line numberDiff line numberDiff line change
@@ -28,5 +28,6 @@ process.on('SIGTERM', async () => {
2828
})
2929

3030
app.listen(port, () => {
31+
console.log(`MQTT Schema Agent running - pid ${process.pid}`)
3132
console.log(`listening on port ${port}`)
3233
})

lib/agent.js

+17-16
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
const got = require('got')
2+
const isUtf8 = require('is-utf8')
23
const mqtt = require('mqtt')
34

45
const schemaGen = require('./schema-generator')
@@ -123,26 +124,26 @@ class Agent {
123124
// console.log(topic)
124125
let type = { type: 'unknown' }
125126
try {
126-
const stringPayload = payload.toString('utf8')
127-
type = { type: 'string' }
128-
switch (stringPayload.charAt(0)) {
129-
case '<':
130-
// probably XML
131-
type = { type: 'xml' }
132-
break
133-
case '{':
134-
case '[':
135-
// probably JSON
136-
try {
137-
const json = JSON.parse(stringPayload)
138-
type = schemaGen.generateSchema(json)
139-
} catch (err) {
140-
console.log(err)
127+
if (isUtf8(payload)) {
128+
const stringPayload = payload.toString('utf8')
129+
type = { type: 'string' }
130+
if (stringPayload.charAt(0) === '<' && stringPayload.charAt(stringPayload.length - 1) === '>') {
131+
type.type = 'xml'
132+
} else {
133+
try {
134+
const json = JSON.parse(stringPayload)
135+
type = schemaGen.generateSchema(json)
136+
} catch (err) {
137+
// Not JSON parseable - default to string
138+
}
141139
}
140+
} else {
141+
type.type = 'bin'
142142
}
143143
} catch (err) {
144-
console.log(err)
144+
console.log(`Error parsing payload on topic '${topic}' ${err}`)
145145
}
146+
// console.log(topic, type)
146147
agent.topics[topic] = {
147148
timestamp: Date.now(),
148149
type

package-lock.json

+6
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+1
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
"body-parser": "^1.20.3",
3232
"express": "^4.21.2",
3333
"got": "^11.8.6",
34+
"is-utf8": "^0.2.1",
3435
"mqtt": "^5.10.3"
3536
},
3637
"devDependencies": {

0 commit comments

Comments
 (0)