bootstrap.js 2.7 KB
/**
 * Modul modem bootstrap
 * @module
 * @since 2019-09-25
 */

const DEFAULT_BAUDRATE = 115200;

const fs = require('fs');
const SerialPort = require('serialport');

const config = require('komodo-sdk/config');
const logger = require('komodo-sdk/logger');

const parsers = require('./serialport-parsers');
const modemCommands = require('./modem-commands');
const ussdCodes = require('./modem-commands/ussd-codes');

const modemInfo = require('./modem-info');
const registerModem = require('./register-modem');

logger.info('Bootstraping modem');

if (!fs.existsSync(config.modem.device)) {
    logger.error(`Modem not found on ${config.modem.device}. Terminating.`);
    process.exit(1);
}

const port = new SerialPort(config.modem.device, {
    baudRate: (config.modem && config.modem.options && config.modem.options.baudRate)
        || DEFAULT_BAUDRATE,
}, async (err) => {
    if (err) {
        logger.warn(`Error opening modem. ${err}. Terminating modem ${config.modem.device}.`);
        process.exit(1);
    }

    global.MODEM_PORT = port;
    parsers.setPort(port);
    // modemCommands.setPort(port);
    port.pipe(parsers.parserReadline);

    await modemCommands.writeToPortAndWaitForOkOrError(`${modemCommands.CTRLZ}AT&FE0\r`);
    await modemCommands.initATCommands();
    await modemCommands.queryManufacturer();
    await modemCommands.queryModel();
    await modemCommands.queryIMEIAndIMSI();
    await modemCommands.queryCOPSAndSignalQuality();

    logger.verbose('Modem state', modemInfo);
    registerModem();

    if (config.debug_sms_destination_on_start) {
        await modemCommands.sendSMS(config.debug_sms_destination_on_start,
            `${config.name} (${modemInfo.imsi || 'UNKNOWN'}) started on ${new Date()}`);
    }

    if (config.debug_ussd_code_on_start) {
        const ussdResponse = await modemCommands.executeUSSD(config.debug_ussd_code_on_start, 2);
        logger.info('USSD RESPONSE', { command: config.debug_ussd_code_on_start, ussdResponse });
    }

    if ((config.bootstrap_sms_quota_check && modemInfo.networkName && modemInfo.networkName === 'TELKOMSEL') || config.bootstrap_tsel_sms_quota_check) {
        const ussdResponse = await modemCommands.executeUSSD(ussdCodes.TSEL_SMS_QUOTA_CHECK, 1);
        logger.info('USSD RESPONSE', { command: config.debug_ussd_code_on_start, ussdResponse });
    }

    setInterval(async () => {
        await modemCommands.initATCommands();
        await modemCommands.queryManufacturer();
        await modemCommands.queryModel();
        await modemCommands.queryIMEIAndIMSI();
        await modemCommands.queryCOPSAndSignalQuality();
        logger.info('Modem state', modemInfo);
        registerModem();
    }, config.interval_beetwen_signal_strength_ms || 30000);
});