Skip to content

Instantly share code, notes, and snippets.

@lafka
Created March 23, 2017 12:45
Show Gist options
  • Save lafka/7c58f114666fd852bb0925e771644b24 to your computer and use it in GitHub Desktop.
Save lafka/7c58f114666fd852bb0925e771644b24 to your computer and use it in GitHub Desktop.
check for changes in network defition and pubish to mqtt
// Test MQTT sync
//
// usage:
// - npm install mqtt request lodash
// - set `networks` to array of networks you want to scan
// - set `auth` to (user,pw) combo
// - set `broker` to something like mqtt://test.mosquitto.org
// - don't be to eager on `reloadInterval` as node fails?? seems to keep sockets open for to long
const request = require('request')
const mqtt = require('mqtt')
const _ = require('lodash')
const auth = "user:pw"
const endpoint = 'https://' + (auth ? auth + '@' : '' ) + 'http.cloud.tiny-mesh.com/v2'
let reloadInterval = 15000
let client = mqtt.connect()
let networks = []
let netStorage = {}
let devStorage = {}
const req = (path, cb) => {
return request(endpoint + path, (err, req, body) => {
process.nextTick( () => cb(JSON.parse(body)) )
if (200 !== req.statusCode)
throw new Error("Failed to GET url[" + res.statusCode + "]: " + endpoint + path)
})
}
const loadNetwork = (nid) =>
req('/network/' + nid, res => publishNetworkUpdates(nid, res))
const loadDevices = (nid) =>
req('/device/' + nid, res => publishDeviceUpdates(nid, res))
// notify of changes in the network resource, exclusive of device changes
const publishNetworkUpdates = (nid, body) => {
body = _.omit(body, 'devices')
if (!netStorage[nid]) {
netStorage[nid ] = body
publish('/' + nid, body)
} else if (!_.isEqual(netStorage[nid], body)) {
publish('/' + nid, body)
}
}
const publishDeviceUpdates = (nid, body) => {
if (!devStorage[nid]) {
devStorage[nid] = body
body.forEach(body => publish('/' + nid + '/' + body.key, body))
} else {
body.forEach(device => {
if (!_.isEqual(devStorage[nid][device.key], device)) {
devStorage[nid][device.key] = device
publish('/' + nid + '/' + device.key, device)
}
})
}
}
const pubprefix = "/tm-test"
const publish = (resource, body) => {
console.log('publish', pubprefix + resource)
client.publish(pubprefix + resource, JSON.stringify(body))
}
const doit = () =>
networks.forEach(
nid => {
loadNetwork(nid)
loadDevices(nid)
})
doit()
client.on('connect', () => setInterval(doit, reloadInterval))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment