Skip to content

Instantly share code, notes, and snippets.

@thomasnordquist
Created January 8, 2019 22:44
Show Gist options
  • Save thomasnordquist/06989758e81994de01c39745062705ae to your computer and use it in GitHub Desktop.
Save thomasnordquist/06989758e81994de01c39745062705ae to your computer and use it in GitHub Desktop.
JSON String => Influx Measurement
const topics = msg.topic.split('/')
let payload
try {
payload = JSON.parse(msg.payload)
} catch (error) {
console.log('mqtt2influx: can\'t interpret payload', payload, error)
return
}
if (typeof payload === 'object') {
handleJsObject(msg.topic, payload)
} else {
const lastIndex = topics.length - 1
const topicStr = topics.slice(0, lastIndex).join('/')
const tag = topics[lastIndex]
handlePossibleMeasurement(topicStr, tag, payload)
}
// FUNCTIONS
function handleJsObject(topic, obj) {
Object.keys(obj).forEach((key) => {
const value = obj[key]
console.log(key, value)
if (typeof value === 'object') {
const newTopic = `${topic}/${key}`
console.log('is object', newTopic, value)
handleJsObject(newTopic, value)
} else {
const tag = key
handlePossibleMeasurement(topic, tag, value)
}
})
}
function handlePossibleMeasurement(topic, tag, value) {
if (typeof value === 'number' && !isNaN(value)) {
emit(topic, tag, value)
} else if (typeof value === 'boolean') {
emit(topic, tag, value === true ? 1 : 0)
}
}
function emit(topic, tag, value) {
const payload = {}
payload[tag] = value
node.send({
payload,
measurement: topic
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment