serialport-parsers.js 6.65 KB
const PARSER_READLINE_DELIMITER = '\r\n';
const PARSER_WAIT_FOR_OK_OR_ERROR_REGEX = /\n(?:OK|ERROR)\r\n/;

const moment = require('moment');
const nodePdu = require('node-pdu');
// const pdu = require('pdu');
const ParserReadline = require('@serialport/parser-readline');
const ParserRegex = require('@serialport/parser-regex');

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

const dbCops = require('./db-cops');
const modemInfo = require('./modem-info');
const reportSender = require('./report-sender2');

let port;

exports.setPort = function setPort(val) {
    logger.info('SERIALPORT-PARSERS: setting port');
    port = val;
};

exports.getPort = function getPort() {
    return port;
};

let ussdCallback = null;
function setUssdCallback(cb) {
    ussdCallback = cb;
}
exports.setUssdCallback = setUssdCallback;

let smsSentCallback = null;
function setSmsSentCallback(cb) {
    smsSentCallback = cb;
}
exports.setSmsSentCallback = setSmsSentCallback;

function isAlphaNumeric(str) {
    const len = str.length;
    // eslint-disable-next-line no-plusplus
    for (let i = 0; i < len; i++) {
        const code = str.charCodeAt(i);
        if (!(code > 47 && code < 58) // numeric (0-9)
            && !(code > 64 && code < 91) // upper alpha (A-Z)
            && !(code > 96 && code < 123)) { // lower alpha (a-z)
            return false;
        }
    }
    return true;
}

function parsePdu(_data) {
    const data = _data && _data.toString().trim().toUpperCase();

    if (!data) return null;
    if (!isAlphaNumeric(data)) return null;

    try {
        const result = nodePdu.parse(data);
        return result;
    } catch (e) {
        return null;
    }
}

function onCSQ(data) {
    const val = data.toString().trim().match(/\+CSQ:\s*(.*)/);
    if (!val || !val[1]) return null;

    const [, signalStrength] = val;

    logger.verbose('Signal quality extracted', { signalQuality: val[1] });

    modemInfo.signalStrength = signalStrength;
    modemInfo.signalStrengthTs = new Date();
    modemInfo.signalStrengthTsReadable = moment(modemInfo.signalStrengthTs).format('YYYY-MM-DD HH:mm:ss');

    return signalStrength;
}

function onPduDeliver(data, parsedData) {
    const from = parsedData.getAddress && parsedData.getAddress().getPhone
        ? parsedData.getAddress().getPhone() : null;

    const msg = parsedData.getData && parsedData.getData().getData
        ? parsedData.getData().getData() : null;

    const ts = new Date(parsedData.getScts().getIsoString());

    logger.info('PDU processed', { ts, from, msg });
    return { ts, from, msg };
}

function onCOPS(data) {
    const val = data.toString().trim().match(/\+COPS:\s*(.*)/);
    if (!val || !val[1]) return null;

    const cops = val[1];

    if (!cops) return null;
    const [mode, format, networkId] = cops.split(',');
    const networkName = networkId ? dbCops[networkId] || networkId : null;

    logger.verbose('COPS extracted', {
        cops, mode, format, networkId, networkName,
    });

    modemInfo.cops = cops;
    modemInfo.networkId = networkId || null;
    modemInfo.networkName = networkName || null;

    return {
        cops, mode, format, networkId, networkName,
    };
}


function isResultCodeIs(data, resultCode) {
    if (!data) return false;
    const cleanedData = (data.toString() || '').trim();
    if (!cleanedData) return false;

    if (resultCode.indexOf('+') !== 0) {
        // eslint-disable-next-line no-param-reassign
        resultCode = `+${resultCode}`;
    }

    if (resultCode.search(/:$/) < 0) {
        // eslint-disable-next-line no-param-reassign
        resultCode += ':';
    }

    return cleanedData.indexOf(resultCode) === 0;
}

const parserReadline = new ParserReadline({ delimiter: PARSER_READLINE_DELIMITER });
parserReadline.on('data', (data) => {
    modemInfo.lastReadTs = new Date();
    logger.verbose('INCOMING', { data: `${data.toString()}${PARSER_READLINE_DELIMITER}`, parser: 'parserReadLine' });

    if (!data) return;

    const pduParsed = parsePdu(data);
    if (pduParsed && pduParsed.constructor.name !== 'Deliver') {
        const pduType = pduParsed.getType();
        logger.warn('WARN-9DA32C41: Unknown PDU message type name. PLEASE REPORT IT TO DEVELOPER AT TEKTRANS', { typeName: pduParsed.constructor.name, pduType, data: data.toString().trim() });
    }

    if (pduParsed && pduParsed.constructor.name === 'Deliver' && pduParsed.getData().getSize()) {
        const pduType = pduParsed.getType();
        logger.verbose('Got a PDU SMS-DELIVER', { pduType });
        const parsedData = onPduDeliver(data, pduParsed);

        if (parsedData.ts && parsedData.from && parsedData.msg) {
            reportSender.incomingSMS(parsedData.ts, parsedData.from, parsedData.msg);
        } else {
            logger.warn('Got a PDU SMS-DELIVER but failed on parsing PDU message');
        }
    } else if (data.toString().trim() === 'ERROR') {
        if (typeof smsSentCallback === 'function') smsSentCallback(data.toString());
    } else if (isResultCodeIs(data, 'CSQ')) {
        logger.verbose('Got a signal quality report', { data: data.toString() });
        onCSQ(data);
    } else if (isResultCodeIs(data, 'COPS:')) {
        logger.verbose('Got a COPS report', { data: data.toString() });
        onCOPS(data);
    } else if (isResultCodeIs(data, 'CMT')) {
        logger.verbose('Got a new message report', { data: data.toString() });
    } else if (isResultCodeIs(data, 'CMTI')) {
        logger.verbose('Got a new message notification report', { data: data.toString() });
    } else if (isResultCodeIs(data, 'CUSD')) {
        logger.verbose('Got a USSD command response', { data: data.toString() });
        if (typeof ussdCallback === 'function') {
            logger.verbose('Calling USSD callback');
            ussdCallback(data.toString());
        } else {
            logger.verbose('Skip unwanted USSD response');
        }
    } else if (isResultCodeIs(data, 'CMGS')) {
        logger.verbose('Got CMGS report', { data: data.toString() });
        if (typeof smsSentCallback === 'function') smsSentCallback(data.toString());
    } else if (isResultCodeIs(data, 'CMS ERROR')) {
        logger.verbose('Got CMS ERROR report', { data: data.toString() });
        if (typeof smsSentCallback === 'function') smsSentCallback(data.toString());
    }
});

const parserWaitForOkOrError = new ParserRegex({ regex: PARSER_WAIT_FOR_OK_OR_ERROR_REGEX });
parserWaitForOkOrError.on('data', (data) => {
    logger.verbose('INCOMING', { data: data.toString(), parser: 'parserWaitForOkOrError' });
});


exports.PARSER_READLINE_DELIMITER = PARSER_READLINE_DELIMITER;
exports.PARSER_WAIT_FOR_OK_OR_ERROR_REGEX = PARSER_WAIT_FOR_OK_OR_ERROR_REGEX;

exports.parserReadline = parserReadline;
exports.parserWaitForOkOrError = parserWaitForOkOrError;