// server.js const ttn = require("ttn") const express = require("express") const ws = require("express-ws") console.log("Starting server...") const appID = "XXXXXXX" // Change this to your app ID const accessKey = "ttn-account-v2.XXXXXXX" // Change this to your access key const deviceID = "XXXXXXX" // create a new http server const server = express() // install the websocket plugin ws(server) server.use(express.static("public")) server.ws("/data", function (ws, req) { console.log("New websocket opened") ttn.data(appID, accessKey) .then(function (client) { client.on("uplink", function (devID, payload) { console.log("Received uplink from", devID) ws.send(JSON.stringify(payload)) }) ws.on("close", function () { client.close() }) // Listen to WebSocket events coming from the client. ws.on("message", function (payload) { const parsed = JSON.parse(payload) console.log("Received websocket message", parsed) // checking if the message comming from the websocket is indead a "downlink" event if (parsed && parsed.type == "downlink") { console.log("Scheduling downlink", parsed) client.send(deviceID, parsed.fields) } }) }) .catch(function (error) { console.error(error) ws.close() }) }) console.log("HTTP server listening on 4000 ...") server.listen(4000)