Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var mosca = require('mosca');
- var mqtt = require('mqtt');
- var fs = require('fs');
- var path = require('path');
- var settings = {
- port: 1883
- };
- var server = new mosca.Server(settings);
- var mqttClient;
- server.on('clientConnected', function(client) {
- console.log('Client connected: ', client.id);
- var CERT = fs.readFileSync(path.join(__dirname, '/cert.pem'));
- var options = {
- port: '443',
- host: 'broker.xively.com',
- cert: CERT,
- rejectUnauthorized: true,
- protocol: 'mqtts',
- clientid: '4679a4f0-3ebf-4b77-b18c-470dfa0ad49f',
- username: '4679a4f0-3ebf-4b77-b18c-470dfa0ad49f',
- password: 'qZS6Qr2ijOQe3H3+l+QUm0gGTKydWtSlRBJR72mbUGs='
- }
- mqttClient = mqtt.connect(options);
- mqttClient.on('message', function (topic, message) {
- var message = {
- topic: topic,
- payload: message
- };
- server.publish(message, function() {
- console.log('A message from Xively was published to local broker');
- });
- });
- mqttClient.on('connect', function () {
- var message = {
- topic: 'local/xivelyReady',
- payload: 'xivelyReady'
- };
- server.publish(message, function() {
- console.log('Xively is ready!');
- });
- });
- });
- server.on('subscribed', function (topic, client) {
- if (topic !== 'local/xivelyReady') {
- mqttClient.subscribe(topic);
- console.log('Subscribed to Xively topic');
- }
- });
- // fired when a message is received
- server.on('published', function(packet, client) {
- if (packet.topic.split('/')[0] === 'localXi') {
- mqttClient.publish(packet.topic.replace(/localXi/i, 'xi'), packet.payload);
- console.log('Message published to xively broker');
- }
- });
- server.on('ready', setup);
- // fired when the mqtt server is ready
- function setup() {
- console.log('Mosca server is up and running');
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement