UNPKG

gd-ant-plus

Version:

A node module for ANT+ - forked from longhorn/ant-plus

798 lines 32.9 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AntPlusScanner = exports.AntPlusSensor = exports.AntPlusBaseSensor = exports.BaseSensor = exports.GarminStick3 = exports.GarminStick2 = exports.USBDriver = exports.DeviceInfo = exports.Messages = exports.Constants = void 0; const events = require("events"); const usb = require("usb"); var Constants; (function (Constants) { Constants[Constants["MESSAGE_TX_SYNC"] = 164] = "MESSAGE_TX_SYNC"; Constants[Constants["DEFAULT_NETWORK_NUMBER"] = 0] = "DEFAULT_NETWORK_NUMBER"; // Configuration messages Constants[Constants["MESSAGE_CHANNEL_UNASSIGN"] = 65] = "MESSAGE_CHANNEL_UNASSIGN"; Constants[Constants["MESSAGE_CHANNEL_ASSIGN"] = 66] = "MESSAGE_CHANNEL_ASSIGN"; Constants[Constants["MESSAGE_CHANNEL_ID"] = 81] = "MESSAGE_CHANNEL_ID"; Constants[Constants["MESSAGE_CHANNEL_PERIOD"] = 67] = "MESSAGE_CHANNEL_PERIOD"; Constants[Constants["MESSAGE_CHANNEL_SEARCH_TIMEOUT"] = 68] = "MESSAGE_CHANNEL_SEARCH_TIMEOUT"; Constants[Constants["MESSAGE_CHANNEL_FREQUENCY"] = 69] = "MESSAGE_CHANNEL_FREQUENCY"; Constants[Constants["MESSAGE_CHANNEL_TX_POWER"] = 96] = "MESSAGE_CHANNEL_TX_POWER"; Constants[Constants["MESSAGE_NETWORK_KEY"] = 70] = "MESSAGE_NETWORK_KEY"; Constants[Constants["MESSAGE_TX_POWER"] = 71] = "MESSAGE_TX_POWER"; Constants[Constants["MESSAGE_PROXIMITY_SEARCH"] = 113] = "MESSAGE_PROXIMITY_SEARCH"; Constants[Constants["MESSAGE_ENABLE_RX_EXT"] = 102] = "MESSAGE_ENABLE_RX_EXT"; Constants[Constants["MESSAGE_LIB_CONFIG"] = 110] = "MESSAGE_LIB_CONFIG"; Constants[Constants["MESSAGE_CHANNEL_OPEN_RX_SCAN"] = 91] = "MESSAGE_CHANNEL_OPEN_RX_SCAN"; // Notification messages Constants[Constants["MESSAGE_STARTUP"] = 111] = "MESSAGE_STARTUP"; // Control messages Constants[Constants["MESSAGE_SYSTEM_RESET"] = 74] = "MESSAGE_SYSTEM_RESET"; Constants[Constants["MESSAGE_CHANNEL_OPEN"] = 75] = "MESSAGE_CHANNEL_OPEN"; Constants[Constants["MESSAGE_CHANNEL_CLOSE"] = 76] = "MESSAGE_CHANNEL_CLOSE"; Constants[Constants["MESSAGE_CHANNEL_REQUEST"] = 77] = "MESSAGE_CHANNEL_REQUEST"; // Data messages Constants[Constants["MESSAGE_CHANNEL_BROADCAST_DATA"] = 78] = "MESSAGE_CHANNEL_BROADCAST_DATA"; Constants[Constants["MESSAGE_CHANNEL_ACKNOWLEDGED_DATA"] = 79] = "MESSAGE_CHANNEL_ACKNOWLEDGED_DATA"; Constants[Constants["MESSAGE_CHANNEL_BURST_DATA"] = 80] = "MESSAGE_CHANNEL_BURST_DATA"; // Channel event messages Constants[Constants["MESSAGE_CHANNEL_EVENT"] = 64] = "MESSAGE_CHANNEL_EVENT"; // Requested response messages Constants[Constants["MESSAGE_CHANNEL_STATUS"] = 82] = "MESSAGE_CHANNEL_STATUS"; //MESSAGE_CHANNEL_ID = 0x51, Constants[Constants["MESSAGE_VERSION"] = 62] = "MESSAGE_VERSION"; Constants[Constants["MESSAGE_CAPABILITIES"] = 84] = "MESSAGE_CAPABILITIES"; Constants[Constants["MESSAGE_SERIAL_NUMBER"] = 97] = "MESSAGE_SERIAL_NUMBER"; // Message parameters Constants[Constants["CHANNEL_TYPE_TWOWAY_RECEIVE"] = 0] = "CHANNEL_TYPE_TWOWAY_RECEIVE"; Constants[Constants["CHANNEL_TYPE_TWOWAY_TRANSMIT"] = 16] = "CHANNEL_TYPE_TWOWAY_TRANSMIT"; Constants[Constants["CHANNEL_TYPE_SHARED_RECEIVE"] = 32] = "CHANNEL_TYPE_SHARED_RECEIVE"; Constants[Constants["CHANNEL_TYPE_SHARED_TRANSMIT"] = 48] = "CHANNEL_TYPE_SHARED_TRANSMIT"; Constants[Constants["CHANNEL_TYPE_ONEWAY_RECEIVE"] = 64] = "CHANNEL_TYPE_ONEWAY_RECEIVE"; Constants[Constants["CHANNEL_TYPE_ONEWAY_TRANSMIT"] = 80] = "CHANNEL_TYPE_ONEWAY_TRANSMIT"; Constants[Constants["RADIO_TX_POWER_MINUS20DB"] = 0] = "RADIO_TX_POWER_MINUS20DB"; Constants[Constants["RADIO_TX_POWER_MINUS10DB"] = 1] = "RADIO_TX_POWER_MINUS10DB"; Constants[Constants["RADIO_TX_POWER_0DB"] = 2] = "RADIO_TX_POWER_0DB"; Constants[Constants["RADIO_TX_POWER_PLUS4DB"] = 3] = "RADIO_TX_POWER_PLUS4DB"; Constants[Constants["RESPONSE_NO_ERROR"] = 0] = "RESPONSE_NO_ERROR"; Constants[Constants["EVENT_RX_SEARCH_TIMEOUT"] = 1] = "EVENT_RX_SEARCH_TIMEOUT"; Constants[Constants["EVENT_RX_FAIL"] = 2] = "EVENT_RX_FAIL"; Constants[Constants["EVENT_TX"] = 3] = "EVENT_TX"; Constants[Constants["EVENT_TRANSFER_RX_FAILED"] = 4] = "EVENT_TRANSFER_RX_FAILED"; Constants[Constants["EVENT_TRANSFER_TX_COMPLETED"] = 5] = "EVENT_TRANSFER_TX_COMPLETED"; Constants[Constants["EVENT_TRANSFER_TX_FAILED"] = 6] = "EVENT_TRANSFER_TX_FAILED"; Constants[Constants["EVENT_CHANNEL_CLOSED"] = 7] = "EVENT_CHANNEL_CLOSED"; Constants[Constants["EVENT_RX_FAIL_GO_TO_SEARCH"] = 8] = "EVENT_RX_FAIL_GO_TO_SEARCH"; Constants[Constants["EVENT_CHANNEL_COLLISION"] = 9] = "EVENT_CHANNEL_COLLISION"; Constants[Constants["EVENT_TRANSFER_TX_START"] = 10] = "EVENT_TRANSFER_TX_START"; Constants[Constants["CHANNEL_IN_WRONG_STATE"] = 21] = "CHANNEL_IN_WRONG_STATE"; Constants[Constants["CHANNEL_NOT_OPENED"] = 22] = "CHANNEL_NOT_OPENED"; Constants[Constants["CHANNEL_ID_NOT_SET"] = 24] = "CHANNEL_ID_NOT_SET"; Constants[Constants["CLOSE_ALL_CHANNELS"] = 25] = "CLOSE_ALL_CHANNELS"; Constants[Constants["TRANSFER_IN_PROGRESS"] = 31] = "TRANSFER_IN_PROGRESS"; Constants[Constants["TRANSFER_SEQUENCE_NUMBER_ERROR"] = 32] = "TRANSFER_SEQUENCE_NUMBER_ERROR"; Constants[Constants["TRANSFER_IN_ERROR"] = 33] = "TRANSFER_IN_ERROR"; Constants[Constants["MESSAGE_SIZE_EXCEEDS_LIMIT"] = 39] = "MESSAGE_SIZE_EXCEEDS_LIMIT"; Constants[Constants["INVALID_MESSAGE"] = 40] = "INVALID_MESSAGE"; Constants[Constants["INVALID_NETWORK_NUMBER"] = 41] = "INVALID_NETWORK_NUMBER"; Constants[Constants["INVALID_LIST_ID"] = 48] = "INVALID_LIST_ID"; Constants[Constants["INVALID_SCAN_TX_CHANNEL"] = 49] = "INVALID_SCAN_TX_CHANNEL"; Constants[Constants["INVALID_PARAMETER_PROVIDED"] = 51] = "INVALID_PARAMETER_PROVIDED"; Constants[Constants["EVENT_QUEUE_OVERFLOW"] = 53] = "EVENT_QUEUE_OVERFLOW"; Constants[Constants["USB_STRING_WRITE_FAIL"] = 112] = "USB_STRING_WRITE_FAIL"; Constants[Constants["CHANNEL_STATE_UNASSIGNED"] = 0] = "CHANNEL_STATE_UNASSIGNED"; Constants[Constants["CHANNEL_STATE_ASSIGNED"] = 1] = "CHANNEL_STATE_ASSIGNED"; Constants[Constants["CHANNEL_STATE_SEARCHING"] = 2] = "CHANNEL_STATE_SEARCHING"; Constants[Constants["CHANNEL_STATE_TRACKING"] = 3] = "CHANNEL_STATE_TRACKING"; Constants[Constants["CAPABILITIES_NO_RECEIVE_CHANNELS"] = 1] = "CAPABILITIES_NO_RECEIVE_CHANNELS"; Constants[Constants["CAPABILITIES_NO_TRANSMIT_CHANNELS"] = 2] = "CAPABILITIES_NO_TRANSMIT_CHANNELS"; Constants[Constants["CAPABILITIES_NO_RECEIVE_MESSAGES"] = 4] = "CAPABILITIES_NO_RECEIVE_MESSAGES"; Constants[Constants["CAPABILITIES_NO_TRANSMIT_MESSAGES"] = 8] = "CAPABILITIES_NO_TRANSMIT_MESSAGES"; Constants[Constants["CAPABILITIES_NO_ACKNOWLEDGED_MESSAGES"] = 16] = "CAPABILITIES_NO_ACKNOWLEDGED_MESSAGES"; Constants[Constants["CAPABILITIES_NO_BURST_MESSAGES"] = 32] = "CAPABILITIES_NO_BURST_MESSAGES"; Constants[Constants["CAPABILITIES_NETWORK_ENABLED"] = 2] = "CAPABILITIES_NETWORK_ENABLED"; Constants[Constants["CAPABILITIES_SERIAL_NUMBER_ENABLED"] = 8] = "CAPABILITIES_SERIAL_NUMBER_ENABLED"; Constants[Constants["CAPABILITIES_PER_CHANNEL_TX_POWER_ENABLED"] = 16] = "CAPABILITIES_PER_CHANNEL_TX_POWER_ENABLED"; Constants[Constants["CAPABILITIES_LOW_PRIORITY_SEARCH_ENABLED"] = 32] = "CAPABILITIES_LOW_PRIORITY_SEARCH_ENABLED"; Constants[Constants["CAPABILITIES_SCRIPT_ENABLED"] = 64] = "CAPABILITIES_SCRIPT_ENABLED"; Constants[Constants["CAPABILITIES_SEARCH_LIST_ENABLED"] = 128] = "CAPABILITIES_SEARCH_LIST_ENABLED"; Constants[Constants["CAPABILITIES_LED_ENABLED"] = 1] = "CAPABILITIES_LED_ENABLED"; Constants[Constants["CAPABILITIES_EXT_MESSAGE_ENABLED"] = 2] = "CAPABILITIES_EXT_MESSAGE_ENABLED"; Constants[Constants["CAPABILITIES_SCAN_MODE_ENABLED"] = 4] = "CAPABILITIES_SCAN_MODE_ENABLED"; Constants[Constants["CAPABILITIES_PROX_SEARCH_ENABLED"] = 16] = "CAPABILITIES_PROX_SEARCH_ENABLED"; Constants[Constants["CAPABILITIES_EXT_ASSIGN_ENABLED"] = 32] = "CAPABILITIES_EXT_ASSIGN_ENABLED"; Constants[Constants["CAPABILITIES_FS_ANTFS_ENABLED"] = 64] = "CAPABILITIES_FS_ANTFS_ENABLED"; Constants[Constants["TIMEOUT_NEVER"] = 255] = "TIMEOUT_NEVER"; })(Constants = exports.Constants || (exports.Constants = {})); class Messages { static resetSystem() { const payload = []; payload.push(0x00); return this.buildMessage(payload, Constants.MESSAGE_SYSTEM_RESET); } static requestMessage(channel, messageID) { let payload = []; payload = payload.concat(this.intToLEHexArray(channel)); payload.push(messageID); return this.buildMessage(payload, Constants.MESSAGE_CHANNEL_REQUEST); } static setNetworkKey() { const payload = []; payload.push(Constants.DEFAULT_NETWORK_NUMBER); payload.push(0xB9); payload.push(0xA5); payload.push(0x21); payload.push(0xFB); payload.push(0xBD); payload.push(0x72); payload.push(0xC3); payload.push(0x45); return this.buildMessage(payload, Constants.MESSAGE_NETWORK_KEY); } static assignChannel(channel, type = 'receive') { let payload = []; payload = payload.concat(this.intToLEHexArray(channel)); if (type === 'receive') { payload.push(Constants.CHANNEL_TYPE_TWOWAY_RECEIVE); } else if (type === 'receive_only') { payload.push(Constants.CHANNEL_TYPE_ONEWAY_RECEIVE); } else if (type === 'receive_shared') { payload.push(Constants.CHANNEL_TYPE_SHARED_RECEIVE); } else if (type === 'transmit') { payload.push(Constants.CHANNEL_TYPE_TWOWAY_TRANSMIT); } else if (type === 'transmit_only') { payload.push(Constants.CHANNEL_TYPE_ONEWAY_TRANSMIT); } else if (type === 'transmit_shared') { payload.push(Constants.CHANNEL_TYPE_SHARED_TRANSMIT); } else { throw 'type not allowed'; } payload.push(Constants.DEFAULT_NETWORK_NUMBER); return this.buildMessage(payload, Constants.MESSAGE_CHANNEL_ASSIGN); } static setDevice(channel, deviceID, deviceType, transmissionType) { let payload = []; payload = payload.concat(this.intToLEHexArray(channel)); payload = payload.concat(this.intToLEHexArray(deviceID, 2)); payload = payload.concat(this.intToLEHexArray(deviceType)); payload = payload.concat(this.intToLEHexArray(transmissionType)); return this.buildMessage(payload, Constants.MESSAGE_CHANNEL_ID); } static searchChannel(channel, timeout) { let payload = []; payload = payload.concat(this.intToLEHexArray(channel)); payload = payload.concat(this.intToLEHexArray(timeout)); return this.buildMessage(payload, Constants.MESSAGE_CHANNEL_SEARCH_TIMEOUT); } static setPeriod(channel, period) { let payload = []; payload = payload.concat(this.intToLEHexArray(channel)); payload = payload.concat(this.intToLEHexArray(period)); return this.buildMessage(payload, Constants.MESSAGE_CHANNEL_PERIOD); } static setFrequency(channel, frequency) { let payload = []; payload = payload.concat(this.intToLEHexArray(channel)); payload = payload.concat(this.intToLEHexArray(frequency)); return this.buildMessage(payload, Constants.MESSAGE_CHANNEL_FREQUENCY); } static setRxExt() { let payload = []; payload = payload.concat(this.intToLEHexArray(0)); payload = payload.concat(this.intToLEHexArray(1)); return this.buildMessage(payload, Constants.MESSAGE_ENABLE_RX_EXT); } static libConfig(channel, how) { let payload = []; payload = payload.concat(this.intToLEHexArray(channel)); payload = payload.concat(this.intToLEHexArray(how)); return this.buildMessage(payload, Constants.MESSAGE_LIB_CONFIG); } static openRxScan() { let payload = []; payload = payload.concat(this.intToLEHexArray(0)); payload = payload.concat(this.intToLEHexArray(1)); return this.buildMessage(payload, Constants.MESSAGE_CHANNEL_OPEN_RX_SCAN); } static openChannel(channel) { let payload = []; payload = payload.concat(this.intToLEHexArray(channel)); return this.buildMessage(payload, Constants.MESSAGE_CHANNEL_OPEN); } static closeChannel(channel) { let payload = []; payload = payload.concat(this.intToLEHexArray(channel)); return this.buildMessage(payload, Constants.MESSAGE_CHANNEL_CLOSE); } static unassignChannel(channel) { let payload = []; payload = payload.concat(this.intToLEHexArray(channel)); return this.buildMessage(payload, Constants.MESSAGE_CHANNEL_UNASSIGN); } static acknowledgedData(payload) { return Messages.buildMessage(payload, Constants.MESSAGE_CHANNEL_ACKNOWLEDGED_DATA); } static broadcastData(payload) { return Messages.buildMessage(payload, Constants.MESSAGE_CHANNEL_BROADCAST_DATA); } static buildMessage(payload = [], msgID = 0x00) { const m = []; m.push(Constants.MESSAGE_TX_SYNC); m.push(payload.length); m.push(msgID); payload.forEach((byte) => { m.push(byte); }); m.push(this.getChecksum(m)); return Buffer.from(m); } static intToLEHexArray(int, numBytes = 1) { numBytes = numBytes || 1; const a = []; const b = Buffer.from(this.decimalToHex(int, numBytes * 2), 'hex'); let i = b.length - 1; while (i >= 0) { a.push(b[i]); i--; } return a; } static decimalToHex(d, numDigits) { let hex = Number(d).toString(16); numDigits = numDigits || 2; while (hex.length < numDigits) { hex = '0' + hex; } // console.log(hex); return hex; } static getChecksum(message) { let checksum = 0; message.forEach((byte) => { checksum = (checksum ^ byte) % 0xFF; }); return checksum; } } exports.Messages = Messages; Messages.BUFFER_INDEX_MSG_LEN = 1; Messages.BUFFER_INDEX_MSG_TYPE = 2; Messages.BUFFER_INDEX_CHANNEL_NUM = 3; Messages.BUFFER_INDEX_MSG_DATA = 4; Messages.BUFFER_INDEX_EXT_MSG_BEGIN = 12; class CancellationTokenListener { constructor(fn, cb) { this.fn = fn; this.cb = cb; this._completed = false; } cancel() { if (!this._completed) { this._completed = true; // @ts-ignore usb.removeListener('attach', this.fn); this.cb(new Error('Canceled')); } } } class DeviceInfo extends usb.Device { } exports.DeviceInfo = DeviceInfo; class USBDriver extends events.EventEmitter { constructor(idVendor, idProduct, dbgLevel = 0, props = {}) { super(); this.idVendor = idVendor; this.idProduct = idProduct; this.detachedKernelDriver = false; this.usedChannels = 0; this.attachedSensors = []; this.maxChannels = 0; this.canScan = false; this.waitingForStartup = false; this.setMaxListeners(50); this.props = props; usb.setDebugLevel(dbgLevel); } getDevices() { try { const allDevices = usb.getDeviceList(); return allDevices .filter((d) => d.deviceDescriptor.idVendor === this.idVendor && d.deviceDescriptor.idProduct === this.idProduct) .filter(d => USBDriver.deviceInUse.indexOf(d) === -1); } catch (err) { const logger = this.props.logger || console; logger.log('getDevices ERROR :', err); return []; } } static listDevices(filterFn) { const allDevices = usb.getDeviceList(); const info = [...allDevices]; info.forEach(d => d.inUse = USBDriver.deviceInUse.indexOf(d) !== -1); if (filterFn === undefined) return info; return info .filter(filterFn); } blockDevice(device) { USBDriver.deviceInUse.push(device); } unblockDevice(device) { let deviceIdx = undefined; for (var i = 0; i < USBDriver.deviceInUse.length; i++) { let blocked = USBDriver.deviceInUse[i]; if (blocked.deviceAddress == device.deviceAddress) { deviceIdx = i; } } if (deviceIdx != undefined) { USBDriver.deviceInUse.splice(deviceIdx, 1); } } is_present() { return this.getDevices().length > 0; } open() { const devices = this.getDevices(); while (devices.length) { try { this.device = devices.shift(); this.device.open(); this.iface = this.device.interfaces[0]; try { if (this.iface.isKernelDriverActive()) { this.detachedKernelDriver = true; this.iface.detachKernelDriver(); } } catch (_a) { // Ignore kernel driver errors; } this.iface.claim(); break; } catch (_b) { // Ignore the error and try with the next device, if present this.device.close(); this.device = undefined; this.iface = undefined; } } if (!this.device) { return false; } USBDriver.deviceInUse.push(this.device); this.waitingForStartup = true; this.inEp = this.iface.endpoints[0]; this.inEp.on('data', (data) => { if (!data.length) { return; } if (this.leftover) { data = Buffer.concat([this.leftover, data]); this.leftover = undefined; } if (data.readUInt8(0) !== 0xA4) { this.emit('error', { error: 'SYNC missing', context: data }); } const len = data.length; let beginBlock = 0; while (beginBlock < len) { if (beginBlock + 1 === len) { this.leftover = data.slice(beginBlock); break; } const blockLen = data.readUInt8(beginBlock + 1); const endBlock = beginBlock + blockLen + 4; if (endBlock > len) { this.leftover = data.slice(beginBlock); break; } const readData = data.slice(beginBlock, endBlock); this.read(readData); beginBlock = endBlock; } }); this.inEp.on('error', (err) => { if (this.props.debug) { const logger = this.props.logger || console; logger.log('ERROR RECV: ', err); } }); this.inEp.on('end', () => { if (this.props.debug) { const logger = this.props.logger || console; logger.log('STOP RECV: '); } }); this.inEp.startPoll(); this.outEp = this.iface.endpoints[1]; let startupCnt = 0; let tsStart = Date.now(); let tsTimeout = tsStart + 1000; this.reset(); let startupTimer = setInterval(() => { if (!this.waitingForStartup) { clearInterval(startupTimer); return; } if (Date.now() > tsTimeout) { startupCnt++; if (this.props.maxAttempts && startupCnt > this.props.maxAttempts) { clearInterval(startupTimer); this.waitingForStartup = false; this.emit('error', { error: 'Startup timeout', context: 'timeout' }); return; } else { tsStart = Date.now(); tsTimeout = tsStart + 1000; this.reset(); } } }, 100); return true; } openAsync(cb) { let ct; const doOpen = () => { try { const result = this.open(); if (result) { ct._completed = true; try { cb(undefined); } catch (_a) { // ignore errors } } else { return false; } } catch (err) { cb(err); } return true; }; const fn = (d) => { if (!d || (d.deviceDescriptor.idVendor === this.idVendor && d.deviceDescriptor.idProduct === this.idProduct)) { if (doOpen()) { // @ts-ignore usb.removeListener('attach', fn); } } }; usb.on('attach', fn); if (this.is_present()) { // @ts-ignore setImmediate(() => usb.emit('attach', this.device)); } return ct = new CancellationTokenListener(fn, cb); } close() { this.detach_all(); this.inEp.stopPoll(() => { // @ts-ignore this.iface.release(true, () => { if (this.detachedKernelDriver) { this.detachedKernelDriver = false; try { this.iface.attachKernelDriver(); } catch (_a) { // Ignore kernel driver errors; } } this.iface = undefined; this.device.reset(() => { this.device.close(); this.emit('shutdown'); const devIdx = USBDriver.deviceInUse.indexOf(this.device); if (devIdx >= 0) { USBDriver.deviceInUse.splice(devIdx, 1); } // @ts-ignore if (usb.listenerCount('attach')) { // @ts-ignore usb.emit('attach', this.device); } this.device = undefined; }); }); }); } reset() { this.detach_all(); this.maxChannels = 0; this.usedChannels = 0; this.write(Messages.resetSystem()); } isScanning() { return this.usedChannels === -1; } attach(sensor, forScan) { if (this.usedChannels < 0) { return false; } if (forScan) { if (this.usedChannels !== 0) { return false; } this.usedChannels = -1; } else { if (this.maxChannels <= this.usedChannels) { return false; } ++this.usedChannels; } this.attachedSensors.push(sensor); return true; } detach(sensor) { const idx = this.attachedSensors.indexOf(sensor); if (idx < 0) { return false; } if (this.usedChannels < 0) { this.usedChannels = 0; } else { --this.usedChannels; } this.attachedSensors.splice(idx, 1); return true; } detach_all() { const copy = this.attachedSensors; copy.forEach((sensor) => sensor.detach()); } write(data) { if (this.props.debug) { const logger = this.props.logger || console; logger.log('DATA SEND: ', data); } this.outEp.transfer(data, (error) => { if (error) { //console.log('ERROR SEND: ', error); } }); } read(data) { if (this.props.debug) { const logger = this.props.logger || console; logger.log('DATA RECV: ', data); } const messageID = data.readUInt8(2); if (messageID === Constants.MESSAGE_STARTUP) { this.waitingForStartup = false; this.write(Messages.requestMessage(0, Constants.MESSAGE_CAPABILITIES)); } else if (messageID === Constants.MESSAGE_CAPABILITIES) { this.maxChannels = data.readUInt8(3); this.canScan = (data.readUInt8(7) & 0x06) === 0x06; this.write(Messages.setNetworkKey()); } else if (messageID === Constants.MESSAGE_CHANNEL_EVENT && data.readUInt8(4) === Constants.MESSAGE_NETWORK_KEY) { this.emit('startup', data); } else { this.emit('read', data); } } } exports.USBDriver = USBDriver; USBDriver.deviceInUse = []; class GarminStick2 extends USBDriver { constructor(dbgLevel = 0) { super(0x0fcf, 0x1008, dbgLevel); } } exports.GarminStick2 = GarminStick2; class GarminStick3 extends USBDriver { constructor(dbgLevel = 0) { super(0x0fcf, 0x1009, dbgLevel); } } exports.GarminStick3 = GarminStick3; class BaseSensor extends events.EventEmitter { constructor(stick) { super(); this.stick = stick; stick.on('read', this.handleEventMessages.bind(this)); } scan(type, frequency) { if (this.channel !== undefined) { throw 'already attached'; } if (!this.stick.canScan) { throw 'stick cannot scan'; } const channel = 0; const onStatus = (status) => { switch (status.msg) { case 0x01: switch (status.code) { case Constants.EVENT_CHANNEL_CLOSED: this.write(Messages.unassignChannel(channel)); break; default: break; } break; case Constants.MESSAGE_CHANNEL_ASSIGN: this.write(Messages.setDevice(channel, 0, 0, 0)); break; case Constants.MESSAGE_CHANNEL_ID: this.write(Messages.setFrequency(channel, frequency)); break; case Constants.MESSAGE_CHANNEL_FREQUENCY: this.write(Messages.setRxExt()); break; case Constants.MESSAGE_ENABLE_RX_EXT: this.write(Messages.libConfig(channel, 0xE0)); break; case Constants.MESSAGE_LIB_CONFIG: this.write(Messages.openRxScan()); break; case Constants.MESSAGE_CHANNEL_OPEN_RX_SCAN: if (this.decodeDataCbk) { this.stick.on('read', this.decodeDataCbk); } process.nextTick(() => this.emit('attached')); break; case Constants.MESSAGE_CHANNEL_CLOSE: break; case Constants.MESSAGE_CHANNEL_UNASSIGN: this.removeListener('status', onStatus); this.channel = undefined; if (this.decodeDataCbk) { this.stick.removeListener('read', this.decodeDataCbk); } process.nextTick(() => this.emit('detached')); break; default: break; } }; if (this.stick.isScanning()) { this.channel = channel; this.deviceID = 0; this.transmissionType = 0; this.on('status', onStatus); if (this.decodeDataCbk) { this.stick.on('read', this.decodeDataCbk); } process.nextTick(() => this.emit('attached')); } else if (this.stick.attach(this, true)) { this.channel = channel; this.deviceID = 0; this.transmissionType = 0; this.on('status', onStatus); this.write(Messages.assignChannel(channel, type)); } else { throw 'cannot attach'; } } attach(channel, type, deviceID, deviceType, transmissionType, timeout, period, frequency) { if (this.channel !== undefined) { throw 'already attached'; } if (!this.stick.attach(this, false)) { throw 'cannot attach'; } this.channel = channel; this.deviceID = deviceID; this.transmissionType = transmissionType; const onStatus = (status) => { switch (status.msg) { case 0x01: switch (status.code) { case Constants.EVENT_CHANNEL_CLOSED: this.write(Messages.unassignChannel(channel)); break; default: break; } break; case Constants.MESSAGE_CHANNEL_ASSIGN: this.write(Messages.setDevice(channel, deviceID, deviceType, transmissionType)); break; case Constants.MESSAGE_CHANNEL_ID: this.write(Messages.searchChannel(channel, timeout)); break; case Constants.MESSAGE_CHANNEL_SEARCH_TIMEOUT: this.write(Messages.setFrequency(channel, frequency)); break; case Constants.MESSAGE_CHANNEL_FREQUENCY: this.write(Messages.setPeriod(channel, period)); break; case Constants.MESSAGE_CHANNEL_PERIOD: this.write(Messages.libConfig(channel, 0xE0)); break; case Constants.MESSAGE_LIB_CONFIG: this.write(Messages.openChannel(channel)); break; case Constants.MESSAGE_CHANNEL_OPEN: if (this.decodeDataCbk) { this.stick.on('read', this.decodeDataCbk); } process.nextTick(() => this.emit('attached')); break; case Constants.MESSAGE_CHANNEL_CLOSE: break; case Constants.MESSAGE_CHANNEL_UNASSIGN: this.removeListener('status', onStatus); this.channel = undefined; if (this.decodeDataCbk) { this.stick.removeListener('read', this.decodeDataCbk); } process.nextTick(() => this.emit('detached')); break; default: break; } }; this.on('status', onStatus); this.write(Messages.assignChannel(channel, type)); } detach() { if (this.channel === undefined) { return; } this.write(Messages.closeChannel(this.channel)); if (!this.stick.detach(this)) { throw 'error detaching'; } } write(data) { this.stick.write(data); } handleEventMessages(data) { const messageID = data.readUInt8(2); if (messageID === Constants.MESSAGE_CHANNEL_EVENT && data.readUInt8(3) === this.channel) { const status = { msg: data.readUInt8(4), code: data.readUInt8(5), }; this.emit('status', status); } } } exports.BaseSensor = BaseSensor; class AntPlusBaseSensor extends BaseSensor { scan(type) { return super.scan(type, 57); } attach(channel, type, deviceID, deviceType, transmissionType, timeout, period) { return super.attach(channel, type, deviceID, deviceType, transmissionType, timeout, period, 57); } } exports.AntPlusBaseSensor = AntPlusBaseSensor; class AntPlusSensor extends AntPlusBaseSensor { scan() { throw 'scanning unsupported'; } attach(channel, type, deviceID, deviceType, transmissionType, timeout, period) { return super.attach(channel, type, deviceID, deviceType, transmissionType, timeout, period); } } exports.AntPlusSensor = AntPlusSensor; class AntPlusScanner extends AntPlusBaseSensor { scan(type) { return super.scan(type); } attach() { throw 'attach unsupported'; } } exports.AntPlusScanner = AntPlusScanner; //# sourceMappingURL=ant.js.map