LoRaWAN-Signal-Mapping/server/ttn-app-server/TTNAppServer.mjs

62 lines
1.8 KiB
JavaScript

"use strict";
import MqttClient from 'simple-mqtt-client';
class TTNAppServer {
get connection_string() {
return `${this.settings.ttn.tls ? "mqtts" : "mqtt"}://${this.settings.ttn.host}:${this.settings.ttn.port}/`
}
// Destructure the awilix container
constructor({ settings, ansi, MessageHandler, log }) {
this.settings = settings;
/** @type {Ansi} */
this.a = ansi;
/** @type {Log} */
this.log = log;
/** @type {MessageHandler} */
this.message_handler = MessageHandler;
}
async run() {
if(this.settings.ttn.app_id == "CHANGE_THIS" || this.settings.ttn.access_key == "CHANGE_THIS") {
this.log.error(`Error: No TTN app id specified. Try filling in the required values in settings.toml. If they don't exist yet, try using server/settings.default.toml as a reference.`);
return false;
}
this.ttn_client = await this.connect();
for(let device_name of this.settings.ttn.devices) {
if(device_name == "CHANGE_THIS") {
this.log.error(`Error: No device names specified. Try filling in the required values in settings.toml. If they don't exist yet, try using server/settings.default.toml as a reference.`);
return false;
}
this.ttn_client.subscribe(`${device_name}/up`, this.handle_message.bind(this));
}
this.log.log(`Connected to ${this.connection_string}`);
}
connect() {
return new Promise((resolve, _reject) => {
this.log.log(`Connecting to ${this.connection_string}`);
MqttClient.new().init(
this.connection_string,
this.settings.ttn.app_id, // Username
this.settings.ttn.access_key, // Password
`${this.settings.ttn.app_id}/devices`, // Base topic
(client) => {
client;
resolve(client);
}
);
})
}
async handle_message(payload) {
await this.message_handler.handle(payload);
}
}
export default TTNAppServer;