"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SerialDriver = void 0;
/* istanbul ignore file */
const events_1 = require("events");
const net_1 = __importDefault(require("net"));
const serialPort_1 = require("../../serialPort");
const socketPortUtils_1 = __importDefault(require("../../socketPortUtils"));
const utils_1 = require("../../../utils");
const writer_1 = require("./writer");
const parser_1 = require("./parser");
const frame_1 = require("./frame");
const debug_1 = __importDefault(require("debug"));
const wait_1 = __importDefault(require("../../../utils/wait"));
const debug = (0, debug_1.default)('zigbee-herdsman:adapter:ezsp:uart');
var NcpResetCode;
(function (NcpResetCode) {
    NcpResetCode[NcpResetCode["RESET_UNKNOWN_REASON"] = 0] = "RESET_UNKNOWN_REASON";
    NcpResetCode[NcpResetCode["RESET_EXTERNAL"] = 1] = "RESET_EXTERNAL";
    NcpResetCode[NcpResetCode["RESET_POWER_ON"] = 2] = "RESET_POWER_ON";
    NcpResetCode[NcpResetCode["RESET_WATCHDOG"] = 3] = "RESET_WATCHDOG";
    NcpResetCode[NcpResetCode["RESET_ASSERT"] = 6] = "RESET_ASSERT";
    NcpResetCode[NcpResetCode["RESET_BOOTLOADER"] = 9] = "RESET_BOOTLOADER";
    NcpResetCode[NcpResetCode["RESET_SOFTWARE"] = 11] = "RESET_SOFTWARE";
    NcpResetCode[NcpResetCode["ERROR_EXCEEDED_MAXIMUM_ACK_TIMEOUT_COUNT"] = 81] = "ERROR_EXCEEDED_MAXIMUM_ACK_TIMEOUT_COUNT";
    NcpResetCode[NcpResetCode["ERROR_UNKNOWN_EM3XX_ERROR"] = 128] = "ERROR_UNKNOWN_EM3XX_ERROR";
})(NcpResetCode || (NcpResetCode = {}));
class SerialDriver extends events_1.EventEmitter {
    serialPort;
    socketPort;
    writer;
    parser;
    initialized;
    portType;
    sendSeq = 0; // next frame number to send
    recvSeq = 0; // next frame number to receive
    ackSeq = 0; // next number after the last accepted frame
    rejectCondition = false;
    waitress;
    queue;
    constructor() {
        super();
        this.initialized = false;
        this.queue = new utils_1.Queue(1);
        this.waitress = new utils_1.Waitress(this.waitressValidator, this.waitressTimeoutFormatter);
    }
    async connect(options) {
        this.portType = socketPortUtils_1.default.isTcpPath(options.path) ? 'socket' : 'serial';
        if (this.portType === 'serial') {
            await this.openSerialPort(options.path, options.baudRate, options.rtscts);
        }
        else {
            await this.openSocketPort(options.path);
        }
    }
    async openSerialPort(path, baudRate, rtscts) {
        const options = {
            path,
            baudRate: typeof baudRate === 'number' ? baudRate : 115200,
            rtscts: typeof rtscts === 'boolean' ? rtscts : false,
            autoOpen: false,
            parity: 'none',
            stopBits: 1,
            xon: false,
            xoff: false,
        };
        // enable software flow control if RTS/CTS not enabled in config
        if (!options.rtscts) {
            debug(`RTS/CTS config is off, enabling software flow control.`);
            options.xon = true;
            options.xoff = true;
        }
        debug(`Opening SerialPort with ${JSON.stringify(options)}`);
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        this.serialPort = new serialPort_1.SerialPort(options);
        this.writer = new writer_1.Writer();
        this.writer.pipe(this.serialPort);
        this.parser = new parser_1.Parser(!options.rtscts); // flag unhandled XON/XOFF in logs if software flow control enabled
        this.serialPort.pipe(this.parser);
        this.parser.on('parsed', this.onParsed.bind(this));
        try {
            await this.serialPort.asyncOpen();
            debug('Serialport opened');
            this.serialPort.once('close', this.onPortClose.bind(this));
            this.serialPort.on('error', this.onPortError.bind(this));
            // reset
            await this.reset();
            this.initialized = true;
        }
        catch (error) {
            this.initialized = false;
            if (this.serialPort.isOpen) {
                this.serialPort.close();
            }
            throw error;
        }
    }
    async openSocketPort(path) {
        const info = socketPortUtils_1.default.parseTcpPath(path);
        debug(`Opening TCP socket with ${info.host}:${info.port}`);
        this.socketPort = new net_1.default.Socket();
        this.socketPort.setNoDelay(true);
        this.socketPort.setKeepAlive(true, 15000);
        this.writer = new writer_1.Writer();
        this.writer.pipe(this.socketPort);
        this.parser = new parser_1.Parser();
        this.socketPort.pipe(this.parser);
        this.parser.on('parsed', this.onParsed.bind(this));
        return new Promise((resolve, reject) => {
            const openError = (err) => {
                this.initialized = false;
                reject(err);
            };
            this.socketPort.on('connect', () => {
                debug('Socket connected');
            });
            this.socketPort.on('ready', async () => {
                debug('Socket ready');
                this.socketPort.removeListener('error', openError);
                this.socketPort.once('close', this.onPortClose.bind(this));
                this.socketPort.on('error', this.onPortError.bind(this));
                // reset
                await this.reset();
                this.initialized = true;
                resolve();
            });
            this.socketPort.once('error', openError);
            this.socketPort.connect(info.port, info.host);
        });
    }
    async onParsed(frame) {
        const rejectCondition = this.rejectCondition;
        try {
            frame.checkCRC();
            /* Frame receive handler */
            switch (frame.type) {
                case frame_1.FrameType.DATA:
                    this.handleDATA(frame);
                    break;
                case frame_1.FrameType.ACK:
                    this.handleACK(frame);
                    break;
                case frame_1.FrameType.NAK:
                    this.handleNAK(frame);
                    break;
                case frame_1.FrameType.RST:
                    this.handleRST(frame);
                    break;
                case frame_1.FrameType.RSTACK:
                    this.handleRSTACK(frame);
                    break;
                case frame_1.FrameType.ERROR:
                    await this.handleError(frame);
                    break;
                default:
                    this.rejectCondition = true;
                    debug(`UNKNOWN FRAME RECEIVED: ${frame}`);
            }
        }
        catch (error) {
            this.rejectCondition = true;
            debug(error);
            debug(`Error while parsing to NpiFrame '${error.stack}'`);
        }
        // We send NAK only if the rejectCondition was set in the current processing
        if (!rejectCondition && this.rejectCondition) {
            // send NAK
            this.writer.sendNAK(this.recvSeq);
        }
    }
    handleDATA(frame) {
        /* Data frame receive handler */
        const frmNum = (frame.control & 0x70) >> 4;
        const reTx = (frame.control & 0x08) >> 3;
        debug(`<-- DATA (${frmNum},${frame.control & 0x07},${reTx}): ${frame}`);
        // Expected package {recvSeq}, but received {frmNum}
        // This happens when the chip sends us a reTx packet, but we are waiting for the next one
        if (this.recvSeq != frmNum) {
            if (reTx) {
                // if the reTx flag is set, then this is a packet replay
                debug(`Unexpected DATA packet sequence ${frmNum} | ${this.recvSeq}: packet replay`);
            }
            else {
                // otherwise, the sequence of packets is out of order - skip or send NAK is needed
                debug(`Unexpected DATA packet sequence ${frmNum} | ${this.recvSeq}: reject condition`);
                this.rejectCondition = true;
                return;
            }
        }
        this.rejectCondition = false;
        this.recvSeq = (frmNum + 1) & 7; // next
        debug(`--> ACK  (${this.recvSeq})`);
        this.writer.sendACK(this.recvSeq);
        const handled = this.handleACK(frame);
        if (reTx && !handled) {
            // if the package is resent and did not expect it, 
            // then will skip it - already processed it earlier
            debug(`Skipping the packet as repeated (${this.recvSeq})`);
            return;
        }
        const data = frame.buffer.subarray(1, -3);
        this.emit('received', frame_1.Frame.makeRandomizedBuffer(data));
    }
    handleACK(frame) {
        /* Handle an acknowledgement frame */
        // next number after the last accepted frame
        this.ackSeq = frame.control & 0x07;
        debug(`<-- ACK (${this.ackSeq}): ${frame}`);
        const handled = this.waitress.resolve({ sequence: this.ackSeq });
        if (!handled && this.sendSeq !== this.ackSeq) {
            // Packet confirmation received for {ackSeq}, but was expected {sendSeq}
            // This happens when the chip has not yet received of the packet {sendSeq} from us,
            // but has already sent us the next one.
            debug(`Unexpected packet sequence ${this.ackSeq} | ${this.sendSeq}`);
        }
        return handled;
    }
    handleNAK(frame) {
        /* Handle negative acknowledgment frame */
        const nakNum = frame.control & 0x07;
        debug(`<-- NAK (${nakNum}): ${frame}`);
        const handled = this.waitress.reject({ sequence: nakNum }, 'Recv NAK frame');
        if (!handled) {
            // send NAK
            debug(`NAK Unexpected packet sequence ${nakNum}`);
        }
        else {
            debug(`NAK Expected packet sequence ${nakNum}`);
        }
    }
    handleRST(frame) {
        debug(`<-- RST:  ${frame}`);
    }
    handleRSTACK(frame) {
        /* Reset acknowledgement frame receive handler */
        let code;
        this.rejectCondition = false;
        debug(`<-- RSTACK ${frame}`);
        try {
            code = NcpResetCode[frame.buffer[2]];
        }
        catch (e) {
            code = NcpResetCode.ERROR_UNKNOWN_EM3XX_ERROR;
        }
        debug(`RSTACK Version: ${frame.buffer[1]} Reason: ${code.toString()} frame: ${frame}`);
        if (NcpResetCode[code].toString() !== NcpResetCode.RESET_SOFTWARE.toString()) {
            return;
        }
        this.waitress.resolve({ sequence: -1 });
    }
    async handleError(frame) {
        debug(`<-- Error ${frame}`);
        try {
            // send reset
            await this.reset();
        }
        catch (error) {
            debug(`Failed to reset on Error Frame: ${error}`);
        }
    }
    async reset() {
        debug('Uart reseting');
        this.parser.reset();
        this.queue.clear();
        this.sendSeq = 0;
        this.recvSeq = 0;
        return this.queue.execute(async () => {
            try {
                debug(`--> Write reset`);
                const waiter = this.waitFor(-1, 10000);
                this.rejectCondition = false;
                this.writer.sendReset();
                debug(`-?- waiting reset`);
                await waiter.start().promise;
                debug(`-+- waiting reset success`);
                await (0, wait_1.default)(2000);
            }
            catch (e) {
                debug(`--> Error: ${e}`);
                this.emit('reset');
                throw new Error(`Reset error: ${e}`);
            }
        });
    }
    async close(emitClose) {
        debug('Closing UART');
        this.queue.clear();
        if (this.initialized) {
            this.initialized = false;
            if (this.portType === 'serial') {
                try {
                    await this.serialPort.asyncFlushAndClose();
                }
                catch (error) {
                    if (emitClose) {
                        this.emit('close');
                    }
                    throw error;
                }
            }
            else {
                this.socketPort.destroy();
            }
        }
        if (emitClose) {
            this.emit('close');
        }
    }
    onPortError(error) {
        debug(`Port error: ${error}`);
    }
    onPortClose(err) {
        debug(`Port closed. Error? ${err}`);
        // on error: serialport passes an Error object (in case of disconnect)
        //           net.Socket passes a boolean (in case of a transmission error)
        // try to reset instead of failing immediately
        if (err != null && err !== false) {
            this.emit('reset');
        }
        else {
            this.initialized = false;
            this.emit('close');
        }
    }
    isInitialized() {
        return this.initialized;
    }
    async sendDATA(data) {
        const seq = this.sendSeq;
        this.sendSeq = ((seq + 1) % 8); // next
        const nextSeq = this.sendSeq;
        const ackSeq = this.recvSeq;
        return this.queue.execute(async () => {
            const randData = frame_1.Frame.makeRandomizedBuffer(data);
            try {
                const waiter = this.waitFor(nextSeq);
                debug(`--> DATA (${seq},${ackSeq},0): ${data.toString('hex')}`);
                this.writer.sendData(randData, seq, 0, ackSeq);
                debug(`-?- waiting (${nextSeq})`);
                await waiter.start().promise;
                debug(`-+- waiting (${nextSeq}) success`);
            }
            catch (e1) {
                debug(`--> Error: ${e1}`);
                debug(`-!- break waiting (${nextSeq})`);
                debug(`Can't send DATA frame (${seq},${ackSeq},0): ${data.toString('hex')}`);
                try {
                    await (0, utils_1.Wait)(500);
                    const waiter = this.waitFor(nextSeq);
                    debug(`->> DATA (${seq},${ackSeq},1): ${data.toString('hex')}`);
                    this.writer.sendData(randData, seq, 1, ackSeq);
                    debug(`-?- rewaiting (${nextSeq})`);
                    await waiter.start().promise;
                    debug(`-+- rewaiting (${nextSeq}) success`);
                }
                catch (e2) {
                    debug(`--> Error: ${e2}`);
                    debug(`-!- break rewaiting (${nextSeq})`);
                    debug(`Can't resend DATA frame (${seq},${ackSeq},1): ${data.toString('hex')}`);
                    if (this.initialized) {
                        this.emit('reset');
                    }
                    throw new Error(`sendDATA error: try 1: ${e1}, try 2: ${e2}`);
                }
            }
        });
    }
    waitFor(sequence, timeout = 4000) {
        return this.waitress.waitFor({ sequence }, timeout);
    }
    waitressTimeoutFormatter(matcher, timeout) {
        return `${JSON.stringify(matcher)} after ${timeout}ms`;
    }
    waitressValidator(payload, matcher) {
        return (payload.sequence === matcher.sequence);
    }
}
exports.SerialDriver = SerialDriver;
//# sourceMappingURL=uart.js.map