├── .gitignore ├── README.md └── mqtt2rest.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # mqtt2rest -- An MQTT to REST Bridge 2 | 3 | Allows connecting traditional REST web services with MQTT. 4 | 5 | Usage: 6 | 7 | # edit mqtt2rest.js to configure REST endpoint 8 | vim mqtt2rest.js 9 | 10 | # install dependencies 11 | npm install mqtt 12 | 13 | # run bridge 14 | node mqtt2rest.js 15 | 16 | Diagram: 17 | 18 | ---------------------------- --------------- ------------- --------------- 19 | | End Device (MQTT Client) |----| MQTT Broker |----| mqtt2rest |-----| REST WebApp | 20 | ---------------------------- --------------- ------------- --------------- 21 | ^^^^^^^ ^^^^ ^^^^ ^^^^^ 22 | an IoT "Thing" such as mosquitto this program such as scriptr.io 23 | 24 | -------------------------------------------------------------------------------- /mqtt2rest.js: -------------------------------------------------------------------------------- 1 | /* mqtt2rest.js */ 2 | 3 | /* mqtt init */ 4 | var mqtt = require('mqtt'); 5 | var mqtt_client = mqtt.connect('mqtt://croft.thethings.girovito.nl'); 6 | 7 | /* http init */ 8 | var https = require('https'); 9 | var options = { 10 | host: 'api.scriptrapps.io', 11 | path: '/ttn_test', 12 | //port: '1337', // optional port 13 | method: 'POST', 14 | headers: { 15 | Authorization: "bearer TTUyMDg1MjNCMDpzY3JpcHRyOjhCNDE0NTVERkYwNjhEMDQ2QkNBMDQwNUVGMjg3MTFG" 16 | }, 17 | }; 18 | 19 | /* display data returned from REST service */ 20 | rest_callback = function(response) { 21 | var str = '' 22 | response.on('data', function (chunk) { 23 | str += chunk; 24 | }); 25 | 26 | response.on('end', function () { 27 | console.log(str); 28 | }); 29 | } 30 | 31 | /* subscribe to some topics */ 32 | mqtt_client.on('connect', function () { 33 | mqtt_client.subscribe('nodes/ABABCCED/packets'); 34 | mqtt_client.subscribe('gateways/008000000000ABFF/status'); 35 | }); 36 | 37 | /* forward MQTT packets to REST */ 38 | mqtt_client.on('message', function (topic, message) { 39 | console.log("MQTT Received Packet from TTN: ",message.toString()); 40 | 41 | console.log("Pushing to REST API... "); 42 | 43 | var req = https.request(options, rest_callback); 44 | req.write(JSON.stringify({topic: topic, message: message.toString()})) 45 | req.end(); 46 | 47 | }); 48 | 49 | --------------------------------------------------------------------------------