UNPKG

spacemouse-webhid

Version:

An npm module for interfacing with the SpaceMouse devices in a browser

56 lines 2.06 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WebHIDDevice = void 0; const events_1 = require("events"); const buffer_1 = require("buffer"); /** * The wrapped browser HIDDevice. * This translates it into the common format (@see CoreHIDDevice) defined by @spacemouse-lib/core */ class WebHIDDevice extends events_1.EventEmitter { device; constructor(device) { super(); this._handleInputReport = this._handleInputReport.bind(this); this._handleError = this._handleError.bind(this); this._handleDisconnect = this._handleDisconnect.bind(this); this.device = device; this.device.addEventListener('inputreport', this._handleInputReport); this.device.addEventListener('error', this._handleError); window.navigator.hid.addEventListener('disconnect', this._handleDisconnect); } async close() { await this.device.close(); this._cleanup(); } // No writes implemented (yet) // public write(data: number[]): void { // this.reportQueue // .add(async () => { // await this.device.sendReport(data[0], new Uint8Array(data.slice(1))) // }) // .catch((err) => { // this.emit('error', err) // }) // } _cleanup() { this.device.removeEventListener('inputreport', this._handleInputReport); this.device.removeEventListener('error', this._handleError); window.navigator.hid.removeEventListener('disconnect', this._handleDisconnect); } _handleInputReport(event) { const buf = buffer_1.Buffer.concat([buffer_1.Buffer.from([event.reportId]), buffer_1.Buffer.from(event.data.buffer)]); this.emit('data', buf); } _handleError(error) { this.emit('error', error); } _handleDisconnect(event) { if (event.device === this.device) { this.emit('error', 'WebHID disconnected'); } this._cleanup(); } } exports.WebHIDDevice = WebHIDDevice; //# sourceMappingURL=web-hid-wrapper.js.map