2019-07-04 16:18:38 +00:00
"use strict" ;
import { decode _payload } from './DecodePayload.mjs' ;
2019-07-10 11:21:38 +00:00
import { get _id _number } from '../Helpers/IdGenerator.mjs' ;
2019-07-04 16:18:38 +00:00
class MessageHandler {
2019-07-10 13:44:52 +00:00
get debug ( ) {
2019-07-15 13:31:39 +00:00
return this . settings . logging . verbose ;
2019-07-10 13:44:52 +00:00
}
constructor ( { settings , ReadingRepo , GatewayRepo } ) {
this . settings = settings ;
2019-07-09 16:31:08 +00:00
this . repo _reading = ReadingRepo ;
this . repo _gateway = GatewayRepo ;
2019-07-04 16:18:38 +00:00
}
2019-07-09 12:14:25 +00:00
async handle ( message ) {
2019-07-10 13:44:52 +00:00
if ( this . debug ) console . log ( message ) ;
2019-07-09 12:14:25 +00:00
2019-07-15 12:49:44 +00:00
if ( this . settings . ttn . encryption _key == "CHANGE_THIS" ) {
this . log . error ( ` Error: No encryption key 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 ;
}
let decoded _payload = decode _payload ( message . payload _raw , this . settings . ttn . encryption _key ) ;
2019-07-10 13:44:52 +00:00
if ( this . debug ) console . log ( decoded _payload ) ;
2019-07-09 16:31:08 +00:00
2019-07-10 11:21:38 +00:00
let rssis = [ ] ;
2019-07-10 13:44:52 +00:00
for ( let gw of message . metadata . gateways ) {
if ( this . debug ) console . log ( "gateway " , gw ) ;
2019-07-10 11:21:38 +00:00
// Insert the gateway info into the database if it doesn't exist already
if ( ! this . repo _gateway . exists ( gw . gtw _id ) ) {
this . repo _gateway . add ( {
id : gw . gtw _id ,
latitude : gw . latitude , longitude : gw . longitude ,
altitude : gw . altitude
} ) ;
}
// Generate an RSSI object
rssis . push ( {
2019-07-10 13:44:52 +00:00
id : await get _id _number ( ) ,
gateway _id : gw . gtw _id ,
2019-07-10 11:21:38 +00:00
rssi : gw . rssi ,
snr : gw . snr ,
channel : gw . channel
} ) ;
}
// Add the reading and the associated RSSIs to the database
2019-07-09 16:31:08 +00:00
this . repo _reading . add ( {
id : decoded _payload . id ,
latitude : decoded _payload . latitude ,
longitude : decoded _payload . longitude ,
data _rate : message . metadata . data _rate ,
2019-07-10 11:21:38 +00:00
code _rate : message . metadata . coding _rate ,
rssis
2019-07-09 16:31:08 +00:00
} ) ;
2019-07-04 16:18:38 +00:00
}
}
export default MessageHandler ;