From 7fdc754084eeb9dc3024d36cc8bc7680d86207fe Mon Sep 17 00:00:00 2001 From: Nathan Kellenicki Date: Tue, 10 Dec 2019 07:23:33 +0900 Subject: [PATCH] Start of hub refactor --- src/basicmotor.ts | 2 +- src/boostmovehub.ts | 5 +- src/controlplushub.ts | 5 +- src/device.ts | 6 +- src/duplotrainbase.ts | 5 +- src/hub.ts | 149 ++------------------------------------- src/lpf2hub.ts | 93 +++++++++++------------- src/poweredup-browser.ts | 15 ++-- src/poweredup-node.ts | 15 ++-- src/puphub.ts | 5 +- src/pupremote.ts | 5 +- src/tachomotor.ts | 2 +- src/wedo2smarthub.ts | 5 +- 13 files changed, 78 insertions(+), 234 deletions(-) diff --git a/src/basicmotor.ts b/src/basicmotor.ts index 4330416..288387c 100644 --- a/src/basicmotor.ts +++ b/src/basicmotor.ts @@ -8,7 +8,7 @@ import { mapSpeed } from "./utils"; export class BasicMotor extends Device { - constructor (hub: Hub, portId: number, type: number = Consts.DeviceType.UNKNOWN) { + constructor (hub: Hub, portId: number, type: Consts.DeviceType = Consts.DeviceType.UNKNOWN) { super(hub, portId, type); } diff --git a/src/boostmovehub.ts b/src/boostmovehub.ts index e36eee3..013b9c9 100644 --- a/src/boostmovehub.ts +++ b/src/boostmovehub.ts @@ -34,9 +34,8 @@ export class BoostMoveHub extends LPF2Hub { protected _currentPort = 0x3b; protected _voltagePort = 0x3c; - constructor (device: IBLEAbstraction, autoSubscribe: boolean = true) { - super(device, autoSubscribe); - this._type = Consts.HubType.BOOST_MOVE_HUB; + constructor (device: IBLEAbstraction) { + super(device, Consts.HubType.BOOST_MOVE_HUB); this._portNames = { "A": 0, "B": 1, diff --git a/src/controlplushub.ts b/src/controlplushub.ts index 8d8cdaf..c23ea51 100644 --- a/src/controlplushub.ts +++ b/src/controlplushub.ts @@ -36,9 +36,8 @@ export class ControlPlusHub extends LPF2Hub { protected _voltageMaxRaw = 4095; protected _voltageMaxV = 9.615; - constructor (device: IBLEAbstraction, autoSubscribe: boolean = true) { - super(device, autoSubscribe); - this._type = Consts.HubType.CONTROL_PLUS_HUB; + constructor (device: IBLEAbstraction) { + super(device, Consts.HubType.CONTROL_PLUS_HUB); this._portNames = { "A": 0, "B": 1, diff --git a/src/device.ts b/src/device.ts index b49e529..86dd1ec 100644 --- a/src/device.ts +++ b/src/device.ts @@ -14,9 +14,9 @@ export class Device extends EventEmitter { private _hub: Hub; private _portId: number; private _connected: boolean = true; - private _type: number; + private _type: Consts.DeviceType; - constructor (hub: Hub, portId: number, type: number = Consts.DeviceType.UNKNOWN) { + constructor (hub: Hub, portId: number, type: Consts.DeviceType = Consts.DeviceType.UNKNOWN) { super(); this._hub = hub; this._portId = portId; @@ -61,7 +61,7 @@ export class Device extends EventEmitter { public subscribe (mode: number) { if (mode !== this._mode) { this._mode = mode; - this.send(Buffer.from([0x41, this.portId, mode, 0x01, 0x00, 0x00, 0x00, 0x01])); + this.hub.subscribe(this.portId, mode); } } diff --git a/src/duplotrainbase.ts b/src/duplotrainbase.ts index fd24fc3..ece154b 100644 --- a/src/duplotrainbase.ts +++ b/src/duplotrainbase.ts @@ -35,9 +35,8 @@ export class DuploTrainBase extends LPF2Hub { protected _voltageMaxV = 6.4; protected _voltageMaxRaw = 3047; - constructor (device: IBLEAbstraction, autoSubscribe: boolean = true) { - super(device, autoSubscribe); - this._type = Consts.HubType.DUPLO_TRAIN_HUB; + constructor (device: IBLEAbstraction) { + super(device, Consts.HubType.DUPLO_TRAIN_HUB); this._portNames = { "MOTOR": 0, "COLOR": 18, diff --git a/src/hub.ts b/src/hub.ts index 76899f7..dfdd4b4 100644 --- a/src/hub.ts +++ b/src/hub.ts @@ -15,10 +15,7 @@ const debug = Debug("hub"); */ export class Hub extends EventEmitter { - - public autoSubscribe: boolean = true; public useSpeedMap: boolean = true; - protected _type: Consts.HubType = Consts.HubType.UNKNOWN; protected _attachedDevices: {[portId: number]: Device} = {}; @@ -39,9 +36,11 @@ export class Hub extends EventEmitter { private _isConnecting = false; private _isConnected = false; - constructor (device: IBLEAbstraction, autoSubscribe: boolean = true) { + private _type: Consts.HubType; + + constructor (device: IBLEAbstraction, type: Consts.HubType = Consts.HubType.UNKNOWN) { super(); - this.autoSubscribe = !!autoSubscribe; + this._type = type; this._bleDevice = device; device.on("disconnect", () => { /** @@ -183,41 +182,6 @@ export class Hub extends EventEmitter { } - // /** - // * Subscribe to sensor notifications on a given port. - // * @method Hub#subscribe - // * @param {string} port - // * @param {number} [mode] The sensor mode to activate. If no mode is provided, the default for that sensor will be chosen. - // * @returns {Promise} Resolved upon successful issuance of command. - // */ - // public subscribe (port: string, mode?: number) { - // return new Promise((resolve, reject) => { - // let newMode = this._getModeForDeviceType(this._portLookup(port).type); - // if (mode !== undefined) { - // newMode = mode; - // } - // this._activatePortDevice(this._portLookup(port).value, this._portLookup(port).type, newMode, 0x00, () => { - // return resolve(); - // }); - // }); - // } - - // /** - // * Unsubscribe to sensor notifications on a given port. - // * @method Hub#unsubscribe - // * @param {string} port - // * @returns {Promise} Resolved upon successful issuance of command. - // */ - // public unsubscribe (port: string) { - // return new Promise((resolve, reject) => { - // const mode = this._getModeForDeviceType(this._portLookup(port).type); - // this._deactivatePortDevice(this._portLookup(port).value, this._portLookup(port).type, mode, 0x00, () => { - // return resolve(); - // }); - // }); - // } - - /** * Sleep a given amount of time. * @@ -246,17 +210,6 @@ export class Hub extends EventEmitter { } - // /** - // * Get the device type for a given port. - // * @method Hub#getPortDeviceType - // * @param {string} port - // * @returns {DeviceType} - // */ - // public getPortDeviceType (port: string) { - // return this._portLookup(port).type; - // } - - public send (message: Buffer, uuid: string, callback?: () => void) { if (callback) { callback(); @@ -264,60 +217,19 @@ export class Hub extends EventEmitter { } - // protected _getCharacteristic (uuid: string) { - // return this._characteristics[uuid.replace(/-/g, "")]; - // } - - - // protected _subscribeToCharacteristic (characteristic: Characteristic, callback: (data: Buffer) => void) { - // characteristic.on("data", (data: Buffer) => { - // return callback(data); - // }); - // characteristic.subscribe((err) => { - // if (err) { - // this.emit("error", err); - // } - // }); - // } + public subscribe (portId: number, mode: number) { + // NK Do nothing here + } protected _attachDevice (device: Device) { - this._attachedDevices[device.portId] = device; - /** * Emits when a device is attached to the Hub. * @event Hub#attach * @param {Device} device */ this.emit("attach", device); - - // if (port.connected) { - // port.type = type; - // if (this.autoSubscribe) { - // this._activatePortDevice(port.value, type, this._getModeForDeviceType(type), 0x00); - // } - // /** - // * Emits when a motor or sensor is attached to the Hub. - // * @event Hub#attach - // * @param {string} port - // * @param {DeviceType} type - // */ - // this.emit("attach", port.id, type); - // } else { - // port.type = Consts.DeviceType.UNKNOWN; - // debug(`Port ${port.id} disconnected`); - // /** - // * Emits when an attached motor or sensor is detached from the Hub. - // * @event Hub#detach - // * @param {string} port - // */ - // if (this._virtualPorts[port.id]) { - // delete this._virtualPorts[port.id]; - // } - // this.emit("detach", port.id); - // } - } @@ -337,44 +249,6 @@ export class Hub extends EventEmitter { } - // protected _getPortForPortNumber (num: number) { - - // for (const key of Object.keys(this._ports)) { - // if (this._ports[key].value === num) { - // return this._ports[key]; - // } - // } - - // for (const key of Object.keys(this._virtualPorts)) { - // if (this._virtualPorts[key].value === num) { - // return this._virtualPorts[key]; - // } - // } - - // return false; - - // } - - - // protected _mapSpeed (speed: number) { // Speed range of -100 to 100 is supported unless speed mapping is turned off, in which case, you're on your own! - // if (!this.useSpeedMap) { - // return speed; - // } - - // if (speed === 127) { - // return 127; // Hard stop - // } - - // if (speed > 100) { - // speed = 100; - // } else if (speed < -100) { - // speed = -100; - // } - - // return speed; - // } - - // protected _calculateRamp (fromSpeed: number, toSpeed: number, time: number, port: Port) { // const emitter = new EventEmitter(); // const steps = Math.abs(toSpeed - fromSpeed); @@ -406,15 +280,6 @@ export class Hub extends EventEmitter { // } - // protected _portLookup (portName: string) { - // const portNameUpper = portName.toUpperCase(); - // const port = this._ports[portNameUpper] || this._virtualPorts[portNameUpper]; - // if (!port) { - // throw new Error(`Port ${portNameUpper} does not exist on this Hub type`); - // } - // return port; - // } - // private _getModeForDeviceType (type: Consts.DeviceType) { // switch (type) { // case Consts.DeviceType.SIMPLE_MEDIUM_LINEAR_MOTOR: diff --git a/src/lpf2hub.ts b/src/lpf2hub.ts index 8f569ee..b596585 100644 --- a/src/lpf2hub.ts +++ b/src/lpf2hub.ts @@ -46,7 +46,7 @@ export class LPF2Hub extends Hub { if (this._currentPort !== undefined) { this.send(Buffer.from([0x41, this._currentPort, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01]), Consts.BLECharacteristic.LPF2_ALL); // Activate current reports } - if (this._type === Consts.HubType.DUPLO_TRAIN_HUB) { + if (this.type === Consts.HubType.DUPLO_TRAIN_HUB) { this.send(Buffer.from([0x41, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x01]), Consts.BLECharacteristic.LPF2_ALL); } await this.sleep(100); @@ -137,15 +137,6 @@ export class LPF2Hub extends Hub { } - public sendRaw (message: Buffer) { - return new Promise((resolve, reject) => { - this.send(message, Consts.BLECharacteristic.LPF2_ALL, () => { - return resolve(); - }); - }); - } - - public send (message: Buffer, uuid: string, callback?: () => void) { message = Buffer.concat([Buffer.alloc(2), message]); message[0] = message.length; @@ -154,14 +145,14 @@ export class LPF2Hub extends Hub { } - // protected _activatePortDevice (port: number, type: number, mode: number, format: number, callback?: () => void) { - // this.send(Buffer.from([0x41, port, mode, 0x01, 0x00, 0x00, 0x00, 0x01]), Consts.BLECharacteristic.LPF2_ALL, callback); - // } + public subscribe (portId: number, mode: number) { + this.send(Buffer.from([0x41, portId, mode, 0x01, 0x00, 0x00, 0x00, 0x01]), Consts.BLECharacteristic.LPF2_ALL); + } - // protected _deactivatePortDevice (port: number, type: number, mode: number, format: number, callback?: () => void) { - // this.send(Buffer.from([0x41, port, mode, 0x01, 0x00, 0x00, 0x00, 0x00]), Consts.BLECharacteristic.LPF2_ALL, callback); - // } + public unsubscribe (portId: number, mode: number) { + this.send(Buffer.from([0x41, portId, mode, 0x01, 0x00, 0x00, 0x00, 0x00]), Consts.BLECharacteristic.LPF2_ALL); + } // protected _combinePorts (port: string, type: number) { @@ -238,11 +229,11 @@ export class LPF2Hub extends Hub { } - private _parseDeviceInfo (data: Buffer) { + private _parseDeviceInfo (message: Buffer) { // Button press reports - if (data[3] === 0x02) { - if (data[5] === 1) { + if (message[3] === 0x02) { + if (message[5] === 1) { /** * Emits when a button is pressed. * @event LPF2Hub#button @@ -251,35 +242,35 @@ export class LPF2Hub extends Hub { */ this.emit("button", "GREEN", Consts.ButtonState.PRESSED); return; - } else if (data[5] === 0) { + } else if (message[5] === 0) { this.emit("button", "GREEN", Consts.ButtonState.RELEASED); return; } // Firmware version - } else if (data[3] === 0x03) { - this._firmwareVersion = decodeVersion(data.readInt32LE(5)); + } else if (message[3] === 0x03) { + this._firmwareVersion = decodeVersion(message.readInt32LE(5)); this._checkFirmware(this._firmwareVersion); // Hardware version - } else if (data[3] === 0x04) { - this._hardwareVersion = decodeVersion(data.readInt32LE(5)); + } else if (message[3] === 0x04) { + this._hardwareVersion = decodeVersion(message.readInt32LE(5)); // RSSI update - } else if (data[3] === 0x05) { - const rssi = data.readInt8(5); + } else if (message[3] === 0x05) { + const rssi = message.readInt8(5); if (rssi !== 0) { this._rssi = rssi; this.emit("rssiChange", this._rssi); } // primary MAC Address - } else if (data[3] === 0x0d) { - this._primaryMACAddress = decodeMACAddress(data.slice(5)); + } else if (message[3] === 0x0d) { + this._primaryMACAddress = decodeMACAddress(message.slice(5)); // Battery level reports - } else if (data[3] === 0x06) { - this._batteryLevel = data[5]; + } else if (message[3] === 0x06) { + this._batteryLevel = message[5]; } } @@ -361,19 +352,19 @@ export class LPF2Hub extends Hub { } - private _parsePortInformationResponse (data: Buffer) { - const port = data[3]; - if (data[4] === 2) { + private _parsePortInformationResponse (message: Buffer) { + const port = message[3]; + if (message[4] === 2) { const modeCombinationMasks: number[] = []; - for (let i = 5; i < data.length; i += 2) { - modeCombinationMasks.push(data.readUInt16LE(i)); + for (let i = 5; i < message.length; i += 2) { + modeCombinationMasks.push(message.readUInt16LE(i)); } modeInfoDebug(`Port ${toHex(port)}, mode combinations [${modeCombinationMasks.map((c) => toBin(c, 0)).join(", ")}]`); return; } - const count = data[6]; - const input = toBin(data.readUInt16LE(7), count); - const output = toBin(data.readUInt16LE(9), count); + const count = message[6]; + const input = toBin(message.readUInt16LE(7), count); + const output = toBin(message.readUInt16LE(9), count); modeInfoDebug(`Port ${toHex(port)}, total modes ${count}, input modes ${input}, output modes ${output}`); for (let i = 0; i < count; i++) { @@ -392,31 +383,31 @@ export class LPF2Hub extends Hub { } - private _parseModeInformationResponse (data: Buffer) { - const port = toHex(data[3]); - const mode = data[4]; - const type = data[5]; + private _parseModeInformationResponse (message: Buffer) { + const port = toHex(message[3]); + const mode = message[4]; + const type = message[5]; switch (type) { case 0x00: // Mode Name - modeInfoDebug(`Port ${port}, mode ${mode}, name ${data.slice(6, data.length).toString()}`); + modeInfoDebug(`Port ${port}, mode ${mode}, name ${message.slice(6, message.length).toString()}`); break; case 0x01: // RAW Range - modeInfoDebug(`Port ${port}, mode ${mode}, RAW min ${data.readFloatLE(6)}, max ${data.readFloatLE(10)}`); + modeInfoDebug(`Port ${port}, mode ${mode}, RAW min ${message.readFloatLE(6)}, max ${message.readFloatLE(10)}`); break; case 0x02: // PCT Range - modeInfoDebug(`Port ${port}, mode ${mode}, PCT min ${data.readFloatLE(6)}, max ${data.readFloatLE(10)}`); + modeInfoDebug(`Port ${port}, mode ${mode}, PCT min ${message.readFloatLE(6)}, max ${message.readFloatLE(10)}`); break; case 0x03: // SI Range - modeInfoDebug(`Port ${port}, mode ${mode}, SI min ${data.readFloatLE(6)}, max ${data.readFloatLE(10)}`); + modeInfoDebug(`Port ${port}, mode ${mode}, SI min ${message.readFloatLE(6)}, max ${message.readFloatLE(10)}`); break; case 0x04: // SI Symbol - modeInfoDebug(`Port ${port}, mode ${mode}, SI symbol ${data.slice(6, data.length).toString()}`); + modeInfoDebug(`Port ${port}, mode ${mode}, SI symbol ${message.slice(6, message.length).toString()}`); break; case 0x80: // Value Format - const numValues = data[6]; - const dataType = ["8bit", "16bit", "32bit", "float"][data[7]]; - const totalFigures = data[8]; - const decimals = data[9]; + const numValues = message[6]; + const dataType = ["8bit", "16bit", "32bit", "float"][message[7]]; + const totalFigures = message[8]; + const decimals = message[9]; modeInfoDebug(`Port ${port}, mode ${mode}, Value ${numValues} x ${dataType}, Decimal format ${totalFigures}.${decimals}`); } } diff --git a/src/poweredup-browser.ts b/src/poweredup-browser.ts index 67f4140..5fab9be 100644 --- a/src/poweredup-browser.ts +++ b/src/poweredup-browser.ts @@ -23,9 +23,6 @@ const debug = Debug("poweredup"); export class PoweredUP extends EventEmitter { - public autoSubscribe: boolean = true; - - private _connectedHubs: {[uuid: string]: Hub} = {}; @@ -184,22 +181,22 @@ export class PoweredUP extends EventEmitter { switch (hubType) { case Consts.HubType.WEDO2_SMART_HUB: - hub = new WeDo2SmartHub(device, this.autoSubscribe); + hub = new WeDo2SmartHub(device); break; case Consts.HubType.BOOST_MOVE_HUB: - hub = new BoostMoveHub(device, this.autoSubscribe); + hub = new BoostMoveHub(device); break; case Consts.HubType.POWERED_UP_HUB: - hub = new PUPHub(device, this.autoSubscribe); + hub = new PUPHub(device); break; case Consts.HubType.POWERED_UP_REMOTE: - hub = new PUPRemote(device, this.autoSubscribe); + hub = new PUPRemote(device); break; case Consts.HubType.DUPLO_TRAIN_HUB: - hub = new DuploTrainBase(device, this.autoSubscribe); + hub = new DuploTrainBase(device); break; case Consts.HubType.CONTROL_PLUS_HUB: - hub = new ControlPlusHub(device, this.autoSubscribe); + hub = new ControlPlusHub(device); break; default: return; diff --git a/src/poweredup-node.ts b/src/poweredup-node.ts index e9a8d82..88a9eb3 100644 --- a/src/poweredup-node.ts +++ b/src/poweredup-node.ts @@ -44,9 +44,6 @@ noble.on("stateChange", (state: string) => { export class PoweredUP extends EventEmitter { - public autoSubscribe: boolean = true; - - private _connectedHubs: {[uuid: string]: Hub} = {}; @@ -144,17 +141,17 @@ export class PoweredUP extends EventEmitter { let hub: Hub; if (await WeDo2SmartHub.IsWeDo2SmartHub(peripheral)) { - hub = new WeDo2SmartHub(device, this.autoSubscribe); + hub = new WeDo2SmartHub(device); } else if (await BoostMoveHub.IsBoostMoveHub(peripheral)) { - hub = new BoostMoveHub(device, this.autoSubscribe); + hub = new BoostMoveHub(device); } else if (await PUPHub.IsPUPHub(peripheral)) { - hub = new PUPHub(device, this.autoSubscribe); + hub = new PUPHub(device); } else if (await PUPRemote.IsPUPRemote(peripheral)) { - hub = new PUPRemote(device, this.autoSubscribe); + hub = new PUPRemote(device); } else if (await DuploTrainBase.IsDuploTrainBase(peripheral)) { - hub = new DuploTrainBase(device, this.autoSubscribe); + hub = new DuploTrainBase(device); } else if (await ControlPlusHub.IsControlPlusHub(peripheral)) { - hub = new ControlPlusHub(device, this.autoSubscribe); + hub = new ControlPlusHub(device); } else { return; } diff --git a/src/puphub.ts b/src/puphub.ts index 4c91643..2134998 100644 --- a/src/puphub.ts +++ b/src/puphub.ts @@ -34,9 +34,8 @@ export class PUPHub extends LPF2Hub { protected _currentPort = 0x3b; protected _voltagePort = 0x3c; - constructor (device: IBLEAbstraction, autoSubscribe: boolean = true) { - super(device, autoSubscribe); - this._type = Consts.HubType.POWERED_UP_HUB; + constructor (device: IBLEAbstraction) { + super(device, Consts.HubType.POWERED_UP_HUB); this._portNames = { "A": 0, "B": 1 diff --git a/src/pupremote.ts b/src/pupremote.ts index 3f8b372..24886c7 100644 --- a/src/pupremote.ts +++ b/src/pupremote.ts @@ -37,9 +37,8 @@ export class PUPRemote extends LPF2Hub { protected _voltageMaxRaw = 3200; - constructor (device: IBLEAbstraction, autoSubscribe: boolean = true) { - super(device, autoSubscribe); - this._type = Consts.HubType.POWERED_UP_REMOTE; + constructor (device: IBLEAbstraction) { + super(device, Consts.HubType.POWERED_UP_REMOTE); this._portNames = { "LEFT": 0, "RIGHT": 1 diff --git a/src/tachomotor.ts b/src/tachomotor.ts index 624a1e7..f12fd89 100644 --- a/src/tachomotor.ts +++ b/src/tachomotor.ts @@ -6,7 +6,7 @@ import { mapSpeed } from "./utils"; export class TachoMotor extends BasicMotor { - constructor (hub: Hub, portId: number, type: number = Consts.DeviceType.UNKNOWN) { + constructor (hub: Hub, portId: number, type: Consts.DeviceType = Consts.DeviceType.UNKNOWN) { super(hub, portId, type); this.on("newListener", (event) => { diff --git a/src/wedo2smarthub.ts b/src/wedo2smarthub.ts index bd6ba7e..1b22944 100644 --- a/src/wedo2smarthub.ts +++ b/src/wedo2smarthub.ts @@ -38,9 +38,8 @@ export class WeDo2SmartHub extends Hub { private _lastTiltY: number = 0; - constructor (device: IBLEAbstraction, autoSubscribe: boolean = true) { - super(device, autoSubscribe); - this._type = Consts.HubType.WEDO2_SMART_HUB; + constructor (device: IBLEAbstraction) { + super(device, Consts.HubType.WEDO2_SMART_HUB); this._portNames = { "A": 1, "B": 2