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.usb.
11 * Low level gnubby 'driver'. One per physical USB device.
12 * @param {Gnubbies} gnubbies The gnubbies instances this device is enumerated
14 * @param {!chrome.usb.ConnectionHandle} dev The device.
15 * @param {number} id The device's id.
16 * @param {number} inEndpoint The device's in endpoint.
17 * @param {number} outEndpoint The device's out endpoint.
19 * @implements {GnubbyDevice}
21 function UsbGnubbyDevice(gnubbies, dev, id, inEndpoint, outEndpoint) {
22 /** @private {Gnubbies} */
23 this.gnubbies_ = gnubbies;
26 this.inEndpoint = inEndpoint;
27 this.outEndpoint = outEndpoint;
30 this.lockCID = 0; // channel ID of client holding a lock, if != 0.
31 this.lockMillis = 0; // current lock period.
32 this.lockTID = null; // timer id of lock timeout.
33 this.closing = false; // device to be closed by receive loop.
34 this.updating = false; // device firmware is in final stage of updating.
35 this.inTransferPending = false;
36 this.outTransferPending = false;
40 * Namespace for the UsbGnubbyDevice implementation.
43 UsbGnubbyDevice.NAMESPACE = 'usb';
45 /** Destroys this low-level device instance. */
46 UsbGnubbyDevice.prototype.destroy = function() {
47 if (!this.dev) return; // Already dead.
49 this.gnubbies_.removeOpenDevice(
50 {namespace: UsbGnubbyDevice.NAMESPACE, device: this.id});
53 console.log(UTIL_fmt('UsbGnubbyDevice.destroy()'));
55 // Synthesize a close error frame to alert all clients,
56 // some of which might be in read state.
58 // Use magic CID 0 to address all.
59 this.publishFrame_(new Uint8Array([
60 0, 0, 0, 0, // broadcast CID
61 GnubbyDevice.CMD_ERROR,
63 GnubbyDevice.GONE]).buffer);
65 // Set all clients to closed status and remove them.
66 while (this.clients.length != 0) {
67 var client = this.clients.shift();
68 if (client) client.closed = true;
72 window.clearTimeout(this.lockTID);
79 chrome.usb.releaseInterface(dev, 0, function() {
80 console.log(UTIL_fmt('Device ' + dev.handle + ' released'));
81 chrome.usb.closeDevice(dev, function() {
82 console.log(UTIL_fmt('Device ' + dev.handle + ' closed'));
88 * Push frame to all clients.
89 * @param {ArrayBuffer} f Data frame
92 UsbGnubbyDevice.prototype.publishFrame_ = function(f) {
93 var old = this.clients;
97 for (var i = 0; i < old.length; ++i) {
99 if (client.receivedFrame(f)) {
100 // Client still alive; keep on list.
101 remaining.push(client);
104 console.log(UTIL_fmt(
105 '[' + client.cid.toString(16) + '] left?'));
108 if (changes) this.clients = remaining;
112 * @return {boolean} whether this device is open and ready to use.
115 UsbGnubbyDevice.prototype.readyToUse_ = function() {
116 if (this.closing) return false;
117 if (!this.dev) return false;
123 * Reads one reply from the low-level device.
126 UsbGnubbyDevice.prototype.readOneReply_ = function() {
127 if (!this.readyToUse_()) return; // No point in continuing.
128 if (this.updating) return; // Do not bother waiting for final update reply.
132 function inTransferComplete(x) {
133 self.inTransferPending = false;
135 if (!self.readyToUse_()) return; // No point in continuing.
137 if (chrome.runtime.lastError) {
138 console.warn(UTIL_fmt('lastError: ' + chrome.runtime.lastError));
139 console.log(chrome.runtime.lastError);
140 window.setTimeout(function() { self.destroy(); }, 0);
145 var u8 = new Uint8Array(x.data);
146 console.log(UTIL_fmt('<' + UTIL_BytesToHex(u8)));
148 self.publishFrame_(x.data);
150 // Write another pending request, if any.
153 self.txqueue.shift(); // Drop sent frame from queue.
154 self.writeOneRequest_();
158 console.log(UTIL_fmt('no x.data!'));
160 window.setTimeout(function() { self.destroy(); }, 0);
164 if (this.inTransferPending == false) {
165 this.inTransferPending = true;
166 chrome.usb.bulkTransfer(
167 /** @type {!chrome.usb.ConnectionHandle} */(this.dev),
168 { direction: 'in', endpoint: this.inEndpoint, length: 2048 },
171 throw 'inTransferPending!';
176 * Register a client for this gnubby.
177 * @param {*} who The client.
179 UsbGnubbyDevice.prototype.registerClient = function(who) {
180 for (var i = 0; i < this.clients.length; ++i) {
181 if (this.clients[i] === who) return; // Already registered.
183 this.clients.push(who);
187 * De-register a client.
188 * @param {*} who The client.
189 * @return {number} The number of remaining listeners for this device, or -1
190 * Returns number of remaining listeners for this device.
191 * if this had no clients to start with.
193 UsbGnubbyDevice.prototype.deregisterClient = function(who) {
194 var current = this.clients;
195 if (current.length == 0) return -1;
197 for (var i = 0; i < current.length; ++i) {
198 var client = current[i];
199 if (client !== who) this.clients.push(client);
201 return this.clients.length;
205 * @param {*} who The client.
206 * @return {boolean} Whether this device has who as a client.
208 UsbGnubbyDevice.prototype.hasClient = function(who) {
209 if (this.clients.length == 0) return false;
210 for (var i = 0; i < this.clients.length; ++i) {
211 if (who === this.clients[i])
218 * Stuff queued frames from txqueue[] to device, one by one.
221 UsbGnubbyDevice.prototype.writeOneRequest_ = function() {
222 if (!this.readyToUse_()) return; // No point in continuing.
224 if (this.txqueue.length == 0) return; // Nothing to send.
226 var frame = this.txqueue[0];
229 function OutTransferComplete(x) {
230 self.outTransferPending = false;
232 if (!self.readyToUse_()) return; // No point in continuing.
234 if (chrome.runtime.lastError) {
235 console.warn(UTIL_fmt('lastError: ' + chrome.runtime.lastError));
236 console.log(chrome.runtime.lastError);
237 window.setTimeout(function() { self.destroy(); }, 0);
241 window.setTimeout(function() { self.readOneReply_(); }, 0);
244 var u8 = new Uint8Array(frame);
246 // See whether this requires scrubbing before logging.
247 var alternateLog = Gnubby.hasOwnProperty('redactRequestLog') &&
248 Gnubby['redactRequestLog'](u8);
250 console.log(UTIL_fmt('>' + alternateLog));
252 console.log(UTIL_fmt('>' + UTIL_BytesToHex(u8)));
255 if (this.outTransferPending == false) {
256 this.outTransferPending = true;
257 chrome.usb.bulkTransfer(
258 /** @type {!chrome.usb.ConnectionHandle} */(this.dev),
259 { direction: 'out', endpoint: this.outEndpoint, data: frame },
260 OutTransferComplete);
262 throw 'outTransferPending!';
267 * Check whether channel is locked for this request or not.
268 * @param {number} cid Channel id
269 * @param {number} cmd Command to be sent
270 * @return {boolean} true if not locked for this request.
273 UsbGnubbyDevice.prototype.checkLock_ = function(cid, cmd) {
275 // We have an active lock.
276 if (this.lockCID != cid) {
277 // Some other channel has active lock.
279 if (cmd != GnubbyDevice.CMD_SYNC) {
280 // Anything but SYNC gets an immediate busy.
281 var busy = new Uint8Array(
286 GnubbyDevice.CMD_ERROR,
289 // Log the synthetic busy too.
290 console.log(UTIL_fmt('<' + UTIL_BytesToHex(busy)));
291 this.publishFrame_(busy.buffer);
295 // SYNC gets to go to the device to flush OS tx/rx queues.
296 // The usb firmware always responds to SYNC, regardless of lock status.
303 * Update or grab lock.
304 * @param {number} cid Channel id
305 * @param {number} cmd Command
306 * @param {number} arg Command argument
309 UsbGnubbyDevice.prototype.updateLock_ = function(cid, cmd, arg) {
310 if (this.lockCID == 0 || this.lockCID == cid) {
311 // It is this caller's or nobody's lock.
313 window.clearTimeout(this.lockTID);
317 if (cmd == GnubbyDevice.CMD_LOCK) {
321 // Set tracking time to be .1 seconds longer than usb device does.
322 this.lockMillis = nseconds * 1000 + 100;
324 // Releasing lock voluntarily.
329 // (re)set the lock timeout if we still hold it.
332 this.lockTID = window.setTimeout(
334 console.warn(UTIL_fmt(
335 'lock for CID ' + cid.toString(16) + ' expired!'));
345 * Queue command to be sent.
346 * If queue was empty, initiate the write.
347 * @param {number} cid The client's channel ID.
348 * @param {number} cmd The command to send.
349 * @param {ArrayBuffer|Uint8Array} data Command argument data
351 UsbGnubbyDevice.prototype.queueCommand = function(cid, cmd, data) {
352 if (!this.dev) return;
353 if (!this.checkLock_(cid, cmd)) return;
355 var u8 = new Uint8Array(data);
356 var frame = new Uint8Array(u8.length + 7);
358 frame[0] = cid >>> 24;
359 frame[1] = cid >>> 16;
360 frame[2] = cid >>> 8;
363 frame[5] = (u8.length >> 8);
364 frame[6] = (u8.length & 255);
368 var lockArg = (u8.length > 0) ? u8[0] : 0;
369 this.updateLock_(cid, cmd, lockArg);
371 var wasEmpty = (this.txqueue.length == 0);
372 this.txqueue.push(frame.buffer);
373 if (wasEmpty) this.writeOneRequest_();
377 * @param {function(Array)} cb Enumerate callback
379 UsbGnubbyDevice.enumerate = function(cb) {
381 var numEnumerated = 0;
384 function enumerated(devs) {
385 allDevs = allDevs.concat(devs);
386 if (++numEnumerated == permittedDevs.length) {
391 GnubbyDevice.getPermittedUsbDevices(function(devs) {
392 permittedDevs = devs;
393 for (var i = 0; i < devs.length; i++) {
394 chrome.usb.getDevices(devs[i], enumerated);
404 * maximumPacketSize: number,
405 * synchronization: (string|undefined),
406 * usage: (string|undefined),
407 * pollingInterval: (number|undefined)
409 * @see http://developer.chrome.com/apps/usb.html#method-listInterfaces
411 var InterfaceEndpoint;
416 * interfaceNumber: number,
417 * alternateSetting: number,
418 * interfaceClass: number,
419 * interfaceSubclass: number,
420 * interfaceProtocol: number,
421 * description: (string|undefined),
422 * endpoints: !Array.<!InterfaceEndpoint>
424 * @see http://developer.chrome.com/apps/usb.html#method-listInterfaces
426 var InterfaceDescriptor;
429 * @param {Gnubbies} gnubbies The gnubbies instances this device is enumerated
431 * @param {number} which The index of the device to open.
432 * @param {!chrome.usb.Device} dev The device to open.
433 * @param {function(number, GnubbyDevice=)} cb Called back with the
434 * result of opening the device.
436 UsbGnubbyDevice.open = function(gnubbies, which, dev, cb) {
437 /** @param {chrome.usb.ConnectionHandle=} handle Connection handle */
438 function deviceOpened(handle) {
440 console.warn(UTIL_fmt('failed to open device. permissions issue?'));
441 cb(-GnubbyDevice.NODEVICE);
444 var nonNullHandle = /** @type {!chrome.usb.ConnectionHandle} */ (handle);
445 chrome.usb.listInterfaces(nonNullHandle, function(descriptors) {
446 var inEndpoint, outEndpoint;
447 for (var i = 0; i < descriptors.length; i++) {
448 var descriptor = /** @type {InterfaceDescriptor} */ (descriptors[i]);
449 for (var j = 0; j < descriptor.endpoints.length; j++) {
450 var endpoint = descriptor.endpoints[j];
451 if (inEndpoint == undefined && endpoint.type == 'bulk' &&
452 endpoint.direction == 'in') {
453 inEndpoint = endpoint.address;
455 if (outEndpoint == undefined && endpoint.type == 'bulk' &&
456 endpoint.direction == 'out') {
457 outEndpoint = endpoint.address;
461 if (inEndpoint == undefined || outEndpoint == undefined) {
462 console.warn(UTIL_fmt('device lacking an endpoint (broken?)'));
463 chrome.usb.closeDevice(nonNullHandle);
464 cb(-GnubbyDevice.NODEVICE);
467 // Try getting it claimed now.
468 chrome.usb.claimInterface(nonNullHandle, 0, function() {
469 if (chrome.runtime.lastError) {
470 console.warn(UTIL_fmt('lastError: ' + chrome.runtime.lastError));
471 console.log(chrome.runtime.lastError);
473 var claimed = !chrome.runtime.lastError;
475 console.warn(UTIL_fmt('failed to claim interface. busy?'));
476 // Claim failed? Let the callers know and bail out.
477 chrome.usb.closeDevice(nonNullHandle);
478 cb(-GnubbyDevice.BUSY);
481 var gnubby = new UsbGnubbyDevice(gnubbies, nonNullHandle, which,
482 inEndpoint, outEndpoint);
483 cb(-GnubbyDevice.OK, gnubby);
488 if (UsbGnubbyDevice.runningOnCrOS === undefined) {
489 UsbGnubbyDevice.runningOnCrOS =
490 (window.navigator.appVersion.indexOf('; CrOS ') != -1);
492 if (UsbGnubbyDevice.runningOnCrOS) {
493 chrome.usb.requestAccess(dev, 0, function(success) {
494 // Even though the argument to requestAccess is a chrome.usb.Device, the
495 // access request is for access to all devices with the same vid/pid.
496 // Curiously, if the first chrome.usb.requestAccess succeeds, a second
497 // call with a separate device with the same vid/pid fails. Since
498 // chrome.usb.openDevice will fail if a previous access request really
499 // failed, just ignore the outcome of the access request and move along.
500 chrome.usb.openDevice(dev, deviceOpened);
503 chrome.usb.openDevice(dev, deviceOpened);
508 * @param {*} dev Chrome usb device
509 * @return {GnubbyDeviceId} A device identifier for the device.
511 UsbGnubbyDevice.deviceToDeviceId = function(dev) {
512 var usbDev = /** @type {!chrome.usb.Device} */ (dev);
514 namespace: UsbGnubbyDevice.NAMESPACE,
515 device: usbDev.device
521 * Registers this implementation with gnubbies.
522 * @param {Gnubbies} gnubbies Gnubbies singleton instance
524 UsbGnubbyDevice.register = function(gnubbies) {
525 var USB_GNUBBY_IMPL = {
526 isSharedAccess: false,
527 enumerate: UsbGnubbyDevice.enumerate,
528 deviceToDeviceId: UsbGnubbyDevice.deviceToDeviceId,
529 open: UsbGnubbyDevice.open
531 gnubbies.registerNamespace(UsbGnubbyDevice.NAMESPACE, USB_GNUBBY_IMPL);