const { SerialPort } = require('serialport');

var port, portInfo;
function delay(time){
    return new Promise(resolve => setTimeout(resolve, time));
}

function waitPortReady(){
    return new Promise((resolve, reject) => {
        port.on('open', () => {
            console.log('> Port opened:', portInfo.path);
            resolve();

        });
    });
}

async function main(){
    var ports = await SerialPort.list();
    portInfo = ports.find(x=> x.path.indexOf('usbserial') >=0);
    if (!portInfo){
        console.log(">No usbserial port found");
        return;
    }

    port = new SerialPort({path: portInfo.path, baudRate: 115200, autoOpen: false});
    port.on('data', data => {
        process.stdout.write(data.toString());
    });

    port.open(err => {
        if (err) {
            console.error("Open failed:", err.message);
        }
    });

    await waitPortReady();
    await delay(1000);
    port.write('AT\r\n');

    //
    // await delay(1000);
    // port.write('AT+CMGF=1\r\n');
    //
    // await delay(1000);
    // port.write('AT+CMGS="+84363844698"\r\n');
    //
    // await delay(1000);
    // port.write('This is test message from KEEVIEW\x1A');
    delay(10000);
    port.close();
}



main();