├── src ├── constant │ ├── LogType.ts │ ├── ActionType.ts │ ├── PassageModeType.ts │ ├── LockedStatus.ts │ ├── OperationType.ts │ ├── DateConstant.ts │ ├── PassageModeOperate.ts │ ├── AudioManage.ts │ ├── ConfigRemoteUnlock.ts │ ├── AutoLockOperate.ts │ ├── CyclicOpType.ts │ ├── ControlAction.ts │ ├── KeyboardPwdType.ts │ ├── ICOperate.ts │ ├── PwdOperateType.ts │ ├── DeviceInfoEnum.ts │ ├── CommandResponse.ts │ ├── index.ts │ ├── LogOperateCategory.ts │ ├── CallbackOperationType.ts │ ├── FeatureValue.ts │ ├── LogOperateNames.ts │ ├── LogOperate.ts │ ├── CommandType.ts │ ├── Lock.ts │ └── APICommand.ts ├── device │ ├── AdminType.ts │ ├── PrivateDataType.ts │ ├── DeviceInfoType.ts │ └── TTDevice.ts ├── util │ ├── digitUtil.ts │ ├── timingUtil.ts │ ├── timeUtil.ts │ ├── jsonUtil.ts │ ├── dscrc_table.ts │ ├── CodecUtils.ts │ └── AESUtil.ts ├── api │ ├── Commands │ │ ├── InitCommand.ts │ │ ├── ResetLockCommand.ts │ │ ├── ControlLampCommand.ts │ │ ├── OperateFinishedCommand.ts │ │ ├── GetSwitchStateCommand.ts │ │ ├── UnknownCommand.ts │ │ ├── CalibrationTimeCommand.ts │ │ ├── CheckRandomCommand.ts │ │ ├── SearchBicycleStatusCommand.ts │ │ ├── ReadDeviceInfoCommand.ts │ │ ├── AESKeyCommand.ts │ │ ├── GetAdminCodeCommand.ts │ │ ├── CheckAdminCommand.ts │ │ ├── SetAdminKeyboardPwdCommand.ts │ │ ├── ScreenPasscodeManageCommand.ts │ │ ├── CheckUserTimeCommand.ts │ │ ├── AudioManageCommand.ts │ │ ├── AddAdminCommand.ts │ │ ├── AutoLockManageCommand.ts │ │ ├── ControlRemoteUnlockCommand.ts │ │ ├── index.ts │ │ ├── LockCommand.ts │ │ ├── UnlockCommand.ts │ │ ├── InitPasswordsCommand.ts │ │ ├── DeviceFeaturesCommand.ts │ │ ├── PassageModeCommand.ts │ │ ├── GetKeyboardPasswordsCommand.ts │ │ ├── CyclicDateCommand.ts │ │ ├── ManageFRCommand.ts │ │ ├── ManageKeyboardPasswordCommand.ts │ │ └── ManageICCommand.ts │ ├── Command.ts │ ├── commandBuilder.ts │ └── ValidityInfo.ts ├── index.ts ├── store │ └── TTLockData.ts ├── scanner │ ├── ScannerInterface.ts │ ├── noble │ │ ├── NobleScannerWebsocket.ts │ │ ├── NobleDescriptor.ts │ │ ├── NobleService.ts │ │ ├── NobleCharacteristic.ts │ │ ├── NobleScanner.ts │ │ └── NobleDevice.ts │ ├── DeviceInterface.ts │ └── BluetoothLeService.ts └── TTLockClient.ts ├── tslint.json ├── examples ├── common │ ├── loadData.js │ ├── saveData.js │ └── options.js ├── clearFR.js ├── clearICCards.js ├── clearPassCodes.js ├── clearPassageMode.js ├── setRemoteUnlock.js ├── deletePassCode.js ├── getICCards.js ├── getFR.js ├── getPassCodes.js ├── addPassCode.js ├── getPassageMode.js ├── setAutoLock.js ├── updatePassCode.js ├── unlock.js ├── deleteLockSound.js ├── reset.js ├── init.js ├── setPassageMode.js ├── deletePassageMode.js ├── addICCard.js ├── addICCardBatch.js ├── lock.js ├── status.js ├── getOperations.js ├── addFR.js └── listen.js ├── docs └── Bad CRC quest.md ├── .gitignore ├── tools ├── dumpCapture.js └── debug.js ├── package.json └── tsconfig.json /src/constant/LogType.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export enum LogType { 4 | ALL = 11, 5 | NEW = 12, 6 | } -------------------------------------------------------------------------------- /src/constant/ActionType.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export enum ActionType { 4 | GET = 1, 5 | SET = 2, 6 | } -------------------------------------------------------------------------------- /src/constant/PassageModeType.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export enum PassageModeType { 4 | WEEKLY = 1, 5 | MONTHLY = 2 6 | } -------------------------------------------------------------------------------- /src/device/AdminType.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export type AdminType = { 4 | adminPs: number; 5 | unlockKey: number; 6 | } -------------------------------------------------------------------------------- /src/constant/LockedStatus.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export enum LockedStatus { 4 | UNKNOWN = -1, 5 | LOCKED = 0, 6 | UNLOCKED = 1 7 | } -------------------------------------------------------------------------------- /src/constant/OperationType.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export enum OperationType { 4 | //Inquire 5 | GET_STATE = 1, 6 | //modify 7 | MODIFY = 2, 8 | } -------------------------------------------------------------------------------- /src/constant/DateConstant.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export enum DateConstant { 4 | START_DATE_TIME = '200001010000', 5 | END_DATE_TIME = '209912012359', 6 | } -------------------------------------------------------------------------------- /src/constant/PassageModeOperate.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export enum PassageModeOperate { 4 | QUERY = 1, 5 | ADD = 2, 6 | DELETE = 3, 7 | CLEAR = 4, 8 | } -------------------------------------------------------------------------------- /src/constant/AudioManage.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export enum AudioManage { 4 | QUERY = 1, 5 | MODIFY = 2, 6 | TURN_ON = 1, 7 | TURN_OFF = 0, 8 | UNKNOWN = -1 9 | } -------------------------------------------------------------------------------- /src/constant/ConfigRemoteUnlock.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export enum ConfigRemoteUnlock { 4 | OP_TYPE_SEARCH = 1, 5 | OP_TYPE_MODIFY = 2, 6 | OP_CLOSE = 0, 7 | OP_OPEN = 1, 8 | } -------------------------------------------------------------------------------- /src/util/digitUtil.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export function padHexString(s: string): string { 4 | if (s.length % 2 != 0) { 5 | return "0" + s; 6 | } else { 7 | return s; 8 | } 9 | } -------------------------------------------------------------------------------- /src/constant/AutoLockOperate.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export enum AutoLockOperate { 4 | /** 5 | * Query blocking time 6 | */ 7 | SEARCH = 0x01, 8 | /** 9 | * Modify the blocking time 10 | */ 11 | MODIFY = 0x02, 12 | } -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "defaultSeverity": "error", 3 | "extends": [ 4 | "tslint:recommended" 5 | ], 6 | "jsRules": {}, 7 | "rules": { 8 | "no-console": false 9 | }, 10 | "rulesDirectory": [] 11 | } -------------------------------------------------------------------------------- /src/util/timingUtil.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Sleep for 5 | * @param ms miliseconds 6 | */ 7 | export function sleep(ms: number): Promise { 8 | return new Promise((resolve) => { 9 | setTimeout(resolve, ms) 10 | }); 11 | } -------------------------------------------------------------------------------- /src/constant/CyclicOpType.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export enum CyclicOpType { 4 | CYCLIC_TYPE_WEEK = 1, 5 | CYCLIC_TYPE_DAY = 2, 6 | CYCLIC_MONTH_DAY = 3, 7 | 8 | QUERY = 1, 9 | ADD = 2, 10 | REMOVE = 3, 11 | CLEAR = 4, 12 | 13 | USER_TYPE_FR = 1, 14 | USER_TYPE_IC = 2, 15 | } -------------------------------------------------------------------------------- /src/util/timeUtil.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export function dateTimeToBuffer(dateTime: string): Buffer { 4 | const result = Buffer.alloc(dateTime.length/2); 5 | for (let i = 0; i < result.length; i++) { 6 | result[i] = parseInt(dateTime.substring(i * 2, i * 2 + 2)); 7 | } 8 | return result; 9 | } -------------------------------------------------------------------------------- /src/device/PrivateDataType.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { CodeSecret } from "../api/Commands/InitPasswordsCommand"; 4 | import { AdminType } from "./AdminType"; 5 | 6 | export type PrivateDataType = { 7 | aesKey?: Buffer; 8 | admin?: AdminType; 9 | adminPasscode?: string; 10 | pwdInfo?: CodeSecret[]; 11 | } -------------------------------------------------------------------------------- /src/constant/ControlAction.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export enum ControlAction { 4 | UNLOCK = 3, 5 | LOCK = 3 << 1, 6 | /** 7 | * Volume gate 8 | */ 9 | ROLLING_GATE_UP = 1, 10 | ROLLING_GATE_DOWN = 1 << 1, 11 | ROLLING_GATE_PAUSE = 1 << 2, 12 | ROLLING_GATE_LOCK = 1 << 3, 13 | /** 14 | * 15 | */ 16 | HOLD = 3 << 3, 17 | } -------------------------------------------------------------------------------- /src/constant/KeyboardPwdType.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export enum KeyboardPwdType { 4 | /** 5 | * Unlimited 6 | */ 7 | PWD_TYPE_PERMANENT = 1, 8 | 9 | /** 10 | * Limited times 11 | */ 12 | PWD_TYPE_COUNT = 2, 13 | 14 | /** 15 | * Limited time 16 | */ 17 | PWD_TYPE_PERIOD = 3, 18 | 19 | /** 20 | * Loop 21 | */ 22 | PWD_TYPE_CIRCLE = 4, 23 | } -------------------------------------------------------------------------------- /examples/common/loadData.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const fs = require('fs/promises'); 3 | 4 | module.exports = async (settingsFile) => { 5 | let lockData = []; 6 | try { 7 | await fs.access(settingsFile); 8 | const lockDataTxt = (await fs.readFile(settingsFile)).toString(); 9 | lockData = JSON.parse(lockDataTxt); 10 | } catch (error) { 11 | console.error(error); 12 | } 13 | return lockData; 14 | } -------------------------------------------------------------------------------- /src/constant/ICOperate.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export enum ICOperate { 4 | IC_SEARCH = 1, 5 | FR_SEARCH = 6, 6 | ADD = 2, 7 | DELETE = 3, 8 | CLEAR = 4, 9 | MODIFY = 5, 10 | 11 | /** 12 | * Fingerprint template data package 13 | */ 14 | WRITE_FR = 7, 15 | 16 | STATUS_ADD_SUCCESS = 0x01, 17 | STATUS_ENTER_ADD_MODE = 0x02, 18 | STATUS_FR_PROGRESS = 0x03, 19 | STATUS_FR_RECEIVE_TEMPLATE = 0x04, 20 | } -------------------------------------------------------------------------------- /src/api/Commands/InitCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { CommandType } from "../../constant/CommandType"; 4 | import { Command } from "../Command"; 5 | 6 | export class InitCommand extends Command { 7 | static COMMAND_TYPE: CommandType = CommandType.COMM_INITIALIZATION; 8 | 9 | protected processData(): void { 10 | // nothing to do 11 | } 12 | 13 | build(): Buffer { 14 | return Buffer.from([]); 15 | } 16 | 17 | } -------------------------------------------------------------------------------- /src/api/Commands/ResetLockCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { CommandType } from "../../constant/CommandType"; 4 | import { Command } from "../Command"; 5 | 6 | export class ResetLockCommand extends Command { 7 | static COMMAND_TYPE: CommandType = CommandType.COMM_RESET_LOCK; 8 | 9 | protected processData(): void { 10 | // nothing to do here 11 | } 12 | 13 | build(): Buffer { 14 | return Buffer.from([]); 15 | } 16 | } -------------------------------------------------------------------------------- /src/api/Commands/ControlLampCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { CommandType } from "../../constant/CommandType"; 4 | import { Command} from "../Command"; 5 | 6 | export class ControlLampCommand extends Command { 7 | static COMMAND_TYPE: CommandType = CommandType.COMM_LAMP; 8 | 9 | protected processData(): void { 10 | throw new Error("Method not implemented."); 11 | } 12 | build(): Buffer { 13 | throw new Error("Method not implemented."); 14 | } 15 | 16 | } -------------------------------------------------------------------------------- /src/api/Commands/OperateFinishedCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { CommandType } from "../../constant/CommandType"; 4 | import { Command } from "../Command"; 5 | 6 | export class OperateFinishedCommand extends Command { 7 | static COMMAND_TYPE: CommandType = CommandType.COMM_GET_ALARM_ERRCORD_OR_OPERATION_FINISHED; 8 | 9 | protected processData(): void { 10 | // nothing to do 11 | } 12 | 13 | build(): Buffer { 14 | return Buffer.from([]); 15 | } 16 | 17 | } -------------------------------------------------------------------------------- /examples/common/saveData.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const fs = require('fs/promises'); 3 | 4 | module.exports = async (settingsFile, lockData) => { 5 | try { 6 | let lockDataTxt = JSON.stringify(lockData); 7 | // console.log(); 8 | // console.log(lockDataTxt); 9 | // console.log(); 10 | await fs.writeFile(settingsFile, lockDataTxt); 11 | } catch (error) { 12 | console.error("Error saving lock data file", error); 13 | return false; 14 | } 15 | return true; 16 | } -------------------------------------------------------------------------------- /src/api/Commands/GetSwitchStateCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { CommandType } from "../../constant/CommandType"; 4 | import { Command } from "../Command"; 5 | 6 | export class GetSwitchStateCommand extends Command { 7 | static COMMAND_TYPE: CommandType = CommandType.COMM_SWITCH; 8 | 9 | protected processData(): void { 10 | throw new Error("Method not implemented."); 11 | } 12 | 13 | build(): Buffer { 14 | throw new Error("Method not implemented."); 15 | } 16 | 17 | } -------------------------------------------------------------------------------- /src/api/Commands/UnknownCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { Command } from "../Command"; 4 | 5 | export class UnknownCommand extends Command { 6 | 7 | protected processData(): void { 8 | if (this.commandData) { 9 | console.error("Unknown command type 0x" + this.commandData.readInt8().toString(16), "succes", this.commandResponse, "data", this.commandData.toString("hex")); 10 | } 11 | } 12 | 13 | build(): Buffer { 14 | throw new Error("Method not implemented."); 15 | } 16 | } -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | process.env.NOBLE_REPORT_ALL_HCI_EVENTS = "1"; 4 | 5 | export { TTLockClient } from "./TTLockClient"; 6 | export { TTLock } from "./device/TTLock"; 7 | export { TTLockData } from "./store/TTLockData"; 8 | export { ValidityInfo } from "./api/ValidityInfo"; 9 | export { PassageModeData, KeyboardPassCode, ICCard } from "./api/Commands"; 10 | export * from "./constant"; 11 | 12 | 13 | // extra stuff used in testing 14 | export * from "./api/Commands"; 15 | export { CommandEnvelope } from "./api/CommandEnvelope"; 16 | export * from "./util/timingUtil"; -------------------------------------------------------------------------------- /src/constant/PwdOperateType.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export enum PwdOperateType { 4 | /** 5 | * Clear keyboard password 6 | */ 7 | PWD_OPERATE_TYPE_CLEAR = 1, 8 | 9 | /** 10 | * Add keyboard password 11 | */ 12 | PWD_OPERATE_TYPE_ADD = 2, 13 | 14 | /** 15 | * Delete a single keyboard password 16 | */ 17 | PWD_OPERATE_TYPE_REMOVE_ONE = 3, 18 | 19 | /** 20 | * Change the keyboard password (the old one is 4, no longer used) 21 | */ 22 | PWD_OPERATE_TYPE_MODIFY = 5, 23 | 24 | /** 25 | * Recovery password 26 | */ 27 | PWD_OPERATE_TYPE_RECOVERY = 6, 28 | } -------------------------------------------------------------------------------- /src/api/Commands/CalibrationTimeCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { CommandType } from "../../constant/CommandType"; 4 | import { Command } from "../Command"; 5 | import moment from "moment"; 6 | import { dateTimeToBuffer } from "../../util/timeUtil"; 7 | 8 | export class CalibrationTimeCommand extends Command { 9 | static COMMAND_TYPE: CommandType = CommandType.COMM_TIME_CALIBRATE; 10 | private time?: string; 11 | 12 | protected processData(): void { 13 | // nothing to do here 14 | } 15 | 16 | build(): Buffer { 17 | if (typeof this.time == "undefined") { 18 | this.time = moment().format("YYMMDDHHmmss"); 19 | } 20 | return dateTimeToBuffer(this.time); 21 | } 22 | 23 | } -------------------------------------------------------------------------------- /src/api/Commands/CheckRandomCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { CommandType } from "../../constant/CommandType"; 4 | import { Command } from "../Command"; 5 | 6 | export class CheckRandomCommand extends Command { 7 | static COMMAND_TYPE: CommandType = CommandType.COMM_CHECK_RANDOM; 8 | 9 | private sum?: number; 10 | 11 | protected processData(): void { 12 | // nothing to do here 13 | } 14 | 15 | build(): Buffer { 16 | if (this.sum) { 17 | const data = Buffer.alloc(4); 18 | data.writeUInt32BE(this.sum); 19 | return data; 20 | } 21 | return Buffer.from([]); 22 | } 23 | 24 | setSum(psFromLock:number, unlockKey: number) { 25 | this.sum = psFromLock + unlockKey; 26 | } 27 | } -------------------------------------------------------------------------------- /src/util/jsonUtil.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Recursively converts all buffers to hex string in an object 5 | * @param json Object to convert Buffers to string 6 | */ 7 | export function stringifyBuffers(json: Object): Object { 8 | if((json instanceof Set) || (json instanceof Map)) { 9 | return json; 10 | } 11 | Object.getOwnPropertyNames(json).forEach((key) => { 12 | const val = Reflect.get(json, key); 13 | if (typeof val == "object" && val instanceof Buffer) { 14 | Reflect.set(json, key, val.toString('hex')); 15 | } else if (typeof val == "object") { 16 | Reflect.set(json, key, stringifyBuffers(val)); 17 | } else { 18 | // Reflect.set(json, key, val); 19 | } 20 | }); 21 | return json; 22 | } -------------------------------------------------------------------------------- /src/api/Commands/SearchBicycleStatusCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { CommandType } from "../../constant/CommandType"; 4 | import { Command } from "../Command"; 5 | 6 | export class SearchBicycleStatusCommand extends Command { 7 | static COMMAND_TYPE: CommandType = CommandType.COMM_SEARCH_BICYCLE_STATUS; 8 | 9 | private lockStatus?: number; 10 | 11 | protected processData(): void { 12 | if (this.commandData && this.commandData.length >= 2) { 13 | this.lockStatus = this.commandData.readInt8(1); 14 | } 15 | } 16 | 17 | build(): Buffer { 18 | return Buffer.from("SCIENER"); 19 | } 20 | 21 | getLockStatus(): number { 22 | if (typeof this.lockStatus != "undefined") { 23 | return this.lockStatus; 24 | } else { 25 | return -1; 26 | } 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /examples/common/options.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = (lockData) => { 4 | let options = { 5 | lockData: lockData, 6 | scannerType: "noble", 7 | scannerOptions: { 8 | websocketHost: "127.0.0.1", 9 | websocketPort: 2846 10 | }, 11 | // uuids: [] 12 | }; 13 | 14 | if (process.env.WEBSOCKET_ENABLE == "1") { 15 | options.scannerType = "noble-websocket"; 16 | if (process.env.WEBSOCKET_HOST) { 17 | options.scannerOptions.websocketHost = process.env.WEBSOCKET_HOST; 18 | } 19 | if (process.env.WEBSOCKET_PORT) { 20 | options.scannerOptions.websocketPort = process.env.WEBSOCKET_PORT; 21 | } 22 | if (process.env.WEBSOCKET_KEY) { 23 | options.scannerOptions.websocketAesKey = process.env.WEBSOCKET_KEY; 24 | } 25 | } 26 | 27 | return options; 28 | } -------------------------------------------------------------------------------- /src/store/TTLockData.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { LogEntry } from "../api/Commands"; 4 | import { CodeSecret } from "../api/Commands/InitPasswordsCommand"; 5 | import { AdminType } from "../device/AdminType"; 6 | 7 | export interface TTLockPrivateData { 8 | aesKey?: string; 9 | admin?: AdminType; 10 | adminPasscode?: string; 11 | pwdInfo?: CodeSecret[]; 12 | } 13 | 14 | export interface TTLockData { 15 | /** MAC address */ 16 | address: string; 17 | /** Battery level */ 18 | battery: number; 19 | /** Signal */ 20 | rssi: number; 21 | /** Auto lock time in seconds */ 22 | autoLockTime: number; 23 | /** -1 unknown, 0 locked, 1 unlocked */ 24 | lockedStatus: number; 25 | /** Lock private data */ 26 | privateData: TTLockPrivateData; 27 | /** Operation Log entries */ 28 | operationLog?: LogEntry[]; 29 | } -------------------------------------------------------------------------------- /src/api/Commands/ReadDeviceInfoCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { CommandType } from "../../constant/CommandType"; 4 | import { DeviceInfoEnum } from "../../constant/DeviceInfoEnum"; 5 | import { Command } from "../Command"; 6 | 7 | export class ReadDeviceInfoCommand extends Command { 8 | static COMMAND_TYPE: CommandType = CommandType.COMM_READ_DEVICE_INFO; 9 | private opType: DeviceInfoEnum = DeviceInfoEnum.MODEL_NUMBER; 10 | 11 | protected processData(): void { 12 | // nothing to do here 13 | } 14 | 15 | setInfoType(infoType: DeviceInfoEnum) { 16 | this.opType = infoType; 17 | } 18 | 19 | getInfoData(): Buffer | void { 20 | if (this.commandData) { 21 | return this.commandData.subarray(0, this.commandData.length - 1); 22 | } 23 | } 24 | 25 | build(): Buffer { 26 | return Buffer.from([this.opType]); 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/constant/DeviceInfoEnum.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export enum DeviceInfoEnum { 4 | /** 5 | * Product number 6 | */ 7 | MODEL_NUMBER = 1, 8 | 9 | /** 10 | * Hardware version number 11 | */ 12 | HARDWARE_REVISION = 2, 13 | 14 | /** 15 | * Firmware version number 16 | */ 17 | FIRMWARE_REVISION = 3, 18 | 19 | /** 20 | * Production Date 21 | */ 22 | MANUFACTURE_DATE = 4, 23 | 24 | /** 25 | * Bluetooth address 26 | */ 27 | MAC_ADDRESS = 5, 28 | 29 | /** 30 | * Clock 31 | */ 32 | LOCK_CLOCK = 6, 33 | 34 | /** 35 | * Operator information 36 | */ 37 | NB_OPERATOR = 7, 38 | 39 | /** 40 | * NB module number (IMEI) 41 | */ 42 | NB_IMEI = 8, 43 | 44 | /** 45 | * NB card information 46 | */ 47 | NB_CARD_INFO = 9, 48 | 49 | /** 50 | * NB signal value 51 | */ 52 | NB_RSSI = 10, 53 | } -------------------------------------------------------------------------------- /src/api/Commands/AESKeyCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { CommandType } from "../../constant/CommandType"; 4 | import { Command } from "../Command"; 5 | 6 | export class AESKeyCommand extends Command { 7 | static COMMAND_TYPE: CommandType = CommandType.COMM_GET_AES_KEY; 8 | 9 | private aesKey?: Buffer; 10 | 11 | protected processData() { 12 | if (this.commandData) { 13 | this.setAESKey(this.commandData); 14 | } 15 | } 16 | 17 | build(): Buffer { 18 | if (this.aesKey) { 19 | return Buffer.concat([ 20 | Buffer.from([AESKeyCommand.COMMAND_TYPE, this.commandResponse]), 21 | this.aesKey 22 | ]); 23 | } else { 24 | return Buffer.from("SCIENER"); 25 | } 26 | } 27 | 28 | setAESKey(key: Buffer) { 29 | this.aesKey = key; 30 | } 31 | 32 | getAESKey(): Buffer | void { 33 | return this.aesKey; 34 | } 35 | } -------------------------------------------------------------------------------- /src/device/DeviceInfoType.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export type DeviceInfoType = { 4 | /** 5 | * hex feature 6 | */ 7 | featureValue: string; 8 | 9 | /** 10 | * Product model(e.g. "M201") 11 | */ 12 | modelNum: string; 13 | /** 14 | * Hardware version(e.g. "1.3") 15 | */ 16 | hardwareRevision: string; 17 | /** 18 | * Firmware version(e.g. "2.1.16.705") 19 | */ 20 | firmwareRevision: string; 21 | /** 22 | * NB lock IMEI 23 | */ 24 | nbNodeId: string; 25 | 26 | /** 27 | * NB operator 28 | */ 29 | nbOperator: string; 30 | 31 | /** 32 | * NB lock card info 33 | */ 34 | nbCardNumber: string; 35 | /** 36 | * NB lock rssi 37 | */ 38 | nbRssi: number; 39 | /** 40 | * Date of manufacture(e.g. "20160707") 41 | */ 42 | factoryDate: string; 43 | /** 44 | * lock clock(e.g. "1701051531") yymmddhhmm 45 | */ 46 | lockClock: string; 47 | } 48 | -------------------------------------------------------------------------------- /examples/clearFR.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, sleep, PassageModeType } = require('../dist'); 4 | const settingsFile = "lockData.json"; 5 | 6 | async function doStuff() { 7 | let lockData = await require("./common/loadData")(settingsFile); 8 | let options = require("./common/options")(lockData); 9 | 10 | const client = new TTLockClient(options); 11 | await client.prepareBTService(); 12 | client.startScanLock(); 13 | console.log("Scan started"); 14 | client.on("foundLock", async (lock) => { 15 | console.log(lock.toJSON()); 16 | console.log(); 17 | 18 | if (lock.isInitialized() && lock.isPaired()) { 19 | await lock.connect(); 20 | console.log("Trying to clear fingerprints"); 21 | console.log(); 22 | console.log(); 23 | const result = await lock.clearFingerprints(); 24 | await lock.disconnect(); 25 | 26 | process.exit(0); 27 | } 28 | }); 29 | } 30 | 31 | doStuff(); -------------------------------------------------------------------------------- /examples/clearICCards.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, sleep, PassageModeType } = require('../dist'); 4 | const settingsFile = "lockData.json"; 5 | 6 | async function doStuff() { 7 | let lockData = await require("./common/loadData")(settingsFile); 8 | let options = require("./common/options")(lockData); 9 | 10 | const client = new TTLockClient(options); 11 | await client.prepareBTService(); 12 | client.startScanLock(); 13 | console.log("Scan started"); 14 | client.on("foundLock", async (lock) => { 15 | console.log(lock.toJSON()); 16 | console.log(); 17 | 18 | if (lock.isInitialized() && lock.isPaired()) { 19 | await lock.connect(); 20 | console.log("Trying to clear IC cards"); 21 | console.log(); 22 | console.log(); 23 | const result = await lock.clearICCards(); 24 | await lock.disconnect(); 25 | 26 | process.exit(0); 27 | } 28 | }); 29 | } 30 | 31 | doStuff(); -------------------------------------------------------------------------------- /examples/clearPassCodes.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, sleep, PassageModeType } = require('../dist'); 4 | const settingsFile = "lockData.json"; 5 | 6 | async function doStuff() { 7 | let lockData = await require("./common/loadData")(settingsFile); 8 | let options = require("./common/options")(lockData); 9 | 10 | const client = new TTLockClient(options); 11 | await client.prepareBTService(); 12 | client.startScanLock(); 13 | console.log("Scan started"); 14 | client.on("foundLock", async (lock) => { 15 | console.log(lock.toJSON()); 16 | console.log(); 17 | 18 | if (lock.isInitialized() && lock.isPaired()) { 19 | await lock.connect(); 20 | console.log("Trying to clear passcodes"); 21 | console.log(); 22 | console.log(); 23 | const result = await lock.clearPassCodes(); 24 | await lock.disconnect(); 25 | 26 | process.exit(0); 27 | } 28 | }); 29 | } 30 | 31 | doStuff(); -------------------------------------------------------------------------------- /examples/clearPassageMode.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, sleep, PassageModeType } = require('../dist'); 4 | const settingsFile = "lockData.json"; 5 | 6 | async function doStuff() { 7 | let lockData = await require("./common/loadData")(settingsFile); 8 | let options = require("./common/options")(lockData); 9 | 10 | const client = new TTLockClient(options); 11 | await client.prepareBTService(); 12 | client.startScanLock(); 13 | console.log("Scan started"); 14 | client.on("foundLock", async (lock) => { 15 | console.log(lock.toJSON()); 16 | console.log(); 17 | 18 | if (lock.isInitialized() && lock.isPaired()) { 19 | await lock.connect(); 20 | console.log("Trying to clear passage mode"); 21 | console.log(); 22 | console.log(); 23 | const result = await lock.clearPassageMode(); 24 | await lock.disconnect(); 25 | 26 | process.exit(0); 27 | } 28 | }); 29 | } 30 | 31 | doStuff(); -------------------------------------------------------------------------------- /examples/setRemoteUnlock.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, sleep, PassageModeType } = require('../dist'); 4 | const settingsFile = "lockData.json"; 5 | 6 | async function doStuff() { 7 | let lockData = await require("./common/loadData")(settingsFile); 8 | let options = require("./common/options")(lockData); 9 | 10 | const client = new TTLockClient(options); 11 | await client.prepareBTService(); 12 | client.startScanLock(); 13 | console.log("Scan started"); 14 | client.on("foundLock", async (lock) => { 15 | console.log(lock.toJSON()); 16 | console.log(); 17 | 18 | if (lock.isInitialized() && lock.isPaired()) { 19 | await lock.connect(); 20 | console.log("Trying to set remote unlock"); 21 | console.log(); 22 | console.log(); 23 | const result = await lock.setRemoteUnlock(1); 24 | await lock.disconnect(); 25 | 26 | process.exit(0); 27 | } 28 | }); 29 | } 30 | 31 | doStuff(); -------------------------------------------------------------------------------- /examples/deletePassCode.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, sleep, PassageModeType } = require('../dist'); 4 | const settingsFile = "lockData.json"; 5 | 6 | async function doStuff() { 7 | let lockData = await require("./common/loadData")(settingsFile); 8 | let options = require("./common/options")(lockData); 9 | 10 | const client = new TTLockClient(options); 11 | await client.prepareBTService(); 12 | client.startScanLock(); 13 | console.log("Scan started"); 14 | client.on("foundLock", async (lock) => { 15 | console.log(lock.toJSON()); 16 | console.log(); 17 | 18 | if (lock.isInitialized() && lock.isPaired()) { 19 | await lock.connect(); 20 | console.log("Trying to delete passcode"); 21 | console.log(); 22 | console.log(); 23 | const result = await lock.deletePassCode(1, '654321'); 24 | await lock.disconnect(); 25 | 26 | process.exit(0); 27 | } 28 | }); 29 | } 30 | 31 | doStuff(); 32 | -------------------------------------------------------------------------------- /docs/Bad CRC quest.md: -------------------------------------------------------------------------------- 1 | https://crccalc.com/ agrees with me ... 2 | 3 | Sending command: 7f5a0503010001000107aa10 ade4c30cccffef87e7a4b85e76213d43fe0d0a 4 | Received response: 7f5a0503020001000154aa10 2d2f9276f7eea8794974e465f0e99e18090d0a 5 | Bad CRC should be 87 and we got 9 6 | 0x57 - 0x09 (+1 in dscrc_table) 7 | 8 | Sending command: 7f5a0503010001000107aa10 4596cae76d5515c2d19981fb27041ebdd80d0a 9 | Received response: 7f5a0503020001000154aa10 2d2f9276f7eea8794974e465f0e99e18090d0a 10 | Bad CRC should be 87 and we got 9 11 | 0x57 - 0x09 12 | Command: 0000 13 | ========= get passCodes { sequence: -1, data: [] } 14 | 15 | ========= get passCodes 0 16 | Sending command: 7f5a0503010001000107aa10784760ace8d2eabb493dd6d0385bebeb7a0d0a 17 | Received response: 7f5a0503020001000154aa20df862dda9de19dbdf73afce5eb29d32a24feca385bf44991075a85692353d6acd00d0a 18 | Bad CRC should be 119 and we got 208 19 | 0x77 - 0xd0 20 | Command: 001700b4140106313233343536063132333435360001010000 21 | 22 | -------------------------------------------------------------------------------- /examples/getICCards.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, sleep, PassageModeType } = require('../dist'); 4 | const settingsFile = "lockData.json"; 5 | 6 | async function doStuff() { 7 | let lockData = await require("./common/loadData")(settingsFile); 8 | let options = require("./common/options")(lockData); 9 | 10 | const client = new TTLockClient(options); 11 | await client.prepareBTService(); 12 | client.startScanLock(); 13 | console.log("Scan started"); 14 | client.on("foundLock", async (lock) => { 15 | console.log(lock.toJSON()); 16 | console.log(); 17 | 18 | if (lock.isInitialized() && lock.isPaired()) { 19 | await lock.connect(); 20 | console.log("Trying to get IC Cards"); 21 | console.log(); 22 | console.log(); 23 | const result = await lock.getICCards(); 24 | await lock.disconnect(); 25 | console.log(result); 26 | 27 | process.exit(0); 28 | } 29 | }); 30 | } 31 | 32 | doStuff(); -------------------------------------------------------------------------------- /examples/getFR.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, sleep, PassageModeType } = require('../dist'); 4 | const settingsFile = "lockData.json"; 5 | 6 | async function doStuff() { 7 | let lockData = await require("./common/loadData")(settingsFile); 8 | let options = require("./common/options")(lockData); 9 | 10 | const client = new TTLockClient(options); 11 | await client.prepareBTService(); 12 | client.startScanLock(); 13 | console.log("Scan started"); 14 | client.on("foundLock", async (lock) => { 15 | console.log(lock.toJSON()); 16 | console.log(); 17 | 18 | if (lock.isInitialized() && lock.isPaired()) { 19 | await lock.connect(); 20 | console.log("Trying to get fingerprints"); 21 | console.log(); 22 | console.log(); 23 | const result = await lock.getFingerprints(); 24 | await lock.disconnect(); 25 | console.log(result); 26 | 27 | process.exit(0); 28 | } 29 | }); 30 | } 31 | 32 | doStuff(); -------------------------------------------------------------------------------- /examples/getPassCodes.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, sleep, PassageModeType } = require('../dist'); 4 | const settingsFile = "lockData.json"; 5 | 6 | async function doStuff() { 7 | let lockData = await require("./common/loadData")(settingsFile); 8 | let options = require("./common/options")(lockData); 9 | 10 | const client = new TTLockClient(options); 11 | await client.prepareBTService(); 12 | client.startScanLock(); 13 | console.log("Scan started"); 14 | client.on("foundLock", async (lock) => { 15 | console.log(lock.toJSON()); 16 | console.log(); 17 | 18 | if (lock.isInitialized() && lock.isPaired()) { 19 | await lock.connect(); 20 | console.log("Trying to get passcodes"); 21 | console.log(); 22 | console.log(); 23 | const result = await lock.getPassCodes(); 24 | await lock.disconnect(); 25 | console.log(result); 26 | 27 | process.exit(0); 28 | } 29 | }); 30 | } 31 | 32 | doStuff(); -------------------------------------------------------------------------------- /examples/addPassCode.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, sleep, PassageModeType } = require('../dist'); 4 | const settingsFile = "lockData.json"; 5 | 6 | async function doStuff() { 7 | let lockData = await require("./common/loadData")(settingsFile); 8 | let options = require("./common/options")(lockData); 9 | 10 | const client = new TTLockClient(options); 11 | await client.prepareBTService(); 12 | client.startScanLock(); 13 | console.log("Scan started"); 14 | client.on("foundLock", async (lock) => { 15 | console.log(lock.toJSON()); 16 | console.log(); 17 | 18 | if (lock.isInitialized() && lock.isPaired()) { 19 | await lock.connect(); 20 | console.log("Trying to add passcode"); 21 | console.log(); 22 | console.log(); 23 | const result = await lock.addPassCode(1, '123456', '202001010000', '202212312359'); 24 | await lock.disconnect(); 25 | 26 | process.exit(0); 27 | } 28 | }); 29 | } 30 | 31 | doStuff(); -------------------------------------------------------------------------------- /examples/getPassageMode.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, sleep, PassageModeType } = require('../dist'); 4 | const settingsFile = "lockData.json"; 5 | 6 | async function doStuff() { 7 | let lockData = await require("./common/loadData")(settingsFile); 8 | let options = require("./common/options")(lockData); 9 | 10 | const client = new TTLockClient(options); 11 | await client.prepareBTService(); 12 | client.startScanLock(); 13 | console.log("Scan started"); 14 | client.on("foundLock", async (lock) => { 15 | console.log(lock.toJSON()); 16 | console.log(); 17 | 18 | if (lock.isInitialized() && lock.isPaired()) { 19 | await lock.connect(); 20 | console.log("Trying to set passage mode"); 21 | console.log(); 22 | console.log(); 23 | const result = await lock.getPassageMode(); 24 | console.log(result); 25 | await lock.disconnect(); 26 | 27 | process.exit(0); 28 | } 29 | }); 30 | } 31 | 32 | doStuff(); -------------------------------------------------------------------------------- /examples/setAutoLock.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, sleep, PassageModeType } = require('../dist'); 4 | const settingsFile = "lockData.json"; 5 | 6 | async function doStuff() { 7 | let lockData = await require("./common/loadData")(settingsFile); 8 | let options = require("./common/options")(lockData); 9 | 10 | const client = new TTLockClient(options); 11 | await client.prepareBTService(); 12 | client.startScanLock(); 13 | console.log("Scan started"); 14 | client.on("foundLock", async (lock) => { 15 | console.log(lock.toJSON()); 16 | console.log(); 17 | 18 | if (lock.isInitialized() && lock.isPaired()) { 19 | await lock.connect(); 20 | console.log("Trying to set auto-lock time"); 21 | console.log(); 22 | console.log(); 23 | const result = await lock.setAutoLockTime(0); 24 | console.log("Result:", result); 25 | await lock.disconnect(); 26 | 27 | process.exit(0); 28 | } 29 | }); 30 | } 31 | 32 | doStuff(); -------------------------------------------------------------------------------- /src/scanner/ScannerInterface.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { EventEmitter } from "events"; 4 | import { DeviceInterface } from "./DeviceInterface"; 5 | 6 | export type ScannerType = "noble" | "noble-websocket"; 7 | 8 | export type ScannerOptions = { 9 | websocketHost?: string, 10 | websocketPort?: number, 11 | websocketAesKey?: string, 12 | websocketUsername?: string, 13 | websocketPassword?: string 14 | } 15 | 16 | export type ScannerStateType = "unknown" | "starting" | "scanning" | "stopping" | "stopped"; 17 | 18 | export interface ScannerInterface extends EventEmitter { 19 | scannerState: ScannerStateType; 20 | startScan(passive: boolean): Promise; 21 | stopScan(): Promise; 22 | getState(): ScannerStateType; 23 | on(event: "ready", listener: () => void): this; 24 | on(event: "discover", listener: (device: DeviceInterface) => void): this; 25 | on(event: "scanStart", listener: () => void): this; 26 | on(event: "scanStop", listener: () => void): this; 27 | } -------------------------------------------------------------------------------- /examples/updatePassCode.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, sleep, PassageModeType } = require('../dist'); 4 | const settingsFile = "lockData.json"; 5 | 6 | async function doStuff() { 7 | let lockData = await require("./common/loadData")(settingsFile); 8 | let options = require("./common/options")(lockData); 9 | 10 | const client = new TTLockClient(options); 11 | await client.prepareBTService(); 12 | client.startScanLock(); 13 | console.log("Scan started"); 14 | client.on("foundLock", async (lock) => { 15 | console.log(lock.toJSON()); 16 | console.log(); 17 | 18 | if (lock.isInitialized() && lock.isPaired()) { 19 | await lock.connect(); 20 | console.log("Trying to edit passcode"); 21 | console.log(); 22 | console.log(); 23 | const result = await lock.updatePassCode(1, '123456', '654321', '202001010000', '202212312359'); 24 | await lock.disconnect(); 25 | 26 | process.exit(0); 27 | } 28 | }); 29 | } 30 | 31 | doStuff(); -------------------------------------------------------------------------------- /examples/unlock.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, sleep } = require('../dist'); 4 | const settingsFile = "lockData.json"; 5 | 6 | async function doStuff() { 7 | let lockData = await require("./common/loadData")(settingsFile); 8 | let options = require("./common/options")(lockData); 9 | 10 | const client = new TTLockClient(options); 11 | await client.prepareBTService(); 12 | client.startScanLock(); 13 | console.log("Scan started"); 14 | client.on("foundLock", async (lock) => { 15 | console.log(lock.toJSON()); 16 | console.log(); 17 | 18 | if (lock.isInitialized() && lock.isPaired()) { 19 | await lock.connect(); 20 | console.log("Trying to unlock the lock"); 21 | console.log(); 22 | console.log(); 23 | const unlock = await lock.unlock(); 24 | await lock.disconnect(); 25 | 26 | await require("./common/saveData")(settingsFile, client.getLockData()); 27 | 28 | process.exit(0); 29 | } 30 | }); 31 | } 32 | 33 | doStuff(); -------------------------------------------------------------------------------- /examples/deleteLockSound.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, sleep, PassageModeType, AudioManage } = require('../dist'); 4 | const settingsFile = "lockData.json"; 5 | 6 | async function doStuff() { 7 | let lockData = await require("./common/loadData")(settingsFile); 8 | let options = require("./common/options")(lockData); 9 | 10 | const client = new TTLockClient(options); 11 | await client.prepareBTService(); 12 | client.startScanLock(); 13 | console.log("Scan started"); 14 | client.on("foundLock", async (lock) => { 15 | console.log(lock.toJSON()); 16 | console.log(); 17 | 18 | if (lock.isInitialized() && lock.isPaired()) { 19 | await lock.connect(); 20 | console.log("Trying to clear lock sound"); 21 | console.log(); 22 | console.log(); 23 | const result = await lock.setLockSound(AudioManage.TURN_OFF); 24 | console.log(result); 25 | await lock.disconnect(); 26 | 27 | process.exit(0); 28 | } 29 | }); 30 | } 31 | 32 | doStuff(); -------------------------------------------------------------------------------- /examples/reset.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, sleep } = require('../dist'); 4 | const fs = require('fs/promises'); 5 | const settingsFile = "lockData.json"; 6 | 7 | async function doStuff() { 8 | let lockData = await require("./common/loadData")(settingsFile); 9 | let options = require("./common/options")(lockData); 10 | 11 | const client = new TTLockClient(options); 12 | await client.prepareBTService(); 13 | client.startScanLock(); 14 | console.log("Scan started"); 15 | client.on("foundLock", async (lock) => { 16 | console.log(lock.toJSON()); 17 | console.log(); 18 | 19 | if (lock.isInitialized() && lock.isPaired()) { 20 | await lock.connect(); 21 | console.log("Trying to reset the lock"); 22 | console.log(); 23 | console.log(); 24 | const reset = await lock.resetLock(); 25 | await lock.disconnect(); 26 | 27 | await require("./common/saveData")(settingsFile, client.getLockData()); 28 | 29 | process.exit(0); 30 | } 31 | }); 32 | } 33 | 34 | doStuff(); -------------------------------------------------------------------------------- /src/constant/CommandResponse.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export enum CommandResponse { 4 | UNKNOWN = -1, 5 | SUCCESS = 0X01, 6 | FAILED = 0X00, 7 | 8 | // INITIALIZED = 0X01, 9 | // NOT_INITIALIZED = 0X00, 10 | // 11 | // // by wan ------ 区分F,G 12 | //// MODE_ADMIN = 0X00, 13 | //// MODE_UNLOCK = 0X01, 14 | // 15 | // ADMIN = 0X01, //管理员 16 | // USER = 0X00, //普通用户 17 | // 18 | // SUCCESS_GET_DYN_PASSWORD = 0X02, 19 | // ERROR_NONE = 0X00, 20 | // ERROR_INVALID_CRC = 0X01, 21 | // ERROR_NO_PERMISSION = 0X02, 22 | // ERROR_WRONG_ID_OR_PASSWORD = 0X03, 23 | // ERROR_REACH_LIMIT = 0X04, 24 | // ERROR_IN_SETTING = 0X05, 25 | // // ------by wan------ 26 | // ERROR_IN_SAME_USERID = 0X06, // 不能添加重名的 27 | // ERROR_NO_ADMIN_YET = 0X07, // 必须先添加一个管理员 28 | // 29 | // ERROR_Dyna_Password_Out_Time = 0X08, // 动态密码过期 30 | // ERROR_NO_DATA = 0X09, // 数据为空 31 | // 32 | // ERROR_LOCK_NO_POWER = 0X0a, // 锁没有电量了 33 | // 34 | // public byte command, 35 | // public byte isSuccess, 36 | // public byte errorCode, 37 | } -------------------------------------------------------------------------------- /src/api/Command.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { CommandResponse } from "../constant/CommandResponse"; 4 | import { CommandType } from "../constant/CommandType"; 5 | 6 | export interface CommandInterface { 7 | readonly COMMAND_TYPE: CommandType; 8 | new(data: Buffer): Command; 9 | } 10 | 11 | export abstract class Command { 12 | protected commandResponse: CommandResponse = CommandResponse.UNKNOWN; 13 | protected commandData?: Buffer; 14 | protected commandRawData?: Buffer; 15 | 16 | constructor(data?: Buffer) { 17 | if (data) { 18 | this.commandResponse = data.readInt8(1); 19 | this.commandData = data.subarray(2); 20 | if (process.env.TTLOCK_DEBUG_COMM == "1") { 21 | console.log('Command:', this.commandData.toString("hex")); 22 | } 23 | this.processData(); 24 | } 25 | } 26 | 27 | getResponse(): CommandResponse { 28 | return this.commandResponse; 29 | } 30 | 31 | getRawData(): Buffer | void { 32 | return this.commandRawData; 33 | } 34 | 35 | protected abstract processData(): void; 36 | abstract build(): Buffer; 37 | } -------------------------------------------------------------------------------- /src/api/Commands/GetAdminCodeCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { CommandType } from "../../constant/CommandType"; 4 | import { Command } from "../Command"; 5 | 6 | export class GetAdminCodeCommand extends Command { 7 | static COMMAND_TYPE: CommandType = CommandType.COMM_GET_ADMIN_CODE; 8 | 9 | private adminPasscode?: string; 10 | 11 | protected processData(): void { 12 | if (this.commandData) { 13 | const len = this.commandData.readUInt8(1); 14 | if (len != this.commandData.length - 2) { 15 | console.error("GetAdminCodeCommand: data size (" + this.commandData.length + ") does not match declared length(" + len + ")"); 16 | } 17 | if (len > 0) { 18 | this.adminPasscode = this.commandData.subarray(2, this.commandData.length - 2).toString(); 19 | } else { 20 | this.adminPasscode = ""; 21 | } 22 | } 23 | } 24 | 25 | build(): Buffer { 26 | return Buffer.from([]); 27 | } 28 | 29 | getAdminPasscode(): string | undefined { 30 | if (this.adminPasscode) { 31 | return this.adminPasscode; 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /examples/init.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, sleep } = require('../dist'); 4 | const settingsFile = "lockData.json"; 5 | 6 | async function doStuff() { 7 | let lockData = await require("./common/loadData")(settingsFile); 8 | let options = require("./common/options")(lockData); 9 | 10 | const client = new TTLockClient(options); 11 | await client.prepareBTService(); 12 | // for (let i = 10; i > 0; i--) { 13 | // console.log("Starting scan...", i); 14 | // await sleep(1000); 15 | // } 16 | client.startScanLock(); 17 | console.log("Scan started"); 18 | client.on("foundLock", async (lock) => { 19 | console.log(lock.toJSON()); 20 | console.log(); 21 | 22 | if (!lock.isInitialized()) { 23 | await lock.connect(); 24 | console.log("Trying to init the lock"); 25 | console.log(); 26 | console.log(); 27 | const inited = await lock.initLock(); 28 | await lock.disconnect(); 29 | 30 | await require("./common/saveData")(settingsFile, client.getLockData()); 31 | 32 | process.exit(0); 33 | } 34 | }); 35 | } 36 | 37 | doStuff(); -------------------------------------------------------------------------------- /examples/setPassageMode.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, sleep, PassageModeType } = require('../dist'); 4 | const settingsFile = "lockData.json"; 5 | 6 | async function doStuff() { 7 | let lockData = await require("./common/loadData")(settingsFile); 8 | let options = require("./common/options")(lockData); 9 | 10 | const client = new TTLockClient(options); 11 | await client.prepareBTService(); 12 | client.startScanLock(); 13 | console.log("Scan started"); 14 | client.on("foundLock", async (lock) => { 15 | console.log(lock.toJSON()); 16 | console.log(); 17 | 18 | if (lock.isInitialized() && lock.isPaired()) { 19 | await lock.connect(); 20 | console.log("Trying to set passage mode"); 21 | console.log(); 22 | console.log(); 23 | const result = await lock.setPassageMode({ 24 | type: PassageModeType.WEEKLY, 25 | weekOrDay: 5, 26 | month: 0, 27 | startHour: "0000", 28 | endHour: "2359" 29 | }); 30 | await lock.disconnect(); 31 | 32 | process.exit(0); 33 | } 34 | }); 35 | } 36 | 37 | doStuff(); -------------------------------------------------------------------------------- /examples/deletePassageMode.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, sleep, PassageModeType } = require('../dist'); 4 | const settingsFile = "lockData.json"; 5 | 6 | async function doStuff() { 7 | let lockData = await require("./common/loadData")(settingsFile); 8 | let options = require("./common/options")(lockData); 9 | 10 | const client = new TTLockClient(options); 11 | await client.prepareBTService(); 12 | client.startScanLock(); 13 | console.log("Scan started"); 14 | client.on("foundLock", async (lock) => { 15 | console.log(lock.toJSON()); 16 | console.log(); 17 | 18 | if (lock.isInitialized() && lock.isPaired()) { 19 | await lock.connect(); 20 | console.log("Trying to set passage mode"); 21 | console.log(); 22 | console.log(); 23 | const result = await lock.deletePassageMode({ 24 | type: PassageModeType.WEEKLY, 25 | weekOrDay: 5, 26 | month: 0, 27 | startHour: "0000", 28 | endHour: "2359" 29 | }); 30 | await lock.disconnect(); 31 | 32 | process.exit(0); 33 | } 34 | }); 35 | } 36 | 37 | doStuff(); -------------------------------------------------------------------------------- /examples/addICCard.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, sleep, PassageModeType } = require('../dist'); 4 | const settingsFile = "lockData.json"; 5 | 6 | async function doStuff() { 7 | let lockData = await require("./common/loadData")(settingsFile); 8 | let options = require("./common/options")(lockData); 9 | 10 | const client = new TTLockClient(options); 11 | await client.prepareBTService(); 12 | client.startScanLock(); 13 | console.log("Scan started"); 14 | client.on("foundLock", async (lock) => { 15 | console.log(lock.toJSON()); 16 | console.log(); 17 | 18 | if (lock.isInitialized() && lock.isPaired()) { 19 | await lock.connect(); 20 | console.log("Trying to add IC Card"); 21 | console.log(); 22 | console.log(); 23 | lock.on("scanICStart", () => { 24 | console.log(); 25 | console.log("Ready to scan an IC Card"); 26 | console.log(); 27 | }); 28 | const result = await lock.addICCard('202001010000', '202212312359'); 29 | console.log(result); 30 | await lock.disconnect(); 31 | 32 | process.exit(0); 33 | } 34 | }); 35 | } 36 | 37 | doStuff(); -------------------------------------------------------------------------------- /src/api/Commands/CheckAdminCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { CommandType } from "../../constant/CommandType"; 4 | import { Command } from "../Command"; 5 | 6 | export class CheckAdminCommand extends Command { 7 | static COMMAND_TYPE: CommandType = CommandType.COMM_CHECK_ADMIN; 8 | 9 | private uid: number = 0; 10 | private adminPs?: number; 11 | private lockFlagPos: number = 0; 12 | 13 | protected processData(): void { 14 | // nothing to do, all incomming data is the 'token' 15 | } 16 | 17 | build(): Buffer { 18 | if (typeof this.adminPs != "undefined") { 19 | const data = Buffer.alloc(11); 20 | data.writeUInt32BE(this.lockFlagPos, 3); // 4 bytes (first one overlaps with adminPs) 21 | data.writeUInt32BE(this.adminPs, 0); // 4 bytes 22 | data.writeUInt32BE(this.uid, 7); 23 | return data; 24 | } else { 25 | return Buffer.from([]); 26 | } 27 | } 28 | 29 | setParams(adminPs: number) { 30 | this.adminPs = adminPs; 31 | } 32 | 33 | getPsFromLock(): number { 34 | if(this.commandData) { 35 | return this.commandData.readUInt32BE(0); 36 | } else { 37 | return -1; 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /src/util/dscrc_table.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export const dscrc_table: number[] = [ 4 | 0, 94,188,226, 97, 63,221,131,194,156,126, 32,163,253, 31, 65, 5 | 157,195, 33,127,252,162, 64, 30, 95, 1,227,189, 62, 96,130,220, 6 | 35,125,159,193, 66, 28,254,160,225,191, 93, 3,128,222, 60, 98, 7 | 190,224, 2, 92,223,129, 99, 61,124, 34,192,158, 29, 67,161,255, 8 | 70, 24,250,164, 39,121,155,197,132,218, 56,102,229,187, 89, 7, 9 | 219,133,103, 57,186,228, 6, 88, 25, 71,165,251,120, 38,196,154, 10 | 101, 59,217,135, 4, 90,184,230,167,249, 27, 69,198,152,122, 36, 11 | 248,166, 68, 26,153,199, 37,123, 58,100,134,216, 91, 5,231,185, 12 | 140,210, 48,110,237,179, 81, 15, 78, 16,242,172, 47,113,147,205, 13 | 17, 79,173,243,112, 46,204,146,211,141,111, 49,178,236, 14, 80, 14 | 175,241, 19, 77,206,144,114, 44,109, 51,209,143, 12, 82,176,238, 15 | 50,108,142,208, 83, 13,239,177,240,174, 76, 18,145,207, 45,115, 16 | 202,148,118, 40,171,245, 23, 73, 8, 86,180,234,105, 55,213,139, 17 | 87, 9,235,181, 54,104,138,212,149,203, 41,119,244,170, 72, 22, 18 | 233,183, 85, 11,136,214, 52,106, 43,117,151,201, 74, 20,246,168, 19 | 116, 42,200,150, 21, 75,169,247,182,232, 10, 84,215,137,107, 53 20 | ]; 21 | -------------------------------------------------------------------------------- /examples/addICCardBatch.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, sleep, PassageModeType } = require('../dist'); 4 | const settingsFile = "lockData.json"; 5 | 6 | const cards = [ 7 | ['202001010000', '202212312359', '1234567890'] 8 | ]; 9 | 10 | async function doStuff() { 11 | let lockData = await require("./common/loadData")(settingsFile); 12 | let options = require("./common/options")(lockData); 13 | 14 | const client = new TTLockClient(options); 15 | await client.prepareBTService(); 16 | client.startScanLock(); 17 | console.log("Scan started"); 18 | client.on("foundLock", async (lock) => { 19 | console.log(lock.toJSON()); 20 | console.log(); 21 | 22 | if (lock.isInitialized() && lock.isPaired()) { 23 | await lock.connect(); 24 | console.log("Trying to add IC Cards"); 25 | console.log(); 26 | console.log(); 27 | for (const card of cards) { 28 | console.log("Adding card", card[2]); 29 | const result = await lock.addICCard(card[0], card[1], card[2]); 30 | console.log(result); 31 | } 32 | await lock.disconnect(); 33 | 34 | process.exit(0); 35 | } 36 | }); 37 | } 38 | 39 | doStuff(); -------------------------------------------------------------------------------- /examples/lock.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, sleep } = require('../dist'); 4 | const fs = require('fs/promises'); 5 | const settingsFile = "lockData.json"; 6 | 7 | async function doStuff() { 8 | let lockData = await require("./common/loadData")(settingsFile); 9 | let options = require("./common/options")(lockData); 10 | 11 | const client = new TTLockClient(options); 12 | await client.prepareBTService(); 13 | client.startScanLock(); 14 | console.log("Scan started"); 15 | client.on("foundLock", async (lock) => { 16 | console.log(lock.toJSON()); 17 | console.log(); 18 | 19 | if (lock.isInitialized() && lock.isPaired()) { 20 | await lock.connect(); 21 | console.log("Trying to lock the lock"); 22 | console.log(); 23 | console.log(); 24 | const unlock = await lock.lock(); 25 | await lock.disconnect(); 26 | const newLockData = client.getLockData(); 27 | console.log(JSON.stringify(newLockData)); 28 | try { 29 | await fs.writeFile(settingsFile, Buffer.from(JSON.stringify(newLockData))); 30 | } catch (error) { 31 | process.exit(1); 32 | } 33 | 34 | process.exit(0); 35 | } 36 | }); 37 | } 38 | 39 | doStuff(); -------------------------------------------------------------------------------- /examples/status.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, sleep, PassageModeType } = require('../dist'); 4 | const settingsFile = "lockData.json"; 5 | 6 | async function doStuff() { 7 | let lockData = await require("./common/loadData")(settingsFile); 8 | let options = require("./common/options")(lockData); 9 | 10 | const client = new TTLockClient(options); 11 | await client.prepareBTService(); 12 | client.startScanLock(); 13 | console.log("Scan started"); 14 | client.on("foundLock", async (lock) => { 15 | console.log(lock.toJSON()); 16 | console.log(); 17 | 18 | if (lock.isInitialized() && lock.isPaired()) { 19 | await lock.connect(); 20 | console.log("Trying to get lock/unlock status"); 21 | console.log(); 22 | console.log(); 23 | const result = await lock.getLockStatus(); 24 | if (result != -1) { 25 | if (result == 0) { 26 | console.log("Lock is locked", result); 27 | } else { 28 | console.log("Lock is unlocked", result); 29 | } 30 | } else { 31 | console.log("Failed to get lock status"); 32 | } 33 | await lock.disconnect(); 34 | 35 | process.exit(0); 36 | } 37 | }); 38 | } 39 | 40 | doStuff(); -------------------------------------------------------------------------------- /src/api/Commands/SetAdminKeyboardPwdCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { CommandType } from "../../constant/CommandType"; 4 | import { Command } from "../Command"; 5 | 6 | export class SetAdminKeyboardPwdCommand extends Command { 7 | static COMMAND_TYPE: CommandType = CommandType.COMM_SET_ADMIN_KEYBOARD_PWD; 8 | 9 | private adminPasscode?: string; 10 | 11 | protected processData(): void { 12 | // do nothing yet, we don't know if the lock returns anything 13 | if(this.commandData && this.commandData.length > 0) { 14 | console.log("SetAdminKeyboardPwdCommand received:", this.commandData); 15 | } 16 | // throw new Error("Method not implemented."); 17 | } 18 | 19 | build(): Buffer { 20 | if (this.adminPasscode) { 21 | const data = Buffer.alloc(this.adminPasscode.length); 22 | for (let i = 0; i < this.adminPasscode.length; i++) { 23 | data[i] = parseInt(this.adminPasscode.charAt(i)); 24 | } 25 | return data; 26 | } else { 27 | return Buffer.from([]); 28 | } 29 | } 30 | 31 | setAdminPasscode(adminPasscode: string) { 32 | this.adminPasscode = adminPasscode; 33 | } 34 | 35 | getAdminPasscode(): string | void { 36 | return this.adminPasscode; 37 | } 38 | } -------------------------------------------------------------------------------- /src/scanner/noble/NobleScannerWebsocket.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { NobleScanner } from "./NobleScanner"; 4 | import { NobleWebsocketBinding } from "./NobleWebsocketBinding"; 5 | const Noble = require("@abandonware/noble/with-bindings"); 6 | 7 | export class NobleScannerWebsocket extends NobleScanner { 8 | private websocketAddress: string; 9 | private websocketPort: number; 10 | private aesKey: string; 11 | private username: string; 12 | private password: string; 13 | 14 | constructor(uuids?: string[], address?: string, port?: number, aesKey?: string, username?: string, password?: string) { 15 | super(uuids || []); 16 | this.websocketAddress = address || "127.0.0.1"; 17 | this.websocketPort = port || 80; 18 | this.aesKey = aesKey || "f8b55c272eb007f501560839be1f1e7e"; 19 | this.username = username || "admin"; 20 | this.password = password || "admin"; 21 | this.createNobleWebsocket(); 22 | this.initNoble(); 23 | } 24 | 25 | protected createNoble() { 26 | 27 | } 28 | 29 | protected createNobleWebsocket() { 30 | const binding = new NobleWebsocketBinding(this.websocketAddress, this.websocketPort, this.aesKey, this.username, this.password); 31 | this.noble = new Noble(binding); 32 | } 33 | } -------------------------------------------------------------------------------- /examples/getOperations.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, LogOperateNames } = require('../dist'); 4 | const settingsFile = "lockData.json"; 5 | 6 | async function doStuff() { 7 | let lockData = await require("./common/loadData")(settingsFile); 8 | let options = require("./common/options")(lockData); 9 | 10 | const client = new TTLockClient(options); 11 | await client.prepareBTService(); 12 | client.startScanLock(); 13 | console.log("Scan started"); 14 | client.on("foundLock", async (lock) => { 15 | console.log(lock.toJSON()); 16 | console.log(); 17 | 18 | if (lock.isInitialized() && lock.isPaired()) { 19 | await lock.connect(); 20 | console.log("Trying to get Operations Log"); 21 | console.log(); 22 | console.log(); 23 | // make a copy so we don't save the record names 24 | const results = JSON.parse(JSON.stringify(await lock.getOperationLog(true, true))); 25 | await lock.disconnect(); 26 | for (let result of results) { 27 | if (result) { 28 | result.recordTypeName = LogOperateNames[result.recordType]; 29 | } 30 | } 31 | console.log(results); 32 | 33 | await require("./common/saveData")(settingsFile, client.getLockData()); 34 | 35 | process.exit(0); 36 | } 37 | }); 38 | } 39 | 40 | doStuff(); -------------------------------------------------------------------------------- /src/constant/index.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export { APICommand } from "./APICommand"; 4 | export { ActionType } from "./ActionType"; 5 | export { AudioManage } from "./AudioManage"; 6 | export { AutoLockOperate } from "./AutoLockOperate"; 7 | export { CallbackOperationType } from "./CallbackOperationType"; 8 | export { CommandResponse } from "./CommandResponse"; 9 | export { CommandType } from "./CommandType"; 10 | export { ConfigRemoteUnlock } from "./ConfigRemoteUnlock"; 11 | export { ControlAction } from "./ControlAction"; 12 | export { CyclicOpType } from "./CyclicOpType"; 13 | export { DateConstant } from "./DateConstant"; 14 | export { DeviceInfoEnum } from "./DeviceInfoEnum"; 15 | export { FeatureValue } from "./FeatureValue"; 16 | export { ICOperate } from "./ICOperate"; 17 | export { KeyboardPwdType } from "./KeyboardPwdType"; 18 | export { LockType, LockVersion } from "./Lock"; 19 | export { LockedStatus } from "./LockedStatus"; 20 | export { LogOperate } from "./LogOperate"; 21 | export { LogType } from "./LogType"; 22 | export { OperationType } from "./OperationType"; 23 | export { PassageModeOperate } from "./PassageModeOperate"; 24 | export { PassageModeType } from "./PassageModeType"; 25 | export { PwdOperateType } from "./PwdOperateType"; 26 | export { LogOperateNames } from "./LogOperateNames"; 27 | export { LogOperateCategory } from "./LogOperateCategory"; 28 | -------------------------------------------------------------------------------- /examples/addFR.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, sleep, PassageModeType } = require('../dist'); 4 | const settingsFile = "lockData.json"; 5 | 6 | async function doStuff() { 7 | let lockData = await require("./common/loadData")(settingsFile); 8 | let options = require("./common/options")(lockData); 9 | 10 | const client = new TTLockClient(options); 11 | await client.prepareBTService(); 12 | client.startScanLock(); 13 | console.log("Scan started"); 14 | client.on("foundLock", async (lock) => { 15 | console.log(lock.toJSON()); 16 | console.log(); 17 | 18 | if (lock.isInitialized() && lock.isPaired()) { 19 | await lock.connect(); 20 | console.log("Trying to add Fingerprint"); 21 | console.log(); 22 | console.log(); 23 | let progress = 0; 24 | lock.on("scanFRStart", () => { 25 | console.log(); 26 | console.log("Ready to scan a finger"); 27 | console.log(); 28 | }); 29 | lock.on("scanFRProgress", () => { 30 | progress++; 31 | console.log(); 32 | console.log("Scanning progress", progress); 33 | console.log(); 34 | }); 35 | const result = await lock.addFingerprint('202001010000', '202212312359'); 36 | console.log(result); 37 | await lock.disconnect(); 38 | 39 | process.exit(0); 40 | } 41 | }); 42 | } 43 | 44 | doStuff(); -------------------------------------------------------------------------------- /src/api/Commands/ScreenPasscodeManageCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { ActionType } from "../../constant/ActionType"; 4 | import { CommandType } from "../../constant/CommandType"; 5 | import { Command } from "../Command"; 6 | 7 | export class ScreenPasscodeManageCommand extends Command { 8 | static COMMAND_TYPE: CommandType = CommandType.COMM_SHOW_PASSWORD; 9 | 10 | private opType: ActionType.GET | ActionType.SET = ActionType.GET; 11 | private opValue?: 0 | 1; // lockData.displayPasscode 12 | 13 | protected processData(): void { 14 | if (this.commandData) { 15 | this.opType = this.commandData.readUInt8(0); 16 | if (this.opType == ActionType.GET && this.commandData.length > 1) { 17 | if (this.commandData.readUInt8(1) == 1) { 18 | this.opValue = 1; 19 | } else { 20 | this.opValue = 0; 21 | } 22 | } 23 | } 24 | } 25 | 26 | build(): Buffer { 27 | if (this.opType == ActionType.GET) { 28 | return Buffer.from([this.opType]); 29 | } else if (this.opType == ActionType.SET && typeof this.opValue != "undefined") { 30 | return Buffer.from([this.opType, this.opValue]); 31 | } else { 32 | return Buffer.from([]); 33 | } 34 | } 35 | 36 | setNewValue(opValue: 0 | 1) { 37 | this.opValue = opValue; 38 | this.opType = ActionType.SET; 39 | } 40 | 41 | getValue(): 0 | 1 | void { 42 | if (this.opValue) { 43 | return this.opValue; 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /src/api/Commands/CheckUserTimeCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { CommandType } from "../../constant/CommandType"; 4 | import { dateTimeToBuffer } from "../../util/timeUtil"; 5 | import { Command } from "../Command"; 6 | 7 | export class CheckUserTimeCommand extends Command { 8 | static COMMAND_TYPE: CommandType = CommandType.COMM_CHECK_USER_TIME; 9 | 10 | private uid?: number; 11 | private startDate?: string; 12 | private endDate?: string; 13 | private lockFlagPos?: number; 14 | 15 | protected processData(): void { 16 | // nothing to do 17 | } 18 | 19 | build(): Buffer { 20 | if (typeof this.uid != "undefined" && this.startDate && this.endDate && typeof this.lockFlagPos != "undefined") { 21 | const data = Buffer.alloc(17); //5+5+3+4 22 | dateTimeToBuffer(this.startDate).copy(data, 0); 23 | data.writeUInt32BE(this.lockFlagPos, 9); // overlap first byte 24 | dateTimeToBuffer(this.endDate).copy(data, 5); 25 | data.writeUInt32BE(this.uid, 13); 26 | return data; 27 | } 28 | return Buffer.from([]); 29 | } 30 | 31 | setPayload(uid: number, startDate: string, endDate: string, lockFlagPos: number) { 32 | this.uid = uid; 33 | this.startDate = startDate; 34 | this.endDate = endDate; 35 | this.lockFlagPos = lockFlagPos; 36 | } 37 | 38 | getPsFromLock(): number { 39 | if (this.commandData) { 40 | return this.commandData.readUInt32BE(0); 41 | } else { 42 | return -1; 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /src/constant/LogOperateCategory.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { LogOperate } from "./LogOperate"; 4 | 5 | export let LogOperateCategory = { 6 | LOCK: [ 7 | LogOperate.OPERATE_BLE_LOCK, 8 | LogOperate.DOOR_SENSOR_LOCK, 9 | LogOperate.FR_LOCK, 10 | LogOperate.PASSCODE_LOCK, 11 | LogOperate.IC_LOCK, 12 | LogOperate.OPERATE_KEY_LOCK, 13 | 14 | ], 15 | UNLOCK: [ 16 | LogOperate.OPERATE_TYPE_MOBILE_UNLOCK, 17 | LogOperate.OPERATE_TYPE_KEYBOARD_PASSWORD_UNLOCK, 18 | LogOperate.OPERATE_TYPE_IC_UNLOCK_SUCCEED, 19 | LogOperate.OPERATE_TYPE_BONG_UNLOCK_SUCCEED, 20 | LogOperate.OPERATE_TYPE_FR_UNLOCK_SUCCEED, 21 | LogOperate.OPERATE_KEY_UNLOCK, 22 | LogOperate.GATEWAY_UNLOCK, 23 | LogOperate.ILLAGEL_UNLOCK, 24 | LogOperate.DOOR_SENSOR_UNLOCK, 25 | ], 26 | FAILED: [ 27 | LogOperate.OPERATE_TYPE_FR_UNLOCK_FAILED, 28 | LogOperate.OPERATE_TYPE_IC_UNLOCK_FAILED, 29 | LogOperate.PASSCODE_UNLOCK_FAILED_LOCK_REVERSE, 30 | LogOperate.IC_UNLOCK_FAILED_LOCK_REVERSE, 31 | LogOperate.FR_UNLOCK_FAILED_LOCK_REVERSE, 32 | LogOperate.APP_UNLOCK_FAILED_LOCK_REVERSE 33 | ], 34 | IC: [ 35 | LogOperate.OPERATE_TYPE_ADD_IC, 36 | LogOperate.OPERATE_TYPE_IC_UNLOCK_SUCCEED, 37 | LogOperate.OPERATE_TYPE_DELETE_IC_SUCCEED, 38 | LogOperate.OPERATE_TYPE_IC_UNLOCK_FAILED 39 | ], 40 | FR: [ 41 | LogOperate.OPERATE_TYPE_FR_UNLOCK_SUCCEED, 42 | LogOperate.OPERATE_TYPE_ADD_FR, 43 | LogOperate.OPERATE_TYPE_FR_UNLOCK_FAILED, 44 | LogOperate.OPERATE_TYPE_DELETE_FR_SUCCEED, 45 | ] 46 | } -------------------------------------------------------------------------------- /src/util/CodecUtils.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** TODO: use Buffers */ 4 | 5 | import { dscrc_table } from "./dscrc_table"; 6 | 7 | export class CodecUtils { 8 | static encodeWithEncrypt(p0: Buffer, key?: number): Buffer { 9 | var seed; 10 | if (key) { 11 | seed = key; 12 | } else { 13 | // generate a random number from 1 to 127 14 | seed = Math.round(Math.random() * 126) + 1; 15 | } 16 | 17 | var encoded = []; 18 | const crc = dscrc_table[p0.length & 0xff]; 19 | 20 | for (var i = 0; i < p0.length; i++) { 21 | encoded.push(seed ^ p0.readInt8(i) ^ crc); 22 | } 23 | if (!key) { 24 | encoded.push(seed); 25 | } 26 | 27 | return Buffer.from(encoded); 28 | } 29 | 30 | static encode(p0: Buffer): Buffer { 31 | return CodecUtils.encodeWithEncrypt(p0); 32 | } 33 | 34 | static decodeWithEncrypt(p0: Buffer, key?: number): Buffer { 35 | var seed; 36 | if (key) { 37 | seed = key; 38 | } else { 39 | seed = p0.readInt8(p0.length - 1); 40 | } 41 | 42 | var decoded = []; 43 | const crc = dscrc_table[p0.length & 0xff]; 44 | 45 | for (var i = 0; i < p0.length - (key ? 0 : 1); i++) { 46 | decoded.push(seed ^ p0[i] ^ crc); 47 | } 48 | 49 | return Buffer.from(decoded); 50 | } 51 | 52 | static decode(p0: Buffer): Buffer { 53 | return CodecUtils.decodeWithEncrypt(p0); 54 | } 55 | 56 | static crccompute(p0: Buffer): number { 57 | var crc = 0; 58 | for (var i = 0; i < p0.length; i++) { 59 | crc = dscrc_table[crc ^ p0.readUInt8(i)]; 60 | } 61 | return crc; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/util/AESUtil.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import crypto from "crypto"; 4 | 5 | /** 6 | * Default encryption key used when the lock is not paired yet 7 | */ 8 | export const defaultAESKey = Buffer.from([ 9 | 0x98, 0x76, 0x23, 0xE8, 10 | 0xA9, 0x23, 0xA1, 0xBB, 11 | 0x3D, 0x9E, 0x7D, 0x03, 12 | 0x78, 0x12, 0x45, 0x88 13 | ]); 14 | 15 | export class AESUtil { 16 | static aesEncrypt(source: Buffer, key?: Buffer): Buffer { 17 | if (source.length == 0) { 18 | return Buffer.from([]); 19 | } 20 | 21 | if (typeof key == "undefined") { 22 | key = defaultAESKey; 23 | } 24 | 25 | if (key.length != 16) { 26 | throw new Error("Invalid key size: " + key.length); 27 | } 28 | 29 | const cipher = crypto.createCipheriv('aes-128-cbc', key, key); 30 | 31 | let encrypted = cipher.update(source); 32 | encrypted = Buffer.concat([encrypted, cipher.final()]); 33 | 34 | return encrypted; 35 | } 36 | 37 | static aesDecrypt(source: Buffer, key?: Buffer): Buffer { 38 | if (source.length == 0) { 39 | return Buffer.from([]); 40 | } 41 | 42 | if (typeof key == "undefined") { 43 | key = defaultAESKey; 44 | } 45 | 46 | if (key.length != 16) { 47 | throw new Error("Invalid key size: " + key.length); 48 | } 49 | 50 | const cipher = crypto.createDecipheriv('aes-128-cbc', key, key); 51 | 52 | try { 53 | let decrypted = cipher.update(source); 54 | decrypted = Buffer.concat([decrypted, cipher.final()]); 55 | 56 | return decrypted; 57 | } catch (error) { 58 | console.error(error); 59 | throw new Error("Decryption failed"); 60 | } 61 | } 62 | } -------------------------------------------------------------------------------- /src/api/commandBuilder.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { CommandType } from "../constant/CommandType"; 4 | import { Command, CommandInterface } from "./Command"; 5 | import * as commands from "./Commands"; 6 | 7 | // TODO: index commands based on COMMAND_TYPE for faster lookup 8 | 9 | function getCommandClass(commandType: CommandType): CommandInterface | void { 10 | let commandTypeInt = commandType; 11 | // if (typeof commandTypeInt == "string") { 12 | // commandTypeInt = commandTypeInt.charCodeAt(0); 13 | // } 14 | const classNames = Object.keys(commands); 15 | for (let i = 0; i < classNames.length; i++) { 16 | if (classNames[i] != "UnknownCommand") { 17 | const commandClass: CommandInterface = Reflect.get(commands, classNames[i]); 18 | let cmdTypeInt = commandClass.COMMAND_TYPE; 19 | // if (typeof cmdTypeInt == 'string') { 20 | // cmdTypeInt = cmdTypeInt.charCodeAt(0); 21 | // } 22 | if (cmdTypeInt == commandTypeInt) { 23 | return commandClass; 24 | } 25 | } 26 | } 27 | } 28 | 29 | export function commandFromData(data: Buffer): Command { 30 | const commandType: CommandType = data.readUInt8(0); 31 | const commandClass = getCommandClass(commandType); 32 | if (commandClass) { 33 | return Reflect.construct(commandClass, [data]); 34 | } else { 35 | return new commands.UnknownCommand(data); 36 | } 37 | } 38 | 39 | export function commandFromType(commandType: CommandType): Command { 40 | const commandClass = getCommandClass(commandType); 41 | if (commandClass) { 42 | return Reflect.construct(commandClass, []); 43 | } else { 44 | return new commands.UnknownCommand(); 45 | } 46 | } -------------------------------------------------------------------------------- /src/api/Commands/AudioManageCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { AudioManage } from "../../constant/AudioManage"; 4 | import { CommandType } from "../../constant/CommandType"; 5 | import { Command } from "../Command"; 6 | 7 | export class AudioManageCommand extends Command { 8 | static COMMAND_TYPE: CommandType = CommandType.COMM_AUDIO_MANAGE; 9 | private opType: AudioManage.QUERY | AudioManage.MODIFY = AudioManage.QUERY; 10 | private opValue?: AudioManage.TURN_ON | AudioManage.TURN_OFF; // lockData.lockSound 11 | private batteryCapacity?: number; 12 | 13 | protected processData(): void { 14 | if (this.commandData && this.commandData.length >= 2) { 15 | this.batteryCapacity = this.commandData.readUInt8(0); 16 | this.opType = this.commandData.readUInt8(1); 17 | if (this.opType == AudioManage.QUERY && this.commandData.length >= 3) { 18 | this.opValue = this.commandData.readUInt8(2); 19 | } 20 | } 21 | } 22 | 23 | build(): Buffer { 24 | if (this.opType == AudioManage.QUERY) { 25 | return Buffer.from([this.opType]); 26 | } else if (this.opType == AudioManage.MODIFY && typeof this.opValue != "undefined") { 27 | return Buffer.from([this.opType, this.opValue]); 28 | } else { 29 | return Buffer.from([]); 30 | } 31 | } 32 | 33 | setNewValue(opValue: AudioManage.TURN_ON | AudioManage.TURN_OFF) { 34 | this.opValue = opValue; 35 | this.opType = AudioManage.MODIFY; 36 | } 37 | 38 | getValue(): AudioManage.TURN_ON | AudioManage.TURN_OFF | void { 39 | if (typeof this.opValue != "undefined") { 40 | return this.opValue; 41 | } 42 | } 43 | 44 | getBatteryCapacity(): number { 45 | if (typeof this.batteryCapacity != "undefined") { 46 | return this.batteryCapacity; 47 | } else { 48 | return -1; 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /src/api/Commands/AddAdminCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { CommandResponse } from "../../constant/CommandResponse"; 4 | import { CommandType } from "../../constant/CommandType"; 5 | import { Command } from "../Command"; 6 | 7 | export class AddAdminCommand extends Command { 8 | static COMMAND_TYPE: CommandType = CommandType.COMM_ADD_ADMIN; 9 | private adminPs?: number; 10 | private unlockKey?: number; 11 | 12 | generateNumber(): number { 13 | return Math.floor(Math.random() * 100000000); 14 | } 15 | 16 | setAdminPs(adminPassword?: number): number { 17 | if (adminPassword) { 18 | this.adminPs = adminPassword; 19 | } else { 20 | this.adminPs = this.generateNumber(); 21 | } 22 | return this.adminPs; 23 | } 24 | 25 | getAdminPs(): number | undefined { 26 | return this.adminPs; 27 | } 28 | 29 | setUnlockKey(unlockNumber?: number): number { 30 | if (unlockNumber) { 31 | this.unlockKey = unlockNumber; 32 | } else { 33 | this.unlockKey = this.generateNumber(); 34 | } 35 | return this.unlockKey; 36 | } 37 | 38 | getUnlockKey(): number | undefined { 39 | return this.unlockKey; 40 | } 41 | 42 | protected processData(): void { 43 | const data = this.commandData?.toString(); 44 | if (data != "SCIENER") { 45 | this.commandResponse = CommandResponse.FAILED; 46 | } 47 | } 48 | 49 | build(): Buffer { 50 | if (this.adminPs && this.unlockKey) { 51 | const adminUnlock = Buffer.alloc(8);//new ArrayBuffer(8); 52 | adminUnlock.writeInt32BE(this.adminPs, 0); 53 | adminUnlock.writeInt32BE(this.unlockKey, 4); 54 | return Buffer.concat([ 55 | adminUnlock, 56 | Buffer.from("SCIENER"), 57 | ]); 58 | } else { 59 | throw new Error("adminPs and unlockKey were not set"); 60 | } 61 | } 62 | 63 | } -------------------------------------------------------------------------------- /src/api/Commands/AutoLockManageCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { AutoLockOperate } from "../../constant/AutoLockOperate"; 4 | import { CommandType } from "../../constant/CommandType"; 5 | import { Command } from "../Command"; 6 | 7 | export class AutoLockManageCommand extends Command { 8 | static COMMAND_TYPE: CommandType = CommandType.COMM_AUTO_LOCK_MANAGE; 9 | 10 | private opType: AutoLockOperate.SEARCH | AutoLockOperate.MODIFY = AutoLockOperate.SEARCH; 11 | private opValue?: number; 12 | private batteryCapacity?: number; 13 | 14 | protected processData(): void { 15 | if (this.commandData && this.commandData.length >= 4) { 16 | // 0 - battery 17 | // 1 - opType 18 | // 2,3 - opValue 19 | // 4,5 - min value 20 | // 6,7 - max value 21 | this.batteryCapacity = this.commandData.readUInt8(0); 22 | this.opType = this.commandData.readUInt8(1); 23 | if (this.opType == AutoLockOperate.SEARCH) { 24 | this.opValue = this.commandData.readUInt16BE(2); 25 | } else { 26 | 27 | } 28 | } 29 | } 30 | build(): Buffer { 31 | if (this.opType == AutoLockOperate.SEARCH) { 32 | return Buffer.from([this.opType]); 33 | } else if (typeof this.opValue != "undefined") { 34 | return Buffer.from([ 35 | this.opType, 36 | this.opValue >> 8, 37 | this.opValue 38 | ]); 39 | } else { 40 | return Buffer.from([]); 41 | } 42 | } 43 | 44 | setTime(opValue: number) { 45 | this.opValue = opValue; 46 | this.opType = AutoLockOperate.MODIFY; 47 | } 48 | 49 | getTime(): number { 50 | if (typeof this.opValue != "undefined") { 51 | return this.opValue; 52 | } else { 53 | return -1; 54 | } 55 | } 56 | 57 | getBatteryCapacity(): number { 58 | if (this.batteryCapacity) { 59 | return this.batteryCapacity; 60 | } else { 61 | return -1; 62 | } 63 | } 64 | } -------------------------------------------------------------------------------- /src/api/Commands/ControlRemoteUnlockCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { CommandType } from "../../constant/CommandType"; 4 | import { ConfigRemoteUnlock } from "../../constant/ConfigRemoteUnlock"; 5 | import { Command } from "../Command"; 6 | 7 | export class ControlRemoteUnlockCommand extends Command { 8 | static COMMAND_TYPE: CommandType = CommandType.COMM_CONTROL_REMOTE_UNLOCK; 9 | 10 | private opType: ConfigRemoteUnlock.OP_TYPE_SEARCH | ConfigRemoteUnlock.OP_TYPE_MODIFY = ConfigRemoteUnlock.OP_TYPE_SEARCH; 11 | private opValue?: ConfigRemoteUnlock.OP_CLOSE | ConfigRemoteUnlock.OP_OPEN; 12 | private batteryCapacity?: number; 13 | 14 | protected processData(): void { 15 | if (this.commandData && this.commandData.length > 1) { 16 | this.batteryCapacity = this.commandData.readUInt8(0); 17 | this.opType = this.commandData.readUInt8(1); 18 | if (this.opType == ConfigRemoteUnlock.OP_TYPE_SEARCH && this.commandData.length > 2) { 19 | this.opValue = this.commandData.readUInt8(2); 20 | } 21 | } 22 | } 23 | 24 | build(): Buffer { 25 | if (this.opType == ConfigRemoteUnlock.OP_TYPE_SEARCH) { 26 | return Buffer.from([this.opType]); 27 | } else if (this.opType == ConfigRemoteUnlock.OP_TYPE_MODIFY && typeof this.opValue != "undefined") { 28 | return Buffer.from([this.opType, this.opValue]); 29 | } else { 30 | return Buffer.from([]); 31 | } 32 | } 33 | 34 | setNewValue(opValue: ConfigRemoteUnlock.OP_CLOSE | ConfigRemoteUnlock.OP_OPEN) { 35 | this.opValue = opValue; 36 | this.opType = ConfigRemoteUnlock.OP_TYPE_MODIFY; 37 | } 38 | 39 | getValue(): ConfigRemoteUnlock.OP_CLOSE | ConfigRemoteUnlock.OP_OPEN | void { 40 | if (typeof this.opValue != "undefined") { 41 | return this.opValue; 42 | } 43 | } 44 | 45 | getBatteryCapacity(): number { 46 | if (typeof this.batteryCapacity != "undefined") { 47 | return this.batteryCapacity; 48 | } else { 49 | return -1; 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /src/constant/CallbackOperationType.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export enum CallbackOperationType { 4 | 5 | UNKNOWN_TYPE = -1, 6 | 7 | INIT_LOCK = 2, 8 | RESET_LOCK = 3, 9 | CONTROL_LOCK = 4, 10 | RESET_KEY = 5, 11 | GET_MUTE_MODE_STATE = 6, 12 | SET_MUTE_MODE_STATE = 7, 13 | GET_REMOTE_UNLOCK_STATE = 8, 14 | SET_REMOTE_UNLOCK_STATE = 9, 15 | GET_PASSCODE_VISIBLE_STATE = 10, 16 | SET_PASSCODE_VISIBLE_STATE = 11, 17 | SET_PASSAGE_MODE = 12, 18 | DELETE_PASSAGE_MODE = 13, 19 | CLEAR_PASSAGE_MODE = 14, 20 | GET_PASSAGE_MODE = 15, 21 | SET_LOCK_TIME = 16, 22 | GET_LOCK_TIME = 17, 23 | GET_OPERATION_LOG = 18, 24 | GET_ELECTRIC_QUALITY = 19, 25 | GET_LOCK_VERSION = 20, 26 | GET_SPECIAL_VALUE = 21, 27 | RECOVERY_DATA = 22, 28 | GET_SYSTEM_INFO = 23, 29 | CREATE_CUSTOM_PASSCODE = 24, 30 | GET_LOCK_STATUS = 25, 31 | SET_AUTO_LOCK_PERIOD = 26, 32 | MODIFY_PASSCODE = 27, 33 | DELETE_PASSCODE = 28, 34 | RESET_PASSCODE = 29, 35 | GET_ALL_VALID_PASSCODES = 30, 36 | GET_PASSCODE_INFO = 31, 37 | MODIFY_ADMIN_PASSCODE = 32, 38 | GET_ADMIN_PASSCODE = 33, 39 | ADD_IC_CARD = 34, 40 | MODIFY_IC_CARD_PERIOD = 35, 41 | ADD_FINGERPRINT = 36, 42 | MODIFY_FINGEPRINT_PERIOD = 37, 43 | GET_ALL_IC_CARDS = 38, 44 | DELETE_IC_CARD = 39, 45 | CLEAR_ALL_IC_CARD = 40, 46 | GET_ALL_FINGERPRINTS = 41, 47 | DELETE_FINGERPRINT = 42, 48 | CLEAR_ALL_FINGERPRINTS = 43, 49 | WRITE_FINGERPRINT_DATA = 44, 50 | ENTER_DFU_MODE = 45, 51 | SET_NB_SERVER = 46, 52 | INIT_KEYPAD = 47, 53 | GET_LOCK_FREEZE_STATE = 48, 54 | SET_LOCK_FREEZE_STATE = 49, 55 | GET_LIGHT_TIME = 50, 56 | SET_LIGHT_TIME = 51, 57 | SET_HOTEL_CARD_SECTION = 52, 58 | CONNECT_LOCK = 53, 59 | SET_LOCK_CONFIG = 54, 60 | GET_LOCK_CONFIG = 55, 61 | SET_HOTEL_DATA = 56, 62 | SET_ELEVATOR_CONTROLABLE_FLOORS = 57, 63 | SET_ELEVATOR_WORK_MODE = 58, 64 | GET_AUTO_LOCK_PERIOD = 59, 65 | 66 | ADD_CYCLIC_IC_CARD = 60, 67 | ADD_CYCLIC_FINGERPRINT = 61, 68 | 69 | SET_NB_ACTIVATE_CONFIG = 62, 70 | GET_NB_ACTIVATE_CONFIG = 63, 71 | SET_NB_ACTIVATE_MODE = 64, 72 | GET_NB_ACITATE_MODE = 65, 73 | 74 | } -------------------------------------------------------------------------------- /src/api/Commands/index.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export { UnknownCommand } from "./UnknownCommand"; 4 | export { InitCommand } from "./InitCommand"; 5 | export { AESKeyCommand } from "./AESKeyCommand"; 6 | export { AddAdminCommand } from "./AddAdminCommand"; 7 | export { CalibrationTimeCommand } from "./CalibrationTimeCommand"; 8 | export { DeviceFeaturesCommand } from "./DeviceFeaturesCommand"; 9 | export { GetSwitchStateCommand } from "./GetSwitchStateCommand"; 10 | export { AudioManageCommand } from "./AudioManageCommand"; 11 | export { ScreenPasscodeManageCommand } from "./ScreenPasscodeManageCommand"; 12 | export { AutoLockManageCommand } from "./AutoLockManageCommand"; 13 | export { ControlLampCommand } from "./ControlLampCommand"; 14 | export { SetAdminKeyboardPwdCommand } from "./SetAdminKeyboardPwdCommand"; 15 | export { InitPasswordsCommand } from "./InitPasswordsCommand"; 16 | export { ControlRemoteUnlockCommand } from "./ControlRemoteUnlockCommand"; 17 | export { OperateFinishedCommand } from "./OperateFinishedCommand"; 18 | export { ReadDeviceInfoCommand } from "./ReadDeviceInfoCommand"; 19 | export { GetAdminCodeCommand } from "./GetAdminCodeCommand"; 20 | export { CheckAdminCommand } from "./CheckAdminCommand"; 21 | export { CheckRandomCommand } from "./CheckRandomCommand"; 22 | export { ResetLockCommand } from "./ResetLockCommand"; 23 | export { CheckUserTimeCommand } from "./CheckUserTimeCommand"; 24 | export { UnlockCommand, UnlockDataInterface } from "./UnlockCommand"; 25 | export { LockCommand } from "./LockCommand"; 26 | export { PassageModeCommand, PassageModeData } from "./PassageModeCommand"; 27 | export { SearchBicycleStatusCommand } from "./SearchBicycleStatusCommand"; 28 | export { ManageKeyboardPasswordCommand } from "./ManageKeyboardPasswordCommand"; 29 | export { GetKeyboardPasswordsCommand, KeyboardPassCode } from "./GetKeyboardPasswordsCommand"; 30 | export { ManageICCommand, ICCard } from "./ManageICCommand"; 31 | export { CyclicDateCommand } from "./CyclicDateCommand"; 32 | export { ManageFRCommand, Fingerprint } from "./ManageFRCommand"; 33 | export { OperationLogCommand, LogEntry } from "./OperationLogCommand"; -------------------------------------------------------------------------------- /src/api/Commands/LockCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import moment from "moment"; 4 | import { CommandType } from "../../constant/CommandType"; 5 | import { Command } from "../Command"; 6 | import { UnlockDataInterface } from "./UnlockCommand"; 7 | 8 | export class LockCommand extends Command { 9 | static COMMAND_TYPE: CommandType = CommandType.COMM_FUNCTION_LOCK; 10 | 11 | private sum?: number; 12 | private uid?: number; 13 | private uniqueid?: number; 14 | private dateTime?: string; 15 | private batteryCapacity?: number; 16 | 17 | protected processData(): void { 18 | if (this.commandData && this.commandData.length > 0) { 19 | this.batteryCapacity = this.commandData.readUInt8(0); 20 | if (this.commandData.length >= 15) { 21 | this.uid = this.commandData.readUInt32BE(1); 22 | this.uniqueid = this.commandData.readUInt32BE(5); 23 | const dateObj = { 24 | year: 2000 + this.commandData.readUInt8(9), 25 | month: this.commandData.readUInt8(10) - 1, 26 | day: this.commandData.readUInt8(11), 27 | hour: this.commandData.readUInt8(12), 28 | minute: this.commandData.readUInt8(13), 29 | second: this.commandData.readUInt8(14) 30 | } 31 | this.dateTime = moment(dateObj).format("YYMMDDHHmmss"); 32 | } 33 | } 34 | } 35 | 36 | build(): Buffer { 37 | if (this.sum) { 38 | const data = Buffer.alloc(8); 39 | data.writeUInt32BE(this.sum, 0); 40 | data.writeUInt32BE(moment().unix(), 4); 41 | return data; 42 | } 43 | return Buffer.from([]); 44 | } 45 | 46 | setSum(psFromLock: number, unlockKey: number) { 47 | this.sum = psFromLock + unlockKey; 48 | } 49 | 50 | getUnlockData(): UnlockDataInterface { 51 | const data: UnlockDataInterface = { 52 | uid: this.uid, 53 | uniqueid: this.uniqueid, 54 | dateTime: this.dateTime, 55 | batteryCapacity: this.batteryCapacity 56 | } 57 | return data; 58 | } 59 | 60 | getBatteryCapacity(): number { 61 | if (typeof this.batteryCapacity != "undefined") { 62 | return this.batteryCapacity; 63 | } else { 64 | return -1; 65 | } 66 | } 67 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | 106 | package-lock.json 107 | lockData.json 108 | docs/capture/ 109 | myEnv.sh -------------------------------------------------------------------------------- /src/api/Commands/UnlockCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import moment from "moment"; 4 | import { CommandType } from "../../constant/CommandType"; 5 | import { Command } from "../Command"; 6 | 7 | export interface UnlockDataInterface { 8 | uid?: number; 9 | uniqueid?: number; 10 | dateTime?: string; 11 | batteryCapacity?: number; 12 | } 13 | 14 | export class UnlockCommand extends Command { 15 | static COMMAND_TYPE: CommandType = CommandType.COMM_UNLOCK; 16 | 17 | private sum?: number; 18 | private uid?: number; 19 | private uniqueid?: number; 20 | private dateTime?: string; 21 | private batteryCapacity?: number; 22 | 23 | protected processData(): void { 24 | if (this.commandData && this.commandData.length > 0) { 25 | this.batteryCapacity = this.commandData.readUInt8(0); 26 | if (this.commandData.length >= 15) { 27 | this.uid = this.commandData.readUInt32BE(1); 28 | this.uniqueid = this.commandData.readUInt32BE(5); 29 | const dateObj = { 30 | year: 2000 + this.commandData.readUInt8(9), 31 | month: this.commandData.readUInt8(10) - 1, 32 | day: this.commandData.readUInt8(11), 33 | hour: this.commandData.readUInt8(12), 34 | minute: this.commandData.readUInt8(13), 35 | second: this.commandData.readUInt8(14) 36 | } 37 | this.dateTime = moment(dateObj).format("YYMMDDHHmmss"); 38 | } 39 | } 40 | } 41 | 42 | build(): Buffer { 43 | if (this.sum) { 44 | const data = Buffer.alloc(8); 45 | data.writeUInt32BE(this.sum, 0); 46 | data.writeUInt32BE(moment().unix(), 4); 47 | return data; 48 | } 49 | return Buffer.from([]); 50 | } 51 | 52 | setSum(psFromLock: number, unlockKey: number) { 53 | this.sum = psFromLock + unlockKey; 54 | } 55 | 56 | getUnlockData(): UnlockDataInterface { 57 | const data: UnlockDataInterface = { 58 | uid: this.uid, 59 | uniqueid: this.uniqueid, 60 | dateTime: this.dateTime, 61 | batteryCapacity: this.batteryCapacity 62 | } 63 | return data; 64 | } 65 | 66 | getBatteryCapacity(): number { 67 | if (typeof this.batteryCapacity != "undefined") { 68 | return this.batteryCapacity; 69 | } else { 70 | return -1; 71 | } 72 | } 73 | } -------------------------------------------------------------------------------- /tools/dumpCapture.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | csv = require('node-csv').createParser(); 3 | const chalk = require('chalk'); 4 | const { TTLockClient, sleep, CommandEnvelope, CommandType } = require('../dist'); 5 | 6 | let isAesNext = false; 7 | let aes = Buffer.from([ 8 | 0x98, 0x76, 0x23, 0xE8, 9 | 0xA9, 0x23, 0xA1, 0xBB, 10 | 0x3D, 0x9E, 0x7D, 0x03, 11 | 0x78, 0x12, 0x45, 0x88 12 | ]); 13 | 14 | csv.parseFile('docs/export_mhacroms_raw.csv', function(err, input) { 15 | // console.log(input); 16 | var data = ""; 17 | var dir = ""; 18 | var counter = 0; 19 | for(const row of input) { 20 | // console.log(row); 21 | if (counter > 0) { // ignore first row 22 | if (row[1] != dir) { 23 | if (data != "") { 24 | console.log(chalk.red("Leftover data"), dir, data); 25 | console.log(""); 26 | } 27 | data = ""; 28 | dir = row[1]; 29 | } 30 | data += row[0]; 31 | if (data.substring(data.length - 4, data.length) == "0d0a") { 32 | // process 33 | // console.log("Process", dir, data); 34 | process(data, dir); 35 | // clear 36 | data = ""; 37 | } 38 | } 39 | counter++; 40 | }; 41 | }); 42 | 43 | function process(data, dir) { 44 | try { 45 | let strippedData = JSON.parse(JSON.stringify(data.substring(0, data.length - 4))); 46 | let binData = Buffer.from(strippedData, "hex"); 47 | if (dir == "Rcvd") { 48 | console.log(chalk.green("Rcvd: " + binData.toString("hex"))); 49 | } else { 50 | console.log(chalk.cyan("Sent: " + binData.toString("hex"))); 51 | } 52 | let envelope = CommandEnvelope.createFromRawData(binData, aes); 53 | if (dir == "Rcvd") { 54 | let command; 55 | try { 56 | command = envelope.getCommand(); 57 | if (envelope.commandType == 25) { 58 | aes = command.aesKey; 59 | } 60 | console.log(command); 61 | } catch (error) { 62 | console.log(envelope); 63 | } 64 | } else { 65 | // console.log(envelope); 66 | console.log("Command type: 0x" + envelope.getCommandType().toString(16)); 67 | console.log("Command data: " + envelope.getData().toString("hex")); 68 | } 69 | console.log(""); 70 | 71 | } catch (error) { 72 | console.error(error); 73 | } 74 | } -------------------------------------------------------------------------------- /src/api/Commands/InitPasswordsCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import moment from "moment"; 4 | import { CommandType } from "../../constant/CommandType"; 5 | import { Command } from "../Command"; 6 | 7 | export interface CodeSecret { 8 | year: number, 9 | code: number, 10 | secret: string 11 | } 12 | 13 | export class InitPasswordsCommand extends Command { 14 | static COMMAND_TYPE: CommandType = CommandType.COMM_INIT_PASSWORDS; 15 | protected pwdInfo?: CodeSecret[]; 16 | 17 | protected processData(): void { 18 | // nothing to do here 19 | } 20 | 21 | build(): Buffer { 22 | let year = this.calculateYear(); 23 | this.pwdInfo = this.generateCodeSecret(year); 24 | 25 | // first data byte is the year 26 | let buffers: Buffer[] = [ 27 | Buffer.from([year % 100]), // last 2 digits of the year 28 | ]; 29 | for (let i = 0; i < 10; i++) { 30 | buffers.push(this.combineCodeSecret(this.pwdInfo[i].code, this.pwdInfo[i].secret)); 31 | } 32 | 33 | return Buffer.concat(buffers); 34 | } 35 | 36 | getPwdInfo(): CodeSecret[] | void { 37 | if (this.pwdInfo) { 38 | return this.pwdInfo; 39 | } 40 | } 41 | 42 | private generateCodeSecret(year: number): CodeSecret[] { 43 | let generated: CodeSecret[] = []; 44 | for (let i = 0; i < 10; i++, year++) { 45 | let secret: string = ""; 46 | for (let j = 0; j < 10; j++) { 47 | secret += Math.floor(Math.random() * 10).toString(); 48 | } 49 | generated.push({ 50 | year: year % 100, 51 | code: Math.floor(Math.random() * 1071), 52 | secret: secret 53 | }); 54 | } 55 | return generated; 56 | } 57 | 58 | private combineCodeSecret(code: number, secret: string): Buffer { 59 | const res = Buffer.alloc(6); 60 | res[0] = code >> 4; 61 | res[1] = code << 4 & 0xFF; 62 | const bigSec = BigInt(secret); 63 | const sec = Buffer.alloc(8); 64 | sec.writeBigInt64BE(bigSec); 65 | sec.copy(res, 2, 4); 66 | res[1] = res[1] | sec[3]; 67 | return res; 68 | } 69 | 70 | private calculateYear(): number { 71 | if (moment().format("MMDD") == "0101") { // someone does not like 1st of Jan 72 | return parseInt(moment().subtract(1, "years").format("YYYY")); 73 | } else { 74 | return parseInt(moment().format("YYYY")); 75 | } 76 | } 77 | } -------------------------------------------------------------------------------- /src/scanner/DeviceInterface.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { EventEmitter } from "events"; 4 | 5 | export interface DeviceInterface extends EventEmitter { 6 | id: string; 7 | uuid: string; 8 | name: string; 9 | address: string; 10 | addressType: string; 11 | connectable: boolean; 12 | rssi: number; 13 | mtu: number; 14 | manufacturerData: Buffer; 15 | services: Map; 16 | busy: boolean; 17 | checkBusy(): boolean; 18 | resetBusy(): boolean; 19 | connect(): Promise; 20 | disconnect(): Promise; 21 | discoverAll(): Promise>; 22 | discoverServices(): Promise>; 23 | readCharacteristics(): Promise; 24 | toJSON(asObject: boolean): string | Object; 25 | toString(): string; 26 | 27 | on(event: "connected", listener: () => void): this; 28 | on(event: "disconnected", listener: () => void): this; 29 | } 30 | 31 | export interface ServiceInterface { 32 | uuid: string; 33 | name?: string; 34 | type?: string; 35 | includedServiceUuids: string[]; 36 | characteristics: Map; 37 | getUUID(): string; 38 | discoverCharacteristics(): Promise>; 39 | readCharacteristics(): Promise>; 40 | toJSON(asObject: boolean): string | Object; 41 | toString(): string; 42 | } 43 | 44 | export interface CharacteristicInterface extends EventEmitter { 45 | uuid: string; 46 | name?: string; 47 | type?: string; 48 | properties: string[]; 49 | isReading: boolean; 50 | lastValue?: Buffer; 51 | descriptors: Map; 52 | getUUID(): string; 53 | discoverDescriptors(): Promise>; 54 | read(): Promise; 55 | write(data: Buffer, withoutResponse: boolean): Promise; 56 | subscribe(): Promise; 57 | toJSON(asObject: boolean): string | Object; 58 | toString(): string; 59 | 60 | on(event: "dataRead", listener: (data: Buffer) => void): this; 61 | } 62 | 63 | export interface DescriptorInterface { 64 | uuid: string; 65 | name?: string; 66 | type?: string; 67 | lastValue?: Buffer; 68 | readValue(): Promise; 69 | writeValue(data: Buffer): Promise; 70 | toJSON(asObject: boolean): string | Object; 71 | toString(): string; 72 | } -------------------------------------------------------------------------------- /src/scanner/noble/NobleDescriptor.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { Descriptor } from "@abandonware/noble"; 4 | import { EventEmitter } from "events"; 5 | import { DescriptorInterface } from "../DeviceInterface"; 6 | import { NobleDevice } from "./NobleDevice"; 7 | 8 | export class NobleDescriptor extends EventEmitter implements DescriptorInterface { 9 | uuid: string; 10 | name?: string | undefined; 11 | type?: string | undefined; 12 | isReading: boolean = false; 13 | lastValue?: Buffer; 14 | private device: NobleDevice; 15 | private descriptor: Descriptor; 16 | 17 | constructor(device: NobleDevice, descriptor: Descriptor) { 18 | super(); 19 | this.device = device; 20 | this.descriptor = descriptor; 21 | this.uuid = descriptor.uuid; 22 | this.name = descriptor.name; 23 | this.type = descriptor.type; 24 | this.descriptor.on("valueRead", this.onRead.bind(this)); 25 | } 26 | 27 | async readValue(): Promise { 28 | this.device.checkBusy(); 29 | if (!this.device.connected) { 30 | this.device.resetBusy(); 31 | throw new Error("NobleDevice is not connected"); 32 | } 33 | this.isReading = true; 34 | try { 35 | this.lastValue = await this.descriptor.readValueAsync(); 36 | } catch (error) { 37 | console.error(error); 38 | } 39 | this.isReading = false; 40 | this.device.resetBusy(); 41 | return this.lastValue; 42 | } 43 | 44 | async writeValue(data: Buffer): Promise { 45 | this.device.checkBusy(); 46 | if (!this.device.connected) { 47 | this.device.resetBusy(); 48 | throw new Error("NobleDevice is not connected"); 49 | } 50 | 51 | await this.descriptor.writeValueAsync(data); 52 | this.lastValue = data; 53 | 54 | this.device.resetBusy(); 55 | } 56 | 57 | private onRead(data: Buffer) { 58 | // if the read notification comes from a manual read, just ignore it 59 | // we are only interested in data pushed by the device 60 | if (!this.isReading) { 61 | this.lastValue = data; 62 | console.log("Descriptor received data", data); 63 | this.emit("valueRead", this.lastValue); 64 | } 65 | } 66 | 67 | toJSON(asObject: boolean = false) { 68 | const json = { 69 | uuid: this.uuid, 70 | name: this.name, 71 | type: this.type, 72 | value: this.lastValue?.toString("hex") 73 | } 74 | 75 | if (asObject) { 76 | return json; 77 | } else { 78 | return JSON.stringify(json); 79 | } 80 | } 81 | 82 | toString(): string { 83 | return this.descriptor.toString(); 84 | } 85 | } -------------------------------------------------------------------------------- /src/device/TTDevice.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { EventEmitter } from "events"; 4 | import { LockType } from "../constant/Lock"; 5 | 6 | export class TTDevice extends EventEmitter { 7 | // public data 8 | id: string = ""; 9 | uuid: string = ""; 10 | name: string = ""; 11 | manufacturer: string = "unknown"; 12 | model: string = "unknown"; 13 | hardware: string = "unknown"; 14 | firmware: string = "unknown"; 15 | address: string = ""; 16 | rssi: number = 0; 17 | /** @type {byte} */ 18 | protocolType: number = 0; 19 | /** @type {byte} */ 20 | protocolVersion: number = 0; 21 | /** @type {byte} */ 22 | scene: number = 0; 23 | /** @type {byte} */ 24 | groupId: number = 0; 25 | /** @type {byte} */ 26 | orgId: number = 0; 27 | /** @type {byte} */ 28 | lockType: LockType = LockType.UNKNOWN; 29 | isTouch: boolean = false; 30 | isUnlock: boolean = false; 31 | hasEvents: boolean = true; 32 | isSettingMode: boolean = false; 33 | /** @type {byte} */ 34 | txPowerLevel: number = 0; 35 | /** @type {byte} */ 36 | batteryCapacity: number = -1; 37 | /** @type {number} */ 38 | date: number = 0; 39 | isWristband: boolean = false; 40 | isRoomLock: boolean = false; 41 | isSafeLock: boolean = false; 42 | isBicycleLock: boolean = false; 43 | isLockcar: boolean = false; 44 | isGlassLock: boolean = false; 45 | isPadLock: boolean = false; 46 | isCyLinder: boolean = false; 47 | isRemoteControlDevice: boolean = false; 48 | isDfuMode: boolean = false; 49 | isNoLockService: boolean = false; 50 | remoteUnlockSwitch: number = 0; 51 | disconnectStatus: number = 0; 52 | parkStatus: number = 0; 53 | 54 | toJSON(asObject:boolean = false): string | Object { 55 | const temp = new TTDevice(); 56 | var json = {}; 57 | 58 | // exclude keys that we don't need from the export 59 | const excludedKeys = new Set([ 60 | "_eventsCount" 61 | ]); 62 | 63 | Object.getOwnPropertyNames(temp).forEach((key) => { 64 | if (!excludedKeys.has(key)) { 65 | const val = Reflect.get(this, key); 66 | if (typeof val != 'undefined' && ((typeof val == "string" && val != "") || typeof val != "string")) { 67 | if ((typeof val) == "object") { 68 | if (val.length && val.length > 0) { 69 | Reflect.set(json, key, val.toString('hex')); 70 | } 71 | } else { 72 | Reflect.set(json, key, val); 73 | } 74 | } 75 | } 76 | }); 77 | 78 | if (asObject) { 79 | return json; 80 | } else { 81 | return JSON.stringify(json); 82 | } 83 | } 84 | } -------------------------------------------------------------------------------- /src/api/Commands/DeviceFeaturesCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { CommandType } from "../../constant/CommandType"; 4 | import { FeatureValue } from "../../constant/FeatureValue"; 5 | import { padHexString } from "../../util/digitUtil"; 6 | import { Command } from "../Command"; 7 | 8 | export class DeviceFeaturesCommand extends Command { 9 | static COMMAND_TYPE: CommandType = CommandType.COMM_SEARCHE_DEVICE_FEATURE; 10 | 11 | private batteryCapacity?: number; 12 | private special?: number; 13 | private featureList?: Set; 14 | 15 | protected processData(): void { 16 | if (this.commandData) { 17 | this.batteryCapacity = this.commandData.readInt8(0); 18 | this.special = this.commandData.readInt32BE(1); 19 | console.log(this.commandData); 20 | const features = this.commandData.readUInt32BE(1); 21 | this.featureList = this.processFeatures(features); 22 | } 23 | } 24 | 25 | protected readFeatures(data?: Buffer): string { 26 | if (data) { 27 | let features: string = ""; 28 | let temp: string = ""; 29 | for (let i = 0; i < data.length; i++) { 30 | temp += padHexString(data.readInt8(i).toString(16)); 31 | if (i % 4 == 3) { 32 | features = temp + features; 33 | temp = ""; 34 | } 35 | } 36 | let i = 0; 37 | while (i < features.length && features.charAt(i) == "0") { 38 | i++; 39 | } 40 | if (i == features.length) { 41 | return "0"; 42 | } 43 | return features.substring(i).toUpperCase(); 44 | } else { 45 | return ""; 46 | } 47 | } 48 | 49 | protected processFeatures(features: number): Set { 50 | let featureList: Set = new Set(); 51 | const featuresBinary = features.toString(2); 52 | Object.values(FeatureValue).forEach((feature) => { 53 | if (typeof feature != "string" && featuresBinary.length > (feature as number)) { 54 | if (featuresBinary.charAt(featuresBinary.length - (feature as number) - 1) == "1") { 55 | featureList.add(feature as FeatureValue); 56 | } 57 | } 58 | }); 59 | return featureList; 60 | } 61 | 62 | getBatteryCapacity(): number { 63 | if (this.batteryCapacity) { 64 | return this.batteryCapacity; 65 | } else { 66 | return -1; 67 | } 68 | } 69 | 70 | getSpecial(): number { 71 | if (this.special) { 72 | return this.special; 73 | } else { 74 | return 0; 75 | } 76 | } 77 | 78 | getFeaturesList(): Set { 79 | if (this.featureList) { 80 | return this.featureList; 81 | } else { 82 | return new Set(); 83 | } 84 | } 85 | 86 | build(): Buffer { 87 | return Buffer.from([]); 88 | } 89 | 90 | } -------------------------------------------------------------------------------- /src/api/ValidityInfo.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import moment from "moment"; 4 | import { DateConstant } from "../constant/DateConstant"; 5 | 6 | export enum ValidityType { 7 | TIMED = 1, 8 | CYCLIC = 4 9 | } 10 | 11 | export interface CyclicConfig { 12 | /** 1-7 monday-sunday */ 13 | weekDay: number, 14 | /** minute of the day for start (Ex: 02:14 = 2*60 + 14 = 134) */ 15 | startTime: number; 16 | /** minute of the day to end (Ex: 16:48 = 16*60 + 48 = 1008) */ 17 | endTime: number; 18 | } 19 | 20 | export class ValidityInfo { 21 | private type: ValidityType; 22 | private startDate: moment.Moment; 23 | private endDate: moment.Moment; 24 | private cycles: CyclicConfig[]; 25 | 26 | constructor(type: ValidityType = ValidityType.TIMED, startDate: string = DateConstant.START_DATE_TIME, endDdate: string = DateConstant.END_DATE_TIME) { 27 | this.type = type; 28 | this.startDate = moment(startDate, "YYYYMMDDHHmm"); 29 | if (!this.startDate.isValid()) { 30 | throw new Error("Invalid startDate"); 31 | } 32 | this.endDate = moment(endDdate, "YYYYMMDDHHmm"); 33 | if (!this.endDate.isValid()) { 34 | throw new Error("Invalid endDate"); 35 | } 36 | this.cycles = []; 37 | } 38 | 39 | setType(type: ValidityType) { 40 | this.type = type; 41 | } 42 | 43 | addCycle(cycle: CyclicConfig): boolean { 44 | if (this.isValidCycle(cycle)) { 45 | this.cycles.push(cycle); 46 | return true; 47 | } 48 | return false; 49 | } 50 | 51 | setStartDate(startDate: string): boolean { 52 | let date = moment(startDate, "YYYYMMDDHHmm"); 53 | if (date.isValid()) { 54 | this.startDate = date; 55 | return true; 56 | } 57 | return false; 58 | } 59 | 60 | setEndDate(endDate: string): boolean { 61 | let date = moment(endDate, "YYYYMMDDHHmm"); 62 | if (date.isValid()) { 63 | this.endDate = date; 64 | return true; 65 | } 66 | return false; 67 | } 68 | 69 | getType(): ValidityType { 70 | return this.type; 71 | } 72 | 73 | getStartDate(): string { 74 | return this.startDate.format("YYYYMMDDHHmm"); 75 | } 76 | 77 | getStartDateMoment(): moment.Moment { 78 | return this.startDate; 79 | } 80 | 81 | getEndDate(): string { 82 | return this.endDate.format("YYYYMMDDHHmm"); 83 | } 84 | 85 | geetEndDateMoment(): moment.Moment { 86 | return this.endDate; 87 | } 88 | 89 | getCycles(): CyclicConfig[] { 90 | return this.cycles; 91 | } 92 | 93 | isValidCycle(cycle: CyclicConfig) { 94 | if (cycle.weekDay < 1 || cycle.weekDay > 7) return false; 95 | if (cycle.startTime < 0 || cycle.startTime > 24 * 60) return false; 96 | if (cycle.endTime < 0 || cycle.endTime > 24 * 60) return false; 97 | return true; 98 | } 99 | } -------------------------------------------------------------------------------- /src/scanner/BluetoothLeService.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { EventEmitter } from "events"; 4 | import { ScannerInterface, ScannerOptions, ScannerType } from "./ScannerInterface"; 5 | import { NobleScanner } from "./noble/NobleScanner"; 6 | import { TTBluetoothDevice } from "../device/TTBluetoothDevice"; 7 | import { DeviceInterface } from "./DeviceInterface"; 8 | import { NobleScannerWebsocket } from "./noble/NobleScannerWebsocket"; 9 | 10 | export { ScannerType } from "./ScannerInterface"; 11 | export const TTLockUUIDs: string[] = ["1910", "00001910-0000-1000-8000-00805f9b34fb"]; 12 | 13 | export interface BluetoothLeService { 14 | on(event: "ready", listener: () => void): this; 15 | on(event: "discover", listener: (device: TTBluetoothDevice) => void): this; 16 | on(event: "scanStart", listener: () => void): this; 17 | on(event: "scanStop", listener: () => void): this; 18 | } 19 | 20 | export class BluetoothLeService extends EventEmitter implements BluetoothLeService { 21 | private scanner: ScannerInterface; 22 | private btDevices: Map; 23 | 24 | constructor(uuids: string[] = TTLockUUIDs, scannerType: ScannerType = "noble", scannerOptions: ScannerOptions) { 25 | super(); 26 | this.btDevices = new Map(); 27 | if (scannerType == "noble") { 28 | this.scanner = new NobleScanner(uuids); 29 | } else if (scannerType == "noble-websocket") { 30 | this.scanner = new NobleScannerWebsocket(uuids, 31 | scannerOptions.websocketHost, 32 | scannerOptions.websocketPort, 33 | scannerOptions.websocketAesKey, 34 | scannerOptions.websocketUsername, 35 | scannerOptions.websocketPassword); 36 | } else { 37 | throw "Invalid parameters"; 38 | } 39 | this.scanner.on("ready", () => this.emit("ready")); 40 | this.scanner.on("discover", this.onDiscover.bind(this)); 41 | this.scanner.on("scanStart", () => this.emit("scanStart")); 42 | this.scanner.on("scanStop", () => this.emit("scanStop")); 43 | } 44 | 45 | async startScan(passive: boolean = false): Promise { 46 | return await this.scanner.startScan(passive); 47 | } 48 | 49 | async stopScan(): Promise { 50 | return await this.scanner.stopScan(); 51 | } 52 | 53 | isScanning(): boolean { 54 | return this.scanner.getState() == "scanning"; 55 | } 56 | 57 | forgetDevice(id: string) { 58 | this.btDevices.delete(id); 59 | } 60 | 61 | private onDiscover(device: DeviceInterface) { 62 | // TODO: move device storage to TTLockClient 63 | // check if the device was previously discovered and update 64 | if(this.btDevices.has(device.id)) { 65 | const ttDevice = this.btDevices.get(device.id); 66 | if (typeof ttDevice != 'undefined') { 67 | ttDevice.updateFromDevice(device); 68 | // this.emit("discover", ttDevice); 69 | } 70 | } else { 71 | const ttDevice = TTBluetoothDevice.createFromDevice(device, this.scanner); 72 | this.btDevices.set(device.id, ttDevice); 73 | this.emit("discover", ttDevice); 74 | } 75 | } 76 | } -------------------------------------------------------------------------------- /src/scanner/noble/NobleService.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { Service } from "@abandonware/noble"; 4 | import { CharacteristicInterface, ServiceInterface } from "../DeviceInterface"; 5 | import { NobleCharacteristic } from "./NobleCharacteristic"; 6 | import { NobleDevice } from "./NobleDevice"; 7 | 8 | export class NobleService implements ServiceInterface { 9 | uuid: string; 10 | name: string; 11 | type: string; 12 | includedServiceUuids: string[]; 13 | characteristics: Map = new Map(); 14 | private device: NobleDevice; 15 | private service: Service; 16 | 17 | constructor(device: NobleDevice, service: Service) { 18 | this.device = device; 19 | this.service = service; 20 | this.uuid = service.uuid; 21 | this.name = service.name; 22 | this.type = service.type; 23 | this.includedServiceUuids = service.includedServiceUuids; 24 | // also add characteristics if they exist 25 | if (service.characteristics && service.characteristics.length > 0) { 26 | this.characteristics = new Map(); 27 | service.characteristics.forEach((characteristic) => { 28 | const c = new NobleCharacteristic(this.device, characteristic); 29 | this.characteristics.set(c.getUUID(), c); 30 | }); 31 | } 32 | } 33 | 34 | getUUID(): string { 35 | if (this.uuid.length > 4) { 36 | return this.uuid.replace("-0000-1000-8000-00805f9b34fb", "").replace("0000", ""); 37 | } 38 | return this.uuid; 39 | } 40 | 41 | async discoverCharacteristics(): Promise> { 42 | try { 43 | this.characteristics = new Map(); 44 | this.device.checkBusy(); 45 | const characteristics = await this.service.discoverCharacteristicsAsync(); 46 | this.device.resetBusy(); 47 | characteristics.forEach((characteristic) => { 48 | const c = new NobleCharacteristic(this.device, characteristic); 49 | this.characteristics.set(c.getUUID(), c); 50 | }); 51 | return this.characteristics; 52 | } catch (error) { 53 | console.error(error); 54 | this.device.resetBusy(); 55 | return new Map(); 56 | } 57 | } 58 | 59 | async readCharacteristics(): Promise> { 60 | if (this.characteristics.size == 0) { 61 | await this.discoverCharacteristics(); 62 | } 63 | 64 | for (let [uuid, characteristic] of this.characteristics) { 65 | await characteristic.read(); 66 | } 67 | 68 | return this.characteristics; 69 | } 70 | 71 | toJSON(asObject: boolean): string | Object { 72 | let json: Record = { 73 | uuid: this.uuid, 74 | name: this.name, 75 | type: this.type, 76 | characteristics: {} 77 | }; 78 | this.characteristics.forEach((characteristic) => { 79 | json.characteristics[characteristic.uuid] = characteristic.toJSON(true); 80 | }); 81 | 82 | if (asObject) { 83 | return json; 84 | } else { 85 | return JSON.stringify(json); 86 | } 87 | } 88 | 89 | toString(): string { 90 | return this.service.toString(); 91 | } 92 | } -------------------------------------------------------------------------------- /examples/listen.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, LogOperate, LockedStatus } = require('../dist'); 4 | const settingsFile = "lockData.json"; 5 | 6 | async function doStuff() { 7 | let lockData = await require("./common/loadData")(settingsFile); 8 | let options = require("./common/options")(lockData); 9 | 10 | const client = new TTLockClient(options); 11 | await client.prepareBTService(); 12 | client.startMonitor(); 13 | console.log("Scan started"); 14 | client.on("foundLock", async (lock) => { 15 | console.log(lock.toJSON()); 16 | console.log(); 17 | 18 | lock.on("locked", (l) => { 19 | console.log("Lock was locked"); 20 | }); 21 | 22 | lock.on("unlocked", (l) => { 23 | console.log("Lock was unlocked"); 24 | }); 25 | 26 | lock.on("updated", async (l, p) => { 27 | if (p.newEvents && l.hasNewEvents()) { 28 | if (!l.isConnected()) { 29 | console.log("Reconnecting to lock to read log"); 30 | const res = await l.connect(); 31 | if (res == false) { 32 | console.log("Unable to connect to lock"); 33 | process.exit(2); 34 | } 35 | } 36 | let operations = await l.getOperationLog(); 37 | console.log(operations); 38 | for (let op of operations) { 39 | switch (op.recordType) { 40 | case LogOperate.OPERATE_TYPE_MOBILE_UNLOCK: 41 | case LogOperate.OPERATE_TYPE_KEYBOARD_PASSWORD_UNLOCK: 42 | case LogOperate.OPERATE_TYPE_IC_UNLOCK_SUCCEED: 43 | case LogOperate.OPERATE_TYPE_BONG_UNLOCK_SUCCEED: 44 | case LogOperate.OPERATE_TYPE_FR_UNLOCK_SUCCEED: 45 | case LogOperate.OPERATE_KEY_UNLOCK: 46 | case LogOperate.GATEWAY_UNLOCK: 47 | case LogOperate.ILLAGEL_UNLOCK: 48 | case LogOperate.DOOR_SENSOR_UNLOCK: 49 | // unlock event 50 | console.log(">>>>>> Lock was unlocked <<<<<<"); 51 | break; 52 | default: 53 | // not unlock event 54 | } 55 | } 56 | const status = await l.getLockStatus(); 57 | if (status == LockedStatus.LOCKED) { 58 | console.log(">>>>>> Lock is now locked <<<<<<"); 59 | } else if (status == LockedStatus.UNLOCKED) { 60 | console.log(">>>>>> Lock is now unlocked <<<<<<"); 61 | } 62 | } 63 | if (p.lockedStatus) { 64 | const status = await l.getLockStatus(); 65 | if (status == LockedStatus.LOCKED) { 66 | console.log(">>>>>> Lock is now locked from new event <<<<<<"); 67 | } 68 | } 69 | 70 | await l.disconnect(); 71 | }); 72 | 73 | if (lock.isInitialized() && lock.isPaired()) { 74 | lock.on("disconnected", () => { 75 | // setTimeout(() => { 76 | // lock.connect(); 77 | // }, 3000); 78 | // client.startScanLock(); 79 | console.log("Disconnected from a known lock"); 80 | client.startMonitor(); 81 | }); 82 | await lock.connect(); 83 | console.log("Connected to a known lock"); 84 | // make sure operation log is up to date 85 | await lock.getOperationLog(); 86 | console.log(); 87 | console.log(); 88 | } 89 | }); 90 | 91 | // save lock data changes 92 | client.on("updatedLockData", async () => { 93 | await require("./common/saveData")(settingsFile, client.getLockData()); 94 | }); 95 | } 96 | 97 | doStuff(); -------------------------------------------------------------------------------- /src/api/Commands/PassageModeCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { CommandType } from "../../constant/CommandType"; 4 | import { PassageModeOperate } from "../../constant/PassageModeOperate"; 5 | import { PassageModeType } from "../../constant/PassageModeType"; 6 | import { Command } from "../Command"; 7 | 8 | export interface PassageModeData { 9 | type: PassageModeType; 10 | /** 1..7 (Monday..Sunday) 0: means ervery day */ 11 | weekOrDay: number; 12 | /** month repeat */ 13 | month: number; 14 | /** HHMM 0:0 means all day*/ 15 | startHour: string; 16 | /** HHMM */ 17 | endHour: string; 18 | } 19 | 20 | export class PassageModeCommand extends Command { 21 | static COMMAND_TYPE: CommandType = CommandType.COMM_CONFIGURE_PASSAGE_MODE; 22 | 23 | opType: PassageModeOperate = PassageModeOperate.QUERY; 24 | sequence?: number; 25 | dataOut?: PassageModeData[]; 26 | dataIn?: PassageModeData; 27 | 28 | protected processData(): void { 29 | if (this.commandData && this.commandData.length > 0) { 30 | this.opType = this.commandData.readInt8(1); 31 | if (this.opType == PassageModeOperate.QUERY) { 32 | this.sequence = this.commandData.readInt8(2); 33 | this.dataOut = []; 34 | let index = 3; 35 | if (this.commandData.length >= 10) { 36 | { 37 | this.dataOut.push({ 38 | type: this.commandData.readInt8(index), 39 | weekOrDay: this.commandData.readInt8(index + 1), 40 | month: this.commandData.readInt8(index + 2), 41 | startHour: this.commandData.readInt8(index + 3).toString().padStart(2, '0') + this.commandData.readInt8(index + 4).toString().padStart(2, '0'), 42 | endHour: this.commandData.readInt8(index + 5).toString().padStart(2, '0') + this.commandData.readInt8(index + 6).toString().padStart(2, '0'), 43 | }); 44 | index += 7; 45 | } while (index < this.commandData.length); 46 | } 47 | } else { 48 | 49 | } 50 | } 51 | } 52 | 53 | build(): Buffer { 54 | if (this.opType == PassageModeOperate.QUERY && typeof this.sequence != "undefined") { 55 | return Buffer.from([this.opType, this.sequence]); 56 | } else if (this.dataIn) { 57 | return Buffer.from([ 58 | this.opType, 59 | this.dataIn.type, 60 | this.dataIn.weekOrDay, 61 | this.dataIn.month, 62 | parseInt(this.dataIn.startHour.substr(0, 2)), 63 | parseInt(this.dataIn.startHour.substr(2, 2)), 64 | parseInt(this.dataIn.endHour.substr(0, 2)), 65 | parseInt(this.dataIn.endHour.substr(2, 2)) 66 | ]); 67 | } else { 68 | return Buffer.from([this.opType]); 69 | } 70 | } 71 | 72 | setSequence(sequence: number = 0) { 73 | this.sequence = sequence; 74 | } 75 | 76 | getSequence(): number { 77 | if (this.sequence) { 78 | return this.sequence; 79 | } else { 80 | return -1; 81 | } 82 | } 83 | 84 | setData(data: PassageModeData, type: PassageModeOperate.ADD | PassageModeOperate.DELETE = PassageModeOperate.ADD) { 85 | this.opType = type; 86 | this.dataIn = data; 87 | } 88 | 89 | setClear() { 90 | this.opType = PassageModeOperate.CLEAR; 91 | } 92 | 93 | getData(): PassageModeData[] { 94 | if (this.dataOut) { 95 | return this.dataOut; 96 | } else { 97 | return [] 98 | } 99 | } 100 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ttlock-sdk-js", 3 | "version": "0.3.14", 4 | "description": "JavaScript port of the TTLock Android SDK", 5 | "main": "dist/index.js", 6 | "types": "dist/index.d.ts", 7 | "files": [ 8 | "dist/**/*" 9 | ], 10 | "scripts": { 11 | "build": "rm -rf ./dist && tsc", 12 | "prepare": "npm run build", 13 | "init": "npm run build && node ./examples/init.js", 14 | "reset": "npm run build && node ./examples/reset.js", 15 | "unlock": "npm run build && node ./examples/unlock.js", 16 | "lock": "npm run build && node ./examples/lock.js", 17 | "status": "npm run build && node ./examples/status.js", 18 | "set-passage": "npm run build && node ./examples/setPassageMode.js", 19 | "get-passage": "npm run build && node ./examples/getPassageMode.js", 20 | "delete-passage": "npm run build && node ./examples/deletePassageMode.js", 21 | "clear-passage": "npm run build && node ./examples/clearPassageMode.js", 22 | "add-passcode": "npm run build && node ./examples/addPassCode.js", 23 | "update-passcode": "npm run build && node ./examples/updatePassCode.js", 24 | "delete-passcode": "npm run build && node ./examples/deletePassCode.js", 25 | "clear-passcodes": "npm run build && node ./examples/clearPassCodes.js", 26 | "get-passcodes": "npm run build && node ./examples/getPassCodes.js", 27 | "add-card": "npm run build && node ./examples/addICCard.js", 28 | "add-card-batch": "npm run build && node ./examples/addICCardBatch.js", 29 | "get-cards": "npm run build && node ./examples/getICCards.js", 30 | "clear-cards": "npm run build && node ./examples/clearICCards.js", 31 | "add-fingerprint": "npm run build && node ./examples/addFR.js", 32 | "get-fingerprints": "npm run build && node ./examples/getFR.js", 33 | "clear-fingerprints": "npm run build && node ./examples/clearFR.js", 34 | "set-autolock": "npm run build && node ./examples/setAutoLock.js", 35 | "listen": "npm run build && node --trace-warnings ./examples/listen.js", 36 | "set-remoteunlock": "npm run build && node ./examples/setRemoteUnlock.js", 37 | "delete-locksound": "npm run build && node ./examples/deleteLockSound.js", 38 | "get-operations": "npm run build && node ./examples/getOperations.js", 39 | "debug-tool": "npm run build && NOBLE_REPORT_ALL_HCI_EVENTS=1 node ./tools/debug.js", 40 | "server-tool": "NOBLE_REPORT_ALL_HCI_EVENTS=1 node ./tools/server.js", 41 | "dump-tool": "npm run build && node ./tools/dumpCapture.js" 42 | }, 43 | "repository": { 44 | "type": "git", 45 | "url": "git+https://github.com/kind3r/ttlock-sdk-js.git" 46 | }, 47 | "keywords": [ 48 | "ttlock", 49 | "sdk", 50 | "library", 51 | "javascript", 52 | "smartlock", 53 | "smart-lock", 54 | "iot", 55 | "unofficial" 56 | ], 57 | "author": "Emanuel Posescu ", 58 | "license": "GPL-3.0", 59 | "bugs": { 60 | "url": "https://github.com/kind3r/ttlock-sdk-js/issues" 61 | }, 62 | "homepage": "https://github.com/kind3r/ttlock-sdk-js#readme", 63 | "devDependencies": { 64 | "@tsconfig/node12": "^1.0.7", 65 | "@types/crypto-js": "^4.0.1", 66 | "@types/node": "^14.14.8", 67 | "@types/ws": "^7.4.0", 68 | "node-csv": "^0.1.2", 69 | "tslint": "^6.1.3", 70 | "typescript": "^4.0.5" 71 | }, 72 | "dependencies": { 73 | "@abandonware/noble": "^1.9.2-13", 74 | "chalk": "^4.1.0", 75 | "crypto-js": "^4.0.0", 76 | "moment": "^2.29.1", 77 | "reconnecting-websocket": "^4.4.0", 78 | "ws": "^7.4.2" 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/api/Commands/GetKeyboardPasswordsCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { CommandType } from "../../constant/CommandType"; 4 | import { KeyboardPwdType } from "../../constant/KeyboardPwdType"; 5 | import { Command } from "../Command"; 6 | 7 | export interface KeyboardPassCode { 8 | type: KeyboardPwdType; 9 | newPassCode: string; 10 | passCode: string; 11 | startDate?: string; 12 | endDate?: string; 13 | } 14 | 15 | export class GetKeyboardPasswordsCommand extends Command { 16 | static COMMAND_TYPE: CommandType = CommandType.COMM_PWD_LIST; 17 | 18 | private sequence?: number; 19 | private passCodes?: KeyboardPassCode[]; 20 | 21 | protected processData(): void { 22 | if (this.commandData && this.commandData.length >= 2) { 23 | const totalLen = this.commandData.readUInt16BE(0); 24 | this.passCodes = []; 25 | if (totalLen > 0) { 26 | this.sequence = this.commandData.readInt16BE(2); 27 | let index = 4; 28 | while (index < this.commandData.length) { 29 | // const len = this.commandData.readUInt8(index++); 30 | index++; 31 | let passCode: KeyboardPassCode = { 32 | type: this.commandData.readUInt8(index++), 33 | newPassCode: "", 34 | passCode: "" 35 | }; 36 | 37 | let codeLen = this.commandData.readUInt8(index++); 38 | passCode.newPassCode = this.commandData.subarray(index, index + codeLen).toString(); 39 | index += codeLen; 40 | 41 | codeLen = this.commandData.readUInt8(index++); 42 | passCode.passCode = this.commandData.subarray(index, index + codeLen).toString(); 43 | index += codeLen; 44 | 45 | passCode.startDate = "20" + this.commandData.readUInt8(index++).toString().padStart(2, '0') // year 46 | + this.commandData.readUInt8(index++).toString().padStart(2, '0') // month 47 | + this.commandData.readUInt8(index++).toString().padStart(2, '0') // day 48 | + this.commandData.readUInt8(index++).toString().padStart(2, '0') // hour 49 | + this.commandData.readUInt8(index++).toString().padStart(2, '0'); // minutes 50 | 51 | switch (passCode.type) { 52 | case KeyboardPwdType.PWD_TYPE_COUNT: 53 | case KeyboardPwdType.PWD_TYPE_PERIOD: 54 | passCode.endDate = "20" + this.commandData.readUInt8(index++).toString().padStart(2, '0') // year 55 | + this.commandData.readUInt8(index++).toString().padStart(2, '0') // month 56 | + this.commandData.readUInt8(index++).toString().padStart(2, '0') // day 57 | + this.commandData.readUInt8(index++).toString().padStart(2, '0') // hour 58 | + this.commandData.readUInt8(index++).toString().padStart(2, '0'); // minutes 59 | break; 60 | case KeyboardPwdType.PWD_TYPE_CIRCLE: 61 | index++; 62 | index++; 63 | } 64 | this.passCodes.push(passCode); 65 | } 66 | } 67 | } 68 | } 69 | 70 | build(): Buffer { 71 | if (typeof this.sequence != "undefined") { 72 | const data = Buffer.alloc(2); 73 | data.writeUInt16BE(this.sequence); 74 | return data; 75 | } else { 76 | return Buffer.from([]); 77 | } 78 | } 79 | 80 | setSequence(sequence: number = 0) { 81 | this.sequence = sequence; 82 | } 83 | 84 | getSequence(): number { 85 | if (this.sequence) { 86 | return this.sequence; 87 | } else { 88 | return -1; 89 | } 90 | } 91 | 92 | getPasscodes(): KeyboardPassCode[] { 93 | if (this.passCodes) { 94 | return this.passCodes; 95 | } 96 | return []; 97 | } 98 | } -------------------------------------------------------------------------------- /src/api/Commands/CyclicDateCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { CommandType } from "../../constant/CommandType"; 4 | import { CyclicOpType } from "../../constant/CyclicOpType"; 5 | import { Command } from "../Command"; 6 | import { CyclicConfig } from "../ValidityInfo"; 7 | 8 | export class CyclicDateCommand extends Command { 9 | static COMMAND_TYPE: CommandType = CommandType.COMM_CYCLIC_CMD; 10 | 11 | private opType?: CyclicOpType; 12 | private userType?: CyclicOpType; 13 | private user?: string; 14 | private cyclicConfig?: CyclicConfig; 15 | 16 | protected processData(): void { 17 | throw new Error("Method not implemented."); 18 | } 19 | 20 | build(): Buffer { 21 | if (typeof this.opType != "undefined") { 22 | switch (this.opType) { 23 | case CyclicOpType.ADD: 24 | case CyclicOpType.CLEAR: 25 | if (typeof this.userType != "undefined" && typeof this.user != "undefined") { 26 | let userLen = this.calculateUserLen(this.userType, this.user); 27 | let data: Buffer; 28 | if (this.opType == CyclicOpType.ADD) { 29 | data = Buffer.alloc(3 + userLen + 11); // why so much, we only requre 7 extra bytes 30 | } else { 31 | data = Buffer.alloc(3 + userLen); 32 | } 33 | switch (userLen) { 34 | case 6: 35 | data.writeBigInt64BE(BigInt(this.user), 1); 36 | break; 37 | case 8: 38 | data.writeBigInt64BE(BigInt(this.user), 3); 39 | break; 40 | case 4: 41 | data.writeInt32BE(parseInt(this.user), 3); 42 | break; 43 | } 44 | data.writeUInt8(this.opType, 0); 45 | data.writeUInt8(this.userType, 1); 46 | data.writeUInt8(userLen, 2); 47 | if (this.opType == CyclicOpType.ADD && typeof this.cyclicConfig != "undefined") { 48 | let index = userLen + 3; 49 | data.writeUInt8(CyclicOpType.CYCLIC_TYPE_WEEK, index++); 50 | data.writeUInt8(this.cyclicConfig.weekDay, index++); 51 | data.writeUInt8(0, index++); 52 | data.writeUInt8(this.cyclicConfig.startTime / 60, index++); 53 | data.writeUInt8(this.cyclicConfig.startTime % 60, index++); 54 | data.writeUInt8(this.cyclicConfig.endTime / 60, index++); 55 | data.writeUInt8(this.cyclicConfig.endTime % 60, index++); 56 | } 57 | return data; 58 | } 59 | break; 60 | default: 61 | throw new Error("opType not implemented"); 62 | } 63 | } 64 | return Buffer.from([]); 65 | } 66 | 67 | addIC(cardNumber: string, cyclicConfig: CyclicConfig) { 68 | this.opType = CyclicOpType.ADD; 69 | this.userType = CyclicOpType.USER_TYPE_IC; 70 | this.user = cardNumber; 71 | this.cyclicConfig = cyclicConfig; 72 | } 73 | 74 | clearIC(cardNumber: string) { 75 | this.opType = CyclicOpType.CLEAR; 76 | this.userType = CyclicOpType.USER_TYPE_IC; 77 | this.user = cardNumber; 78 | } 79 | 80 | addFR(fpNumber: string, cyclicConfig: CyclicConfig) { 81 | this.opType = CyclicOpType.ADD; 82 | this.userType = CyclicOpType.USER_TYPE_FR; 83 | this.user = fpNumber; 84 | this.cyclicConfig = cyclicConfig; 85 | } 86 | 87 | clearFR(fpNumber: string) { 88 | this.opType = CyclicOpType.CLEAR; 89 | this.userType = CyclicOpType.USER_TYPE_FR; 90 | this.user = fpNumber; 91 | } 92 | 93 | private calculateUserLen(userType: CyclicOpType, user: string): number { 94 | let userLen = 8; 95 | if (userType == CyclicOpType.USER_TYPE_FR) { 96 | userLen = 6; 97 | } else { 98 | if (BigInt(user) <= 0xffffffff) { 99 | userLen = 4; 100 | } 101 | } 102 | return userLen; 103 | } 104 | } -------------------------------------------------------------------------------- /src/constant/FeatureValue.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export enum FeatureValue { 4 | /** 5 | * Password 6 | */ 7 | PASSCODE = 0, 8 | 9 | /** 10 | * CARD 11 | */ 12 | IC = 1, 13 | 14 | /** 15 | * Fingerprint 16 | */ 17 | FINGER_PRINT = 2, 18 | 19 | /** 20 | * wristband 21 | */ 22 | WRIST_BAND = 3, 23 | 24 | /** 25 | * Automatic locking function 26 | */ 27 | AUTO_LOCK = 4, 28 | 29 | /** 30 | * Password with delete function 31 | */ 32 | PASSCODE_WITH_DELETE_FUNCTION = 5, 33 | 34 | /** 35 | * Support firmware upgrade setting instructions 36 | */ 37 | FIRMWARE_SETTTING = 6, 38 | 39 | /** 40 | * Modify password (custom) function 41 | */ 42 | MODIFY_PASSCODE_FUNCTION = 7, 43 | 44 | /** 45 | * Blocking instruction 46 | */ 47 | MANUAL_LOCK = 8, 48 | 49 | /** 50 | * Support password display or hide 51 | */ 52 | PASSWORD_DISPLAY_OR_HIDE = 9, 53 | 54 | /** 55 | * Support gateway unlock command 56 | */ 57 | GATEWAY_UNLOCK = 10, 58 | 59 | /** 60 | * Support gateway freeze and unfreeze instructions 61 | */ 62 | FREEZE_LOCK = 11, 63 | 64 | /** 65 | * Support cycle password 66 | */ 67 | CYCLIC_PASSWORD = 12, 68 | 69 | /** 70 | * Support door sensor 71 | */ 72 | MAGNETOMETER = 13, 73 | 74 | /** 75 | * Support remote unlocking configuration 76 | */ 77 | CONFIG_GATEWAY_UNLOCK = 14, 78 | 79 | /** 80 | * Audio management 81 | */ 82 | AUDIO_MANAGEMENT = 15, 83 | 84 | /** 85 | * Support NB 86 | */ 87 | NB_LOCK = 16, 88 | 89 | // /** 90 | // * Support hotel lock card system 91 | // */ 92 | // @Deprecated 93 | // HOTEL_LOCK = 0x20000, 94 | 95 | /** 96 | * Support reading the administrator password 97 | */ 98 | GET_ADMIN_CODE = 18, 99 | 100 | /** 101 | * Support hotel lock card system 102 | */ 103 | HOTEL_LOCK = 19, 104 | 105 | /** 106 | * Lock without clock chip 107 | */ 108 | LOCK_NO_CLOCK_CHIP = 20, 109 | 110 | /** 111 | * Bluetooth does not broadcast, and it cannot be realized by clicking on the app to unlock 112 | */ 113 | CAN_NOT_CLICK_UNLOCK = 21, 114 | 115 | /** 116 | * Support the normal open mode from a few hours to a few hours on a certain day 117 | */ 118 | PASSAGE_MODE = 22, 119 | 120 | /** 121 | * In the case of supporting the normally open mode and setting the automatic lock, whether to support the closing of the automatic lock 122 | */ 123 | PASSAGE_MODE_AND_AUTO_LOCK_AND_CAN_CLOSE = 23, 124 | 125 | WIRELESS_KEYBOARD = 24, 126 | 127 | /** 128 | * flashlight 129 | */ 130 | LAMP = 25, 131 | 132 | /** 133 | * Anti-tamper switch configuration 134 | */ 135 | TAMPER_ALERT = 28, 136 | 137 | /** 138 | * Reset key configuration 139 | */ 140 | RESET_BUTTON = 29, 141 | 142 | /** 143 | * Anti-lock 144 | */ 145 | PRIVACK_LOCK = 30, 146 | 147 | /** 148 | * Deadlock (the original 31 is not used) 149 | */ 150 | DEAD_LOCK = 32, 151 | 152 | /** 153 | * Support normally open mode exception 154 | */ 155 | // PASSAGE_MODE_ = 33, 156 | 157 | CYCLIC_IC_OR_FINGER_PRINT = 34, 158 | 159 | /** 160 | * Support left and right door opening settings 161 | */ 162 | UNLOCK_DIRECTION = 36, 163 | /** 164 | * Finger vein 165 | */ 166 | FINGER_VEIN = 37, 167 | 168 | /** 169 | * Telink Bluetooth chip 170 | */ 171 | TELINK_CHIP = 38, 172 | 173 | /** 174 | * Support NB activation configuration 175 | */ 176 | NB_ACTIVITE_CONFIGURATION = 39, 177 | 178 | /** 179 | * Support cyclic password recovery function 180 | */ 181 | CYCLIC_PASSCODE_CAN_RECOVERY = 40, 182 | 183 | /** 184 | * Support wireless key 185 | */ 186 | WIRELESS_KEY_FOB = 41, 187 | 188 | /** 189 | * Support reading accessory battery information 190 | */ 191 | ACCESSORY_BATTERY = 42, 192 | } -------------------------------------------------------------------------------- /tools/debug.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { TTLockClient, sleep, CommandEnvelope } = require('../dist'); 4 | 5 | // const uuids = []; 6 | const api = new TTLockClient({ 7 | // uuids: uuids, 8 | // scannerType: "noble" 9 | }); 10 | 11 | async function doStuff() { 12 | api.prepareBTService(); 13 | for (let i = 10; i > 0; i--) { 14 | console.log("Starting scan...", i); 15 | await sleep(1000); 16 | } 17 | api.startScanLock(); 18 | console.log("Scan started"); 19 | api.on("foundLock", async (device) => { 20 | await device.connect(); 21 | // don't disconnect so we receive subscriptions 22 | // await device.disconnect(); 23 | console.log(device.toJSON()); 24 | console.log(); 25 | 26 | if (!device.isInitialized()) { 27 | console.log("Trying to init the lock"); 28 | console.log(); 29 | console.log(); 30 | const inited = await device.initLock(); 31 | if (!inited) { 32 | process.exit(1); 33 | } 34 | await device.disconnect(); 35 | console.log(); 36 | console.log(); 37 | console.log(device.toJSON()); 38 | console.log(); 39 | console.log(); 40 | console.log("Sleeping 10 seconds"); 41 | await sleep(10000); 42 | console.log("Reseting to factory defaults"); 43 | await device.connect(); 44 | console.log(); 45 | console.log(); 46 | await device.resetLock(); 47 | console.log(); 48 | console.log(); 49 | console.log("Lock reset to factory defaults"); 50 | process.exit(0); 51 | } 52 | }); 53 | } 54 | 55 | // doStuff(); 56 | 57 | let defaultAes = Buffer.from("987623E8A923A1BB3D9E7D0378124588", "hex"); 58 | let aes = Buffer.from("e817e962c7176c296403f646129f362c", "hex"); 59 | // let sent = Buffer.from("7f5a0503010001000190aa108419ca5d7ddc8fa963e1118cacf6f26b27", "hex"); 60 | let received = Buffer.from("7f5a0503020001000154aa1095a3bd4703fde2b76397587b6ee44b7b28", "hex"); 61 | let receivedCommand = CommandEnvelope.createFromRawData(received, aes); 62 | // receivedCommand.buildCommandBuffer(); 63 | let cmd = receivedCommand.getCommand(); 64 | // console.log(cmd.getData()); 65 | console.log(receivedCommand); 66 | console.log(receivedCommand.getCommandType().toString(16), String.fromCharCode(receivedCommand.getCommandType())); 67 | console.log(receivedCommand.getData().toString("hex")); 68 | console.log(cmd.getType()); 69 | // console.log(cmd); 70 | // console.log(cmd.getPsFromLock()); 71 | // let cmd = commandFromData(receivedCommand.getData()); 72 | 73 | 74 | let data = receivedCommand.getData(); 75 | // let data = Buffer.from("140ed0cf86ee2d2d70dd779a28060154283feb3941263687ae30417a9318e137103988e11a13110e0d48f20f013685f67c23d064c2943815e06e8c27ef", "hex"); 76 | 77 | //////////////////////// 78 | // InitPasswordsCommand 79 | // console.log("data length:", data.length); 80 | // console.log("year:", data.readUInt8(0)); 81 | // for (let i = 0; i < 10; i++) { 82 | // const codeSecret = data.subarray(i * 6 + 1, i * 6 + 1 + 6); 83 | // // console.log(codeSecret); 84 | // let code = 0; 85 | // code = codeSecret.readUInt16BE(0) >> 4 & 0xFFFF; 86 | // // code = codeSecret.readUInt8(0) << 4 & 0xFF; 87 | // // code = code | (codeSecret.readUInt8(1) >> 4); 88 | // let sec = Buffer.alloc(8); 89 | // sec[3] = (codeSecret.readUInt8(1) << 4 & 0xFF) >> 4; 90 | // codeSecret.copy(sec, 4, 2); 91 | // console.log("Code:",code, "Secret:", sec.readBigUInt64BE(0).toString()); 92 | // } 93 | 94 | 95 | // console.log(data.toString()); 96 | 97 | // for (let i = 0; i < 10; i++) { 98 | // console.log(data.readUInt8(i)); 99 | // } 100 | // console.log(data.readUInt32BE(0), data.readUInt32BE(4), data.subarray(8).toString()); 101 | // console.log(data.toString()); 102 | 103 | // console.log(data.subarray(0, 5)); 104 | // console.log(data.subarray(5, 5)); 105 | // const data2 = Buffer.alloc(4); 106 | // data.copy(data2, 1, 10, 13); 107 | // console.log(data2.readUInt32BE(0)); 108 | // console.log(data.readUInt32BE(0)); 109 | -------------------------------------------------------------------------------- /src/constant/LogOperateNames.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { LogOperate } from "./LogOperate"; 4 | 5 | export let LogOperateNames: string[] = []; 6 | LogOperateNames[LogOperate.OPERATE_TYPE_MOBILE_UNLOCK] = "Bluetooth unlock"; 7 | // //Server unlock 8 | // OPERATE_TYPE_SERVER_UNLOCK = 3; 9 | LogOperateNames[LogOperate.OPERATE_TYPE_KEYBOARD_PASSWORD_UNLOCK] = "Password unlock"; 10 | LogOperateNames[LogOperate.OPERATE_TYPE_KEYBOARD_MODIFY_PASSWORD] = "Change the password on the keyboard"; 11 | LogOperateNames[LogOperate.OPERATE_TYPE_KEYBOARD_REMOVE_SINGLE_PASSWORD] = "Delete a single password on the keyboard"; 12 | LogOperateNames[LogOperate.OPERATE_TYPE_ERROR_PASSWORD_UNLOCK] = "Wrong password unlock"; 13 | LogOperateNames[LogOperate.OPERATE_TYPE_KEYBOARD_REMOVE_ALL_PASSWORDS] = "Delete all passwords on the keyboard"; 14 | LogOperateNames[LogOperate.OPERATE_TYPE_KEYBOARD_PASSWORD_KICKED] = "The password is squeezed out"; 15 | LogOperateNames[LogOperate.OPERATE_TYPE_USE_DELETE_CODE] = "The password with the delete function is unlocked for the first time; and the previous password is cleared"; 16 | LogOperateNames[LogOperate.OPERATE_TYPE_PASSCODE_EXPIRED] = "Password expired"; 17 | LogOperateNames[LogOperate.OPERATE_TYPE_SPACE_INSUFFICIENT] = "The password unlock failed; and the storage capacity is insufficient"; 18 | LogOperateNames[LogOperate.OPERATE_TYPE_PASSCODE_IN_BLACK_LIST] = "Password unlock failed—the password is in the blacklist"; 19 | LogOperateNames[LogOperate.OPERATE_TYPE_DOOR_REBOOT] = "The door lock is powered on again (that is; the battery is reconnected)"; 20 | LogOperateNames[LogOperate.OPERATE_TYPE_ADD_IC] = "Add IC card successfully"; 21 | LogOperateNames[LogOperate.OPERATE_TYPE_CLEAR_IC_SUCCEED] = "Successfully emptied the IC card"; 22 | LogOperateNames[LogOperate.OPERATE_TYPE_IC_UNLOCK_SUCCEED] = "IC card opened successfully"; 23 | LogOperateNames[LogOperate.OPERATE_TYPE_DELETE_IC_SUCCEED] = "Delete a single IC card successfully"; 24 | LogOperateNames[LogOperate.OPERATE_TYPE_BONG_UNLOCK_SUCCEED] = "Bong bracelet opened the door successfully"; 25 | LogOperateNames[LogOperate.OPERATE_TYPE_FR_UNLOCK_SUCCEED] = "Fingerprint opens the door successfully"; 26 | LogOperateNames[LogOperate.OPERATE_TYPE_ADD_FR] = "The fingerprint is added successfully"; 27 | LogOperateNames[LogOperate.OPERATE_TYPE_FR_UNLOCK_FAILED] = "Fingerprint opening failed"; 28 | LogOperateNames[LogOperate.OPERATE_TYPE_DELETE_FR_SUCCEED] = "Delete a single fingerprint successfully"; 29 | LogOperateNames[LogOperate.OPERATE_TYPE_CLEAR_FR_SUCCEED] = "Clear fingerprints successfully"; 30 | LogOperateNames[LogOperate.OPERATE_TYPE_IC_UNLOCK_FAILED] = "IC card failed to open the door-expired or not valid"; 31 | LogOperateNames[LogOperate.OPERATE_BLE_LOCK] = "Bluetooth or net closed lock"; 32 | LogOperateNames[LogOperate.OPERATE_KEY_UNLOCK] = "Mechanical key unlock"; 33 | LogOperateNames[LogOperate.GATEWAY_UNLOCK] = "Gateway unlock"; 34 | LogOperateNames[LogOperate.ILLAGEL_UNLOCK] = "Illegal unlocking (such as pedaling)"; 35 | LogOperateNames[LogOperate.DOOR_SENSOR_LOCK] = "Close the door sensor"; 36 | LogOperateNames[LogOperate.DOOR_SENSOR_UNLOCK] = "Door sensor open"; 37 | LogOperateNames[LogOperate.DOOR_GO_OUT] = "Outgoing records"; 38 | LogOperateNames[LogOperate.FR_LOCK] = "Fingerprint lock"; 39 | LogOperateNames[LogOperate.PASSCODE_LOCK] = "Password lock"; 40 | LogOperateNames[LogOperate.IC_LOCK] = "IC card lock"; 41 | LogOperateNames[LogOperate.OPERATE_KEY_LOCK] = "Mechanical key lock"; 42 | LogOperateNames[LogOperate.REMOTE_CONTROL_KEY] = "Remote control button"; 43 | LogOperateNames[LogOperate.PASSCODE_UNLOCK_FAILED_LOCK_REVERSE] = "Password unlock failed; the door is locked"; 44 | LogOperateNames[LogOperate.IC_UNLOCK_FAILED_LOCK_REVERSE] = "The IC card fails to unlock and the door is locked"; 45 | LogOperateNames[LogOperate.FR_UNLOCK_FAILED_LOCK_REVERSE] = "Fingerprint unlocking fails; the door is locked"; 46 | LogOperateNames[LogOperate.APP_UNLOCK_FAILED_LOCK_REVERSE] = "The app fails to unlock and the door is locked"; 47 | //42 ~ 48 no parameters 48 | LogOperateNames[LogOperate.WIRELESS_KEY_FOB] = "Wireless key"; 49 | LogOperateNames[LogOperate.WIRELESS_KEY_PAD] = "Wireless keyboard battery"; 50 | 51 | // export default LogOperateNames; -------------------------------------------------------------------------------- /src/constant/LogOperate.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export enum LogOperate { 4 | //Phone unlock 5 | /** 6 | * Bluetooth unlock 7 | */ 8 | OPERATE_TYPE_MOBILE_UNLOCK = 1, 9 | 10 | // //Server unlock 11 | // OPERATE_TYPE_SERVER_UNLOCK = 3, 12 | 13 | //Password unlock 14 | OPERATE_TYPE_KEYBOARD_PASSWORD_UNLOCK = 4, 15 | 16 | //Change the password on the keyboard 17 | OPERATE_TYPE_KEYBOARD_MODIFY_PASSWORD = 5, 18 | 19 | //Delete a single password on the keyboard 20 | OPERATE_TYPE_KEYBOARD_REMOVE_SINGLE_PASSWORD = 6, 21 | 22 | //Wrong password unlock 23 | OPERATE_TYPE_ERROR_PASSWORD_UNLOCK = 7, 24 | 25 | //Delete all passwords on the keyboard 26 | OPERATE_TYPE_KEYBOARD_REMOVE_ALL_PASSWORDS = 8, 27 | 28 | //The password is squeezed out 29 | OPERATE_TYPE_KEYBOARD_PASSWORD_KICKED = 9, 30 | 31 | /** 32 | * The password with the delete function is unlocked for the first time, and the previous password is cleared 33 | */ 34 | OPERATE_TYPE_USE_DELETE_CODE = 10, 35 | 36 | /** 37 | * Password expired 38 | */ 39 | OPERATE_TYPE_PASSCODE_EXPIRED = 11, 40 | 41 | /** 42 | * The password unlock failed, and the storage capacity is insufficient 43 | */ 44 | OPERATE_TYPE_SPACE_INSUFFICIENT = 12, 45 | 46 | /** 47 | * Password unlock failed—the password is in the blacklist 48 | */ 49 | OPERATE_TYPE_PASSCODE_IN_BLACK_LIST = 13, 50 | 51 | /** 52 | * The door lock is powered on again (that is, the battery is reconnected) 53 | */ 54 | OPERATE_TYPE_DOOR_REBOOT = 14, 55 | 56 | /** 57 | * Add IC card successfully 58 | */ 59 | OPERATE_TYPE_ADD_IC = 15, 60 | 61 | /** 62 | * Successfully emptied the IC card 63 | */ 64 | OPERATE_TYPE_CLEAR_IC_SUCCEED = 16, 65 | 66 | /** 67 | * IC card opened successfully 68 | */ 69 | OPERATE_TYPE_IC_UNLOCK_SUCCEED = 17, 70 | 71 | /** 72 | * Delete a single IC card successfully 73 | */ 74 | OPERATE_TYPE_DELETE_IC_SUCCEED = 18, 75 | 76 | /** 77 | * Bong bracelet opened the door successfully 78 | */ 79 | OPERATE_TYPE_BONG_UNLOCK_SUCCEED = 19, 80 | 81 | /** 82 | * Fingerprint opens the door successfully 83 | */ 84 | OPERATE_TYPE_FR_UNLOCK_SUCCEED = 20, 85 | 86 | /** 87 | * The fingerprint is added successfully 88 | */ 89 | OPERATE_TYPE_ADD_FR = 21, 90 | 91 | /** 92 | * Fingerprint opening failed 93 | */ 94 | OPERATE_TYPE_FR_UNLOCK_FAILED = 22, 95 | 96 | /** 97 | * Delete a single fingerprint successfully 98 | */ 99 | OPERATE_TYPE_DELETE_FR_SUCCEED = 23, 100 | 101 | /** 102 | * Clear fingerprints successfully 103 | */ 104 | OPERATE_TYPE_CLEAR_FR_SUCCEED = 24, 105 | 106 | /** 107 | * IC card failed to open the door-expired or not valid 108 | */ 109 | OPERATE_TYPE_IC_UNLOCK_FAILED = 25, 110 | 111 | /** 112 | * Bluetooth or net closed lock 113 | */ 114 | OPERATE_BLE_LOCK = 26, 115 | 116 | /** 117 | * Mechanical key unlock 118 | */ 119 | OPERATE_KEY_UNLOCK = 27, 120 | 121 | /** 122 | * Gateway unlock 123 | */ 124 | GATEWAY_UNLOCK = 28, 125 | 126 | /** 127 | * Illegal unlocking (such as pedaling) 128 | */ 129 | ILLAGEL_UNLOCK = 29, 130 | 131 | /** 132 | * Close the door sensor 133 | */ 134 | DOOR_SENSOR_LOCK = 30, 135 | 136 | /** 137 | * Door sensor open 138 | */ 139 | DOOR_SENSOR_UNLOCK = 31, 140 | 141 | /** 142 | * Outgoing records 143 | */ 144 | DOOR_GO_OUT = 32, 145 | 146 | /** 147 | * Fingerprint lock 148 | */ 149 | FR_LOCK = 33, 150 | 151 | /** 152 | * Password lock 153 | */ 154 | PASSCODE_LOCK = 34, 155 | 156 | IC_LOCK = 35, 157 | 158 | /** 159 | * Mechanical key lock 160 | */ 161 | OPERATE_KEY_LOCK = 36, 162 | 163 | /** 164 | * Remote control button 165 | */ 166 | REMOTE_CONTROL_KEY = 37, 167 | 168 | /** 169 | * Password unlock failed, the door is locked 170 | */ 171 | PASSCODE_UNLOCK_FAILED_LOCK_REVERSE = 38, 172 | 173 | /** 174 | * The IC card fails to unlock and the door is locked 175 | */ 176 | IC_UNLOCK_FAILED_LOCK_REVERSE = 39, 177 | 178 | /** 179 | * Fingerprint unlocking fails, the door is locked 180 | */ 181 | FR_UNLOCK_FAILED_LOCK_REVERSE = 40, 182 | 183 | /** 184 | * The app fails to unlock and the door is locked 185 | */ 186 | APP_UNLOCK_FAILED_LOCK_REVERSE = 41, 187 | 188 | //42 ~ 48 no parameters 189 | 190 | /** 191 | * Wireless key 192 | */ 193 | WIRELESS_KEY_FOB = 55, 194 | 195 | /** 196 | * Wireless keyboard battery 197 | */ 198 | WIRELESS_KEY_PAD = 56, 199 | } -------------------------------------------------------------------------------- /src/constant/CommandType.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export enum CommandType { 4 | COMM_UNSET = -1, 5 | 6 | COMM_INITIALIZATION = 0x45, // 'E' 7 | COMM_GET_AES_KEY = 0x19, 8 | COMM_RESPONSE = 0x54, // 'T' 9 | 10 | /** 11 | * Add management 12 | */ 13 | COMM_ADD_ADMIN = 0x56, // 'V' 14 | 15 | /** 16 | * Check the administrator 17 | */ 18 | COMM_CHECK_ADMIN = 0x41, // 'A' 19 | 20 | /** 21 | * Administrator keyboard password 22 | */ 23 | COMM_SET_ADMIN_KEYBOARD_PWD = 0x53, // 'S' 24 | 25 | /** 26 | * Delete password 27 | */ 28 | COMM_SET_DELETE_PWD = 0x44, // 'D' 29 | 30 | /** 31 | * Set the lock name 32 | */ 33 | COMM_SET_LOCK_NAME = 0x4E, // 'N' 34 | 35 | /** 36 | * Sync keyboard password 37 | */ 38 | COMM_SYN_KEYBOARD_PWD = 0x49, // 'I' 39 | 40 | /** 41 | * Verify user time 42 | */ 43 | COMM_CHECK_USER_TIME = 0x55, // 'U' 44 | 45 | /** 46 | * Get the parking lock alarm record (the parking lock is moved) 47 | * To determine the completion of operations such as adding and password 48 | */ 49 | COMM_GET_ALARM_ERRCORD_OR_OPERATION_FINISHED = 0x57, // 'W' 50 | 51 | /** 52 | * Open the door 53 | */ 54 | COMM_UNLOCK = 0x47, // 'G' 55 | 56 | /** 57 | * close the door 58 | */ 59 | COMM_LOCK = 0x4C, // 'L' 60 | 61 | /** 62 | * Calibration time 63 | */ 64 | COMM_TIME_CALIBRATE = 0x43, // 'C' 65 | 66 | /** 67 | * Manage keyboard password 68 | */ 69 | COMM_MANAGE_KEYBOARD_PASSWORD = 0x03, 70 | 71 | /** 72 | * Get a valid keyboard password in the lock 73 | */ 74 | COMM_GET_VALID_KEYBOARD_PASSWORD = 0x04, 75 | 76 | /** 77 | * Get operation records 78 | */ 79 | COMM_GET_OPERATE_LOG = 0x25, 80 | 81 | /** 82 | * Random number verification 83 | */ 84 | COMM_CHECK_RANDOM = 0x30, 85 | 86 | /** 87 | * Three generations 88 | * Password initialization 89 | */ 90 | COMM_INIT_PASSWORDS = 0x31, 91 | 92 | /** 93 | * Read password parameters 94 | */ 95 | COMM_READ_PWD_PARA = 0x32, 96 | 97 | /** 98 | * Modify the number of valid keyboard passwords 99 | */ 100 | COMM_RESET_KEYBOARD_PWD_COUNT = 0x33, 101 | 102 | /** 103 | * Read door lock time 104 | */ 105 | COMM_GET_LOCK_TIME = 0x34, 106 | 107 | /** 108 | * Reset lock 109 | */ 110 | COMM_RESET_LOCK = 0x52, // 'R' 111 | 112 | /** 113 | * Query device characteristics 114 | */ 115 | COMM_SEARCHE_DEVICE_FEATURE = 0x01, 116 | 117 | /** 118 | * IC card management 119 | */ 120 | COMM_IC_MANAGE = 0x05, 121 | 122 | /** 123 | * Fingerprint management 124 | */ 125 | COMM_FR_MANAGE = 0x06, 126 | 127 | /** 128 | * Get password list 129 | */ 130 | COMM_PWD_LIST = 0x07, 131 | 132 | /** 133 | * Set the bracelet KEY 134 | */ 135 | COMM_SET_WRIST_BAND_KEY = 0x35, 136 | 137 | /** 138 | * Automatic locking management (including door sensor) 139 | */ 140 | COMM_AUTO_LOCK_MANAGE = 0x36, 141 | 142 | /** 143 | * Read device information 144 | */ 145 | COMM_READ_DEVICE_INFO = 0x90, 146 | 147 | /** 148 | * Enter upgrade mode 149 | */ 150 | COMM_ENTER_DFU_MODE = 0x02, 151 | 152 | /** 153 | * Query bicycle status (including door sensor) 154 | */ 155 | COMM_SEARCH_BICYCLE_STATUS = 0x14, 156 | 157 | /** 158 | * Locked 159 | */ 160 | COMM_FUNCTION_LOCK = 0x58, 161 | 162 | /** 163 | * The password is displayed on the screen 164 | */ 165 | COMM_SHOW_PASSWORD = 0x59, 166 | 167 | /** 168 | * Control remote unlocking 169 | */ 170 | COMM_CONTROL_REMOTE_UNLOCK = 0x37, 171 | 172 | COMM_AUDIO_MANAGE = 0x62, 173 | 174 | COMM_REMOTE_CONTROL_DEVICE_MANAGE = 0x63, 175 | 176 | /** 177 | * For NB networked door locks, through this command, App tells the address information of the door lock server 178 | */ 179 | COMM_CONFIGURE_NB_ADDRESS = 0x12, 180 | 181 | /** 182 | * Hotel lock parameter configuration 183 | */ 184 | COMM_CONFIGURE_HOTEL_DATA = 0x64, 185 | 186 | /** 187 | * Read the administrator password 188 | */ 189 | COMM_GET_ADMIN_CODE = 0x65, 190 | 191 | /** 192 | * Normally open mode management 193 | */ 194 | COMM_CONFIGURE_PASSAGE_MODE = 0x66, 195 | 196 | /** 197 | * Switch control instructions (privacy lock, tamper-proof alarm, reset lock) 198 | */ 199 | COMM_SWITCH = 0x68, 200 | 201 | COMM_FREEZE_LOCK = 0x61, 202 | 203 | COMM_LAMP = 0x67, 204 | 205 | /** 206 | * Deadlock instruction 207 | */ 208 | COMM_DEAD_LOCK = 0x69, 209 | 210 | /** 211 | * Cycle instructions 212 | */ 213 | COMM_CYCLIC_CMD = 0x70, 214 | 215 | /** 216 | * Get accessory battery 217 | */ 218 | COMM_ACCESSORY_BATTERY = 0x74, 219 | 220 | COMM_NB_ACTIVATE_CONFIGURATION = 0x13, 221 | } -------------------------------------------------------------------------------- /src/scanner/noble/NobleCharacteristic.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { Characteristic } from "@abandonware/noble"; 4 | import { EventEmitter } from "events"; 5 | import { sleep } from "../../util/timingUtil"; 6 | import { CharacteristicInterface, DescriptorInterface } from "../DeviceInterface"; 7 | import { NobleDescriptor } from "./NobleDescriptor"; 8 | import { NobleDevice } from "./NobleDevice"; 9 | 10 | export class NobleCharacteristic extends EventEmitter implements CharacteristicInterface { 11 | uuid: string; 12 | name?: string | undefined; 13 | type?: string | undefined; 14 | properties: string[]; 15 | isReading: boolean = false; 16 | lastValue?: Buffer; 17 | descriptors: Map = new Map(); 18 | private device: NobleDevice; 19 | private characteristic: Characteristic; 20 | 21 | constructor(device: NobleDevice, characteristic: Characteristic) { 22 | super(); 23 | this.device = device; 24 | this.characteristic = characteristic; 25 | this.uuid = characteristic.uuid; 26 | this.name = characteristic.name; 27 | this.type = characteristic.type; 28 | this.properties = characteristic.properties; 29 | this.characteristic.on("read", this.onRead.bind(this)); 30 | } 31 | 32 | getUUID(): string { 33 | if (this.uuid.length > 4) { 34 | return this.uuid.replace("-0000-1000-8000-00805f9b34fb", "").replace("0000", ""); 35 | } 36 | return this.uuid; 37 | } 38 | 39 | async discoverDescriptors(): Promise> { 40 | this.device.checkBusy(); 41 | if (!this.device.connected) { 42 | this.device.resetBusy(); 43 | throw new Error("NobleDevice is not connected"); 44 | } 45 | try { 46 | const descriptors = await this.characteristic.discoverDescriptorsAsync(); 47 | this.descriptors = new Map(); 48 | descriptors.forEach((descriptor) => { 49 | this.descriptors.set(descriptor.uuid, new NobleDescriptor(this.device, descriptor)); 50 | }); 51 | } catch (error) { 52 | console.error(error); 53 | } 54 | this.device.resetBusy(); 55 | return this.descriptors; 56 | } 57 | 58 | async read(): Promise { 59 | if (!this.properties.includes("read")) { 60 | return; 61 | } 62 | this.device.checkBusy(); 63 | if (!this.device.connected) { 64 | this.device.resetBusy(); 65 | throw new Error("NobleDevice is not connected"); 66 | } 67 | this.isReading = true; 68 | try { 69 | this.lastValue = await this.characteristic.readAsync(); 70 | } catch (error) { 71 | console.error(error); 72 | } 73 | this.isReading = false; 74 | this.device.resetBusy(); 75 | return this.lastValue; 76 | } 77 | 78 | async write(data: Buffer, withoutResponse: boolean): Promise { 79 | if (!this.properties.includes("write") && !this.properties.includes("writeWithoutResponse")) { 80 | return false; 81 | } 82 | this.device.checkBusy(); 83 | if (!this.device.connected) { 84 | this.device.resetBusy(); 85 | return false; 86 | // throw new Error("NobleDevice is not connected"); 87 | } 88 | 89 | let written = false; 90 | let writeError = false; 91 | let counter = 5000; 92 | 93 | // await this.characteristic.writeAsync(data, withoutResponse); 94 | this.characteristic.write(data, withoutResponse, (error) => { 95 | if (error) { 96 | writeError = true; 97 | } 98 | written = true; 99 | }); 100 | do { 101 | await sleep(1); 102 | counter--; 103 | } while (!written && counter > 0); 104 | 105 | this.device.resetBusy(); 106 | return written && !writeError; 107 | } 108 | 109 | async subscribe(): Promise { 110 | await this.characteristic.subscribeAsync(); 111 | // await this.characteristic.notifyAsync(true); 112 | } 113 | 114 | private onRead(data: Buffer) { 115 | // if the read notification comes from a manual read, just ignore it 116 | // we are only interested in data pushed by the device 117 | if (!this.isReading) { 118 | this.lastValue = data; 119 | this.emit("dataRead", this.lastValue); 120 | } 121 | } 122 | 123 | toJSON(asObject: boolean): string | Object { 124 | let json: Record = { 125 | uuid: this.uuid, 126 | name: this.name, 127 | type: this.type, 128 | properties: this.properties, 129 | value: this.lastValue?.toString("hex"), 130 | descriptors: {} 131 | } 132 | this.descriptors.forEach((descriptor) => { 133 | json.descriptors[this.uuid] = this.toJSON(true); 134 | }); 135 | 136 | if (asObject) { 137 | return json; 138 | } else { 139 | return JSON.stringify(json); 140 | } 141 | } 142 | 143 | toString(): string { 144 | return this.characteristic.toString(); 145 | } 146 | } -------------------------------------------------------------------------------- /src/constant/Lock.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { TTDevice } from "../device/TTDevice"; 4 | 5 | export enum LockType { 6 | UNKNOWN = 0, 7 | LOCK_TYPE_V1 = 1, 8 | /** 3.0 */ 9 | LOCK_TYPE_V2 = 2, 10 | /** 5.1 */ 11 | LOCK_TYPE_V2S = 3, 12 | /** 5.4 */ 13 | LOCK_TYPE_V2S_PLUS = 4, 14 | /** Third generation lock 5.3 */ 15 | LOCK_TYPE_V3 = 5, 16 | /** Parking lock a.1 */ 17 | LOCK_TYPE_CAR = 6, 18 | /** Third generation parking lock 5.3.7 */ 19 | LOCK_TYPE_V3_CAR = 8, 20 | /** Electric car lock b.1 */ 21 | LOCK_TYPE_MOBI = 7, 22 | 23 | // /** Remote control equipment 5.3.10 */ 24 | // static LOCK_TYPE_REMOTE_CONTROL_DEVICE:number = 9; 25 | // /** safe lock */ 26 | // static LOCK_TYPE_SAFE_LOCK:number = 8; 27 | // /** bicycle lock */ 28 | // static LOCK_TYPE_BICYCLE:number = 9; 29 | } 30 | 31 | export class LockVersion { 32 | 33 | static lockVersion_V2S_PLUS: LockVersion = new LockVersion(5, 4, 1, 1, 1); 34 | static lockVersion_V3: LockVersion = new LockVersion(5, 3, 1, 1, 1); 35 | static lockVersion_V2S: LockVersion = new LockVersion(5, 1, 1, 1, 1); 36 | /** 37 | *The second-generation parking lock scene is also changed to 7 38 | */ 39 | static lockVersion_Va: LockVersion = new LockVersion(0x0a, 1, 0x07, 1, 1); 40 | /** 41 | *The electric car lock scene will be changed to 1 and there is no electric car lock 42 | */ 43 | static lockVersion_Vb: LockVersion = new LockVersion(0x0b, 1, 0x01, 1, 1); 44 | static lockVersion_V2: LockVersion = new LockVersion(3, 0, 0, 0, 0); 45 | static lockVersion_V3_car: LockVersion = new LockVersion(5, 3, 7, 1, 1); 46 | 47 | private protocolType: number; 48 | private protocolVersion: number; 49 | private scene: number; 50 | private groupId: number; 51 | private orgId: number; 52 | 53 | constructor(protocolType: number, protocolVersion: number, scene: number, groupId: number, orgId: number) { 54 | this.protocolType = protocolType; 55 | this.protocolVersion = protocolVersion; 56 | this.scene = scene; 57 | this.groupId = groupId; 58 | this.orgId = orgId; 59 | } 60 | 61 | getProtocolType(): number { 62 | return this.protocolType; 63 | } 64 | setProtocolType(protocolType: number): void { 65 | this.protocolType = protocolType; 66 | } 67 | getProtocolVersion(): number { 68 | return this.protocolVersion; 69 | } 70 | setProtocolVersion(protocolVersion: number): void { 71 | this.protocolVersion = protocolVersion; 72 | } 73 | getScene(): number { 74 | return this.scene; 75 | } 76 | setScene(scene: number): void { 77 | this.scene = scene; 78 | } 79 | getGroupId(): number { 80 | return this.groupId; 81 | } 82 | setGroupId(groupId: number): void { 83 | this.groupId = groupId; 84 | } 85 | getOrgId(): number { 86 | return this.orgId; 87 | } 88 | setOrgId(orgId: number): void { 89 | this.orgId = orgId; 90 | } 91 | 92 | static getLockVersion(lockType: LockType): LockVersion | null { 93 | switch (lockType) { 94 | case LockType.LOCK_TYPE_V3_CAR: 95 | return LockVersion.lockVersion_V3_car; 96 | case LockType.LOCK_TYPE_V3: 97 | return LockVersion.lockVersion_V3; 98 | case LockType.LOCK_TYPE_V2S_PLUS: 99 | return LockVersion.lockVersion_V2S_PLUS; 100 | case LockType.LOCK_TYPE_V2S: 101 | return LockVersion.lockVersion_V2S; 102 | case LockType.LOCK_TYPE_CAR: 103 | return LockVersion.lockVersion_Va; 104 | case LockType.LOCK_TYPE_MOBI: 105 | return LockVersion.lockVersion_Vb; 106 | case LockType.LOCK_TYPE_V2: 107 | return LockVersion.lockVersion_V2; 108 | default: 109 | return null; 110 | } 111 | } 112 | 113 | static getLockType(device: TTDevice): LockType { 114 | if (device.lockType == LockType.UNKNOWN) { 115 | if (device.protocolType == 5 && device.protocolVersion == 3 && device.scene == 7) { 116 | device.lockType = LockType.LOCK_TYPE_V3_CAR; 117 | } 118 | else if (device.protocolType == 10 && device.protocolVersion == 1) { 119 | device.lockType = LockType.LOCK_TYPE_CAR; 120 | } 121 | else if (device.protocolType == 11 && device.protocolVersion == 1) { 122 | device.lockType = LockType.LOCK_TYPE_MOBI; 123 | } 124 | else if (device.protocolType == 5 && device.protocolVersion == 4) { 125 | device.lockType = LockType.LOCK_TYPE_V2S_PLUS; 126 | } 127 | else if (device.protocolType == 5 && device.protocolVersion == 3) { 128 | device.lockType = LockType.LOCK_TYPE_V3; 129 | } 130 | else if ((device.protocolType == 5 && device.protocolVersion == 1) || (device.name != null && device.name.toUpperCase().startsWith("LOCK_"))) { 131 | device.lockType = LockType.LOCK_TYPE_V2S; 132 | } 133 | } 134 | return device.lockType; 135 | } 136 | 137 | toString(): string { 138 | return this.protocolType + "," + this.protocolVersion + "," + this.scene + "," + this.groupId + "," + this.orgId; 139 | } 140 | 141 | } 142 | -------------------------------------------------------------------------------- /src/scanner/noble/NobleScanner.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { ScannerInterface, ScannerStateType } from "../ScannerInterface"; 4 | import nobleObj from "@abandonware/noble"; 5 | import { EventEmitter } from "events"; 6 | import { NobleDevice } from "./NobleDevice"; 7 | 8 | type nobleStateType = "unknown" | "resetting" | "unsupported" | "unauthorized" | "poweredOff" | "poweredOn"; 9 | 10 | export class NobleScanner extends EventEmitter implements ScannerInterface { 11 | uuids: string[]; 12 | scannerState: ScannerStateType = "unknown"; 13 | private nobleState: nobleStateType = "unknown"; 14 | private devices: Map = new Map(); 15 | protected noble?: typeof nobleObj; 16 | 17 | constructor(uuids: string[] = []) { 18 | super(); 19 | this.uuids = uuids; 20 | this.createNoble(); 21 | this.initNoble(); 22 | } 23 | 24 | protected createNoble() { 25 | this.noble = nobleObj; 26 | } 27 | 28 | protected initNoble() { 29 | if (typeof this.noble != "undefined") { 30 | this.noble.on('discover', this.onNobleDiscover.bind(this)); 31 | this.noble.on('stateChange', this.onNobleStateChange.bind(this)); 32 | this.noble.on('scanStart', this.onNobleScanStart.bind(this)); 33 | this.noble.on('scanStop', this.onNobleScanStop.bind(this)); 34 | } 35 | } 36 | 37 | getState(): ScannerStateType { 38 | return this.scannerState; 39 | } 40 | 41 | async startScan(passive: boolean): Promise { 42 | if (this.scannerState == "unknown" || this.scannerState == "stopped") { 43 | if (this.nobleState == "poweredOn") { 44 | this.scannerState = "starting"; 45 | // Fake passive mode using allowDuplicates for gateway only 46 | return await this.startNobleScan(passive); 47 | } else { 48 | return false; 49 | } 50 | } 51 | return false; 52 | } 53 | 54 | async stopScan(): Promise { 55 | if (this.scannerState == "scanning") { 56 | this.scannerState = "stopping"; 57 | return await this.stopNobleScan(); 58 | } 59 | return false; 60 | } 61 | 62 | private async startNobleScan(allowDuplicates: boolean = true): Promise { 63 | try { 64 | if (typeof this.noble != "undefined") { 65 | await this.noble.startScanningAsync(this.uuids, allowDuplicates); 66 | this.scannerState = "scanning"; 67 | return true; 68 | } 69 | } catch (error) { 70 | console.error(error); 71 | if (this.scannerState == "starting") { 72 | this.scannerState = "stopped"; 73 | } 74 | } 75 | return false; 76 | } 77 | 78 | private async stopNobleScan(): Promise { 79 | try { 80 | if (typeof this.noble != "undefined") { 81 | await this.noble.stopScanningAsync(); 82 | this.scannerState = "stopped"; 83 | return true; 84 | } 85 | } catch (error) { 86 | console.error(error); 87 | if (this.scannerState == "stopping") { 88 | this.scannerState = "scanning"; 89 | } 90 | } 91 | return false; 92 | } 93 | 94 | protected onNobleStateChange(state: nobleStateType): void { 95 | this.nobleState = state; 96 | if (this.nobleState == "poweredOn") { 97 | this.emit("ready"); 98 | } 99 | if (this.scannerState == "starting" && this.nobleState == "poweredOn") { 100 | this.startNobleScan(); 101 | } 102 | } 103 | 104 | protected async onNobleDiscover(peripheral: nobleObj.Peripheral): Promise { 105 | if (!this.devices.has(peripheral.id)) { 106 | const nobleDevice = new NobleDevice(peripheral); 107 | this.devices.set(peripheral.id, nobleDevice); 108 | if (this.checkPeripheralAdvertisement(peripheral)) { 109 | this.emit("discover", nobleDevice); 110 | } 111 | } else { 112 | //if the device was already found, maybe advertisement has changed 113 | let nobleDevice = this.devices.get(peripheral.id); 114 | if (typeof nobleDevice != "undefined") { 115 | nobleDevice.updateFromPeripheral(); 116 | if (this.checkPeripheralAdvertisement(peripheral)) { 117 | this.emit("discover", nobleDevice); 118 | } 119 | } 120 | } 121 | } 122 | 123 | protected checkPeripheralAdvertisement(peripheral: nobleObj.Peripheral): boolean { 124 | if (typeof this.uuids == "undefined" || this.uuids.length == 0) { 125 | return true; 126 | } 127 | 128 | if (typeof peripheral.advertisement != "undefined" && typeof peripheral.advertisement.serviceUuids != "undefined" && peripheral.advertisement.serviceUuids.length > 0) { 129 | // console.log(peripheral.advertisement.serviceUuids); 130 | for(let service of peripheral.advertisement.serviceUuids) { 131 | if (this.uuids.indexOf(service.replace('0x', '')) != -1) { 132 | return true; 133 | } 134 | } 135 | } 136 | return false; 137 | } 138 | 139 | protected onNobleScanStart(): void { 140 | this.scannerState = "scanning"; 141 | this.emit("scanStart"); 142 | } 143 | 144 | protected onNobleScanStop(): void { 145 | this.scannerState = "stopped"; 146 | this.emit("scanStop"); 147 | } 148 | } 149 | 150 | -------------------------------------------------------------------------------- /src/constant/APICommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export enum APICommand { 4 | OP_GET_LOCK_VERSION = 1, 5 | OP_ADD_ADMIN = 2, //Add administrator 6 | OP_UNLOCK_ADMIN = 3, //The administrator opens the door 7 | OP_UNLOCK_EKEY = 4, //Guantong users open the door 8 | OP_SET_KEYBOARD_PASSWORD = 5, //Set the administrator keyboard password 9 | OP_CALIBRATE_TIME = 6, 10 | OP_SET_NORMAL_USER_PASSWORD = 7, //Set delete password 11 | OP_READ_NORMAL_USER_PASSWORD = 8, 12 | OP_CLEAR_NORMAL_USER_PASSWORD = 9, 13 | OP_REMOVE_SINGLE_NORMAL_USER_PASSWORD = 10, 14 | OP_RESET_KEYBOARD_PASSWORD = 11, //Reset keyboard password 15 | OP_SET_DELETE_PASSWORD = 12, 16 | OP_LOCK_ADMIN = 13, //Parking lock admin closes the lock 17 | OP_LOCK_EKEY = 14, //Parking lock EKEY close lock 18 | OP_RESET_EKEY = 15, //set lockFlag 19 | 20 | /** 21 | * Initialization password 22 | */ 23 | OP_INIT_PWD = 16, 24 | 25 | //Set the lock name 26 | OP_SET_LOCK_NAME = 17, 27 | 28 | //Read door lock time 29 | OP_GET_LOCK_TIME = 18, 30 | 31 | //reset 32 | OP_RESET_LOCK = 19, 33 | 34 | /** 35 | * Add a one-time password, start time and end time are required 36 | */ 37 | OP_ADD_ONCE_KEYBOARD_PASSWORD = 20, 38 | 39 | /** 40 | * Add permanent keyboard password, need start time 41 | */ 42 | OP_ADD_PERMANENT_KEYBOARD_PASSWORD = 21, 43 | 44 | /** 45 | * Add period password 46 | */ 47 | OP_ADD_PERIOD_KEYBOARD_PASSWORD = 22, 48 | 49 | /** 50 | * change Password 51 | */ 52 | OP_MODIFY_KEYBOARD_PASSWORD = 23, 53 | 54 | /** 55 | * Delete a single password 56 | */ 57 | OP_REMOVE_ONE_PASSWORD = 24, 58 | 59 | /** 60 | * Delete all passwords in the lock 61 | */ 62 | OP_REMOVE_ALL_KEYBOARD_PASSWORD = 25, 63 | 64 | /** 65 | * Get operation log 66 | */ 67 | OP_GET_OPERATE_LOG = 26, 68 | 69 | /** 70 | * Query device characteristics 71 | */ 72 | OP_SEARCH_DEVICE_FEATURE = 27, 73 | 74 | /** 75 | * Query IC card number 76 | */ 77 | OP_SEARCH_IC_CARD_NO = 28, 78 | 79 | /** 80 | * Add IC card 81 | */ 82 | OP_ADD_IC = 29, 83 | 84 | /** 85 | * Modify the validity period of the IC card 86 | */ 87 | OP_MODIFY_IC_PERIOD = 30, 88 | 89 | /** 90 | * Delete IC card 91 | */ 92 | OP_DELETE_IC = 31, 93 | 94 | /** 95 | * Clear IC card 96 | */ 97 | OP_CLEAR_IC = 32, 98 | 99 | /** 100 | * Set the bracelet KEY 101 | */ 102 | OP_SET_WRIST_KEY = 33, 103 | 104 | /** 105 | * Add fingerprint 106 | */ 107 | OP_ADD_FR = 34, 108 | 109 | /** 110 | * Modify fingerprint validity period 111 | */ 112 | OP_MODIFY_FR_PERIOD = 35, 113 | 114 | /** 115 | * Delete fingerprint 116 | */ 117 | OP_DELETE_FR = 36, 118 | 119 | /** 120 | * Clear fingerprint 121 | */ 122 | OP_CLEAR_FR = 37, 123 | 124 | /** 125 | * Query the shortest and longest lockout time 126 | */ 127 | OP_SEARCH_AUTO_LOCK_PERIOD = 38, 128 | 129 | /** 130 | * Set the blocking time 131 | */ 132 | OP_SET_AUTO_LOCK_TIME = 39, 133 | 134 | /** 135 | * Enter upgrade mode 136 | */ 137 | OP_ENTER_DFU_MODE = 40, 138 | 139 | /** 140 | * Delete passwords in batch 141 | */ 142 | OP_BATCH_DELETE_PASSWORD = 41, 143 | 144 | /** 145 | * Locking function 146 | */ 147 | OP_LOCK = 42, 148 | 149 | /** 150 | * Show hidden password 151 | */ 152 | OP_SHOW_PASSWORD_ON_SCREEN = 43, 153 | 154 | /** 155 | * Data recovery 156 | */ 157 | OP_RECOVERY_DATA = 44, 158 | 159 | /** 160 | * Read password parameters 161 | */ 162 | OP_READ_PWD_PARA = 45, 163 | 164 | 165 | /** 166 | * Query fingerprint list 167 | */ 168 | OP_SEARCH_FR = 46, 169 | 170 | /** 171 | * Query password list 172 | */ 173 | OP_SEARCH_PWD = 47, 174 | 175 | /** 176 | * Control remote unlock switch 177 | */ 178 | OP_CONTROL_REMOTE_UNLOCK = 48, 179 | 180 | /** 181 | * Get battery 182 | */ 183 | OP_GET_POW = 49, 184 | 185 | OP_AUDIO_MANAGEMENT = 50, 186 | 187 | OP_REMOTE_CONTROL_DEVICE_MANAGEMENT = 51, 188 | 189 | /** 190 | * Door sensor operation 191 | */ 192 | OP_DOOR_SENSOR = 52, 193 | 194 | /** 195 | * Detection door sensor 196 | */ 197 | OP_DETECT_DOOR_SENSOR = 53, 198 | 199 | /** 200 | * Get lock switch status 201 | */ 202 | OP_GET_LOCK_SWITCH_STATE = 54, 203 | 204 | /** 205 | * Read device information 206 | */ 207 | OP_GET_DEVICE_INFO = 55, 208 | 209 | /** 210 | * Configure NB lock server address 211 | */ 212 | OP_CONFIGURE_NB_SERVER_ADDRESS = 56, 213 | 214 | OP_GET_ADMIN_KEYBOARD_PASSWORD = 57, //Read the administrator keyboard password 215 | 216 | OP_WRITE_FR = 58, //Write fingerprint data 217 | 218 | OP_QUERY_PASSAGE_MODE = 59, 219 | OP_ADD_OR_MODIFY_PASSAGE_MODE = 60, 220 | OP_DELETE_PASSAGE_MODE = 61, 221 | OP_CLEAR_PASSAGE_MODE = 62, 222 | OP_FREEZE_LOCK = 63, 223 | OP_LOCK_LAMP = 64, 224 | OP_SET_HOTEL_DATA = 65, 225 | OP_SET_SWITCH = 66, 226 | OP_GET_SWITCH = 67, 227 | OP_SET_HOTEL_CARD_SECTION = 68, 228 | OP_DEAD_LOCK = 69, 229 | OP_SET_ELEVATOR_CONTROL_FLOORS = 70, 230 | OP_SET_ELEVATOR_WORK_MODE = 71, 231 | OP_SET_NB_ACTIVATE_CONFIG = 72, 232 | OP_GET_NB_ACTIVATE_CONFIG = 73, 233 | OP_SET_NB_ACTIVATE_MODE = 74, 234 | OP_GET_NB_ACTIVATE_MODE = 75, 235 | } 236 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@tsconfig/node12/tsconfig.json", 3 | "compilerOptions": { 4 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 5 | 6 | /* Basic Options */ 7 | // "incremental": true, /* Enable incremental compilation */ 8 | // "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ 9 | // "module": "system", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ 10 | // "lib": [], /* Specify library files to be included in the compilation. */ 11 | // "allowJs": true, /* Allow javascript files to be compiled. */ 12 | "checkJs": true, /* Report errors in .js files. */ 13 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 14 | "declaration": true, /* Generates corresponding '.d.ts' file. */ 15 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 16 | // "sourceMap": true, /* Generates corresponding '.map' file. */ 17 | // "outFile": "./dist/ttlock-sdk.js", /* Concatenate and emit output to single file. */ 18 | "outDir": "./dist", /* Redirect output structure to the directory. */ 19 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 20 | // "composite": true, /* Enable project compilation */ 21 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 22 | // "removeComments": true, /* Do not emit comments to output. */ 23 | // "noEmit": true, /* Do not emit outputs. */ 24 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 25 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 26 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 27 | 28 | /* Strict Type-Checking Options */ 29 | // "strict": true, /* Enable all strict type-checking options. */ 30 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 31 | // "strictNullChecks": true, /* Enable strict null checks. */ 32 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 33 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 34 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 35 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 36 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 37 | 38 | /* Additional Checks */ 39 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 40 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 41 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 42 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 43 | 44 | /* Module Resolution Options */ 45 | // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 46 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 47 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 48 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 49 | // "typeRoots": [], /* List of folders to include type definitions from. */ 50 | // "types": [], /* Type declaration files to be included in compilation. */ 51 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 52 | // "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 53 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 54 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 55 | 56 | /* Source Map Options */ 57 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 58 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 59 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 60 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 61 | 62 | /* Experimental Options */ 63 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 64 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 65 | 66 | /* Advanced Options */ 67 | // "skipLibCheck": true, /* Skip type checking of declaration files. */ 68 | // "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ 69 | }, 70 | "include": ["src/**/*"] 71 | } 72 | -------------------------------------------------------------------------------- /src/TTLockClient.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import events from "events"; 4 | import { LockType } from "./constant/Lock"; 5 | import { TTBluetoothDevice } from "./device/TTBluetoothDevice"; 6 | import { TTLock } from "./device/TTLock"; 7 | 8 | import { BluetoothLeService, TTLockUUIDs, ScannerType } from "./scanner/BluetoothLeService"; 9 | import { ScannerOptions } from "./scanner/ScannerInterface"; 10 | import { TTLockData } from "./store/TTLockData"; 11 | import { sleep } from "./util/timingUtil"; 12 | 13 | export interface Settings { 14 | uuids?: string[]; 15 | scannerType?: ScannerType; 16 | scannerOptions?: ScannerOptions; 17 | lockData?: TTLockData[]; 18 | } 19 | 20 | export interface TTLockClient { 21 | on(event: "ready", listener: () => void): this; 22 | on(event: "foundLock", listener: (lock: TTLock) => void): this; 23 | on(event: "scanStart", listener: () => void): this; 24 | on(event: "scanStop", listener: () => void): this; 25 | on(event: "updatedLockData", listener: () => void): this; 26 | on(event: "monitorStart", listener: () => void): this; 27 | on(event: "monitorStop", listener: () => void): this; 28 | } 29 | 30 | export class TTLockClient extends events.EventEmitter implements TTLockClient { 31 | bleService: BluetoothLeService | null = null; 32 | uuids: string[]; 33 | scannerType: ScannerType = "noble"; 34 | scannerOptions: ScannerOptions; 35 | lockData: Map; 36 | private adapterReady: boolean; 37 | private lockDevices: Map = new Map(); 38 | private scanning: boolean = false; 39 | private monitoring: boolean = false; 40 | 41 | constructor(options: Settings) { 42 | super(); 43 | 44 | this.adapterReady = false; 45 | 46 | if (options.uuids) { 47 | this.uuids = options.uuids; 48 | } else { 49 | this.uuids = TTLockUUIDs; 50 | } 51 | 52 | if (typeof options.scannerType != "undefined") { 53 | this.scannerType = options.scannerType; 54 | } 55 | 56 | if (typeof options.scannerOptions != "undefined") { 57 | this.scannerOptions = options.scannerOptions; 58 | } else { 59 | this.scannerOptions = {}; 60 | } 61 | 62 | this.lockData = new Map(); 63 | if (options.lockData && options.lockData.length > 0) { 64 | this.setLockData(options.lockData); 65 | } 66 | } 67 | 68 | async prepareBTService(): Promise { 69 | if (this.bleService == null) { 70 | this.bleService = new BluetoothLeService(this.uuids, this.scannerType, this.scannerOptions); 71 | this.bleService.on("ready", () => { this.adapterReady = true; this.emit("ready") }); 72 | this.bleService.on("scanStart", this.onScanStart.bind(this)); 73 | this.bleService.on("scanStop", this.onScanStop.bind(this)); 74 | this.bleService.on("discover", this.onScanResult.bind(this)); 75 | // wait for adapter to become ready 76 | let counter = 5; 77 | do { 78 | await sleep(500); 79 | counter--; 80 | } while (counter > 0 && !this.adapterReady); 81 | return this.adapterReady; 82 | } 83 | return true; 84 | } 85 | 86 | stopBTService(): boolean { 87 | if (this.bleService != null) { 88 | this.stopScanLock(); 89 | this.bleService = null; 90 | } 91 | return true; 92 | } 93 | 94 | async startScanLock(): Promise { 95 | if (this.bleService != null && !this.scanning && !this.monitoring) { 96 | this.scanning = true; 97 | this.scanning = await this.bleService.startScan(); 98 | return this.scanning; 99 | } 100 | return false; 101 | } 102 | 103 | async stopScanLock(): Promise { 104 | if (this.bleService != null && this.isScanning()) { 105 | return await this.bleService.stopScan(); 106 | } 107 | return true; 108 | } 109 | 110 | async startMonitor(): Promise { 111 | if (this.bleService != null && !this.scanning && !this.monitoring) { 112 | this.monitoring = true; 113 | this.monitoring = await this.bleService.startScan(true); 114 | return this.monitoring; 115 | } 116 | return false; 117 | } 118 | 119 | async stopMonitor(): Promise { 120 | if (this.bleService != null && this.isMonitoring()) { 121 | return await this.bleService.stopScan(); 122 | } 123 | return false; 124 | } 125 | 126 | isScanning(): boolean { 127 | if (this.bleService) { 128 | return (this.bleService.isScanning() && this.scanning); 129 | } 130 | return false; 131 | } 132 | 133 | isMonitoring(): boolean { 134 | if (this.bleService) { 135 | return (this.bleService.isScanning() && this.monitoring); 136 | } 137 | return false; 138 | } 139 | 140 | getLockData(): TTLockData[] { 141 | const lockData: TTLockData[] = []; 142 | for (let [id, lock] of this.lockData) { 143 | lockData.push(lock); 144 | } 145 | return lockData; 146 | } 147 | 148 | setLockData(newLockData: TTLockData[]): void { 149 | this.lockData = new Map(); 150 | if (newLockData && newLockData.length > 0) { 151 | newLockData.forEach((lockData) => { 152 | this.lockData.set(lockData.address, lockData); 153 | const lock = this.lockDevices.get(lockData.address); 154 | if (typeof lock != "undefined") { 155 | lock.updateLockData(lockData); 156 | } 157 | }); 158 | } 159 | } 160 | 161 | private onScanStart(): void { 162 | if (this.scanning) { 163 | this.emit("scanStart"); 164 | } else if (this.monitoring) { 165 | this.emit("monitorStart"); 166 | } 167 | } 168 | 169 | private onScanStop(): void { 170 | if (this.scanning) { 171 | this.emit("scanStop"); 172 | this.scanning = false; 173 | } else if (this.monitoring) { 174 | this.emit("monitorStop"); 175 | this.monitoring = false; 176 | } 177 | } 178 | 179 | private onScanResult(device: TTBluetoothDevice): void { 180 | // Is it a Lock device ? 181 | if (device.lockType != LockType.UNKNOWN) { 182 | 183 | if (!this.lockDevices.has(device.address)) { 184 | const data = this.lockData.get(device.address); 185 | const lock = new TTLock(device, data); 186 | this.lockDevices.set(device.address, lock); 187 | lock.on("dataUpdated", (lock) => { 188 | const lockData = lock.getLockData(); 189 | if (typeof lockData != "undefined") { 190 | this.lockData.set(lockData.address, lockData); 191 | this.emit("updatedLockData"); 192 | } 193 | }); 194 | lock.on("lockReset", (address, id) => { 195 | this.lockData.delete(address); 196 | this.lockDevices.delete(address); 197 | this.bleService?.forgetDevice(id); 198 | this.emit("updatedLockData"); 199 | }); 200 | 201 | this.emit("foundLock", lock); 202 | } 203 | 204 | } 205 | } 206 | } 207 | -------------------------------------------------------------------------------- /src/api/Commands/ManageFRCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { CommandType } from "../../constant/CommandType"; 4 | import { ICOperate } from "../../constant/ICOperate"; 5 | import { dateTimeToBuffer } from "../../util/timeUtil"; 6 | import { Command } from "../Command"; 7 | 8 | export interface Fingerprint { 9 | fpNumber: string; 10 | startDate: string; 11 | endDate: string; 12 | } 13 | 14 | export class ManageFRCommand extends Command { 15 | static COMMAND_TYPE: CommandType = CommandType.COMM_FR_MANAGE; 16 | 17 | private opType?: ICOperate; 18 | private sequence?: number; 19 | private fingerprints?: Fingerprint[]; 20 | private fpNumber?: string; 21 | private startDate?: string; 22 | private endDate?: string; 23 | private batteryCapacity?: number; 24 | 25 | protected processData(): void { 26 | if (this.commandData && this.commandData.length > 1) { 27 | this.batteryCapacity = this.commandData.readUInt8(0); 28 | this.opType = this.commandData.readUInt8(1); 29 | switch(this.opType) { 30 | case ICOperate.FR_SEARCH: 31 | this.fingerprints = []; 32 | this.sequence = this.commandData.readInt16BE(2); 33 | let index = 4; 34 | while (index < this.commandData.length) { 35 | let fingerprint: Fingerprint = { 36 | fpNumber: "", 37 | startDate: "", 38 | endDate: "" 39 | }; 40 | 41 | const fp: Buffer = Buffer.alloc(8); 42 | this.commandData.copy(fp, 2, index); 43 | fingerprint.fpNumber = fp.readBigInt64BE().toString(); 44 | index += 6; 45 | 46 | fingerprint.startDate = "20" + this.commandData.readUInt8(index++).toString().padStart(2, '0') // year 47 | + this.commandData.readUInt8(index++).toString().padStart(2, '0') // month 48 | + this.commandData.readUInt8(index++).toString().padStart(2, '0') // day 49 | + this.commandData.readUInt8(index++).toString().padStart(2, '0') // hour 50 | + this.commandData.readUInt8(index++).toString().padStart(2, '0'); // minutes 51 | 52 | fingerprint.endDate = "20" + this.commandData.readUInt8(index++).toString().padStart(2, '0') // year 53 | + this.commandData.readUInt8(index++).toString().padStart(2, '0') // month 54 | + this.commandData.readUInt8(index++).toString().padStart(2, '0') // day 55 | + this.commandData.readUInt8(index++).toString().padStart(2, '0') // hour 56 | + this.commandData.readUInt8(index++).toString().padStart(2, '0'); // minutes 57 | 58 | this.fingerprints.push(fingerprint); 59 | } 60 | break; 61 | case ICOperate.ADD: 62 | let status = this.commandData.readUInt8(2); 63 | this.opType = status; 64 | switch (status) { 65 | case ICOperate.STATUS_ADD_SUCCESS: 66 | // TODO: APICommand.OP_RECOVERY_DATA 67 | const fp: Buffer = Buffer.alloc(8); 68 | this.commandData.copy(fp, 2, 3); 69 | this.fpNumber = fp.readBigInt64BE().toString(); 70 | break; 71 | case ICOperate.STATUS_ENTER_ADD_MODE: 72 | // entered add mode 73 | break; 74 | case ICOperate.STATUS_FR_PROGRESS: 75 | // progress reading fingerprint 76 | break; 77 | case ICOperate.STATUS_FR_RECEIVE_TEMPLATE: 78 | // ready to receive fingerprint template 79 | break; 80 | } 81 | break; 82 | case ICOperate.MODIFY: 83 | break; 84 | case ICOperate.DELETE: 85 | break; 86 | case ICOperate.CLEAR: 87 | break; 88 | } 89 | } 90 | } 91 | 92 | build(): Buffer { 93 | if (typeof this.opType != "undefined") { 94 | switch (this.opType) { 95 | case ICOperate.FR_SEARCH: 96 | if (typeof this.sequence != "undefined") { 97 | const data = Buffer.alloc(3); 98 | data.writeUInt8(this.opType, 0); 99 | data.writeUInt16BE(this.sequence, 1); 100 | return data; 101 | } 102 | break; 103 | case ICOperate.ADD: 104 | case ICOperate.MODIFY: 105 | if (typeof this.fpNumber == "undefined") { 106 | return Buffer.from([this.opType]); 107 | } else { 108 | if (this.fpNumber && this.startDate && this.endDate) { 109 | const data: Buffer = Buffer.alloc(17); 110 | data.writeUInt8(this.opType, 0); 111 | 112 | const fp: Buffer = Buffer.alloc(8); 113 | fp.writeBigInt64BE(BigInt(this.fpNumber)); 114 | fp.copy(data, 1, 2); 115 | 116 | dateTimeToBuffer(this.startDate.substr(2) + this.endDate.substr(2)).copy(data, 7); 117 | 118 | return data; 119 | } 120 | } 121 | break; 122 | case ICOperate.CLEAR: 123 | return Buffer.from([this.opType]); 124 | case ICOperate.DELETE: 125 | if (this.fpNumber) { 126 | const data = Buffer.alloc(7); 127 | data.writeUInt8(this.opType, 0); 128 | 129 | const fp: Buffer = Buffer.alloc(8); 130 | fp.writeBigInt64BE(BigInt(this.fpNumber)); 131 | fp.copy(data, 1, 2); 132 | 133 | return data; 134 | } 135 | break; 136 | } 137 | } 138 | return Buffer.from([]); 139 | } 140 | 141 | getType(): ICOperate { 142 | return this.opType || ICOperate.IC_SEARCH; 143 | } 144 | 145 | getFpNumber(): string { 146 | if (this.fpNumber) { 147 | return this.fpNumber; 148 | } 149 | return ""; 150 | } 151 | 152 | setSequence(sequence: number = 0) { 153 | this.sequence = sequence; 154 | this.opType = ICOperate.FR_SEARCH; 155 | } 156 | 157 | getSequence(): number { 158 | if (this.sequence) { 159 | return this.sequence; 160 | } else { 161 | return -1; 162 | } 163 | } 164 | 165 | setAdd(): void { 166 | this.opType = ICOperate.ADD; 167 | } 168 | 169 | setModify(fpNumber: string, startDate: string, endDate: string): void { 170 | this.fpNumber = fpNumber; 171 | this.startDate = startDate; 172 | this.endDate = endDate; 173 | this.opType = ICOperate.MODIFY; 174 | } 175 | 176 | setDelete(fpNumber: string): void { 177 | this.fpNumber = fpNumber; 178 | this.opType = ICOperate.DELETE; 179 | } 180 | 181 | setClear(): void { 182 | this.opType = ICOperate.CLEAR; 183 | } 184 | 185 | getFingerprints(): Fingerprint[] { 186 | if (this.fingerprints) { 187 | return this.fingerprints; 188 | } 189 | return []; 190 | } 191 | 192 | getBatteryCapacity(): number { 193 | if (this.batteryCapacity) { 194 | return this.batteryCapacity; 195 | } else { 196 | return -1; 197 | } 198 | } 199 | } -------------------------------------------------------------------------------- /src/api/Commands/ManageKeyboardPasswordCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import moment from "moment"; 4 | import { CommandType } from "../../constant/CommandType"; 5 | import { DateConstant } from "../../constant/DateConstant"; 6 | import { KeyboardPwdType } from "../../constant/KeyboardPwdType"; 7 | import { PwdOperateType } from "../../constant/PwdOperateType"; 8 | import { Command } from "../Command"; 9 | 10 | export class ManageKeyboardPasswordCommand extends Command { 11 | static COMMAND_TYPE: CommandType = CommandType.COMM_MANAGE_KEYBOARD_PASSWORD; 12 | 13 | private opType: PwdOperateType = PwdOperateType.PWD_OPERATE_TYPE_ADD; 14 | private type?: KeyboardPwdType; 15 | private oldPassCode?: string; 16 | private passCode?: string; 17 | private startDate?: moment.Moment; 18 | private endDate?: moment.Moment; 19 | 20 | protected processData(): void { 21 | if (this.commandData && this.commandData.length > 1) { 22 | this.opType = this.commandData.readUInt8(1); 23 | } 24 | } 25 | 26 | build(): Buffer { 27 | switch (this.opType) { 28 | case PwdOperateType.PWD_OPERATE_TYPE_CLEAR: 29 | return Buffer.from([this.opType]); 30 | case PwdOperateType.PWD_OPERATE_TYPE_ADD: 31 | return this.buildAdd(); 32 | case PwdOperateType.PWD_OPERATE_TYPE_REMOVE_ONE: 33 | return this.buildDel(); 34 | case PwdOperateType.PWD_OPERATE_TYPE_MODIFY: 35 | return this.buildEdit(); 36 | } 37 | return Buffer.from([]); 38 | } 39 | 40 | getOpType(): PwdOperateType { 41 | return this.opType; 42 | } 43 | 44 | addPasscode(type: KeyboardPwdType, passCode: string, startDate: string = DateConstant.START_DATE_TIME, endDate: string = DateConstant.END_DATE_TIME): boolean { 45 | this.type = type; 46 | if (passCode.length >= 4 && passCode.length <= 9) { 47 | this.oldPassCode = ""; 48 | this.passCode = passCode; 49 | } else { 50 | return false; 51 | } 52 | this.startDate = moment(startDate, "YYYYMMDDHHmm"); 53 | if (!this.startDate.isValid()) { 54 | return false; 55 | } 56 | this.endDate = moment(endDate, "YYYYMMDDHHmm"); 57 | if (!this.endDate.isValid()) { 58 | return false; 59 | } 60 | this.opType = PwdOperateType.PWD_OPERATE_TYPE_ADD; 61 | return true; 62 | } 63 | 64 | updatePasscode(type: KeyboardPwdType, oldPassCode: string, newPassCode: string, startDate: string = DateConstant.START_DATE_TIME, endDate: string = DateConstant.END_DATE_TIME): boolean { 65 | this.type = type; 66 | if (oldPassCode.length >= 4 && oldPassCode.length <= 9) { 67 | this.oldPassCode = oldPassCode; 68 | } else { 69 | return false; 70 | } 71 | if (newPassCode.length >= 4 && newPassCode.length <= 9) { 72 | this.passCode = newPassCode; 73 | } else { 74 | return false; 75 | } 76 | this.startDate = moment(startDate, "YYYYMMDDHHmm"); 77 | if (!this.startDate.isValid()) { 78 | return false; 79 | } 80 | this.endDate = moment(endDate, "YYYYMMDDHHmm"); 81 | if (!this.endDate.isValid()) { 82 | return false; 83 | } 84 | this.opType = PwdOperateType.PWD_OPERATE_TYPE_MODIFY; 85 | return true; 86 | } 87 | 88 | deletePasscode(type: KeyboardPwdType, oldPassCode: string): boolean { 89 | this.type = type; 90 | if (oldPassCode.length >= 4 && oldPassCode.length <= 9) { 91 | this.oldPassCode = oldPassCode; 92 | } else { 93 | return false; 94 | } 95 | this.opType = PwdOperateType.PWD_OPERATE_TYPE_REMOVE_ONE; 96 | return true; 97 | } 98 | 99 | clearAllPasscodes() { 100 | this.opType = PwdOperateType.PWD_OPERATE_TYPE_CLEAR; 101 | } 102 | 103 | private buildAdd(): Buffer { 104 | if (typeof this.type != "undefined" && typeof this.passCode != "undefined" && this.startDate && this.endDate) { 105 | let data: Buffer; 106 | if (this.type == KeyboardPwdType.PWD_TYPE_PERMANENT) { 107 | data = Buffer.alloc(1 + 1 + 1 + this.passCode.length + 5 + 5); 108 | } else { 109 | data = Buffer.alloc(1 + 1 + 1 + this.passCode.length + 5); 110 | } 111 | let index = 0; 112 | data.writeUInt8(this.opType, index++); 113 | data.writeUInt8(this.type, index++); 114 | data.writeUInt8(this.passCode.length, index++); 115 | 116 | for (let i = 0; i < this.passCode.length; i++) { 117 | data.writeUInt8(this.passCode.charCodeAt(i), index++); 118 | } 119 | 120 | data.writeUInt8(parseInt(this.startDate.format("YY")), index++); 121 | data.writeUInt8(parseInt(this.startDate.format("MM")), index++); 122 | data.writeUInt8(parseInt(this.startDate.format("DD")), index++); 123 | data.writeUInt8(parseInt(this.startDate.format("HH")), index++); 124 | data.writeUInt8(parseInt(this.startDate.format("mm")), index++); 125 | 126 | if (this.type != KeyboardPwdType.PWD_TYPE_PERMANENT) { 127 | data.writeUInt8(parseInt(this.endDate.format("YY")), index++); 128 | data.writeUInt8(parseInt(this.endDate.format("MM")), index++); 129 | data.writeUInt8(parseInt(this.endDate.format("DD")), index++); 130 | data.writeUInt8(parseInt(this.endDate.format("HH")), index++); 131 | data.writeUInt8(parseInt(this.endDate.format("mm")), index++); 132 | } 133 | 134 | return data; 135 | } else { 136 | return Buffer.from([]); 137 | } 138 | } 139 | 140 | private buildDel(): Buffer { 141 | if (typeof this.type != "undefined" && typeof this.oldPassCode != "undefined") { 142 | let data: Buffer = Buffer.alloc(1 + 1 + 1 + this.oldPassCode.length); 143 | let index = 0; 144 | data.writeUInt8(this.opType, index++); 145 | data.writeUInt8(this.type, index++); 146 | data.writeUInt8(this.oldPassCode.length, index++); 147 | 148 | for (let i = 0; i < this.oldPassCode.length; i++) { 149 | data.writeUInt8(this.oldPassCode.charCodeAt(i), index++); 150 | } 151 | 152 | return data; 153 | } else { 154 | return Buffer.from([]); 155 | } 156 | } 157 | 158 | private buildEdit(): Buffer { 159 | if (typeof this.type != "undefined" && typeof this.oldPassCode != "undefined" && typeof this.passCode != "undefined" && this.startDate && this.endDate) { 160 | let data: Buffer = Buffer.alloc(1 + 1 + 1 + this.oldPassCode.length + 1 + this.passCode.length + 5 + 5); 161 | let index = 0; 162 | data.writeUInt8(this.opType, index++); 163 | data.writeUInt8(this.type, index++); 164 | data.writeUInt8(this.oldPassCode.length, index++); 165 | for (let i = 0; i < this.oldPassCode.length; i++) { 166 | data.writeUInt8(this.oldPassCode.charCodeAt(i), index++); 167 | } 168 | 169 | data.writeUInt8(this.passCode.length, index++); 170 | for (let i = 0; i < this.passCode.length; i++) { 171 | data.writeUInt8(this.passCode.charCodeAt(i), index++); 172 | } 173 | 174 | data.writeUInt8(parseInt(this.startDate.format("YY")), index++); 175 | data.writeUInt8(parseInt(this.startDate.format("MM")), index++); 176 | data.writeUInt8(parseInt(this.startDate.format("DD")), index++); 177 | data.writeUInt8(parseInt(this.startDate.format("HH")), index++); 178 | data.writeUInt8(parseInt(this.startDate.format("mm")), index++); 179 | 180 | data.writeUInt8(parseInt(this.endDate.format("YY")), index++); 181 | data.writeUInt8(parseInt(this.endDate.format("MM")), index++); 182 | data.writeUInt8(parseInt(this.endDate.format("DD")), index++); 183 | data.writeUInt8(parseInt(this.endDate.format("HH")), index++); 184 | data.writeUInt8(parseInt(this.endDate.format("mm")), index++); 185 | 186 | return data; 187 | } else { 188 | return Buffer.from([]); 189 | } 190 | } 191 | } -------------------------------------------------------------------------------- /src/api/Commands/ManageICCommand.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { CommandType } from "../../constant/CommandType"; 4 | import { ICOperate } from "../../constant/ICOperate"; 5 | import { dateTimeToBuffer } from "../../util/timeUtil"; 6 | import { Command } from "../Command"; 7 | 8 | export interface ICCard { 9 | cardNumber: string; 10 | startDate: string; 11 | endDate: string; 12 | } 13 | 14 | export class ManageICCommand extends Command { 15 | static COMMAND_TYPE: CommandType = CommandType.COMM_IC_MANAGE; 16 | 17 | private opType?: ICOperate; 18 | private sequence?: number; 19 | private cards?: ICCard[]; 20 | private cardNumber?: string; 21 | private startDate?: string; 22 | private endDate?: string; 23 | private batteryCapacity?: number; 24 | 25 | protected processData(): void { 26 | if (this.commandData && this.commandData.length > 1) { 27 | this.batteryCapacity = this.commandData.readUInt8(0); 28 | this.opType = this.commandData.readUInt8(1); 29 | switch(this.opType) { 30 | case ICOperate.IC_SEARCH: 31 | this.cards = []; 32 | this.sequence = this.commandData.readInt16BE(2); 33 | let index = 4; 34 | while (index < this.commandData.length) { 35 | let card: ICCard = { 36 | cardNumber: "", 37 | startDate: "", 38 | endDate: "" 39 | }; 40 | if (this.commandData.length == 24) { 41 | card.cardNumber = this.commandData.readBigUInt64BE(index).toString(); 42 | index += 8; 43 | } else { 44 | card.cardNumber = this.commandData.readUInt32BE(index).toString(); 45 | index += 4; 46 | } 47 | 48 | card.startDate = "20" + this.commandData.readUInt8(index++).toString().padStart(2, '0') // year 49 | + this.commandData.readUInt8(index++).toString().padStart(2, '0') // month 50 | + this.commandData.readUInt8(index++).toString().padStart(2, '0') // day 51 | + this.commandData.readUInt8(index++).toString().padStart(2, '0') // hour 52 | + this.commandData.readUInt8(index++).toString().padStart(2, '0'); // minutes 53 | 54 | card.endDate = "20" + this.commandData.readUInt8(index++).toString().padStart(2, '0') // year 55 | + this.commandData.readUInt8(index++).toString().padStart(2, '0') // month 56 | + this.commandData.readUInt8(index++).toString().padStart(2, '0') // day 57 | + this.commandData.readUInt8(index++).toString().padStart(2, '0') // hour 58 | + this.commandData.readUInt8(index++).toString().padStart(2, '0'); // minutes 59 | 60 | this.cards.push(card); 61 | } 62 | break; 63 | case ICOperate.ADD: 64 | let status = this.commandData.readUInt8(2); 65 | this.opType = status; 66 | switch (status) { 67 | case ICOperate.STATUS_ADD_SUCCESS: 68 | // TODO: APICommand.OP_RECOVERY_DATA 69 | let len = this.commandData.length - 3; 70 | // remaining length should be 4 or 8, but if the last 4 bytes are 0xff they should be ignored 71 | if (len == 4 || this.commandData.readUInt32BE(this.commandData.length - 5).toString(16) == 'ffffffff') { 72 | this.cardNumber = this.commandData.readUInt32BE(3).toString(); 73 | } else { 74 | this.cardNumber = this.commandData.readBigUInt64BE(3).toString(); 75 | } 76 | break; 77 | case ICOperate.STATUS_ENTER_ADD_MODE: 78 | // entered add mode 79 | break; 80 | 81 | } 82 | break; 83 | case ICOperate.MODIFY: 84 | break; 85 | case ICOperate.DELETE: 86 | break; 87 | case ICOperate.CLEAR: 88 | break; 89 | } 90 | } 91 | } 92 | 93 | build(): Buffer { 94 | if (this.opType) { 95 | switch (this.opType) { 96 | case ICOperate.IC_SEARCH: 97 | if (typeof this.sequence != "undefined") { 98 | let data = Buffer.alloc(3); 99 | data.writeUInt8(this.opType, 0); 100 | data.writeUInt16BE(this.sequence, 1); 101 | return data; 102 | } 103 | break; 104 | case ICOperate.ADD: 105 | case ICOperate.MODIFY: 106 | if (typeof this.cardNumber == "undefined") { 107 | return Buffer.from([this.opType]); 108 | } else { 109 | if (this.cardNumber && this.startDate && this.endDate) { 110 | let data: Buffer; 111 | let index = 0; 112 | if (this.cardNumber.length > 10) { 113 | data = Buffer.alloc(19); 114 | data.writeBigUInt64BE(BigInt(this.cardNumber), 1); 115 | index = 9; 116 | } else { 117 | data = Buffer.alloc(15); 118 | data.writeUInt32BE(parseInt(this.cardNumber), 1); 119 | index = 5; 120 | } 121 | data.writeUInt8(this.opType, 0); 122 | 123 | dateTimeToBuffer(this.startDate.substr(2) + this.endDate.substr(2)).copy(data, index); 124 | 125 | return data; 126 | } 127 | } 128 | break; 129 | case ICOperate.CLEAR: 130 | return Buffer.from([this.opType]); 131 | case ICOperate.DELETE: 132 | if (this.cardNumber) { 133 | if (this.cardNumber.length > 10) { 134 | const data = Buffer.alloc(9); 135 | data.writeUInt8(this.opType, 0); 136 | data.writeBigUInt64BE(BigInt(this.cardNumber), 1); 137 | } else { 138 | const data = Buffer.alloc(5); 139 | data.writeUInt8(this.opType, 0); 140 | data.writeUInt32BE(parseInt(this.cardNumber), 1); 141 | return data; 142 | } 143 | } 144 | break; 145 | } 146 | } 147 | return Buffer.from([]); 148 | } 149 | 150 | getType(): ICOperate { 151 | return this.opType || ICOperate.IC_SEARCH; 152 | } 153 | 154 | getCardNumber(): string { 155 | if (this.cardNumber) { 156 | return this.cardNumber; 157 | } 158 | else return ""; 159 | } 160 | 161 | setSequence(sequence: number = 0) { 162 | this.sequence = sequence; 163 | this.opType = ICOperate.IC_SEARCH; 164 | } 165 | 166 | getSequence(): number { 167 | if (this.sequence) { 168 | return this.sequence; 169 | } else { 170 | return -1; 171 | } 172 | } 173 | 174 | setAdd(cardNumber?: string, startDate?: string, endDate?: string): void { 175 | if (typeof cardNumber != "undefined" && typeof startDate != "undefined" && typeof endDate != "undefined") { 176 | this.cardNumber = cardNumber; 177 | this.startDate = startDate; 178 | this.endDate = endDate; 179 | } 180 | this.opType = ICOperate.ADD; 181 | } 182 | 183 | setModify(cardNumber: string, startDate: string, endDate: string): void { 184 | this.cardNumber = cardNumber; 185 | this.startDate = startDate; 186 | this.endDate = endDate; 187 | this.opType = ICOperate.MODIFY; 188 | } 189 | 190 | setDelete(cardNumber: string): void { 191 | this.cardNumber = cardNumber; 192 | this.opType = ICOperate.DELETE; 193 | } 194 | 195 | setClear(): void { 196 | this.opType = ICOperate.CLEAR; 197 | } 198 | 199 | getCards(): ICCard[] { 200 | if (this.cards) { 201 | return this.cards; 202 | } 203 | return []; 204 | } 205 | 206 | getBatteryCapacity(): number { 207 | if (this.batteryCapacity) { 208 | return this.batteryCapacity; 209 | } else { 210 | return -1; 211 | } 212 | } 213 | } -------------------------------------------------------------------------------- /src/scanner/noble/NobleDevice.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { DeviceInterface, ServiceInterface } from "../DeviceInterface"; 4 | import { Peripheral, Service } from "@abandonware/noble"; 5 | import { EventEmitter } from "events"; 6 | import { NobleService } from "./NobleService"; 7 | import { sleep } from "../../util/timingUtil"; 8 | 9 | export class NobleDevice extends EventEmitter implements DeviceInterface { 10 | id: string; 11 | uuid: string; 12 | name: string; 13 | address: string; 14 | addressType: string; 15 | connectable: boolean; 16 | connecting: boolean = false; 17 | connected: boolean = false; 18 | rssi: number; 19 | mtu: number = 20; 20 | manufacturerData: Buffer; 21 | services: Map; 22 | busy: boolean = false; 23 | private peripheral: Peripheral; 24 | 25 | constructor(peripheral: Peripheral) { 26 | super(); 27 | this.peripheral = peripheral; 28 | this.id = peripheral.id; 29 | this.uuid = peripheral.uuid; 30 | this.name = peripheral.advertisement.localName; 31 | this.address = peripheral.address.replace(/\-/g, ':').toUpperCase(); 32 | this.addressType = peripheral.addressType; 33 | this.connectable = peripheral.connectable; 34 | this.rssi = peripheral.rssi 35 | // this.mtu = peripheral.mtu; 36 | if (peripheral.advertisement.manufacturerData) { 37 | this.manufacturerData = peripheral.advertisement.manufacturerData; 38 | } else { 39 | this.manufacturerData = Buffer.from([]); 40 | } 41 | this.peripheral.on("connect", this.onConnect.bind(this)); 42 | this.peripheral.on("disconnect", this.onDisconnect.bind(this)); 43 | this.services = new Map(); 44 | } 45 | 46 | updateFromPeripheral() { 47 | this.name = this.peripheral.advertisement.localName; 48 | this.address = this.peripheral.address.replace(/\-/g, ':').toUpperCase(); 49 | this.addressType = this.peripheral.addressType; 50 | this.connectable = this.peripheral.connectable; 51 | this.rssi = this.peripheral.rssi 52 | // this.mtu = peripheral.mtu; 53 | if (this.peripheral.advertisement.manufacturerData) { 54 | this.manufacturerData = this.peripheral.advertisement.manufacturerData; 55 | } else { 56 | this.manufacturerData = Buffer.from([]); 57 | } 58 | } 59 | 60 | checkBusy(): boolean { 61 | if (this.busy) { 62 | throw new Error("NobleDevice is busy"); 63 | } else { 64 | this.busy = true; 65 | return true; 66 | } 67 | } 68 | 69 | resetBusy(): boolean { 70 | if (this.busy) { 71 | this.busy = false; 72 | } 73 | return this.busy; 74 | } 75 | 76 | async connect(timeout: number = 10): Promise { 77 | if (this.connectable && !this.connected && !this.connecting) { 78 | if (this.peripheral.state == "connected") { 79 | this.connected = true; 80 | return true; 81 | } 82 | this.connecting = true; 83 | console.log("Peripheral connect start"); 84 | this.peripheral.connect((error) => { 85 | if (typeof error != "undefined" && error != null) { 86 | console.log("Peripheral connect error:", error); 87 | } else { 88 | console.log("Peripheral state:", this.peripheral.state); 89 | if (this.peripheral.state == "connected") { 90 | this.connected = true; 91 | this.connecting = false; 92 | } 93 | } 94 | }); 95 | let timeoutCycles = timeout * 10; 96 | do { 97 | await sleep(100); 98 | timeoutCycles--; 99 | } while (!this.connected && timeoutCycles > 0 && this.connecting); 100 | await sleep(10); 101 | if (!this.connected) { 102 | this.connecting = false; 103 | try { 104 | this.peripheral.cancelConnect(); 105 | } catch (error) { } 106 | return false; 107 | } 108 | console.log("Device emiting connected"); 109 | this.emit("connected"); 110 | return true; 111 | } 112 | console.log("Peripheral state:", this.peripheral.state); 113 | return false; 114 | } 115 | 116 | async disconnect(): Promise { 117 | if (this.connectable && this.connected) { 118 | try { 119 | await this.peripheral.disconnectAsync(); 120 | return true; 121 | } catch (error) { 122 | console.error(error); 123 | return false; 124 | } 125 | } 126 | return false; 127 | } 128 | 129 | /** 130 | * Discover all services, characteristics and descriptors 131 | */ 132 | async discoverAll(): Promise> { 133 | try { 134 | this.checkBusy(); 135 | if (!this.connected) { 136 | this.resetBusy(); 137 | throw new Error("NobleDevice not connected"); 138 | } 139 | const snc = await this.peripheral.discoverAllServicesAndCharacteristicsAsync(); 140 | this.resetBusy(); 141 | this.services = new Map(); 142 | snc.services.forEach((service) => { 143 | const s = new NobleService(this, service); 144 | this.services.set(s.getUUID(), s); 145 | }); 146 | return this.services; 147 | } catch (error) { 148 | console.error(error); 149 | this.resetBusy(); 150 | return new Map(); 151 | } 152 | } 153 | 154 | /** 155 | * Discover services only 156 | */ 157 | async discoverServices(): Promise> { 158 | try { 159 | this.checkBusy(); 160 | if (!this.connected) { 161 | this.resetBusy(); 162 | throw new Error("NobleDevice not connected"); 163 | } 164 | let timeoutCycles = 10 * 100; 165 | let services: Service[] = []; 166 | this.services = new Map(); 167 | this.peripheral.discoverServices([], (error, discoveredServices) => { 168 | services = discoveredServices; 169 | }); 170 | do { 171 | await sleep(10); 172 | timeoutCycles--; 173 | } while (services.length == 0 && timeoutCycles > 0 && this.connected); 174 | // const services = await this.peripheral.discoverServicesAsync(); 175 | this.resetBusy(); 176 | if (!this.connected) { 177 | return this.services; 178 | } 179 | if (services.length > 0) { 180 | for (let service of services) { 181 | const s = new NobleService(this, service); 182 | this.services.set(s.getUUID(), s); 183 | } 184 | } 185 | return this.services; 186 | } catch (error) { 187 | console.error(error); 188 | this.resetBusy(); 189 | return new Map(); 190 | } 191 | } 192 | 193 | /** 194 | * Read all available characteristics 195 | */ 196 | async readCharacteristics(): Promise { 197 | try { 198 | if (!this.connected) { 199 | throw new Error("NobleDevice not connected"); 200 | } 201 | if (this.services.size == 0) { 202 | await this.discoverServices(); 203 | } 204 | for (let [uuid, service] of this.services) { 205 | for (let [uuid, characteristic] of service.characteristics) { 206 | if (characteristic.properties.includes("read")) { 207 | console.log("Reading", uuid); 208 | const data = await characteristic.read(); 209 | if (typeof data != "undefined") { 210 | console.log("Data", data.toString("ascii")); 211 | } 212 | } 213 | } 214 | } 215 | return true; 216 | } catch (error) { 217 | console.error(error); 218 | return false; 219 | } 220 | } 221 | 222 | onConnect(error: string) { 223 | console.log("Peripheral connect triggered"); 224 | // if (typeof error != "undefined" && error != "" && error != null) { 225 | // this.connected = false; 226 | // } else { 227 | // this.connected = true; 228 | // } 229 | // this.connecting = false; 230 | } 231 | 232 | onDisconnect(error: string) { 233 | this.connected = false; 234 | this.connecting = false; 235 | this.resetBusy(); 236 | this.services = new Map(); 237 | this.emit("disconnected"); 238 | } 239 | 240 | toString(): string { 241 | let text = ""; 242 | this.services.forEach((service) => { 243 | text += service.toString() + "\n"; 244 | }); 245 | return text; 246 | } 247 | 248 | toJSON(asObject: boolean = false): string | Object { 249 | let json: Record = { 250 | id: this.id, 251 | uuid: this.uuid, 252 | name: this.name, 253 | address: this.address, 254 | addressType: this.addressType, 255 | connectable: this.connectable, 256 | rssi: this.rssi, 257 | mtu: this.mtu, 258 | services: {} 259 | }; 260 | let services: Record = {} 261 | this.services.forEach((service) => { 262 | json.services[service.uuid] = service.toJSON(true); 263 | }); 264 | 265 | if (asObject) { 266 | return json; 267 | } else { 268 | return JSON.stringify(json); 269 | } 270 | } 271 | } --------------------------------------------------------------------------------