var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
import { QueueComProtocol } from '@iotize/tap/protocol/core';
import { from, Observable } from 'rxjs';
import { first, map, share } from 'rxjs/operators';
import { BleConfig } from './ble-config';
import { BLEPacketBuilder } from './ble-packet-builder';
import { BLEPacketSplitter } from './ble-packet-splitter';
import { debug } from './debug';
import { BleComError } from './errors';
import { sanitizeUUID } from './util';
export var DEFAULT_BLE_OPTIONS = {
    mtu: BleConfig.maxPacketLengthWithoutOffset + 1,
    maximumBufferLength: 255,
    waitForWriteAcknowledge: true,
    preferedComServiceType: 'large-frame',
    sanitizeUUID: false
};
/**
 * Abstract class for BLE communication
 *
 * With ble communication, data is split into sub packets.
 * This class handles creation of packet chunks.
 *
 * - You must only implement the function to send one packet chunk writeLwm2mPacketChunk()
 * -
 */
var UniversalBleProtocolAdapter = /** @class */ (function (_super) {
    __extends(UniversalBleProtocolAdapter, _super);
    function UniversalBleProtocolAdapter(peripheral, bleOptions) {
        if (bleOptions === void 0) { bleOptions = {}; }
        var _this = _super.call(this) || this;
        _this.peripheral = peripheral;
        _this._useSplitter = true;
        _this.bleOptions = __assign(__assign({}, DEFAULT_BLE_OPTIONS), bleOptions);
        _this.options.connect.timeout = 8000;
        _this.options.send.timeout = 4000;
        _this.options.disconnect.timeout = 8000;
        return _this;
    }
    Object.defineProperty(UniversalBleProtocolAdapter.prototype, "lwm2mCharc", {
        get: function () {
            if (!this._lwm2mCharc) {
                throw new Error("Illegal state error, lwm2m characteristic is not set");
            }
            return this._lwm2mCharc;
        },
        enumerable: true,
        configurable: true
    });
    UniversalBleProtocolAdapter.prototype.sanitizeUUID = function (uuid) {
        return this.bleOptions.sanitizeUUID
            ? sanitizeUUID(uuid)
            : uuid;
    };
    UniversalBleProtocolAdapter.prototype._connect = function () {
        var _this = this;
        return new Observable(function (emitter) {
            (function () { return __awaiter(_this, void 0, void 0, function () {
                var _a, err_1;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            _b.trys.push([0, 3, , 4]);
                            return [4 /*yield*/, this.peripheral.connect()];
                        case 1:
                            _b.sent();
                            _a = this;
                            return [4 /*yield*/, this.setupLwm2mCharacteristic()];
                        case 2:
                            _a._lwm2mCharc = _b.sent();
                            emitter.next(null);
                            emitter.complete();
                            return [3 /*break*/, 4];
                        case 3:
                            err_1 = _b.sent();
                            emitter.error(err_1);
                            return [3 /*break*/, 4];
                        case 4: return [2 /*return*/];
                    }
                });
            }); })();
        }).pipe(share());
    };
    UniversalBleProtocolAdapter.prototype._disconnect = function () {
        this._lwm2mCharc = undefined;
        if (this.peripheral) {
            return from(this.peripheral.disconnect());
        }
        return from(Promise.resolve());
    };
    UniversalBleProtocolAdapter.prototype.setupLwm2mCharacteristic = function () {
        return __awaiter(this, void 0, void 0, function () {
            var lwm2mServiceUUIDs, serviceMap, charac;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        lwm2mServiceUUIDs = [
                            this.sanitizeUUID(BleConfig.services.lwm2m.service)
                        ];
                        if (this.bleOptions.preferedComServiceType === 'large-frame') {
                            lwm2mServiceUUIDs.push(this.sanitizeUUID(BleConfig.services.fastLwm2m.service));
                        }
                        return [4 /*yield*/, this.peripheral.discoverServices(lwm2mServiceUUIDs)];
                    case 1:
                        serviceMap = _a.sent();
                        debug('Found services ', Object.keys(serviceMap).join(', '), 'asked for services: ', lwm2mServiceUUIDs.join(', '));
                        return [4 /*yield*/, this._selectLwm2mCharacteristic(serviceMap)];
                    case 2:
                        charac = _a.sent();
                        return [4 /*yield*/, charac.enableNotifications(true)];
                    case 3:
                        _a.sent();
                        return [2 /*return*/, charac];
                }
            });
        });
    };
    UniversalBleProtocolAdapter.prototype._selectLwm2mCharacteristic = function (serviceMap) {
        return __awaiter(this, void 0, void 0, function () {
            var largeFrameServiceUUID, legacyLwm2mServiceUUID;
            return __generator(this, function (_a) {
                largeFrameServiceUUID = this.sanitizeUUID(BleConfig.services.fastLwm2m.service);
                legacyLwm2mServiceUUID = this.sanitizeUUID(BleConfig.services.lwm2m.service);
                if (this.bleOptions.preferedComServiceType === 'legacy' && legacyLwm2mServiceUUID in serviceMap) {
                    debug('Force usage of legacy lwm2m characteristic UUID: ' + legacyLwm2mServiceUUID);
                    return [2 /*return*/, this._getLegacyLwm2mCharacteristic(serviceMap[legacyLwm2mServiceUUID])];
                }
                else if (largeFrameServiceUUID in serviceMap) {
                    debug('Found fast lwm2m characteristic UUID: ' + largeFrameServiceUUID);
                    return [2 /*return*/, this._getLargeFrameLwm2mCharacteristic(serviceMap[largeFrameServiceUUID])];
                }
                else if (legacyLwm2mServiceUUID in serviceMap) {
                    debug('Found legacy lwm2m characteristic UUID: ' + legacyLwm2mServiceUUID);
                    return [2 /*return*/, this._getLegacyLwm2mCharacteristic(serviceMap[legacyLwm2mServiceUUID])];
                }
                else {
                    throw BleComError.serviceNotFound(legacyLwm2mServiceUUID);
                }
                return [2 /*return*/];
            });
        });
    };
    UniversalBleProtocolAdapter.prototype._getLargeFrameLwm2mCharacteristic = function (service) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.bleOptions.mtu = 255; // TODO read from device
                        this._useSplitter = false;
                        return [4 /*yield*/, service.getCharacteristic(this.sanitizeUUID(BleConfig.services.fastLwm2m.charac))];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    UniversalBleProtocolAdapter.prototype._getLegacyLwm2mCharacteristic = function (service) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.bleOptions.mtu = BleConfig.maxPacketLengthWithoutOffset + 1;
                        this._useSplitter = true;
                        return [4 /*yield*/, service.getCharacteristic(this.sanitizeUUID(BleConfig.services.lwm2m.charac))];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    UniversalBleProtocolAdapter.prototype.read = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                // debug('read()...');
                if (!this._readPromise) {
                    this._readPromise = this._createReadPromise();
                }
                return [2 /*return*/, this._readPromise];
            });
        });
    };
    UniversalBleProtocolAdapter.prototype.readUnit = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.lwm2mCharc.data.pipe(first(), map(function (info) { return info.data; })).toPromise()];
            });
        });
    };
    UniversalBleProtocolAdapter.prototype.write = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var chunks, chunks_1, chunks_1_1, chunk, e_1_1;
            var e_1, _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        // debug('write()...');
                        this._readPromise = this._createReadPromise();
                        if (!this.useSplitter) return [3 /*break*/, 9];
                        chunks = BLEPacketSplitter.wrapWithChecksum(data, this.chunkSize).getPackets();
                        _b.label = 1;
                    case 1:
                        _b.trys.push([1, 6, 7, 8]);
                        chunks_1 = __values(chunks), chunks_1_1 = chunks_1.next();
                        _b.label = 2;
                    case 2:
                        if (!!chunks_1_1.done) return [3 /*break*/, 5];
                        chunk = chunks_1_1.value;
                        return [4 /*yield*/, this.writeUnit(chunk)];
                    case 3:
                        _b.sent();
                        _b.label = 4;
                    case 4:
                        chunks_1_1 = chunks_1.next();
                        return [3 /*break*/, 2];
                    case 5: return [3 /*break*/, 8];
                    case 6:
                        e_1_1 = _b.sent();
                        e_1 = { error: e_1_1 };
                        return [3 /*break*/, 8];
                    case 7:
                        try {
                            if (chunks_1_1 && !chunks_1_1.done && (_a = chunks_1.return)) _a.call(chunks_1);
                        }
                        finally { if (e_1) throw e_1.error; }
                        return [7 /*endfinally*/];
                    case 8: return [3 /*break*/, 10];
                    case 9: return [2 /*return*/, this.writeUnit(data)];
                    case 10: return [2 /*return*/];
                }
            });
        });
    };
    Object.defineProperty(UniversalBleProtocolAdapter.prototype, "useSplitter", {
        get: function () {
            return this._useSplitter;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(UniversalBleProtocolAdapter.prototype, "chunkSize", {
        get: function () {
            return this.bleOptions.mtu - 1;
        },
        enumerable: true,
        configurable: true
    });
    UniversalBleProtocolAdapter.prototype.writeUnit = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (data.length > this.bleOptions.mtu) {
                            throw BleComError.writeSizeAboveMTU(data, this.bleOptions.mtu);
                        }
                        if (!this.bleOptions.waitForWriteAcknowledge) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.lwm2mCharc.write(data, true)];
                    case 1:
                        _a.sent();
                        return [3 /*break*/, 3];
                    case 2:
                        this.lwm2mCharc.write(data, true).catch(function (err) {
                            console.warn("Write error ignored", err);
                        });
                        _a.label = 3;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    UniversalBleProtocolAdapter.prototype._createReadPromise = function () {
        return __awaiter(this, void 0, void 0, function () {
            var packetBuilder, chunk;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!this.useSplitter) return [3 /*break*/, 4];
                        packetBuilder = new BLEPacketBuilder(this.bleOptions.maximumBufferLength);
                        _a.label = 1;
                    case 1:
                        if (!!packetBuilder.hasAllChunks()) return [3 /*break*/, 3];
                        return [4 /*yield*/, this.readUnit()];
                    case 2:
                        chunk = _a.sent();
                        packetBuilder.append(chunk);
                        return [3 /*break*/, 1];
                    case 3:
                        if (packetBuilder.isChecksumValid()) {
                            return [2 /*return*/, packetBuilder.getData()];
                        }
                        else {
                            throw BleComError.invalidBleChunkChecksum(packetBuilder);
                        }
                        return [3 /*break*/, 5];
                    case 4: return [2 /*return*/, this.readUnit()];
                    case 5: return [2 /*return*/];
                }
            });
        });
    };
    return UniversalBleProtocolAdapter;
}(QueueComProtocol));
export { UniversalBleProtocolAdapter };
//# sourceMappingURL=data:application/json;base64, 