"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(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 };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
require("../client/impl/frame/stream-generated");
require("../core/extensions");
var rxjs_1 = require("rxjs");
var operators_1 = require("rxjs/operators");
var api_1 = require("../client/api");
var impl_1 = require("../client/impl");
var lwm2m_command_converter_1 = require("../client/impl/converter/lwm2m-command-converter");
var default_iotize_client_1 = require("../client/impl/default-iotize-client");
var crc_1 = require("../core/error-detection/crc");
var format_helper_1 = require("../core/format/format-helper");
var logger_1 = require("../logger");
var step_operations_1 = require("../util/step-operations");
var api_config_factory_1 = require("./config/api-config-factory");
var crypto_helper_1 = require("./config/crypto-helper");
var converter_1 = require("./converter");
var scram_interceptor_1 = require("./interceptors/scram-interceptor");
var iotize_device_services_1 = require("./iotize-device-services");
var model_1 = require("./model");
var scram_1 = require("./scram");
var service_1 = require("./service");
var target_variable_1 = require("./target-variable");
var bundle_manager_1 = require("./target-variable/bundle-manager");
var logger = logger_1.default('Device');
exports.NFC_PAIRING_COMMAND = Uint8Array.from([
    0x00,
    0xA4,
    0x04,
    0x00,
    0x07,
    // DATA
    0xF0,
    0x02,
    0x4C,
    0x77,
    0x4D,
    0x32,
    0x4D,
    // --
    0x90,
    0x00,
]);
var Tap;
(function (Tap) {
    function create() {
        return new IoTizeDevice(default_iotize_client_1.DefaultIoTizeClient.create());
    }
    Tap.create = create;
    function fromProtocol(protocol) {
        var client = default_iotize_client_1.DefaultIoTizeClient.create();
        client.addComProtocol(protocol);
        return new IoTizeDevice(client);
    }
    Tap.fromProtocol = fromProtocol;
})(Tap = exports.Tap || (exports.Tap = {}));
/**
 *
 * @deprecated Use Tap instead
 */
