Created
December 4, 2016 11:42
-
-
Save jamesbulpin/9e4567294eb93e5d572e0734be8d1999 to your computer and use it in GitHub Desktop.
MQTT-Octoblu connector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const util = require('util'); | |
var S = require('string'); | |
var mqtt = require('mqtt'); | |
var meshblu = require('meshblu'); | |
var meshbluJSON = require("./meshblu.json"); | |
// Specifies how you want your message payload to be passed | |
// from Octoblu to your device | |
var MESSAGE_SCHEMA = { | |
type: 'object', | |
properties: { | |
topic: { | |
type: 'string', | |
required: true | |
}, | |
message: { | |
type: 'string', | |
required: true | |
} | |
} | |
}; | |
connectionTimer = setTimeout(function() { | |
console.log("Timeout setting up connections, exiting."); | |
process.exit(1); | |
}, 120000); | |
// Not specifying a UUID/Token auto-registers a new device | |
var conn = meshblu.createConnection({ | |
"uuid": meshbluJSON.uuid, | |
"token": meshbluJSON.token, | |
"server": "meshblu.octoblu.com", | |
"port": 80 | |
}); | |
conn.on('notReady', function(data){ | |
console.log('Octoblu UUID FAILED AUTHENTICATION!'); | |
console.log(data); | |
client.publish("Log/ops", "Octoblu connection failed: " + util.format(data)); | |
}); | |
var client = mqtt.connect('mqtt://localhost', {protocolId: 'MQIsdp', protocolVersion: 3}); | |
client.on('connect', function () { | |
console.log("Connected to MQTT"); | |
client.subscribe('Octoblu/#'); | |
}); | |
client.on('message', function (topic, message) { | |
console.log("MQTT RX t=" + topic + " m=" + message.toString()); | |
var p = S(topic).splitLeft("/", 1); | |
if (p.length > 1) { | |
client.publish("Log/octoblu/outbound/" + topic, message.toString()); | |
conn.message({ | |
"devices": "*", | |
"topic": topic, | |
"message": message.toString() | |
}); | |
} | |
}); | |
conn.on('ready', function(rdata){ | |
console.log('UUID AUTHENTICATED!'); | |
console.log(rdata); | |
clearTimeout(connectionTimer); | |
connectionTimer = undefined; | |
conn.update({ | |
"uuid": meshbluJSON.uuid, | |
"token": meshbluJSON.token, | |
"messageSchema": MESSAGE_SCHEMA, | |
}); | |
conn.on('message', function(data){ | |
console.log('Octoblu message received'); | |
console.log(data); | |
if (('topic' in data) && ('message' in data)) { | |
client.publish(data.topic, data.message); | |
client.publish("Log/octoblu/inbound/" + data.topic, data.message); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment