1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
6 * @fileoverview Implements a low-level gnubby driver based on chrome.hid.
11 * Low level gnubby 'driver'. One per physical USB device.
12 * @param {Gnubbies} gnubbies The gnubbies instances this device is enumerated
14 * @param {!chrome.hid.HidConnectInfo} dev The connection to the device.
15 * @param {number} id The device's id.
17 * @implements {GnubbyDevice}
19 function HidGnubbyDevice(gnubbies, dev, id) {
20 /** @private {Gnubbies} */
21 this.gnubbies_ = gnubbies;
26 this.lockCID = 0; // channel ID of client holding a lock, if != 0.
27 this.lockMillis = 0; // current lock period.
28 this.lockTID = null; // timer id of lock timeout.
29 this.closing = false; // device to be closed by receive loop.
30 this.updating = false; // device firmware is in final stage of updating.
34 * Namespace for the HidGnubbyDevice implementation.
37 HidGnubbyDevice.NAMESPACE = 'hid';
39 /** Destroys this low-level device instance. */
40 HidGnubbyDevice.prototype.destroy = function() {
41 if (!this.dev) return; // Already dead.
43 this.gnubbies_.removeOpenDevice(
44 {namespace: HidGnubbyDevice.NAMESPACE, device: this.id});
47 console.log(UTIL_fmt('HidGnubbyDevice.destroy()'));
49 // Synthesize a close error frame to alert all clients,
50 // some of which might be in read state.
52 // Use magic CID 0 to address all.
53 this.publishFrame_(new Uint8Array([
54 0, 0, 0, 0, // broadcast CID
55 GnubbyDevice.CMD_ERROR,
57 GnubbyDevice.GONE]).buffer);
59 // Set all clients to closed status and remove them.
60 while (this.clients.length != 0) {
61 var client = this.clients.shift();
62 if (client) client.closed = true;
66 window.clearTimeout(this.lockTID);
73 chrome.hid.disconnect(dev.connectionId, function() {
74 if (chrome.runtime.lastError) {
75 console.warn(UTIL_fmt('Device ' + dev.connectionId +
76 ' couldn\'t be disconnected:'));
77 console.warn(UTIL_fmt(chrome.runtime.lastError.message));
80 console.log(UTIL_fmt('Device ' + dev.connectionId + ' closed'));
85 * Push frame to all clients.
86 * @param {ArrayBuffer} f Data to push
89 HidGnubbyDevice.prototype.publishFrame_ = function(f) {
90 var old = this.clients;
94 for (var i = 0; i < old.length; ++i) {
96 if (client.receivedFrame(f)) {
97 // Client still alive; keep on list.
98 remaining.push(client);
101 console.log(UTIL_fmt(
102 '[' + Gnubby.hexCid(client.cid) + '] left?'));
105 if (changes) this.clients = remaining;
109 * Register a client for this gnubby.
110 * @param {*} who The client.
112 HidGnubbyDevice.prototype.registerClient = function(who) {
113 for (var i = 0; i < this.clients.length; ++i) {
114 if (this.clients[i] === who) return; // Already registered.
116 this.clients.push(who);
117 if (this.clients.length == 1) {
118 // First client? Kick off read loop.
124 * De-register a client.
125 * @param {*} who The client.
126 * @return {number} The number of remaining listeners for this device, or -1
127 * Returns number of remaining listeners for this device.
128 * if this had no clients to start with.
130 HidGnubbyDevice.prototype.deregisterClient = function(who) {
131 var current = this.clients;
132 if (current.length == 0) return -1;
134 for (var i = 0; i < current.length; ++i) {
135 var client = current[i];
136 if (client !== who) this.clients.push(client);
138 return this.clients.length;
142 * @param {*} who The client.
143 * @return {boolean} Whether this device has who as a client.
145 HidGnubbyDevice.prototype.hasClient = function(who) {
146 if (this.clients.length == 0) return false;
147 for (var i = 0; i < this.clients.length; ++i) {
148 if (who === this.clients[i])
155 * Reads all incoming frames and notifies clients of their receipt.
158 HidGnubbyDevice.prototype.readLoop_ = function() {
159 //console.log(UTIL_fmt('entering readLoop'));
160 if (!this.dev) return;
167 // No interested listeners, yet we hit readLoop().
168 // Must be clean-up. We do this here to make sure no transfer is pending.
169 if (!this.clients.length) {
175 // firmwareUpdate() sets this.updating when writing the last block before
176 // the signature. We process that reply with the already pending
177 // read transfer but we do not want to start another read transfer for the
178 // signature block, since that request will have no reply.
179 // Instead we will see the device drop and re-appear on the bus.
180 // Current libusb on some platforms gets unhappy when transfer are pending
181 // when that happens.
182 // TODO: revisit once Chrome stabilizes its behavior.
184 console.log(UTIL_fmt('device updating. Ending readLoop()'));
190 this.dev.connectionId,
191 function(report_id, data) {
192 if (chrome.runtime.lastError || !data) {
193 console.log(UTIL_fmt('receive got lastError:'));
194 console.log(UTIL_fmt(chrome.runtime.lastError.message));
195 window.setTimeout(function() { self.destroy(); }, 0);
198 var u8 = new Uint8Array(data);
199 console.log(UTIL_fmt('<' + UTIL_BytesToHex(u8)));
201 self.publishFrame_(data);
204 window.setTimeout(function() { self.readLoop_(); }, 0);
210 * Check whether channel is locked for this request or not.
211 * @param {number} cid Channel id
212 * @param {number} cmd Request command
213 * @return {boolean} true if not locked for this request.
216 HidGnubbyDevice.prototype.checkLock_ = function(cid, cmd) {
218 // We have an active lock.
219 if (this.lockCID != cid) {
220 // Some other channel has active lock.
222 if (cmd != GnubbyDevice.CMD_SYNC &&
223 cmd != GnubbyDevice.CMD_INIT) {
224 // Anything but SYNC|INIT gets an immediate busy.
225 var busy = new Uint8Array(
230 GnubbyDevice.CMD_ERROR,
233 // Log the synthetic busy too.
234 console.log(UTIL_fmt('<' + UTIL_BytesToHex(busy)));
235 this.publishFrame_(busy.buffer);
239 // SYNC|INIT gets to go to the device to flush OS tx/rx queues.
240 // The usb firmware is to alway respond to SYNC/INIT,
241 // regardless of lock status.
248 * Update or grab lock.
249 * @param {number} cid Channel ID
250 * @param {number} cmd Command
251 * @param {number} arg Command argument
254 HidGnubbyDevice.prototype.updateLock_ = function(cid, cmd, arg) {
255 if (this.lockCID == 0 || this.lockCID == cid) {
256 // It is this caller's or nobody's lock.
258 window.clearTimeout(this.lockTID);
262 if (cmd == GnubbyDevice.CMD_LOCK) {
266 // Set tracking time to be .1 seconds longer than usb device does.
267 this.lockMillis = nseconds * 1000 + 100;
269 // Releasing lock voluntarily.
274 // (re)set the lock timeout if we still hold it.
277 this.lockTID = window.setTimeout(
279 console.warn(UTIL_fmt(
280 'lock for CID ' + Gnubby.hexCid(cid) + ' expired!'));
290 * Queue command to be sent.
291 * If queue was empty, initiate the write.
292 * @param {number} cid The client's channel ID.
293 * @param {number} cmd The command to send.
294 * @param {ArrayBuffer|Uint8Array} data Command arguments
296 HidGnubbyDevice.prototype.queueCommand = function(cid, cmd, data) {
297 if (!this.dev) return;
298 if (!this.checkLock_(cid, cmd)) return;
300 var u8 = new Uint8Array(data);
301 var f = new Uint8Array(64);
303 HidGnubbyDevice.setCid_(f, cid);
305 f[5] = (u8.length >> 8);
306 f[6] = (u8.length & 255);
308 var lockArg = (u8.length > 0) ? u8[0] : 0;
310 // Fragment over our 64 byte frames.
313 for (var i = 0; i < u8.length; ++i) {
316 this.queueFrame_(f.buffer, cid, cmd, lockArg);
318 f = new Uint8Array(64);
319 HidGnubbyDevice.setCid_(f, cid);
325 this.queueFrame_(f.buffer, cid, cmd, lockArg);
330 * Sets the channel id in the frame.
331 * @param {Uint8Array} frame Data frame
332 * @param {number} cid The client's channel ID.
335 HidGnubbyDevice.setCid_ = function(frame, cid) {
336 frame[0] = cid >>> 24;
337 frame[1] = cid >>> 16;
338 frame[2] = cid >>> 8;
343 * Updates the lock, and queues the frame for sending. Also begins sending if
344 * no other writes are outstanding.
345 * @param {ArrayBuffer} frame Data frame
346 * @param {number} cid The client's channel ID.
347 * @param {number} cmd The command to send.
348 * @param {number} arg Command argument
351 HidGnubbyDevice.prototype.queueFrame_ = function(frame, cid, cmd, arg) {
352 this.updateLock_(cid, cmd, arg);
353 var wasEmpty = (this.txqueue.length == 0);
354 this.txqueue.push(frame);
355 if (wasEmpty) this.writePump_();
359 * Stuff queued frames from txqueue[] to device, one by one.
362 HidGnubbyDevice.prototype.writePump_ = function() {
363 if (!this.dev) return; // Ignore.
365 if (this.txqueue.length == 0) return; // Done with current queue.
367 var frame = this.txqueue[0];
370 function transferComplete() {
371 if (chrome.runtime.lastError) {
372 console.log(UTIL_fmt('send got lastError:'));
373 console.log(UTIL_fmt(chrome.runtime.lastError.message));
374 window.setTimeout(function() { self.destroy(); }, 0);
377 self.txqueue.shift(); // drop sent frame from queue.
378 if (self.txqueue.length != 0) {
379 window.setTimeout(function() { self.writePump_(); }, 0);
383 var u8 = new Uint8Array(frame);
385 // See whether this requires scrubbing before logging.
386 var alternateLog = Gnubby.hasOwnProperty('redactRequestLog') &&
387 Gnubby['redactRequestLog'](u8);
389 console.log(UTIL_fmt('>' + alternateLog));
391 console.log(UTIL_fmt('>' + UTIL_BytesToHex(u8)));
394 var u8f = new Uint8Array(64);
395 for (var i = 0; i < u8.length; ++i) {
400 this.dev.connectionId,
401 0, // report Id. Must be 0 for our use.
408 * List of legacy HID devices that do not support the F1D0 usage page as
409 * mandated by the spec, but still need to be supported.
410 * TODO: remove when these devices no longer need to be supported.
413 HidGnubbyDevice.HID_VID_PIDS = [
414 {'vendorId': 4176, 'productId': 512} // Google-specific Yubico HID
418 * @param {function(Array)} cb Enumeration callback
420 HidGnubbyDevice.enumerate = function(cb) {
422 * One pass using getDevices, and one for each of the hardcoded vid/pids.
425 var ENUMERATE_PASSES = 1 + HidGnubbyDevice.HID_VID_PIDS.length;
426 var numEnumerated = 0;
429 function enumerated(f1d0Enumerated, devs) {
430 // Don't double-add a device; it'll just confuse things.
431 // We assume the various calls to getDevices() return from the same
433 for (var i = 0; i < devs.length; i++) {
435 dev.f1d0Only = f1d0Enumerated;
436 // Unfortunately indexOf is not usable, since the two calls produce
437 // different objects. Compare their deviceIds instead.
439 for (var j = 0; j < allDevs.length; j++) {
440 if (allDevs[j].deviceId == dev.deviceId) {
442 allDevs[j].f1d0Only &= f1d0Enumerated;
450 if (++numEnumerated == ENUMERATE_PASSES) {
455 // Pass 1: usagePage-based enumeration.
456 chrome.hid.getDevices({filters: [{usagePage: 0xf1d0}]},
457 enumerated.bind(null, true));
458 // Pass 2: vid/pid-based enumeration, for legacy devices.
459 for (var i = 0; i < HidGnubbyDevice.HID_VID_PIDS.length; i++) {
460 var dev = HidGnubbyDevice.HID_VID_PIDS[i];
461 chrome.hid.getDevices({filters: [dev]}, enumerated.bind(null, false));
466 * @param {Gnubbies} gnubbies The gnubbies instances this device is enumerated
468 * @param {number} which The index of the device to open.
469 * @param {!chrome.hid.HidDeviceInfo} dev The device to open.
470 * @param {function(number, GnubbyDevice=)} cb Called back with the
471 * result of opening the device.
473 HidGnubbyDevice.open = function(gnubbies, which, dev, cb) {
474 chrome.hid.connect(dev.deviceId, function(handle) {
475 if (chrome.runtime.lastError) {
476 console.log(UTIL_fmt('connect got lastError:'));
477 console.log(UTIL_fmt(chrome.runtime.lastError.message));
480 console.warn(UTIL_fmt('failed to connect device. permissions issue?'));
481 cb(-GnubbyDevice.NODEVICE);
484 var nonNullHandle = /** @type {!chrome.hid.HidConnectInfo} */ (handle);
485 var gnubby = new HidGnubbyDevice(gnubbies, nonNullHandle, which);
486 cb(-GnubbyDevice.OK, gnubby);
491 * @param {*} dev A browser API device object
492 * @return {GnubbyDeviceId} A device identifier for the device.
494 HidGnubbyDevice.deviceToDeviceId = function(dev) {
495 var hidDev = /** @type {!chrome.hid.HidDeviceInfo} */ (dev);
497 namespace: HidGnubbyDevice.NAMESPACE,
498 device: hidDev.deviceId
504 * Registers this implementation with gnubbies.
505 * @param {Gnubbies} gnubbies Gnubbies registry
507 HidGnubbyDevice.register = function(gnubbies) {
508 var HID_GNUBBY_IMPL = {
509 isSharedAccess: true,
510 enumerate: HidGnubbyDevice.enumerate,
511 deviceToDeviceId: HidGnubbyDevice.deviceToDeviceId,
512 open: HidGnubbyDevice.open
514 gnubbies.registerNamespace(HidGnubbyDevice.NAMESPACE, HID_GNUBBY_IMPL);