var IoTizeDevice = /** @class */ (function () {
    function IoTizeDevice(client) {
        this._client = client;
        this._apiConfig = api_config_factory_1.ApiConfigFactory.getDefaultInstance();
        this._services = iotize_device_services_1.IoTizeDeviceService.create(this._client, this._apiConfig);
        this._lwm2m = new Lwm2mInterface(this.client, this._apiConfig);
        this._scramInterceptor = new scram_interceptor_1.ScramInterceptor(this._services.scram, this.apiConfig);
        this._client.addInterceptor(this._scramInterceptor);
        this._initCache();
        // this._converterProvider = new ConverterProvider(PathToTypeMap, DefaultConverterMap);
    }
    Object.defineProperty(IoTizeDevice.prototype, "lockOptions", {
        /**
         * Get cached lock options
         * May no be synchronized with real device state
         */
        get: function () {
            if (!this._interfaceLockOptions) {
                this._interfaceLockOptions = {
                    factoryReset: false,
                    resourceFactory: false,
                    hashPassword: false,
                    resourceLogUid: false,
                    scramActivated: false
                };
            }
            return this._interfaceLockOptions;
        },
        set: function (value) {
            this._interfaceLockOptions = value;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IoTizeDevice.prototype, "currentSessionState", {
        get: function () {
            return this._sessionState$.value;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IoTizeDevice.prototype, "sessionKey", {
        /**
         * Get current session key for encrypted communicatioin
         */
        get: function () {
            return this._scramInterceptor.sessionKey;
        },
        /**
         * Setter for the session key
         * @param key if null, it will stop encryption and remove session key. If true it will update session key used for encryption
         */
        set: function (key) {
            this._scramInterceptor.sessionKey = key;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IoTizeDevice.prototype, "client", {
        get: function () {
            return this._client;
        },
        set: function (client) {
            this._client = client;
            this._services.client = client;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IoTizeDevice.prototype, "sessionState", {
        /**
         * Listen to session state changed
         */
        get: function () {
            // if (!this.isConnected()){
            //     throw new C
            // }
            return this._sessionState$;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * @deprecated use {@link Tap.create()} instead
     *
     */
    IoTizeDevice.create = function () {
        return Tap.create();
    };
    /**
     * @deprecated
     * @param protocol
     */
    IoTizeDevice.fromProtocol = function (protocol) {
        return Tap.fromProtocol(protocol);
    };
    /**
     * Enable/Disable encrytion when communicating with a device
     * @param enable true if requests must be encrypted
     * @param resetSessionKey true if you want to reset the the session key.
     * @param refreshInitializationVector true if you want to change initialization vectors
     *
     */
    IoTizeDevice.prototype.encryption = function (enable, resetSessionKey, refreshInitializationVector) {
        if (resetSessionKey === void 0) { resetSessionKey = false; }
        if (refreshInitializationVector === void 0) { refreshInitializationVector = false; }
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._scramInterceptor.encryption(enable, resetSessionKey, refreshInitializationVector)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    IoTizeDevice.prototype.setEncryptionKeys = function (keys) {
        this._scramInterceptor.setEncryptionKeys(keys);
    };
    IoTizeDevice.prototype.setEncryptedFrameCounter = function (frameCounter) {
        this._scramInterceptor.setFrameCounter(frameCounter);
    };
    IoTizeDevice.prototype.getEncryptionOptions = function () {
        return this._scramInterceptor.options;
    };
    IoTizeDevice.prototype.refreshEncryptionInitializationVector = function () {
        return this._scramInterceptor.refreshEncryptionInitializationVector();
    };
    IoTizeDevice.prototype.setInitializationVectorRefreshPeriod = function (period) {
        return this._scramInterceptor.setInitializationVectorRefreshPeriod(period);
    };
    /**
     * Enable/Disable encrytion when communicating with a device
     * @param enable true if requests must be encrypted
     * @param resetSessionKey true if you want to reset the the session key.
     * @param refreshInitializationVector true if you want to change initialization vectors
     *
     * @deprecated use {@link encryption()} instead
     */
    IoTizeDevice.prototype.enableEncryption = function (enable, resetSessionKey, refreshInitializationVector) {
        if (resetSessionKey === void 0) { resetSessionKey = false; }
        if (refreshInitializationVector === void 0) { refreshInitializationVector = false; }
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.encryption(enable, resetSessionKey, refreshInitializationVector)];
            });
        });
    };
    Object.defineProperty(IoTizeDevice.prototype, "protocol", {
        get: function () {
            return this.client.getCurrentProtocol();
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Connect with the given communication protocol
     * TODO what if there is already a connected communication protocol
     * @param protocol
     */
    IoTizeDevice.prototype.connect = function (protocol) {
        // this._clearCache();
        if (protocol) {
            this.client.addComProtocol(protocol, "default");
        }
        return this._client.connect().toPromise();
    };
    /**
     * Disconnect device
     */
    IoTizeDevice.prototype.disconnect = function (options) {
        if (options === void 0) { options = { clearCache: true, clearSession: true }; }
        if (options.clearCache) {
            this.clearCache();
        }
        if (options.clearSession) {
            this.clearSession();
        }
        return this._client.disconnect().toPromise();
    };
    IoTizeDevice.prototype.isConnected = function () {
        if (!this._client) {
            return false;
        }
        return this._client.isConnected();
    };
    Object.defineProperty(IoTizeDevice.prototype, "variables", {
        get: function () {
            if (!this._variableManager) {
                this._variableManager = new target_variable_1.VariableManager(this);
            }
            return this._variableManager;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IoTizeDevice.prototype, "bundles", {
        get: function () {
            if (!this._bundleManager) {
                this._bundleManager = new bundle_manager_1.BundleManager(this.service.bundle, this.service.variable);
            }
            return this._bundleManager;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Setter for hashPassword option
     * @deprecated this should not be used anymore as this configuration must be read from the tap
     */
    // public set hashPassword(enabled: boolean) {
    //     if (!this.interfaceLockOptions) {
    //         this.interfaceLockOptions = {
    //             factoryReset: false,
    //             hashPassword: enabled,
    //             resourceFactory: false,
    //             resourceLogUid: false,
    //             scramActivated: false
    //         }
    //     }
    //     this.interfaceLockOptions.hashPassword = enabled;
    // }
    /**
     * Return true if password will be hashed
     * @deprecated
     */
    // public get hashPassword() {
    //     if (!this.interfaceLockOptions) {
    //         return false;
    //     }
    //     return this.interfaceLockOptions.hashPassword;
    // }
    /**
     * Tap logout
     * Reject if logout failed
     */
    IoTizeDevice.prototype.logout = function () {
        return __awaiter(this, void 0, void 0, function () {
            var response;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this._interfaceLockOptions = undefined;
                        return [4 /*yield*/, this.encryption(false, true)];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, this.service.interface.logout()];
                    case 2:
                        response = _a.sent();
                        response.successful();
                        return [4 /*yield*/, this.refreshSessionState()];
                    case 3:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Change password for the groupId (If groupId is not specified, it will be changed for the current group id)
     * @param newPassword the new password
     * @param userIdOrName default to the current group id
     * @param userPassword the current user password. if provided it will perform a login before changing password
     */
    IoTizeDevice.prototype.changePassword = function (newPassword, userId, userPassword) {
        return __awaiter(this, void 0, void 0, function () {
            var currentUserId, lockInfo, currentUsername, passwordBytes;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        currentUserId = undefined;
                        if (!!userId) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.service.interface.getCurrentGroupId()];
                    case 1:
                        userId = (_a.sent()).body();
                        currentUserId = userId;
                        _a.label = 2;
                    case 2: return [4 /*yield*/, this.getLockInfo()];
                    case 3:
                        lockInfo = _a.sent();
                        if (!userPassword) return [3 /*break*/, 8];
                        if (!(currentUserId === undefined)) return [3 /*break*/, 5];
                        return [4 /*yield*/, this.service.interface.getCurrentGroupId()];
                    case 4:
                        currentUserId = (_a.sent()).body();
                        _a.label = 5;
                    case 5: return [4 /*yield*/, this.service.group.getName(currentUserId)];
                    case 6:
                        currentUsername = (_a.sent()).body();
                        return [4 /*yield*/, this.login(currentUsername, userPassword, false)];
                    case 7:
                        _a.sent();
                        _a.label = 8;
                    case 8:
                        if (!lockInfo.scramActivated) return [3 /*break*/, 10];
                        return [4 /*yield*/, this.scramAuth.changeUserPassword(newPassword, userId)];
                    case 9:
                        _a.sent();
                        return [3 /*break*/, 14];
                    case 10:
                        if (!lockInfo.hashPassword) return [3 /*break*/, 12];
                        passwordBytes = scram_1.ScramAuth.hashPassword(newPassword);
                        return [4 /*yield*/, this.service.group.changePasswordKey(userId, passwordBytes)];
                    case 11:
                        (_a.sent()).successful();
                        return [3 /*break*/, 14];
                    case 12: return [4 /*yield*/, this.service.group.changePassword(userId, newPassword)];
                    case 13:
                        (_a.sent()).successful();
                        _a.label = 14;
                    case 14: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Upload single packets to single packet store (one by one)
     * Unsubsribe from observable to cancel this operation
     *
     * @warning this is an experimental function. It may be modified in future releases
     * @experimental
     *
     * TODO use dependency injection instead
     */
    IoTizeDevice.prototype.loadSinglePacketInStore = function (packets) {
        var _this = this;
        var operations = packets.map(function (packet) {
            return function (observer, index) { return __awaiter(_this, void 0, void 0, function () {
                var result;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            logger.debug("sendSinglePacket", "sending packet " + (index + 1) + "/" + packets.length, packet);
                            return [4 /*yield*/, this.service.singlePacket.writePartialSinglePacket(packet)];
                        case 1:
                            result = _a.sent();
                            result.successful();
                            observer.next({
                                total: packets.length,
                                current: index + 1,
                                done: false
                            });
                            logger.debug("sendSinglePacket", "Packet " + (index + 1) + "/" + packets.length + " SENT!");
                            return [2 /*return*/];
                    }
                });
            }); };
        });
        return step_operations_1.StepOperations.sequential(operations).asObservable();
    };
    /**
     * Send a single packet to the tap and execute
     *
     * @warning this is an experimental function. It may be modified in future releases
     * @experimental
     *
     * TODO maybe move to extension ?
     */
    IoTizeDevice.prototype.sendSinglePacket = function (packetOrModel) {
        var _this = this;
        try {
            var packet_1;
            if (!(packetOrModel instanceof Uint8Array)) {
                var converter = new converter_1.SinglePacketConverter();
                packetOrModel = api_1.SinglePacket.fillComputedField(packetOrModel);
                packet_1 = converter.encode(packetOrModel);
            }
            else {
                packet_1 = packetOrModel;
            }
            if (packet_1.length > api_1.SinglePacket.MAX_PART_SIZE) {
                var packetBuilder = new api_1.SinglePacket.Splitter(api_1.SinglePacket.MAX_PART_SIZE);
                var packets_1 = packetBuilder.chunk(packet_1);
                return this.loadSinglePacketInStore(packets_1)
                    .pipe(operators_1.concat(rxjs_1.Observable.create(function (observer) { return __awaiter(_this, void 0, void 0, function () {
                    var expectedCrc, err_1;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                _a.trys.push([0, 2, , 3]);
                                expectedCrc = crc_1.CRC.fromBytes(packet_1);
                                return [4 /*yield*/, this.service.singlePacket.bspe(expectedCrc)];
                            case 1:
                                (_a.sent()).successful();
                                observer.next({
                                    total: packets_1.length,
                                    current: packets_1.length,
                                    done: true,
                                    crc: expectedCrc
                                });
                                observer.complete();
                                return [3 /*break*/, 3];
                            case 2:
                                err_1 = _a.sent();
                                observer.error(err_1);
                                return [3 /*break*/, 3];
                            case 3: return [2 /*return*/];
                        }
                    });
                }); })));
            }
            else {
                return rxjs_1.Observable.create(function (observer) { return __awaiter(_this, void 0, void 0, function () {
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0: return [4 /*yield*/, this.service.singlePacket.writeSmallSinglePacket(packet_1)];
                            case 1:
                                (_a.sent()).successful();
                                observer.next({
                                    total: 1,
                                    current: 1,
                                    done: true
                                });
                                observer.complete();
                                return [2 /*return*/];
                        }
                    });
                }); });
            }
        }
        catch (error) {
            return rxjs_1.throwError(error);
        }
    };
    /**
     * Configure current tap instance thanks to a TapConfigurator
     * @param configurator
     */
    IoTizeDevice.prototype.configure = function (configurator) {
        return configurator.configure(this).toPromise();
    };
    /**
     *
     * @param protocol
     */
    IoTizeDevice.prototype.useComProtocol = function (protocol) {
        this.client.useComProtocol(protocol);
        return this;
    };
    /**
     * Tap login
     *
     */
    IoTizeDevice.prototype.login = function (username, password, refreshSessionState) {
        if (refreshSessionState === void 0) { refreshSessionState = true; }
        return __awaiter(this, void 0, void 0, function () {
            var lockInfos, auth, loginParms, response;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!this._isLoggedIn()) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.logout()];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2:
                        logger.debug("Login with username " + username + "...");
                        return [4 /*yield*/, this.getLockInfo()];
                    case 3:
                        lockInfos = _a.sent();
                        logger.debug("Lock infos:", lockInfos);
                        if (!lockInfos.scramActivated) return [3 /*break*/, 6];
                        logger.debug("Using scram login");
                        auth = this.scramAuth;
                        loginParms = {
                            username: username,
                            password: password
                        };
                        return [4 /*yield*/, auth.login(loginParms)];
                    case 4:
                        _a.sent();
                        loginParms.password = '';
                        logger.debug("Scram login successful!");
                        this.sessionKey = auth.getSessionKey();
                        return [4 /*yield*/, this.enableEncryption(true, false)];
                    case 5:
                        _a.sent();
                        return [3 /*break*/, 11];
                    case 6:
                        response = void 0;
                        if (!lockInfos.hashPassword) return [3 /*break*/, 8];
                        logger.debug("Using hash password login");
                        return [4 /*yield*/, this.service.interface.loginWithHash({
                                username: username,
                                password: format_helper_1.FormatHelper.hexStringToBuffer(crypto_helper_1.CryptoHelper.passwordHasher.hash(password))
                            })];
                    case 7:
                        response = _a.sent();
                        return [3 /*break*/, 10];
                    case 8:
                        logger.debug("Using regular login");
                        return [4 /*yield*/, this.service.interface.login({
                                username: username,
                                password: password
                            })];
                    case 9:
                        response = _a.sent();
                        _a.label = 10;
                    case 10:
                        response.successful();
                        _a.label = 11;
                    case 11:
                        if (!this.currentSessionState) {
                            this._sessionState$.next(IoTizeDevice.INITIAL_SESSION_STATE);
                        }
                        this.currentSessionState.startTime = new Date();
                        if (!refreshSessionState) return [3 /*break*/, 13];
                        return [4 /*yield*/, this.refreshSessionState()];
                    case 12:
                        _a.sent();
                        _a.label = 13;
                    case 13: return [2 /*return*/, true];
                }
            });
        });
    };
    IoTizeDevice.prototype._isLoggedIn = function () {
        return (this.currentSessionState != undefined && this.currentSessionState.name !== IoTizeDevice.INITIAL_SESSION_STATE.name);
    };
    /**
     *
     * @param commands run mutiple requests in one
     * @param expectedCodeRet
     */
    IoTizeDevice.prototype.multiRequests = function (commands, expectedCodeRet) {
        if (expectedCodeRet === void 0) { expectedCodeRet = model_1.MultiRequest.ExpectedResultCode.ANYTHING; }
        return __awaiter(this, void 0, void 0, function () {
            var decoders, multiRequestData, response, body, responses;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        decoders = [];
                        multiRequestData = {
                            requests: commands.map(function (call) {
                                var _a = service_1.AbstractService.callToCommandArgs(call, _this.apiConfig), cmd = _a[0], bodyDecoder = _a[1];
                                decoders.push(bodyDecoder);
                                var request = {
                                    header: {
                                        methodType: cmd.getMethod(),
                                        path: cmd.getHeader().path
                                    },
                                    payload: cmd.getData()
                                };
                                return {
                                    expectedCodeRet: expectedCodeRet,
                                    request: request,
                                    requestLen: request.payload.length + lwm2m_command_converter_1.IotizeLWM2MCommandConverter.HEADER_LENGTH
                                };
                            })
                        };
                        return [4 /*yield*/, this.service.interface.multiRequest(multiRequestData)];
                    case 1:
                        response = _a.sent();
                        body = response.body();
                        responses = body.responses
                            .map(function (responseItem, index) {
                            var response = impl_1.ResponseImpl.create(responseItem.response.codeRet, responseItem.response.data);
                            var decoder = decoders[index];
                            if (decoder) {
                                response.setBodyDecoder(decoder);
                            }
                            return response;
                        });
                        return [2 /*return*/, responses];
                }
            });
        });
    };
    /**
     * Send an NFC pairing request
     */
    IoTizeDevice.prototype.nfcPairing = function () {
        return __awaiter(this, void 0, void 0, function () {
            var response;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.client.send(exports.NFC_PAIRING_COMMAND).toPromise()];
                    case 1:
                        response = _a.sent();
                        response.successful();
                        return [2 /*return*/, response];
                }
            });
        });
    };
    Object.defineProperty(IoTizeDevice.prototype, "scramAuth", {
        get: function () {
            if (!this._scramAuth) {
                this._scramAuth = new scram_1.ScramAuth(this);
            }
            return this._scramAuth;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IoTizeDevice.prototype, "rooter", {
        get: function () {
            return this._apiConfig.routes;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IoTizeDevice.prototype, "apiConfig", {
        get: function () {
            return this._apiConfig;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IoTizeDevice.prototype, "service", {
        get: function () {
            return this._services;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IoTizeDevice.prototype, "lwm2m", {
        /**
         * @experimental
         */
        get: function () {
            return this._lwm2m;
        },
        enumerable: true,
        configurable: true
    });
    // /**
    //  * @deprecated use lwm2m object instead ? 
    //  */
    // public lwm2mCall(...calls: ServiceCallType[]) {
    //     if (calls.length > 1) {
    //         throw new Error("Multiple calls are not implemented yet");
    //     }
    //     let args = AbstractService.callToCommandArgs(calls[0], this.apiConfig);
    //     var response = this.client.command<string>(args[0], args[1]).toPromise();
    //     return response;
    // }
    /**
     * Initialize device cache
     */
    IoTizeDevice.prototype._initCache = function () {
        if (!this._sessionState$) {
            this._sessionState$ = new rxjs_1.BehaviorSubject(IoTizeDevice.INITIAL_SESSION_STATE);
        }
        this.clearCache();
        this.clearSession();
    };
    /**
     * Clear cache
     */
    IoTizeDevice.prototype.clearCache = function () {
        this._interfaceLockOptions = undefined;
        this._scramInterceptor.ivSupported = true;
    };
    /**
     * Clear session encryption keys
     */
    IoTizeDevice.prototype.clearSession = function () {
        this.sessionKey = undefined;
    };
    /**
     * Read session state from the device
     * This will perform a few tap requests
     *
     * TODO we should invalidate encryption key if session state changed
     * TODO we should use multi commands to improve performance
     */
    IoTizeDevice.prototype.refreshSessionState = function () {
        return __awaiter(this, void 0, void 0, function () {
            var groupId, currentSessionState, _a, _b;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        logger.debug('[TAP]', "Refreshing session state (current=" + this.currentSessionState.name + ")...");
                        return [4 /*yield*/, this.service.interface.getCurrentGroupId()];
                    case 1:
                        groupId = (_c.sent()).body();
                        if (!(groupId != this.currentSessionState.groupId)) return [3 /*break*/, 4];
                        currentSessionState = this.currentSessionState;
                        currentSessionState.groupId = groupId;
                        _a = currentSessionState;
                        return [4 /*yield*/, this.service.group.getName(groupId)];
                    case 2:
                        _a.name = (_c.sent()).body();
                        _b = currentSessionState;
                        return [4 /*yield*/, this.service.group.getSessionLifetime(groupId)];
                    case 3:
                        _b.lifeTime = (_c.sent()).body();
                        logger.debug('[TAP]', "Notifying new session state: " + currentSessionState.name);
                        this._sessionState$.next(currentSessionState);
                        return [3 /*break*/, 5];
                    case 4:
                        logger.debug('[TAP]', "Session state did not changed: " + this.currentSessionState.name + " (id=" + groupId + ")");
                        _c.label = 5;
                    case 5: return [2 /*return*/, this.currentSessionState];
                }
            });
        });
    };
    /**
     * Get lock info
     */
    IoTizeDevice.prototype.getLockInfo = function () {
        return __awaiter(this, void 0, void 0, function () {
            var response;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!!this._interfaceLockOptions) return [3 /*break*/, 2];
                        logger.debug("Reading interface lock options from device...");
                        return [4 /*yield*/, this.service.interface.getLock()];
                    case 1:
                        response = _a.sent();
                        this._interfaceLockOptions = response.body();
                        _a.label = 2;
                    case 2: return [2 /*return*/, this._interfaceLockOptions];
                }
            });
        });
    };
    IoTizeDevice.prototype.getSecurityOptions = function () {
        return __awaiter(this, void 0, void 0, function () {
            var options, securityOptions;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this._interfaceLockOptions = undefined;
                        return [4 /*yield*/, this.getLockInfo()];
                    case 1:
                        options = _a.sent();
                        securityOptions = {
                            disableFactoryResetByResource: options.resourceFactory,
                            disableLoginWithUID: options.resourceLogUid,
                            disableFactoryResetByHardware: options.factoryReset,
                            scramActivated: options.scramActivated,
                            hashPassword: options.hashPassword
                        };
                        return [2 /*return*/, securityOptions];
                }
            });
        });
    };
    IoTizeDevice.TAG = "Tap";
    IoTizeDevice.INITIAL_SESSION_STATE = {
        groupId: 0,
        lifeTime: -1,
        name: "anonymous",
        startTime: undefined
    };
    return IoTizeDevice;
}());
exports.IoTizeDevice = IoTizeDevice;
var Lwm2mInterface = /** @class */ (function () {
    function Lwm2mInterface(client, apiConfig) {
        this.client = client;
        this.apiConfig = apiConfig;
    }
    Lwm2mInterface.prototype.get = function (path, body) {
        return this.call({
            path: path,
            methodType: 'GET',
            body: body
        });
    };
    Lwm2mInterface.prototype.put = function (path, body) {
        return this.call({
            path: path,
            methodType: 'PUT',
            body: body
        });
    };
    Lwm2mInterface.prototype.post = function (path, body) {
        return this.call({
            path: path,
            methodType: 'POST',
            body: body
        });
    };
    Lwm2mInterface.prototype.call = function (call) {
        var _a = service_1.AbstractService.callToCommandArgs(call, this.apiConfig), request = _a[0], bodyDecoder = _a[1];
        var response = this.client.command(request, bodyDecoder).toPromise();
        return response;
    };
    return Lwm2mInterface;
}());
exports.Lwm2mInterface = Lwm2mInterface;
