"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AshParser = void 0;
/* istanbul ignore file */
const debug_1 = __importDefault(require("debug"));
const stream_1 = require("stream");
const enums_1 = require("./enums");
const debug = (0, debug_1.default)('zigbee-herdsman:adapter:ember:uart:ash:parser');
class AshParser extends stream_1.Transform {
    buffer;
    constructor(opts) {
        super(opts);
        this.buffer = Buffer.alloc(0);
    }
    _transform(chunk, encoding, cb) {
        let data = Buffer.concat([this.buffer, chunk]);
        let position;
        while ((position = data.indexOf(enums_1.AshReservedByte.FLAG)) !== -1) {
            // emit the frame via 'data' event
            const frame = data.subarray(0, position + 1);
            setImmediate(() => {
                debug(`<<<< [FRAME raw=${frame.toString('hex')}]`);
                this.push(frame);
            });
            // remove the frame from internal buffer (set below)
            data = data.subarray(position + 1);
        }
        this.buffer = data;
        cb();
    }
    _flush(cb) {
        this.push(this.buffer);
        this.buffer = Buffer.alloc(0);
        cb();
    }
}
exports.AshParser = AshParser;
//# sourceMappingURL=parser.js.map