How to use device method in devicefarmer-stf

Best JavaScript code snippet using devicefarmer-stf

usbDevice.https.any.js

Source:usbDevice.https.any.js Github

copy

Full Screen

1// META: timeout=long2// META: script=/webusb/resources/fake-devices.js3// META: script=/webusb/resources/usb-helpers.js4'use strict';5function assertRejectsWithNotFoundError(promise) {6 return assertRejectsWithError(promise, 'NotFoundError');7}8function assertRejectsWithTypeError(promise) {9 return assertRejectsWithError(promise, 'TypeError');10}11function assertRejectsWithNotOpenError(promise) {12 return assertRejectsWithError(13 promise, 'InvalidStateError', 'The device must be opened first.');14}15function assertRejectsWithNotConfiguredError(promise) {16 return assertRejectsWithError(17 promise, 'InvalidStateError',18 'The device must have a configuration selected.');19}20function assertRejectsWithDeviceStateChangeInProgressError(promise) {21 return assertRejectsWithError(22 promise, 'InvalidStateError',23 'An operation that changes the device state is in progress.');24}25function assertRejectsWithInterfaceStateChangeInProgressError(promise) {26 return assertRejectsWithError(27 promise, 'InvalidStateError',28 'An operation that changes interface state is in progress.');29}30usb_test(() => {31 return getFakeDevice().then(({ device, fakeDevice }) => {32 return waitForDisconnect(fakeDevice)33 .then(() => assertRejectsWithNotFoundError(device.open()));34 });35}, 'open rejects when called on a disconnected device');36usb_test(() => {37 return getFakeDevice().then(({ device, fakeDevice }) => {38 return device.open()39 .then(() => waitForDisconnect(fakeDevice))40 .then(() => {41 assert_false(device.opened);42 });43 });44}, 'disconnection closes the device');45usb_test(() => {46 return getFakeDevice().then(({ device }) => {47 assert_false(device.opened);48 return device.open().then(() => {49 assert_true(device.opened);50 return device.close().then(() => {51 assert_false(device.opened);52 });53 });54 });55}, 'a device can be opened and closed');56usb_test(() => {57 return getFakeDevice().then(({ device }) => {58 return device.open()59 .then(() => device.open())60 .then(() => device.open())61 .then(() => device.open())62 .then(() => device.close())63 .then(() => device.close())64 .then(() => device.close())65 .then(() => device.close());66 });67}, 'open and close can be called multiple times');68usb_test(async () => {69 let { device } = await getFakeDevice();70 await Promise.all([71 device.open(),72 assertRejectsWithDeviceStateChangeInProgressError(device.open()),73 assertRejectsWithDeviceStateChangeInProgressError(device.close()),74 ]);75 await Promise.all([76 device.close(),77 assertRejectsWithDeviceStateChangeInProgressError(device.open()),78 assertRejectsWithDeviceStateChangeInProgressError(device.close()),79 ]);80}, 'open and close cannot be called again while open or close are in progress');81usb_test(async () => {82 let { device } = await getFakeDevice();83 await device.open();84 return Promise.all([85 device.selectConfiguration(1),86 assertRejectsWithDeviceStateChangeInProgressError(87 device.claimInterface(0)),88 assertRejectsWithDeviceStateChangeInProgressError(89 device.releaseInterface(0)),90 assertRejectsWithDeviceStateChangeInProgressError(device.open()),91 assertRejectsWithDeviceStateChangeInProgressError(92 device.selectConfiguration(1)),93 assertRejectsWithDeviceStateChangeInProgressError(device.reset()),94 assertRejectsWithDeviceStateChangeInProgressError(95 device.selectAlternateInterface(0, 0)),96 assertRejectsWithDeviceStateChangeInProgressError(97 device.controlTransferOut({98 requestType: 'standard',99 recipient: 'interface',100 request: 0x42,101 value: 0x1234,102 index: 0x0000,103 })),104 assertRejectsWithDeviceStateChangeInProgressError(105 device.controlTransferOut({106 requestType: 'standard',107 recipient: 'interface',108 request: 0x42,109 value: 0x1234,110 index: 0x0000,111 }, new Uint8Array([1, 2, 3]))),112 assertRejectsWithDeviceStateChangeInProgressError(113 device.controlTransferIn({114 requestType: 'standard',115 recipient: 'interface',116 request: 0x42,117 value: 0x1234,118 index: 0x0000119 }, 0)),120 assertRejectsWithDeviceStateChangeInProgressError(device.close()),121 ]);122}, 'device operations reject if an device state change is in progress');123usb_test(() => {124 return getFakeDevice().then(({ device, fakeDevice }) => {125 return device.open()126 .then(() => waitForDisconnect(fakeDevice))127 .then(() => assertRejectsWithNotFoundError(device.close()));128 });129}, 'close rejects when called on a disconnected device');130usb_test(() => {131 return getFakeDevice().then(({ device, fakeDevice }) => {132 return device.open()133 .then(() => waitForDisconnect(fakeDevice))134 .then(() => assertRejectsWithNotFoundError(device.selectConfiguration(1)));135 });136}, 'selectConfiguration rejects when called on a disconnected device');137usb_test(() => {138 return getFakeDevice().then(({ device }) => Promise.all([139 assertRejectsWithNotOpenError(device.selectConfiguration(1)),140 assertRejectsWithNotOpenError(device.claimInterface(0)),141 assertRejectsWithNotOpenError(device.releaseInterface(0)),142 assertRejectsWithNotOpenError(device.selectAlternateInterface(0, 1)),143 assertRejectsWithNotOpenError(device.controlTransferIn({144 requestType: 'vendor',145 recipient: 'device',146 request: 0x42,147 value: 0x1234,148 index: 0x5678149 }, 7)),150 assertRejectsWithNotOpenError(device.controlTransferOut({151 requestType: 'vendor',152 recipient: 'device',153 request: 0x42,154 value: 0x1234,155 index: 0x5678156 }, new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]))),157 assertRejectsWithNotOpenError(device.clearHalt('in', 1)),158 assertRejectsWithNotOpenError(device.transferIn(1, 8)),159 assertRejectsWithNotOpenError(160 device.transferOut(1, new ArrayBuffer(8))),161 assertRejectsWithNotOpenError(device.isochronousTransferIn(1, [8])),162 assertRejectsWithNotOpenError(163 device.isochronousTransferOut(1, new ArrayBuffer(8), [8])),164 assertRejectsWithNotOpenError(device.reset())165 ]));166}, 'methods requiring it reject when the device is not open');167usb_test(() => {168 return getFakeDevice().then(({ device }) => {169 assert_equals(device.configuration, null);170 return device.open()171 .then(() => {172 assert_equals(device.configuration, null);173 return device.selectConfiguration(1);174 })175 .then(() => {176 assertDeviceInfoEquals(177 device.configuration, fakeDeviceInit.configurations[0]);178 })179 .then(() => device.close());180 });181}, 'device configuration can be set and queried');182usb_test(async () => {183 let { device } = await getFakeDevice();184 assert_equals(device.configuration, null);185 await device.open();186 assert_equals(device.configuration, null);187 await device.selectConfiguration(1);188 await device.selectConfiguration(1);189 assertDeviceInfoEquals(190 device.configuration, fakeDeviceInit.configurations[0]);191 await device.selectConfiguration(2);192 assertDeviceInfoEquals(193 device.configuration, fakeDeviceInit.configurations[1]);194 await device.close();195}, 'a device configuration value can be set again');196usb_test(() => {197 return getFakeDevice().then(({ device }) => {198 assert_equals(device.configuration, null);199 return device.open()200 .then(() => assertRejectsWithError(201 device.selectConfiguration(3), 'NotFoundError',202 'The configuration value provided is not supported by the device.'))203 .then(() => device.close());204 });205}, 'selectConfiguration rejects on invalid configurations');206usb_test(() => {207 return getFakeDevice().then(({ device }) => {208 assert_equals(device.configuration, null);209 return device.open().then(() => Promise.all([210 assertRejectsWithNotConfiguredError(device.claimInterface(0)),211 assertRejectsWithNotConfiguredError(device.releaseInterface(0)),212 assertRejectsWithNotConfiguredError(device.selectAlternateInterface(0, 1)),213 assertRejectsWithNotConfiguredError(device.controlTransferIn({214 requestType: 'vendor',215 recipient: 'device',216 request: 0x42,217 value: 0x1234,218 index: 0x5678219 }, 7)),220 assertRejectsWithNotConfiguredError(device.controlTransferOut({221 requestType: 'vendor',222 recipient: 'device',223 request: 0x42,224 value: 0x1234,225 index: 0x5678226 }, new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]))),227 assertRejectsWithNotConfiguredError(device.clearHalt('in', 1)),228 assertRejectsWithNotConfiguredError(device.transferIn(1, 8)),229 assertRejectsWithNotConfiguredError(230 device.transferOut(1, new ArrayBuffer(8))),231 assertRejectsWithNotConfiguredError(232 device.isochronousTransferIn(1, [8])),233 assertRejectsWithNotConfiguredError(234 device.isochronousTransferOut(1, new ArrayBuffer(8), [8])),235 ])).then(() => device.close());236 });237}, 'methods requiring it reject when the device is unconfigured');238usb_test(() => {239 return getFakeDevice().then(({ device }) => {240 return device.open()241 .then(() => device.selectConfiguration(1))242 .then(() => device.claimInterface(0))243 .then(() => {244 assert_true(device.configuration.interfaces[0].claimed);245 return device.releaseInterface(0);246 })247 .then(() => {248 assert_false(device.configuration.interfaces[0].claimed);249 return device.close();250 });251 });252}, 'an interface can be claimed and released');253usb_test(async () => {254 let { device } = await getFakeDevice()255 await device.open();256 await device.selectConfiguration(1);257 await device.claimInterface(0);258 assert_true(device.configuration.interfaces[0].claimed);259 await device.claimInterface(0);260 assert_true(device.configuration.interfaces[0].claimed);261 await device.close();262}, 'an interface can be claimed multiple times');263usb_test(async () => {264 let { device } = await getFakeDevice();265 await device.open();266 await device.selectConfiguration(1);267 await device.claimInterface(0);268 assert_true(device.configuration.interfaces[0].claimed);269 await device.releaseInterface(0);270 assert_false(device.configuration.interfaces[0].claimed);271 await device.releaseInterface(0);272 assert_false(device.configuration.interfaces[0].claimed);273 await device.close();274}, 'an interface can be released multiple times');275usb_test(async () => {276 let { device } = await getFakeDevice();277 await device.open();278 await device.selectConfiguration(1);279 return Promise.all([280 device.claimInterface(0),281 assertRejectsWithInterfaceStateChangeInProgressError(282 device.claimInterface(0)),283 assertRejectsWithInterfaceStateChangeInProgressError(284 device.releaseInterface(0)),285 assertRejectsWithInterfaceStateChangeInProgressError(device.open()),286 assertRejectsWithInterfaceStateChangeInProgressError(287 device.selectConfiguration(1)),288 assertRejectsWithInterfaceStateChangeInProgressError(device.reset()),289 assertRejectsWithInterfaceStateChangeInProgressError(290 device.selectAlternateInterface(0, 0)),291 assertRejectsWithInterfaceStateChangeInProgressError(292 device.controlTransferOut({293 requestType: 'standard',294 recipient: 'interface',295 request: 0x42,296 value: 0x1234,297 index: 0x0000,298 })),299 assertRejectsWithInterfaceStateChangeInProgressError(300 device.controlTransferOut({301 requestType: 'standard',302 recipient: 'interface',303 request: 0x42,304 value: 0x1234,305 index: 0x0000,306 }, new Uint8Array([1, 2, 3]))),307 assertRejectsWithInterfaceStateChangeInProgressError(308 device.controlTransferIn({309 requestType: 'standard',310 recipient: 'interface',311 request: 0x42,312 value: 0x1234,313 index: 0x0000314 }, 0)),315 assertRejectsWithInterfaceStateChangeInProgressError(device.close()),316 ]);317}, 'device operations reject if an interface state change is in progress');318usb_test(async () => {319 let { device } = await getFakeDevice();320 await device.open();321 await device.selectConfiguration(1);322 await device.claimInterface(0);323 assert_true(device.configuration.interfaces[0].claimed);324 await device.close(0);325 assert_false(device.configuration.interfaces[0].claimed);326}, 'interfaces are released on close');327usb_test(() => {328 return getFakeDevice().then(({ device }) => {329 const message = 'The interface number provided is not supported by the ' +330 'device in its current configuration.';331 return device.open()332 .then(() => device.selectConfiguration(1))333 .then(() => Promise.all([334 assertRejectsWithError(335 device.claimInterface(2), 'NotFoundError', message),336 assertRejectsWithError(337 device.releaseInterface(2), 'NotFoundError', message),338 ]))339 .then(() => device.close());340 });341}, 'a non-existent interface cannot be claimed or released');342usb_test(() => {343 return getFakeDevice().then(({ device, fakeDevice }) => {344 return device.open()345 .then(() => device.selectConfiguration(1))346 .then(() => waitForDisconnect(fakeDevice))347 .then(() => assertRejectsWithNotFoundError(device.claimInterface(0)));348 });349}, 'claimInterface rejects when called on a disconnected device');350usb_test(() => {351 return getFakeDevice().then(({ device, fakeDevice }) => {352 return device.open()353 .then(() => device.selectConfiguration(1))354 .then(() => device.claimInterface(0))355 .then(() => waitForDisconnect(fakeDevice))356 .then(() => assertRejectsWithNotFoundError(device.releaseInterface(0)));357 });358}, 'releaseInterface rejects when called on a disconnected device');359usb_test(() => {360 return getFakeDevice().then(({ device }) => {361 return device.open()362 .then(() => device.selectConfiguration(2))363 .then(() => device.claimInterface(0))364 .then(() => device.selectAlternateInterface(0, 1))365 .then(() => device.close());366 });367}, 'can select an alternate interface');368usb_test(() => {369 return getFakeDevice().then(({ device }) => {370 return device.open()371 .then(() => device.selectConfiguration(2))372 .then(() => device.claimInterface(0))373 .then(() => assertRejectsWithError(374 device.selectAlternateInterface(0, 2), 'NotFoundError',375 'The alternate setting provided is not supported by the device in ' +376 'its current configuration.'))377 .then(() => device.close());378 });379}, 'cannot select a non-existent alternate interface');380usb_test(() => {381 return getFakeDevice().then(({ device, fakeDevice }) => {382 return device.open()383 .then(() => device.selectConfiguration(2))384 .then(() => device.claimInterface(0))385 .then(() => waitForDisconnect(fakeDevice))386 .then(() => assertRejectsWithNotFoundError(device.selectAlternateInterface(0, 1)));387 });388}, 'selectAlternateInterface rejects when called on a disconnected device');389usb_test(async () => {390 let { device } = await getFakeDevice();391 let usbRequestTypes = ['standard', 'class', 'vendor'];392 let usbRecipients = ['device', 'interface', 'endpoint', 'other'];393 await device.open();394 await device.selectConfiguration(1);395 await device.claimInterface(0);396 await device.selectAlternateInterface(0, 0);397 for (const requestType of usbRequestTypes) {398 for (const recipient of usbRecipients) {399 let index = recipient === 'interface' ? 0x5600 : 0x5681;400 let result = await device.controlTransferIn({401 requestType: requestType,402 recipient: recipient,403 request: 0x42,404 value: 0x1234,405 index: index406 }, 7);407 assert_true(result instanceof USBInTransferResult);408 assert_equals(result.status, 'ok');409 assert_equals(result.data.byteLength, 7);410 assert_equals(result.data.getUint16(0), 0x07);411 assert_equals(result.data.getUint8(2), 0x42);412 assert_equals(result.data.getUint16(3), 0x1234);413 assert_equals(result.data.getUint16(5), index);414 }415 }416 await device.close();417}, 'can issue all types of IN control transfers');418usb_test(() => {419 return getFakeDevice().then(({ device, fakeDevice }) => {420 return device.open()421 .then(() => device.selectConfiguration(1))422 .then(() => waitForDisconnect(fakeDevice))423 .then(() => assertRejectsWithNotFoundError(device.controlTransferIn({424 requestType: 'vendor',425 recipient: 'device',426 request: 0x42,427 value: 0x1234,428 index: 0x5678429 }, 7)));430 });431}, 'controlTransferIn rejects when called on a disconnected device');432usb_test(async () => {433 let { device } = await getFakeDevice();434 let usbRequestTypes = ['standard', 'class', 'vendor'];435 let usbRecipients = ['device', 'interface', 'endpoint', 'other'];436 let dataArray = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);437 let dataTypes = [dataArray, dataArray.buffer];438 await device.open();439 await device.selectConfiguration(1);440 await device.claimInterface(0);441 await device.selectAlternateInterface(0, 0);442 for (const requestType of usbRequestTypes) {443 for (const recipient of usbRecipients) {444 let index = recipient === 'interface' ? 0x5600 : 0x5681;445 let transferParams = {446 requestType: requestType,447 recipient: recipient,448 request: 0x42,449 value: 0x1234,450 index: index451 };452 for (const data of dataTypes) {453 let result = await device.controlTransferOut(transferParams, data);454 assert_true(result instanceof USBOutTransferResult);455 assert_equals(result.status, 'ok');456 assert_equals(result.bytesWritten, 8);457 }458 let result = await device.controlTransferOut(transferParams);459 assert_true(result instanceof USBOutTransferResult);460 assert_equals(result.status, 'ok');461 }462 }463 await device.close();464}, 'can issue all types of OUT control transfers');465usb_test(() => {466 return getFakeDevice().then(({ device, fakeDevice }) => {467 return device.open()468 .then(() => device.selectConfiguration(1))469 .then(() => waitForDisconnect(fakeDevice))470 .then(() => assertRejectsWithNotFoundError(device.controlTransferOut({471 requestType: 'vendor',472 recipient: 'device',473 request: 0x42,474 value: 0x1234,475 index: 0x5678476 }, new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]))));477 });478}, 'controlTransferOut rejects when called on a disconnected device');479usb_test(async () => {480 let { device } = await getFakeDevice();481 await device.open();482 await device.selectConfiguration(1);483 await device.claimInterface(0);484 assertRejectsWithTypeError(device.controlTransferOut({485 requestType: 'invalid',486 recipient: 'device',487 request: 0x42,488 value: 0x1234,489 index: 0x5678490 }, new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8])));491 assertRejectsWithTypeError(device.controlTransferIn({492 requestType: 'invalid',493 recipient: 'device',494 request: 0x42,495 value: 0x1234,496 index: 0x5678497 }, 0));498 await device.close();499}, 'control transfers with a invalid request type reject');500usb_test(async () => {501 let { device } = await getFakeDevice();502 await device.open();503 await device.selectConfiguration(1);504 await device.claimInterface(0);505 assertRejectsWithTypeError(device.controlTransferOut({506 requestType: 'vendor',507 recipient: 'invalid',508 request: 0x42,509 value: 0x1234,510 index: 0x5678511 }, new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8])));512 assertRejectsWithTypeError(device.controlTransferIn({513 requestType: 'vendor',514 recipient: 'invalid',515 request: 0x42,516 value: 0x1234,517 index: 0x5678518 }, 0));519}, 'control transfers with a invalid recipient type reject');520usb_test(async () => {521 let { device } = await getFakeDevice();522 await device.open();523 await device.selectConfiguration(1);524 await device.claimInterface(0);525 assertRejectsWithNotFoundError(device.controlTransferOut({526 requestType: 'vendor',527 recipient: 'interface',528 request: 0x42,529 value: 0x1234,530 index: 0x0002 // Last byte of index is interface number.531 }, new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8])));532 assertRejectsWithNotFoundError(device.controlTransferIn({533 requestType: 'vendor',534 recipient: 'interface',535 request: 0x42,536 value: 0x1234,537 index: 0x0002 // Last byte of index is interface number.538 }, 0));539}, 'control transfers to a non-existant interface reject');540usb_test(() => {541 return getFakeDevice().then(({ device }) => {542 let interfaceRequest = {543 requestType: 'vendor',544 recipient: 'interface',545 request: 0x42,546 value: 0x1234,547 index: 0x5600 // Last byte of index is interface number.548 };549 let endpointRequest = {550 requestType: 'vendor',551 recipient: 'endpoint',552 request: 0x42,553 value: 0x1234,554 index: 0x5681 // Last byte of index is endpoint address.555 };556 let data = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);557 return device.open()558 .then(() => device.selectConfiguration(1))559 .then(() => Promise.all([560 assertRejectsWithError(561 device.controlTransferIn(interfaceRequest, 7),562 'InvalidStateError'),563 assertRejectsWithError(564 device.controlTransferIn(endpointRequest, 7),565 'NotFoundError'),566 assertRejectsWithError(567 device.controlTransferOut(interfaceRequest, data),568 'InvalidStateError'),569 assertRejectsWithError(570 device.controlTransferOut(endpointRequest, data),571 'NotFoundError'),572 ]))573 .then(() => device.claimInterface(0))574 .then(() => Promise.all([575 device.controlTransferIn(interfaceRequest, 7).then(result => {576 assert_true(result instanceof USBInTransferResult);577 assert_equals(result.status, 'ok');578 assert_equals(result.data.byteLength, 7);579 assert_equals(result.data.getUint16(0), 0x07);580 assert_equals(result.data.getUint8(2), 0x42);581 assert_equals(result.data.getUint16(3), 0x1234);582 assert_equals(result.data.getUint16(5), 0x5600);583 }),584 device.controlTransferIn(endpointRequest, 7).then(result => {585 assert_true(result instanceof USBInTransferResult);586 assert_equals(result.status, 'ok');587 assert_equals(result.data.byteLength, 7);588 assert_equals(result.data.getUint16(0), 0x07);589 assert_equals(result.data.getUint8(2), 0x42);590 assert_equals(result.data.getUint16(3), 0x1234);591 assert_equals(result.data.getUint16(5), 0x5681);592 }),593 device.controlTransferOut(interfaceRequest, data),594 device.controlTransferOut(endpointRequest, data),595 ]))596 .then(() => device.close());597 });598}, 'requests to interfaces and endpoint require an interface claim');599usb_test(() => {600 return getFakeDevice().then(({ device }) => {601 return device.open()602 .then(() => device.selectConfiguration(1))603 .then(() => device.claimInterface(0))604 .then(() => device.clearHalt('in', 1))605 .then(() => device.close());606 });607}, 'can clear a halt condition');608usb_test(() => {609 return getFakeDevice().then(({ device, fakeDevice }) => {610 return device.open()611 .then(() => device.selectConfiguration(1))612 .then(() => device.claimInterface(0))613 .then(() => waitForDisconnect(fakeDevice))614 .then(() => assertRejectsWithNotFoundError(device.clearHalt('in', 1)));615 });616}, 'clearHalt rejects when called on a disconnected device');617usb_test(() => {618 return getFakeDevice().then(({ device }) => {619 let data = new DataView(new ArrayBuffer(1024));620 for (let i = 0; i < 1024; ++i)621 data.setUint8(i, i & 0xff);622 const notFoundMessage = 'The specified endpoint is not part of a claimed ' +623 'and selected alternate interface.';624 const rangeError = 'The specified endpoint number is out of range.';625 return device.open()626 .then(() => device.selectConfiguration(1))627 .then(() => device.claimInterface(0))628 .then(() => Promise.all([629 assertRejectsWithError(device.transferIn(2, 8),630 'NotFoundError', notFoundMessage), // Unclaimed631 assertRejectsWithError(device.transferIn(3, 8), 'NotFoundError',632 notFoundMessage), // Non-existent633 assertRejectsWithError(634 device.transferIn(16, 8), 'IndexSizeError', rangeError),635 assertRejectsWithError(device.transferOut(2, data),636 'NotFoundError', notFoundMessage), // Unclaimed637 assertRejectsWithError(device.transferOut(3, data), 'NotFoundError',638 notFoundMessage), // Non-existent639 assertRejectsWithError(640 device.transferOut(16, data), 'IndexSizeError', rangeError),641 ]));642 });643}, 'transfers to unavailable endpoints are rejected');644usb_test(() => {645 return getFakeDevice().then(({ device }) => {646 return device.open()647 .then(() => device.selectConfiguration(1))648 .then(() => device.claimInterface(0))649 .then(() => device.transferIn(1, 8))650 .then(result => {651 assert_true(result instanceof USBInTransferResult);652 assert_equals(result.status, 'ok');653 assert_equals(result.data.byteLength, 8);654 for (let i = 0; i < 8; ++i)655 assert_equals(result.data.getUint8(i), i, 'mismatch at byte ' + i);656 return device.close();657 });658 });659}, 'can issue IN interrupt transfer');660usb_test(() => {661 return getFakeDevice().then(({ device }) => {662 return device.open()663 .then(() => device.selectConfiguration(1))664 .then(() => device.claimInterface(1))665 .then(() => device.transferIn(2, 1024))666 .then(result => {667 assert_true(result instanceof USBInTransferResult);668 assert_equals(result.status, 'ok');669 assert_equals(result.data.byteLength, 1024);670 for (let i = 0; i < 1024; ++i)671 assert_equals(result.data.getUint8(i), i & 0xff,672 'mismatch at byte ' + i);673 return device.close();674 });675 });676}, 'can issue IN bulk transfer');677usb_test(() => {678 return getFakeDevice().then(({ device, fakeDevice }) => {679 return device.open()680 .then(() => device.selectConfiguration(1))681 .then(() => device.claimInterface(1))682 .then(() => waitForDisconnect(fakeDevice))683 .then(() => assertRejectsWithNotFoundError(device.transferIn(2, 1024)));684 });685}, 'transferIn rejects if called on a disconnected device');686usb_test(() => {687 return getFakeDevice().then(({ device }) => {688 return device.open()689 .then(() => device.selectConfiguration(1))690 .then(() => device.claimInterface(1))691 .then(() => {692 let data = new DataView(new ArrayBuffer(1024));693 for (let i = 0; i < 1024; ++i)694 data.setUint8(i, i & 0xff);695 return device.transferOut(2, data);696 })697 .then(result => {698 assert_true(result instanceof USBOutTransferResult);699 assert_equals(result.status, 'ok');700 assert_equals(result.bytesWritten, 1024);701 return device.close();702 });703 });704}, 'can issue OUT bulk transfer');705usb_test(() => {706 return getFakeDevice().then(({ device, fakeDevice }) => {707 return device.open()708 .then(() => device.selectConfiguration(1))709 .then(() => device.claimInterface(1))710 .then(() => {711 let data = new DataView(new ArrayBuffer(1024));712 for (let i = 0; i < 1024; ++i)713 data.setUint8(i, i & 0xff);714 return waitForDisconnect(fakeDevice)715 .then(() => assertRejectsWithNotFoundError(device.transferOut(2, data)));716 });717 });718}, 'transferOut rejects if called on a disconnected device');719usb_test(() => {720 return getFakeDevice().then(({ device }) => {721 return device.open()722 .then(() => device.selectConfiguration(2))723 .then(() => device.claimInterface(0))724 .then(() => device.selectAlternateInterface(0, 1))725 .then(() => device.isochronousTransferIn(726 1, [64, 64, 64, 64, 64, 64, 64, 64]))727 .then(result => {728 assert_true(result instanceof USBIsochronousInTransferResult);729 assert_equals(result.data.byteLength, 64 * 8, 'buffer size');730 assert_equals(result.packets.length, 8, 'number of packets');731 let byteOffset = 0;732 for (let i = 0; i < result.packets.length; ++i) {733 assert_true(734 result.packets[i] instanceof USBIsochronousInTransferPacket);735 assert_equals(result.packets[i].status, 'ok');736 assert_equals(result.packets[i].data.byteLength, 64);737 assert_equals(result.packets[i].data.buffer, result.data.buffer);738 assert_equals(result.packets[i].data.byteOffset, byteOffset);739 for (let j = 0; j < 64; ++j)740 assert_equals(result.packets[i].data.getUint8(j), j & 0xff,741 'mismatch at byte ' + j + ' of packet ' + i);742 byteOffset += result.packets[i].data.byteLength;743 }744 return device.close();745 });746 });747}, 'can issue IN isochronous transfer');748usb_test(() => {749 return getFakeDevice().then(({ device, fakeDevice }) => {750 return device.open()751 .then(() => device.selectConfiguration(2))752 .then(() => device.claimInterface(0))753 .then(() => device.selectAlternateInterface(0, 1))754 .then(() => waitForDisconnect(fakeDevice))755 .then(() => assertRejectsWithNotFoundError(device.isochronousTransferIn(756 1, [64, 64, 64, 64, 64, 64, 64, 64])));757 });758}, 'isochronousTransferIn rejects when called on a disconnected device');759usb_test(() => {760 return getFakeDevice().then(({ device }) => {761 return device.open()762 .then(() => device.selectConfiguration(2))763 .then(() => device.claimInterface(0))764 .then(() => device.selectAlternateInterface(0, 1))765 .then(() => {766 let data = new DataView(new ArrayBuffer(64 * 8));767 for (let i = 0; i < 8; ++i) {768 for (let j = 0; j < 64; ++j)769 data.setUint8(i * j, j & 0xff);770 }771 return device.isochronousTransferOut(772 1, data, [64, 64, 64, 64, 64, 64, 64, 64]);773 })774 .then(result => {775 assert_true(result instanceof USBIsochronousOutTransferResult);776 assert_equals(result.packets.length, 8, 'number of packets');777 let byteOffset = 0;778 for (let i = 0; i < result.packets.length; ++i) {779 assert_true(780 result.packets[i] instanceof USBIsochronousOutTransferPacket);781 assert_equals(result.packets[i].status, 'ok');782 assert_equals(result.packets[i].bytesWritten, 64);783 }784 return device.close();785 });786 });787}, 'can issue OUT isochronous transfer');788usb_test(() => {789 return getFakeDevice().then(({ device, fakeDevice }) => {790 return device.open()791 .then(() => device.selectConfiguration(2))792 .then(() => device.claimInterface(0))793 .then(() => device.selectAlternateInterface(0, 1))794 .then(() => {795 let data = new DataView(new ArrayBuffer(64 * 8));796 for (let i = 0; i < 8; ++i) {797 for (let j = 0; j < 64; ++j)798 data.setUint8(i * j, j & 0xff);799 }800 return waitForDisconnect(fakeDevice)801 .then(() => assertRejectsWithNotFoundError(device.isochronousTransferOut(802 1, data, [64, 64, 64, 64, 64, 64, 64, 64])));803 });804 });805}, 'isochronousTransferOut rejects when called on a disconnected device');806usb_test(() => {807 return getFakeDevice().then(({ device }) => {808 return device.open().then(() => device.reset()).then(() => device.close());809 });810}, 'can reset the device');811usb_test(() => {812 return getFakeDevice().then(({ device, fakeDevice }) => {813 return device.open()814 .then(() => waitForDisconnect(fakeDevice))815 .then(() => assertRejectsWithNotFoundError(device.reset()));816 });...

Full Screen

Full Screen

device.py

Source:device.py Github

copy

Full Screen

...56 self.device_id = device_id57 return self.device_id58 def query_download_filename(self, file_id=None):59 pass60 def ping_device(self):61 pass62 def check_device(self):63 pass64 def cleanup_device(self, reboot=False):65 pass66 def reboot_device(self):67 pass68 def query_device_root(self):69 pass70 def wait_for_device(self, interval=60, max_attempts=20):71 pass72 def install_app(self, file_path):73 pass74# ADBDeviceHandler {{{175class ADBDeviceHandler(BaseDeviceHandler):76 def __init__(self, **kwargs):77 super(ADBDeviceHandler, self).__init__(**kwargs)78 self.default_port = 555579 def query_device_exe(self, exe_name):80 return self.query_exe(exe_name, exe_dict="device_exes")81 def _query_config_device_id(self):82 return BaseDeviceHandler.query_device_id(self)83 def query_device_id(self, auto_connect=True):84 if self.device_id:85 return self.device_id86 device_id = self._query_config_device_id()87 if device_id:88 if auto_connect:89 self.ping_device(auto_connect=True)90 else:91 self.info("Trying to find device...")92 devices = self._query_attached_devices()93 if not devices:94 self.add_device_flag(DEVICE_NOT_CONNECTED)95 self.fatal("No device connected via adb!\nUse 'adb connect' or specify a device_id or device_ip in config!")96 elif len(devices) > 1:97 self.warning("""More than one device detected; specify 'device_id' or\n'device_ip' to target a specific device!""")98 device_id = devices[0]99 self.info("Found %s." % device_id)100 self.device_id = device_id101 return self.device_id102 # maintenance {{{2103 def ping_device(self, auto_connect=False, silent=False):104 if auto_connect and not self._query_attached_devices():105 self.connect_device()106 if not silent:107 self.info("Determining device connectivity over adb...")108 device_id = self.query_device_id()109 adb = self.query_exe('adb')110 uptime = self.query_device_exe('uptime')111 output = self.get_output_from_command([adb, "-s", device_id,112 "shell", uptime],113 silent=silent)114 if str(output).startswith("up time:"):115 if not silent:116 self.info("Found %s." % device_id)117 return True118 elif auto_connect:119 # TODO retry?120 self.connect_device()121 return self.ping_device()122 else:123 if not silent:124 self.error("Can't find a device.")125 return False126 def _query_attached_devices(self):127 devices = []128 adb = self.query_exe('adb')129 output = self.get_output_from_command([adb, "devices"])130 starting_list = False131 if output is None:132 self.add_device_flag(DEVICE_HOST_ERROR)133 self.fatal("Can't get output from 'adb devices'; install the Android SDK!")134 for line in output:135 if 'adb: command not found' in line:136 self.add_device_flag(DEVICE_HOST_ERROR)137 self.fatal("Can't find adb; install the Android SDK!")138 if line.startswith("* daemon"):139 continue140 if line.startswith("List of devices"):141 starting_list = True142 continue143 # TODO somehow otherwise determine whether this is an actual144 # device?145 if starting_list:146 devices.append(re.split('\s+', line)[0])147 return devices148 def connect_device(self):149 self.info("Connecting device...")150 adb = self.query_exe('adb')151 cmd = [adb, "connect"]152 device_id = self._query_config_device_id()153 if device_id:154 devices = self._query_attached_devices()155 if device_id in devices:156 # TODO is this the right behavior?157 self.disconnect_device()158 cmd.append(device_id)159 # TODO error check160 self.run_command(cmd, error_list=ADBErrorList)161 def disconnect_device(self):162 self.info("Disconnecting device...")163 device_id = self.query_device_id()164 if device_id:165 adb = self.query_exe('adb')166 # TODO error check167 self.run_command([adb, "-s", device_id,168 "disconnect"],169 error_list=ADBErrorList)170 else:171 self.info("No device found.")172 def check_device(self):173 if not self.ping_device(auto_connect=True):174 self.add_device_flag(DEVICE_NOT_CONNECTED)175 self.fatal("Can't find device!")176 if self.query_device_root() is None:177 self.add_device_flag(DEVICE_NOT_CONNECTED)178 self.fatal("Can't connect to device!")179 def reboot_device(self):180 if not self.ping_device(auto_connect=True):181 self.add_device_flag(DEVICE_NOT_REBOOTED)182 self.error("Can't reboot disconnected device!")183 return False184 device_id = self.query_device_id()185 self.info("Rebooting device...")186 adb = self.query_exe('adb')187 cmd = [adb, "-s", device_id, "reboot"]188 self.info("Running command (in the background): %s" % cmd)189 # This won't exit until much later, but we don't need to wait.190 # However, some error checking would be good.191 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,192 stderr=subprocess.STDOUT)193 time.sleep(10)194 self.disconnect_device()195 status = False196 try:197 self.wait_for_device()198 status = True199 except DeviceException:200 self.error("Can't reconnect to device!")201 if p.poll() is None:202 p.kill()203 p.wait()204 return status205 def cleanup_device(self, reboot=False):206 self.info("Cleaning up device.")207 c = self.config208 device_id = self.query_device_id()209 status = self.remove_device_root()210 if not status:211 self.add_device_flag(DEVICE_CANT_REMOVE_DEVROOT)212 self.fatal("Can't remove device root!")213 if c.get("enable_automation"):214 self.remove_etc_hosts()215 if c.get("device_package_name"):216 adb = self.query_exe('adb')217 killall = self.query_device_exe('killall')218 self.run_command([adb, "-s", device_id, "shell",219 killall, c["device_package_name"]],220 error_list=ADBErrorList)221 self.uninstall_app(c['device_package_name'])222 if reboot:223 self.reboot_device()224 # device calls {{{2225 def query_device_root(self, silent=False):226 if self.device_root:227 return self.device_root228 device_root = None229 device_id = self.query_device_id()230 adb = self.query_exe('adb')231 output = self.get_output_from_command("%s -s %s shell df" % (adb, device_id),232 silent=silent)233 # TODO this assumes we're connected; error checking?234 if output is None or ' not found' in str(output):235 self.error("Can't get output from 'adb shell df'!\n%s" % output)236 return None237 if "/mnt/sdcard" in output:238 device_root = "/mnt/sdcard/tests"239 else:240 device_root = "/data/local/tmp/tests"241 if not silent:242 self.info("Device root is %s" % str(device_root))243 self.device_root = device_root244 return self.device_root245 # TODO from here on down needs to be copied to Base+SUT246 def wait_for_device(self, interval=60, max_attempts=20):247 self.info("Waiting for device to come back...")248 time.sleep(interval)249 tries = 0250 while tries <= max_attempts:251 tries += 1252 self.info("Try %d" % tries)253 if self.ping_device(auto_connect=True, silent=True):254 return self.ping_device()255 time.sleep(interval)256 raise DeviceException("Remote Device Error: waiting for device timed out.")257 def query_device_time(self):258 device_id = self.query_device_id()259 adb = self.query_exe('adb')260 # adb shell 'date' will give a date string261 date_string = self.get_output_from_command([adb, "-s", device_id,262 "shell", "date"])263 # TODO what to do when we error?264 return date_string265 def set_device_time(self, device_time=None, error_level='error'):266 # adb shell date -s YYYYMMDD.hhmmss will set date267 device_id = self.query_device_id()268 if device_time is None:269 device_time = time.strftime("%Y%m%d.%H%M%S")270 self.info(self.query_device_time())271 adb = self.query_exe('adb')272 status = self.run_command([adb, "-s", device_id, "shell", "date", "-s",273 str(device_time)],274 error_list=ADBErrorList)275 self.info(self.query_device_time())276 return status277 def query_device_file_exists(self, file_name):278 device_id = self.query_device_id()279 adb = self.query_exe('adb')280 output = self.get_output_from_command([adb, "-s", device_id,281 "shell", "ls", "-d", file_name])282 if str(output).rstrip() == file_name:283 return True284 return False285 def remove_device_root(self, error_level='error'):286 device_root = self.query_device_root()287 device_id = self.query_device_id()288 if device_root is None:289 self.add_device_flag(DEVICE_UNREACHABLE)290 self.fatal("Can't connect to device!")291 adb = self.query_exe('adb')292 if self.query_device_file_exists(device_root):293 self.info("Removing device root %s." % device_root)294 self.run_command([adb, "-s", device_id, "shell", "rm",295 "-r", device_root], error_list=ADBErrorList)296 if self.query_device_file_exists(device_root):297 self.add_device_flag(DEVICE_CANT_REMOVE_DEVROOT)298 self.log("Unable to remove device root!", level=error_level)299 return False300 return True301 def install_app(self, file_path):302 c = self.config303 device_id = self.query_device_id()304 adb = self.query_exe('adb')305 if self._log_level_at_least(DEBUG):306 self.run_command([adb, "-s", device_id, "shell", "ps"],307 error_list=ADBErrorList)308 uptime = self.query_device_exe('uptime')309 self.run_command([adb, "-s", "shell", uptime],310 error_list=ADBErrorList)311 if not c['enable_automation']:312 # -s to install on sdcard? Needs to be config driven313 self.run_command([adb, "-s", device_id, "install", '-r',314 file_path],315 error_list=ADBErrorList)316 else:317 # A slow-booting device may not allow installs, temporarily.318 # Wait up to a few minutes if not immediately successful.319 # Note that "adb install" typically writes status messages320 # to stderr and the adb return code may not differentiate321 # successful installations from failures; instead we check322 # the command output.323 install_complete = False324 retries = 0325 while retries < 6:326 output = self.get_output_from_command([adb, "-s", device_id,327 "install", '-r',328 file_path],329 ignore_errors=True)330 if output and output.lower().find("success") >= 0:331 install_complete = True332 break333 self.warning("Failed to install %s" % file_path)334 time.sleep(30)335 retries = retries + 1336 if not install_complete:337 self.fatal("Failed to install %s!" % file_path)338 def uninstall_app(self, package_name, package_root="/data/data",339 error_level="error"):340 c = self.config341 device_id = self.query_device_id()342 self.info("Uninstalling %s..." % package_name)343 if self.query_device_file_exists('%s/%s' % (package_root, package_name)):344 adb = self.query_exe('adb')345 cmd = [adb, "-s", device_id, "uninstall"]346 if not c.get('enable_automation'):347 cmd.append("-k")348 cmd.append(package_name)349 status = self.run_command(cmd, error_list=ADBErrorList)350 # TODO is this the right error check?351 if status:352 self.log("Failed to uninstall %s!" % package_name,353 level=error_level)354 # Device-type-specific. {{{2355 def remove_etc_hosts(self, hosts_file="/system/etc/hosts"):356 c = self.config357 if c['device_type'] not in ("tegra250",):358 self.debug("No need to remove /etc/hosts on a non-Tegra250.")359 return360 device_id = self.query_device_id()361 if self.query_device_file_exists(hosts_file):362 self.info("Removing %s file." % hosts_file)363 adb = self.query_exe('adb')364 self.run_command([adb, "-s", device_id, "shell",365 "mount", "-o", "remount,rw", "-t", "yaffs2",366 "/dev/block/mtdblock3", "/system"],367 error_list=ADBErrorList)368 self.run_command([adb, "-s", device_id, "shell", "rm",369 hosts_file])370 if self.query_device_file_exists(hosts_file):371 self.add_device_flag(DEVICE_CANT_REMOVE_ETC_HOSTS)372 self.fatal("Unable to remove %s!" % hosts_file)373 else:374 self.debug("%s file doesn't exist; skipping." % hosts_file)375# SUTDeviceHandler {{{1376class SUTDeviceHandler(BaseDeviceHandler):377 def __init__(self, **kwargs):378 super(SUTDeviceHandler, self).__init__(**kwargs)379 self.devicemanager = None380 self.default_port = 20701381 self.default_heartbeat_port = 20700382 self.DMError = None383 def query_devicemanager(self):384 if self.devicemanager:385 return self.devicemanager386 c = self.config387 site_packages_path = self.script_obj.query_python_site_packages_path()388 dm_path = os.path.join(site_packages_path, 'mozdevice')389 sys.path.append(dm_path)390 try:391 from devicemanagerSUT import DeviceManagerSUT392 from devicemanagerSUT import DMError393 self.DMError = DMError394 self.devicemanager = DeviceManagerSUT(c['device_ip'])395 # TODO configurable?396 self.devicemanager.debug = c.get('devicemanager_debug_level', 0)397 except ImportError, e:398 self.fatal("Can't import DeviceManagerSUT! %s\nDid you check out talos?" % str(e))399 return self.devicemanager400 # maintenance {{{2401 def ping_device(self):402 #TODO writeme403 pass404 def check_device(self):405 self.info("Checking for device root to verify the device is alive.")406 dev_root = self.query_device_root(strict=True)407 if not dev_root:408 self.add_device_flag(DEVICE_UNREACHABLE)409 self.fatal("Can't get dev_root from devicemanager; is the device up?")410 self.info("Found a dev_root of %s." % str(dev_root))411 def wait_for_device(self, interval=60, max_attempts=20):412 self.info("Waiting for device to come back...")413 time.sleep(interval)414 success = False415 attempts = 0416 while attempts <= max_attempts:417 attempts += 1418 self.info("Try %d" % attempts)419 if self.query_device_root() is not None:420 success = True421 break422 time.sleep(interval)423 if not success:424 self.add_device_flag(DEVICE_UNREACHABLE)425 self.fatal("Waiting for tegra timed out.")426 else:427 self.info("Device came back.")428 def cleanup_device(self, reboot=False):429 c = self.config430 dev_root = self.query_device_root()431 dm = self.query_devicemanager()432 if dm.dirExists(dev_root):433 self.info("Removing dev_root %s..." % dev_root)434 try:435 dm.removeDir(dev_root)436 except self.DMError:437 self.add_device_flag(DEVICE_CANT_REMOVE_DEVROOT)438 self.fatal("Can't remove dev_root!")439 if c.get("enable_automation"):440 self.remove_etc_hosts()441 # TODO I need to abstract this uninstall as we'll need to clean442 # multiple packages off devices.443 if c.get("device_package_name"):444 if dm.dirExists('/data/data/%s' % c['device_package_name']):445 self.info("Uninstalling %s..." % c['device_package_name'])446 dm.uninstallAppAndReboot(c['device_package_name'])447 self.wait_for_device()448 elif reboot:449 self.reboot_device()450 # device calls {{{2451 def query_device_root(self, strict=False):452 c = self.config453 dm = self.query_devicemanager()454 dev_root = dm.getDeviceRoot()455 if strict and c.get('enable_automation'):456 if not str(dev_root).startswith("/mnt/sdcard"):457 self.add_device_flag(DEVICE_MISSING_SDCARD)458 self.fatal("dev_root from devicemanager [%s] is not correct!" %459 str(dev_root))460 if not dev_root or dev_root == "/tests":461 return None462 return dev_root463 def query_device_time(self):464 dm = self.query_devicemanager()465 timestamp = int(dm.getCurrentTime()) # epoch time in milliseconds466 dt = datetime.datetime.utcfromtimestamp(timestamp / 1000)467 self.info("Current device time is %s" % dt.strftime('%Y/%m/%d %H:%M:%S'))468 return dt469 def set_device_time(self):470 dm = self.query_devicemanager()471 s = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')472 self.info("Setting device time to %s" % s)473 try:474 dm.sendCMD(['settime %s' % s])475 return True476 except self.DMError, e:477 self.add_device_flag(DEVICE_CANT_SET_TIME)478 self.fatal("Exception while setting device time: %s" % str(e))479 def install_app(self, file_path):480 dev_root = self.query_device_root(strict=True)481 if not dev_root:482 self.add_device_flag(DEVICE_UNREACHABLE)483 # TODO wait_for_device?484 self.fatal("dev_root %s not correct!" % str(dev_root))485 dm = self.query_devicemanager()486 c = self.config487 if c.get('enable_automation'):488 self.query_device_time()489 self.set_device_time()490 self.query_device_time()491 dm.getInfo('process')492 dm.getInfo('memory')493 dm.getInfo('uptime')494 # This target needs to not use os.path.join due to differences with win495 # Paths vs. unix paths.496 target = "/".join([dev_root, os.path.basename(file_path)])497 self.info("Installing %s on device..." % file_path)498 dm.pushFile(file_path, target)499 # TODO screen resolution500 # TODO do something with status?501 try:502 dm.installApp(target)503 self.info('-' * 42)504 self.info("Sleeping for 90 seconds...")505 time.sleep(90)506 self.info('installApp(%s) done - gathering debug info' % target)507 try:508 self.info(repr(dm.getInfo('process')))509 self.info(repr(dm.getInfo('memory')))510 self.info(repr(dm.getInfo('uptime')))511 self.info(repr(dm.sendCMD(['exec su -c "logcat -d -v time *:W"'])))512 except Exception, e:513 self.info("Exception hit while trying to run logcat: %s" % str(e))514 self.fatal("Remote Device Error: can't run logcat")515 except self.DMError:516 self.fatal("Remote Device Error: installApp() call failed - exiting")517 def reboot_device(self):518 dm = self.query_devicemanager()519 # logcat?520 self.info("Rebooting device...")521 try:522 dm.reboot()523 except self.DMError:524 self.add_device_flag(DEVICE_NOT_REBOOTED)525 self.fatal("Can't reboot device!")526 self.wait_for_device()527 dm.getInfo('uptime')528 # device type specific {{{2529 def remove_etc_hosts(self, hosts_file="/system/etc/hosts"):530 c = self.config531 # TODO figure this out532 if c['device_type'] not in ("tegra250",) or True:533 self.debug("No need to remove /etc/hosts on a non-Tegra250.")534 return535 dm = self.query_devicemanager()536 if dm.fileExists(hosts_file):537 self.info("Removing %s file." % hosts_file)538 try:539 dm.sendCMD(['exec mount -o remount,rw -t yaffs2 /dev/block/mtdblock3 /system'])540 dm.sendCMD(['exec rm %s' % hosts_file])541 except self.DMError:542 self.add_device_flag(DEVICE_CANT_REMOVE_ETC_HOSTS)543 self.fatal("Unable to remove %s!" % hosts_file)544 if dm.fileExists(hosts_file):545 self.add_device_flag(DEVICE_CANT_REMOVE_ETC_HOSTS)546 self.fatal("Unable to remove %s!" % hosts_file)547 else:548 self.debug("%s file doesn't exist; skipping." % hosts_file)549# SUTDeviceMozdeviceMixin {{{1550class SUTDeviceMozdeviceMixin(SUTDeviceHandler):551 '''552 This SUT device manager class makes calls through mozdevice (from mozbase) [1]553 directly rather than calling SUT tools.554 [1] https://github.com/mozilla/mozbase/blob/master/mozdevice/mozdevice/devicemanagerSUT.py555 '''556 dm = None557 def query_devicemanager(self):558 if self.dm:559 return self.dm560 sys.path.append(self.query_python_site_packages_path())561 from mozdevice.devicemanagerSUT import DeviceManagerSUT562 self.info("Connecting to: %s" % self.mozpool_device)563 self.dm = DeviceManagerSUT(self.mozpool_device)564 # No need for 300 second SUT socket timeouts here565 self.dm.default_timeout = 30566 return self.dm567 def query_file(self, filename):568 dm = self.query_devicemanager()569 if not dm.fileExists(filename):570 raise Exception("Expected file (%s) not found" % filename)571 file_contents = dm.pullFile(filename)572 if file_contents is None:573 raise Exception("Unable to read file (%s)" % filename)574 return file_contents575 def set_device_epoch_time(self, timestamp=int(time.time())):576 dm = self.query_devicemanager()577 dm._runCmds([{'cmd': 'setutime %s' % timestamp}])578 return dm._runCmds([{'cmd': 'clok'}])579 def get_logcat(self):580 dm = self.query_devicemanager()581 return dm.getLogcat()582# DeviceMixin {{{1583DEVICE_PROTOCOL_DICT = {584 'adb': ADBDeviceHandler,585 'sut': SUTDeviceHandler,586}587device_config_options = [[588 ["--device-ip"],589 {"action": "store",590 "dest": "device_ip",591 "help": "Specify the IP address of the device."592 }593], [594 ["--device-port"],595 {"action": "store",596 "dest": "device_port",597 "help": "Specify the IP port of the device."598 }599], [600 ["--device-heartbeat-port"],601 {"action": "store",602 "dest": "device_heartbeat_port",603 "help": "Specify the heartbeat port of the SUT device."604 }605], [606 ["--device-protocol"],607 {"action": "store",608 "type": "choice",609 "dest": "device_protocol",610 "choices": DEVICE_PROTOCOL_DICT.keys(),611 "help": "Specify the device communication protocol."612 }613], [614 ["--device-type"],615 # A bit useless atm, but we can add new device types as we add support616 # for them.617 {"action": "store",618 "type": "choice",619 "choices": ["non-tegra", "tegra250"],620 "default": "non-tegra",621 "dest": "device_type",622 "help": "Specify the device type."623 }624], [625 ["--devicemanager-path"],626 {"action": "store",627 "dest": "devicemanager_path",628 "help": "Specify the parent dir of devicemanagerSUT.py."629 }630]]631class DeviceMixin(object):632 '''BaseScript mixin, designed to interface with the device.633 '''634 device_handler = None635 device_root = None636 def query_device_handler(self):637 if self.device_handler:638 return self.device_handler639 c = self.config640 device_protocol = c.get('device_protocol')641 device_class = DEVICE_PROTOCOL_DICT.get(device_protocol)642 if not device_class:643 self.fatal("Unknown device_protocol %s; set via --device-protocol!" % str(device_protocol))644 self.device_handler = device_class(645 log_obj=self.log_obj,646 config=self.config,647 script_obj=self,648 )649 return self.device_handler650 def check_device(self):651 dh = self.query_device_handler()652 return dh.check_device()653 def cleanup_device(self, **kwargs):654 dh = self.query_device_handler()655 return dh.cleanup_device(**kwargs)656 def install_app(self):657 dh = self.query_device_handler()658 return dh.install_app(file_path=self.installer_path)659 def reboot_device(self):660 dh = self.query_device_handler()...

Full Screen

Full Screen

test_accounts_device_registration.js

Source:test_accounts_device_registration.js Github

copy

Full Screen

...100 },101 DEVICE_REGISTRATION_VERSION102 });103}104add_task(function* test_updateDeviceRegistration_with_new_device() {105 const deviceName = "foo";106 const deviceType = "bar";107 const credentials = getTestUser("baz");108 delete credentials.deviceId;109 const fxa = new MockFxAccounts({ name: deviceName });110 yield fxa.internal.setSignedInUser(credentials);111 const spy = {112 registerDevice: { count: 0, args: [] },113 updateDevice: { count: 0, args: [] },114 getDeviceList: { count: 0, args: [] }115 };116 const client = fxa.internal.fxAccountsClient;117 client.registerDevice = function () {118 spy.registerDevice.count += 1;119 spy.registerDevice.args.push(arguments);120 return Promise.resolve({121 id: "newly-generated device id",122 createdAt: Date.now(),123 name: deviceName,124 type: deviceType125 });126 };127 client.updateDevice = function () {128 spy.updateDevice.count += 1;129 spy.updateDevice.args.push(arguments);130 return Promise.resolve({});131 };132 client.getDeviceList = function () {133 spy.getDeviceList.count += 1;134 spy.getDeviceList.args.push(arguments);135 return Promise.resolve([]);136 };137 const result = yield fxa.updateDeviceRegistration();138 do_check_eq(result, "newly-generated device id");139 do_check_eq(spy.updateDevice.count, 0);140 do_check_eq(spy.getDeviceList.count, 0);141 do_check_eq(spy.registerDevice.count, 1);142 do_check_eq(spy.registerDevice.args[0].length, 4);143 do_check_eq(spy.registerDevice.args[0][0], credentials.sessionToken);144 do_check_eq(spy.registerDevice.args[0][1], deviceName);145 do_check_eq(spy.registerDevice.args[0][2], "desktop");146 do_check_eq(spy.registerDevice.args[0][3].pushCallback, "http://mochi.test:8888");147 do_check_eq(spy.registerDevice.args[0][3].pushPublicKey, BOGUS_PUBLICKEY);148 do_check_eq(spy.registerDevice.args[0][3].pushAuthKey, BOGUS_AUTHKEY);149 const state = fxa.internal.currentAccountState;150 const data = yield state.getUserAccountData();151 do_check_eq(data.deviceId, "newly-generated device id");152 do_check_eq(data.deviceRegistrationVersion, DEVICE_REGISTRATION_VERSION);153});154add_task(function* test_updateDeviceRegistration_with_existing_device() {155 const deviceName = "phil's device";156 const deviceType = "desktop";157 const credentials = getTestUser("pb");158 const fxa = new MockFxAccounts({ name: deviceName });159 yield fxa.internal.setSignedInUser(credentials);160 const spy = {161 registerDevice: { count: 0, args: [] },162 updateDevice: { count: 0, args: [] },163 getDeviceList: { count: 0, args: [] }164 };165 const client = fxa.internal.fxAccountsClient;166 client.registerDevice = function () {167 spy.registerDevice.count += 1;168 spy.registerDevice.args.push(arguments);...

Full Screen

Full Screen

device.test.js

Source:device.test.js Github

copy

Full Screen

1/* eslint-env mocha */2const assert = require('assert');3const Device = require('../src/device');4const FileInfo = require('../src/file-info');5describe('Device', () => {6 it('scanimage-a1.txt', () => {7 const file = FileInfo.create('test/resource/scanimage-a1.txt');8 const device = Device.from(file.toText());9 assert.strictEqual(device.id, 'plustek:libusb:001:008');10 assert.deepStrictEqual(device.features['--mode'].options, ['Lineart', 'Gray', 'Color']);11 assert.strictEqual(device.features['--mode'].default, 'Color');12 assert.strictEqual(device.features['--source'], undefined);13 assert.deepStrictEqual(device.features['--resolution'].options, [50, 75, 150, 300, 600, 1200]);14 assert.strictEqual(device.features['--resolution'].default, 50);15 assert.strictEqual(device.features['-l'].limits[0], 0);16 assert.strictEqual(device.features['-l'].limits[1], 215);17 assert.strictEqual(device.features['-l'].default, 0);18 assert.strictEqual(device.features['-t'].limits[0], 0);19 assert.strictEqual(device.features['-t'].limits[1], 297);20 assert.strictEqual(device.features['-t'].default, 0);21 assert.strictEqual(device.features['-x'].limits[0], 0);22 assert.strictEqual(device.features['-x'].limits[1], 215);23 assert.strictEqual(device.features['-x'].default, 103);24 assert.strictEqual(device.features['-y'].limits[0], 0);25 assert.strictEqual(device.features['-y'].limits[1], 297);26 assert.strictEqual(device.features['-y'].default, 76.2);27 assert.strictEqual(device.features['--brightness'].limits[0], -100);28 assert.strictEqual(device.features['--brightness'].limits[1], 100);29 assert.strictEqual(device.features['--brightness'].interval, 1);30 assert.strictEqual(device.features['--brightness'].default, 0);31 assert.strictEqual(device.features['--contrast'].limits[0], -100);32 assert.strictEqual(device.features['--contrast'].limits[1], 100);33 assert.strictEqual(device.features['--contrast'].interval, 1);34 assert.strictEqual(device.features['--contrast'].default, 0);35 });36 it('scanimage-a2.txt', () => {37 const file = FileInfo.create('test/resource/scanimage-a2.txt');38 const device = Device.from(file.toText());39 assert.strictEqual(device.id, 'epson2:libusb:001:029');40 assert.deepStrictEqual(device.features['--mode'].options, ['Lineart', 'Gray', 'Color']);41 assert.strictEqual(device.features['--mode'].default, 'Lineart');42 assert.strictEqual(device.features['--source'], undefined);43 assert.deepStrictEqual(device.features['--resolution'].options, [75, 300, 600, 1200]);44 assert.strictEqual(device.features['--resolution'].default, 75);45 assert.strictEqual(device.features['-l'].limits[0], 0);46 assert.strictEqual(device.features['-l'].limits[1], 215.9);47 assert.strictEqual(device.features['-l'].default, 0);48 assert.strictEqual(device.features['-t'].limits[0], 0);49 assert.strictEqual(device.features['-t'].limits[1], 297.1);50 assert.strictEqual(device.features['-t'].default, 0);51 assert.strictEqual(device.features['-x'].limits[0], 0);52 assert.strictEqual(device.features['-x'].limits[1], 215.9);53 assert.strictEqual(device.features['-x'].default, 215.9);54 assert.strictEqual(device.features['-y'].limits[0], 0);55 assert.strictEqual(device.features['-y'].limits[1], 297.1);56 assert.strictEqual(device.features['-y'].default, 297.1);57 assert.strictEqual(device.features['--brightness'], undefined);58 assert.strictEqual(device.features['--contrast'], undefined);59 });60 it('scanimage-a3.txt', () => {61 const file = FileInfo.create('test/resource/scanimage-a3.txt');62 const device = Device.from(file.toText());63 assert.strictEqual(device.id, 'magic');64 assert.deepStrictEqual(device.features['--mode'].options, ['Lineart', 'Gray', '24bitColor']);65 assert.strictEqual(device.features['--mode'].default, '24bitColor');66 assert.strictEqual(device.features['--source'], undefined);67 assert.deepStrictEqual(device.features['--resolution'].options, [75, 300, 600, 1200]);68 assert.strictEqual(device.features['--resolution'].default, 75);69 assert.strictEqual(device.features['-l'].limits[0], 0);70 assert.strictEqual(device.features['-l'].limits[1], 215.9);71 assert.strictEqual(device.features['-t'].limits[0], 0);72 assert.strictEqual(device.features['-t'].limits[1], 297.1);73 assert.strictEqual(device.features['-x'].limits[0], 0);74 assert.strictEqual(device.features['-x'].limits[1], 215.9);75 assert.strictEqual(device.features['-y'].limits[0], 0);76 assert.strictEqual(device.features['-y'].limits[1], 297.1);77 assert.strictEqual(device.features['--brightness'].limits[0], -50);78 assert.strictEqual(device.features['--brightness'].limits[1], 50);79 assert.strictEqual(device.features['--brightness'].interval, 1);80 assert.strictEqual(device.features['--brightness'].default, 0);81 assert.strictEqual(device.features['--contrast'].limits[0], -50);82 assert.strictEqual(device.features['--contrast'].limits[1], 50);83 assert.strictEqual(device.features['--contrast'].interval, 10);84 assert.strictEqual(device.features['--contrast'].default, 0);85 });86 it('scanimage-a4.txt', () => {87 const file = FileInfo.create('test/resource/scanimage-a4.txt');88 const device = Device.from(file.toText());89 assert.strictEqual(device.id, 'net:192.168.1.4:xerox_mfp:libusb:001:003');90 assert.deepStrictEqual(device.features['--mode'].options, ['Lineart', 'Halftone', 'Gray', 'Color']);91 assert.strictEqual(device.features['--mode'].default, 'Color');92 assert.deepStrictEqual(device.features['--source'].options, ['Flatbed', 'ADF', 'Auto']);93 assert.strictEqual(device.features['--source'].default, 'Flatbed');94 assert.deepStrictEqual(device.features['--resolution'].options, [75, 100, 150, 200, 300, 600, 1200]);95 assert.strictEqual(device.features['--resolution'].default, 150);96 assert.strictEqual(device.features['-l'].limits[0], 0);97 assert.strictEqual(device.features['-l'].limits[1], 215.9);98 assert.strictEqual(device.features['-t'].limits[0], 0);99 assert.strictEqual(device.features['-t'].limits[1], 297.1);100 assert.strictEqual(device.features['-x'].limits[0], 0);101 assert.strictEqual(device.features['-x'].limits[1], 215.9);102 assert.strictEqual(device.features['-y'].limits[0], 0);103 assert.strictEqual(device.features['-y'].limits[1], 297.1);104 assert.strictEqual(device.features['--brightness'], undefined);105 assert.strictEqual(device.features['--contrast'], undefined);106 });107 it('scanimage-a5.txt', () => {108 const file = FileInfo.create('test/resource/scanimage-a5.txt');109 const device = Device.from(file.toText());110 assert.strictEqual(device.id, 'pixma:04A91766_004AE4');111 assert.deepStrictEqual(device.features['--mode'].options, ['Color', 'Gray', 'Lineart']);112 assert.strictEqual(device.features['--mode'].default, 'Color');113 assert.deepStrictEqual(device.features['--source'].options, ['Flatbed', 'Automatic Document Feeder']);114 assert.strictEqual(device.features['--source'].default, 'Flatbed');115 assert.deepStrictEqual(device.features['--resolution'].options, [75, 150, 300, 600, 1200]);116 assert.strictEqual(device.features['--resolution'].default, 75);117 assert.strictEqual(device.features['-l'].limits[0], 0);118 assert.strictEqual(device.features['-l'].limits[1], 216);119 assert.strictEqual(device.features['-t'].limits[0], 0);120 assert.strictEqual(device.features['-t'].limits[1], 355.6);121 assert.strictEqual(device.features['-x'].limits[0], 0);122 assert.strictEqual(device.features['-x'].limits[1], 216);123 assert.strictEqual(device.features['-y'].limits[0], 0);124 assert.strictEqual(device.features['-y'].limits[1], 355.6);125 assert.strictEqual(device.features['--brightness'], undefined);126 assert.strictEqual(device.features['--contrast'], undefined);127 });128 it('scanimage-a6.txt', () => {129 const file = FileInfo.create('test/resource/scanimage-a6.txt');130 const device = Device.from(file.toText());131 assert.strictEqual(device.id, 'brother4:bus9;dev1');132 assert.deepStrictEqual(device.features['--mode'].options, ['Black & White', 'Gray[Error Diffusion]', 'True Gray', '24bit Color[Fast]']);133 assert.strictEqual(device.features['--mode'].default, '24bit Color[Fast]');134 assert.deepStrictEqual(device.features['--source'].options, ['FlatBed', 'Automatic Document Feeder(left aligned)', 'Automatic Document Feeder(left aligned,Duplex)', 'Automatic Document Feeder(centrally aligned)', 'Automatic Document Feeder(centrally aligned,Duplex)']);135 assert.strictEqual(device.features['--source'].default, 'Automatic Document Feeder(left aligned)');136 assert.deepStrictEqual(device.features['--resolution'].options, [100, 150, 200, 300, 400, 600, 1200, 2400, 4800, 9600]);137 assert.strictEqual(device.features['--resolution'].default, 200);138 assert.strictEqual(device.features['-l'].limits[0], 0);139 assert.strictEqual(device.features['-l'].limits[1], 215.9);140 assert.strictEqual(device.features['-t'].limits[0], 0);141 assert.strictEqual(device.features['-t'].limits[1], 355.6);142 assert.strictEqual(device.features['-x'].limits[0], 0);143 assert.strictEqual(device.features['-x'].limits[1], 215.9);144 assert.strictEqual(device.features['-y'].limits[0], 0);145 assert.strictEqual(device.features['-y'].limits[1], 355.6);146 assert.strictEqual(device.features['--brightness'], undefined);147 assert.strictEqual(device.features['--contrast'], undefined);148 });149 it('scanimage-a8.txt', () => {150 const file = FileInfo.create('test/resource/scanimage-a8.txt');151 const device = Device.from(file.toText());152 assert.strictEqual(device.id, 'umax1220u:libusb:001:004');153 assert.deepStrictEqual(device.features['--resolution'].options, [75, 150, 300, 600]);154 assert.strictEqual(device.features['--resolution'].default, 75);155 assert.strictEqual(device.features['-l'].limits[0], 0);156 assert.strictEqual(device.features['-l'].limits[1], 228.6);157 assert.strictEqual(device.features['-l'].default, 0);158 assert.strictEqual(device.features['-t'].limits[0], 0);159 assert.strictEqual(device.features['-t'].limits[1], 298);160 assert.strictEqual(device.features['-t'].default, 0);161 assert.strictEqual(device.features['-x'].limits[0], 0);162 assert.strictEqual(device.features['-x'].limits[1], 228.6);163 assert.strictEqual(device.features['-x'].default, 228.6);164 assert.strictEqual(device.features['-y'].limits[0], 0);165 assert.strictEqual(device.features['-y'].limits[1], 298);166 assert.strictEqual(device.features['-y'].default, 298);167 });168 it('scanimage-a9.txt', () => {169 const file = FileInfo.create('test/resource/scanimage-a9.txt');170 const device = Device.from(file.toText());171 assert.strictEqual(device.id, 'utsushi:esci:usb:/sys/devices/platform/soc/20980000.usb/usb1/1-1/1-1.2/1-1.2:1.0');172 assert.deepStrictEqual(device.features['--mode'].options, ['Monochrome', 'Grayscale', 'Color']);173 assert.strictEqual(device.features['--mode'].default, 'Color');174 assert.strictEqual(device.features['--source'], undefined);175 assert.deepStrictEqual(device.features['--resolution'].options, [50, 75, 150, 300, 600, 1200]);176 assert.strictEqual(device.features['--resolution'].default, 75);177 assert.strictEqual(device.features['-l'].limits[0], 0);178 assert.strictEqual(device.features['-l'].limits[1], 215.9);179 assert.strictEqual(device.features['-l'].default, 0);180 assert.strictEqual(device.features['-t'].limits[0], 0);181 assert.strictEqual(device.features['-t'].limits[1], 297.1);182 assert.strictEqual(device.features['-t'].default, 0);183 assert.strictEqual(device.features['-x'].limits[0], 0);184 assert.strictEqual(device.features['-x'].limits[1], 215.9);185 assert.strictEqual(device.features['-x'].default, 215.9);186 assert.strictEqual(device.features['-y'].limits[0], 0);187 assert.strictEqual(device.features['-y'].limits[1], 297.1);188 assert.strictEqual(device.features['-y'].default, 297.1);189 });...

Full Screen

Full Screen

device.service.ts

Source:device.service.ts Github

copy

Full Screen

1///2/// Copyright © 2016-2022 The Thingsboard Authors3///4/// Licensed under the Apache License, Version 2.0 (the "License");5/// you may not use this file except in compliance with the License.6/// You may obtain a copy of the License at7///8/// http://www.apache.org/licenses/LICENSE-2.09///10/// Unless required by applicable law or agreed to in writing, software11/// distributed under the License is distributed on an "AS IS" BASIS,12/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13/// See the License for the specific language governing permissions and14/// limitations under the License.15///16import { Injectable } from '@angular/core';17import { defaultHttpOptionsFromConfig, RequestConfig } from './http-utils';18import { Observable, ReplaySubject } from 'rxjs';19import { HttpClient } from '@angular/common/http';20import { PageLink } from '@shared/models/page/page-link';21import { PageData } from '@shared/models/page/page-data';22import {23 ClaimRequest,24 ClaimResult,25 Device,26 DeviceCredentials,27 DeviceInfo,28 DeviceSearchQuery29} from '@app/shared/models/device.models';30import { EntitySubtype } from '@app/shared/models/entity-type.models';31import { AuthService } from '@core/auth/auth.service';32import { BulkImportRequest, BulkImportResult } from '@home/components/import-export/import-export.models';33import { PersistentRpc, RpcStatus } from '@shared/models/rpc.models';34@Injectable({35 providedIn: 'root'36})37export class DeviceService {38 constructor(39 private http: HttpClient40 ) { }41 public getTenantDeviceInfos(pageLink: PageLink, type: string = '',42 config?: RequestConfig): Observable<PageData<DeviceInfo>> {43 return this.http.get<PageData<DeviceInfo>>(`/api/tenant/deviceInfos${pageLink.toQuery()}&type=${type}`,44 defaultHttpOptionsFromConfig(config));45 }46 public getTenantDeviceInfosByDeviceProfileId(pageLink: PageLink, deviceProfileId: string = '',47 config?: RequestConfig): Observable<PageData<DeviceInfo>> {48 return this.http.get<PageData<DeviceInfo>>(`/api/tenant/deviceInfos${pageLink.toQuery()}&deviceProfileId=${deviceProfileId}`,49 defaultHttpOptionsFromConfig(config));50 }51 public getCustomerDeviceInfos(customerId: string, pageLink: PageLink, type: string = '',52 config?: RequestConfig): Observable<PageData<DeviceInfo>> {53 return this.http.get<PageData<DeviceInfo>>(`/api/customer/${customerId}/deviceInfos${pageLink.toQuery()}&type=${type}`,54 defaultHttpOptionsFromConfig(config));55 }56 public getCustomerDeviceInfosByDeviceProfileId(customerId: string, pageLink: PageLink, deviceProfileId: string = '',57 config?: RequestConfig): Observable<PageData<DeviceInfo>> {58 return this.http.get<PageData<DeviceInfo>>(`/api/customer/${customerId}/deviceInfos${pageLink.toQuery()}&deviceProfileId=${deviceProfileId}`,59 defaultHttpOptionsFromConfig(config));60 }61 public getDevice(deviceId: string, config?: RequestConfig): Observable<Device> {62 return this.http.get<Device>(`/api/device/${deviceId}`, defaultHttpOptionsFromConfig(config));63 }64 public getDevices(deviceIds: Array<string>, config?: RequestConfig): Observable<Array<Device>> {65 return this.http.get<Array<Device>>(`/api/devices?deviceIds=${deviceIds.join(',')}`, defaultHttpOptionsFromConfig(config));66 }67 public getDeviceInfo(deviceId: string, config?: RequestConfig): Observable<DeviceInfo> {68 return this.http.get<DeviceInfo>(`/api/device/info/${deviceId}`, defaultHttpOptionsFromConfig(config));69 }70 public saveDevice(device: Device, config?: RequestConfig): Observable<Device> {71 return this.http.post<Device>('/api/device', device, defaultHttpOptionsFromConfig(config));72 }73 public deleteDevice(deviceId: string, config?: RequestConfig) {74 return this.http.delete(`/api/device/${deviceId}`, defaultHttpOptionsFromConfig(config));75 }76 public getDeviceTypes(config?: RequestConfig): Observable<Array<EntitySubtype>> {77 return this.http.get<Array<EntitySubtype>>('/api/device/types', defaultHttpOptionsFromConfig(config));78 }79 public getDeviceCredentials(deviceId: string, sync: boolean = false, config?: RequestConfig): Observable<DeviceCredentials> {80 const url = `/api/device/${deviceId}/credentials`;81 if (sync) {82 const responseSubject = new ReplaySubject<DeviceCredentials>();83 const request = new XMLHttpRequest();84 request.open('GET', url, false);85 request.setRequestHeader('Accept', 'application/json, text/plain, */*');86 const jwtToken = AuthService.getJwtToken();87 if (jwtToken) {88 request.setRequestHeader('X-Authorization', 'Bearer ' + jwtToken);89 }90 request.send(null);91 if (request.status === 200) {92 const credentials = JSON.parse(request.responseText) as DeviceCredentials;93 responseSubject.next(credentials);94 } else {95 responseSubject.error(null);96 }97 return responseSubject.asObservable();98 } else {99 return this.http.get<DeviceCredentials>(url, defaultHttpOptionsFromConfig(config));100 }101 }102 public saveDeviceCredentials(deviceCredentials: DeviceCredentials, config?: RequestConfig): Observable<DeviceCredentials> {103 return this.http.post<DeviceCredentials>('/api/device/credentials', deviceCredentials, defaultHttpOptionsFromConfig(config));104 }105 public makeDevicePublic(deviceId: string, config?: RequestConfig): Observable<Device> {106 return this.http.post<Device>(`/api/customer/public/device/${deviceId}`, null, defaultHttpOptionsFromConfig(config));107 }108 public assignDeviceToCustomer(customerId: string, deviceId: string,109 config?: RequestConfig): Observable<Device> {110 return this.http.post<Device>(`/api/customer/${customerId}/device/${deviceId}`, null, defaultHttpOptionsFromConfig(config));111 }112 public unassignDeviceFromCustomer(deviceId: string, config?: RequestConfig) {113 return this.http.delete(`/api/customer/device/${deviceId}`, defaultHttpOptionsFromConfig(config));114 }115 public sendOneWayRpcCommand(deviceId: string, requestBody: any, config?: RequestConfig): Observable<any> {116 return this.http.post<Device>(`/api/rpc/oneway/${deviceId}`, requestBody, defaultHttpOptionsFromConfig(config));117 }118 public sendTwoWayRpcCommand(deviceId: string, requestBody: any, config?: RequestConfig): Observable<any> {119 return this.http.post<Device>(`/api/rpc/twoway/${deviceId}`, requestBody, defaultHttpOptionsFromConfig(config));120 }121 public getPersistedRpc(rpcId: string, fullResponse = false, config?: RequestConfig): Observable<PersistentRpc> {122 return this.http.get<PersistentRpc>(`/api/rpc/persistent/${rpcId}`, defaultHttpOptionsFromConfig(config));123 }124 public deletePersistedRpc(rpcId: string, config?: RequestConfig) {125 return this.http.delete<PersistentRpc>(`/api/rpc/persistent/${rpcId}`, defaultHttpOptionsFromConfig(config));126 }127 public getPersistedRpcRequests(deviceId: string, pageLink: PageLink,128 rpcStatus?: RpcStatus, config?: RequestConfig): Observable<PageData<PersistentRpc>> {129 let url = `/api/rpc/persistent/device/${deviceId}${pageLink.toQuery()}`;130 if (rpcStatus && rpcStatus.length) {131 url += `&rpcStatus=${rpcStatus}`;132 }133 return this.http.get<PageData<PersistentRpc>>(url, defaultHttpOptionsFromConfig(config));134 }135 public findByQuery(query: DeviceSearchQuery,136 config?: RequestConfig): Observable<Array<Device>> {137 return this.http.post<Array<Device>>('/api/devices', query, defaultHttpOptionsFromConfig(config));138 }139 public findByName(deviceName: string, config?: RequestConfig): Observable<Device> {140 return this.http.get<Device>(`/api/tenant/devices?deviceName=${deviceName}`, defaultHttpOptionsFromConfig(config));141 }142 public claimDevice(deviceName: string, claimRequest: ClaimRequest,143 config?: RequestConfig): Observable<ClaimResult> {144 return this.http.post<ClaimResult>(`/api/customer/device/${deviceName}/claim`, claimRequest, defaultHttpOptionsFromConfig(config));145 }146 public unclaimDevice(deviceName: string, config?: RequestConfig) {147 return this.http.delete(`/api/customer/device/${deviceName}/claim`, defaultHttpOptionsFromConfig(config));148 }149 public assignDeviceToEdge(edgeId: string, deviceId: string,150 config?: RequestConfig): Observable<Device> {151 return this.http.post<Device>(`/api/edge/${edgeId}/device/${deviceId}`,152 defaultHttpOptionsFromConfig(config));153 }154 public unassignDeviceFromEdge(edgeId: string, deviceId: string,155 config?: RequestConfig) {156 return this.http.delete(`/api/edge/${edgeId}/device/${deviceId}`,157 defaultHttpOptionsFromConfig(config));158 }159 public getEdgeDevices(edgeId: string, pageLink: PageLink, type: string = '',160 config?: RequestConfig): Observable<PageData<DeviceInfo>> {161 return this.http.get<PageData<DeviceInfo>>(`/api/edge/${edgeId}/devices${pageLink.toQuery()}&type=${type}`,162 defaultHttpOptionsFromConfig(config));163 }164 public bulkImportDevices(entitiesData: BulkImportRequest, config?: RequestConfig): Observable<BulkImportResult> {165 return this.http.post<BulkImportResult>('/api/device/bulk_import', entitiesData, defaultHttpOptionsFromConfig(config));166 }...

Full Screen

Full Screen

device_spec_test.py

Source:device_spec_test.py Github

copy

Full Screen

1# Copyright 2019 The TensorFlow Authors. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14# ==============================================================================15"""Tests for tensorflow.python.framework.device_spec."""16from __future__ import absolute_import17from __future__ import division18from __future__ import print_function19from absl.testing import parameterized20from tensorflow.python.framework import device_spec21from tensorflow.python.framework import test_util22from tensorflow.python.platform import googletest23TEST_V1_AND_V2 = (("v1", device_spec.DeviceSpecV1),24 ("v2", device_spec.DeviceSpecV2))25class DeviceSpecTest(test_util.TensorFlowTestCase, parameterized.TestCase):26 @parameterized.named_parameters(*TEST_V1_AND_V2)27 def test_empty(self, device_spec_type):28 d = device_spec_type()29 self.assertEqual("", d.to_string())30 d.parse_from_string("")31 self.assertEqual("", d.to_string())32 @parameterized.named_parameters(*TEST_V1_AND_V2)33 def test_constructor(self, device_spec_type):34 d = device_spec_type(job="j", replica=0, task=1,35 device_type="CPU", device_index=2)36 self.assertEqual("j", d.job)37 self.assertEqual(0, d.replica)38 self.assertEqual(1, d.task)39 self.assertEqual("CPU", d.device_type)40 self.assertEqual(2, d.device_index)41 self.assertEqual("/job:j/replica:0/task:1/device:CPU:2", d.to_string())42 d = device_spec_type(device_type="GPU", device_index=0)43 self.assertEqual("/device:GPU:0", d.to_string())44 def testto_string_legacy(self):45 """DeviceSpecV1 allows direct mutation."""46 d = device_spec.DeviceSpecV1()47 d.job = "foo"48 self.assertEqual("/job:foo", d.to_string())49 d.task = 350 self.assertEqual("/job:foo/task:3", d.to_string())51 d.device_type = "CPU"52 d.device_index = 053 self.assertEqual("/job:foo/task:3/device:CPU:0", d.to_string())54 d.task = None55 d.replica = 1256 self.assertEqual("/job:foo/replica:12/device:CPU:0", d.to_string())57 d.device_type = "GPU"58 d.device_index = 259 self.assertEqual("/job:foo/replica:12/device:GPU:2", d.to_string())60 d.device_type = "CPU"61 d.device_index = 162 self.assertEqual("/job:foo/replica:12/device:CPU:1", d.to_string())63 d.device_type = None64 d.device_index = None65 self.assertEqual("/job:foo/replica:12", d.to_string())66 # Test wildcard67 d = device_spec.DeviceSpecV1(job="foo", replica=12, task=3,68 device_type="GPU")69 self.assertEqual("/job:foo/replica:12/task:3/device:GPU:*", d.to_string())70 @parameterized.named_parameters(*TEST_V1_AND_V2)71 def test_replace(self, device_spec_type):72 d = device_spec_type()73 d = d.replace(job="foo")74 self.assertEqual("/job:foo", d.to_string())75 d = d.replace(task=3)76 self.assertEqual("/job:foo/task:3", d.to_string())77 d = d.replace(device_type="CPU", device_index=0)78 self.assertEqual("/job:foo/task:3/device:CPU:0", d.to_string())79 d = d.replace(task=None, replica=12)80 self.assertEqual("/job:foo/replica:12/device:CPU:0", d.to_string())81 d = d.replace(device_type="GPU", device_index=2)82 self.assertEqual("/job:foo/replica:12/device:GPU:2", d.to_string())83 d = d.replace(device_type="CPU", device_index=1)84 self.assertEqual("/job:foo/replica:12/device:CPU:1", d.to_string())85 d = d.replace(device_type=None, device_index=None)86 self.assertEqual("/job:foo/replica:12", d.to_string())87 # Test wildcard88 d = device_spec.DeviceSpecV1(job="foo", replica=12, task=3,89 device_type="GPU")90 self.assertEqual("/job:foo/replica:12/task:3/device:GPU:*", d.to_string())91 @parameterized.named_parameters(*TEST_V1_AND_V2)92 def testto_string(self, device_spec_type):93 d = device_spec_type(job="foo")94 self.assertEqual("/job:foo", d.to_string())95 d = device_spec_type(job="foo", task=3)96 self.assertEqual("/job:foo/task:3", d.to_string())97 d = device_spec_type(job="foo", task=3, device_type="cpu", device_index=0)98 self.assertEqual("/job:foo/task:3/device:CPU:0", d.to_string())99 d = device_spec_type(job="foo", replica=12, device_type="cpu",100 device_index=0)101 self.assertEqual("/job:foo/replica:12/device:CPU:0", d.to_string())102 d = device_spec_type(job="foo", replica=12, device_type="gpu",103 device_index=2)104 self.assertEqual("/job:foo/replica:12/device:GPU:2", d.to_string())105 d = device_spec_type(job="foo", replica=12)106 self.assertEqual("/job:foo/replica:12", d.to_string())107 # Test wildcard108 d = device_spec_type(job="foo", replica=12, task=3, device_type="GPU")109 self.assertEqual("/job:foo/replica:12/task:3/device:GPU:*", d.to_string())110 def test_parse_legacy(self):111 d = device_spec.DeviceSpecV1()112 d.parse_from_string("/job:foo/replica:0")113 self.assertEqual("/job:foo/replica:0", d.to_string())114 d.parse_from_string("/replica:1/task:0/cpu:0")115 self.assertEqual("/replica:1/task:0/device:CPU:0", d.to_string())116 d.parse_from_string("/replica:1/task:0/device:CPU:0")117 self.assertEqual("/replica:1/task:0/device:CPU:0", d.to_string())118 d.parse_from_string("/job:muu/device:GPU:2")119 self.assertEqual("/job:muu/device:GPU:2", d.to_string())120 with self.assertRaisesRegexp(ValueError, "Cannot specify multiple"):121 d.parse_from_string("/job:muu/device:GPU:2/cpu:0")122 @parameterized.named_parameters(*TEST_V1_AND_V2)123 def test_to_from_string(self, device_spec_type):124 d = device_spec_type.from_string("/job:foo/replica:0")125 self.assertEqual("/job:foo/replica:0", d.to_string())126 self.assertEqual(0, d.replica)127 d = device_spec_type.from_string("/replica:1/task:0/cpu:0")128 self.assertEqual("/replica:1/task:0/device:CPU:0", d.to_string())129 self.assertAllEqual([1, 0, "CPU", 0],130 [d.replica, d.task, d.device_type, d.device_index])131 d = device_spec_type.from_string("/replica:1/task:0/device:CPU:0")132 self.assertEqual("/replica:1/task:0/device:CPU:0", d.to_string())133 self.assertAllEqual([1, 0, "CPU", 0],134 [d.replica, d.task, d.device_type, d.device_index])135 d = device_spec_type.from_string("/job:muu/device:GPU:2")136 self.assertEqual("/job:muu/device:GPU:2", d.to_string())137 self.assertAllEqual(["muu", "GPU", 2],138 [d.job, d.device_type, d.device_index])139 with self.assertRaisesRegexp(ValueError, "Cannot specify multiple"):140 d.parse_from_string("/job:muu/device:GPU:2/cpu:0")141 def test_merge_legacy(self):142 d = device_spec.DeviceSpecV1.from_string("/job:foo/replica:0")143 self.assertEqual("/job:foo/replica:0", d.to_string())144 d.merge_from(device_spec.DeviceSpecV1.from_string("/task:1/device:GPU:2"))145 self.assertEqual("/job:foo/replica:0/task:1/device:GPU:2", d.to_string())146 d = device_spec.DeviceSpecV1()147 d.merge_from(device_spec.DeviceSpecV1.from_string("/task:1/cpu:0"))148 self.assertEqual("/task:1/device:CPU:0", d.to_string())149 d.merge_from(device_spec.DeviceSpecV1.from_string("/job:boo/device:GPU:0"))150 self.assertEqual("/job:boo/task:1/device:GPU:0", d.to_string())151 d.merge_from(device_spec.DeviceSpecV1.from_string("/job:muu/cpu:2"))152 self.assertEqual("/job:muu/task:1/device:CPU:2", d.to_string())153 d.merge_from(device_spec.DeviceSpecV1.from_string(154 "/job:muu/device:MyFunnyDevice:2"))155 self.assertEqual("/job:muu/task:1/device:MyFunnyDevice:2", d.to_string())156 def test_merge_removed(self):157 with self.assertRaises(AttributeError):158 d = device_spec.DeviceSpecV2()159 d.merge_from(device_spec.DeviceSpecV2.from_string("/task:1/cpu:0"))160 @parameterized.named_parameters(*TEST_V1_AND_V2)161 def test_combine(self, device_spec_type):162 d = device_spec_type.from_string("/job:foo/replica:0")163 self.assertEqual("/job:foo/replica:0", d.to_string())164 d = d.make_merged_spec(165 device_spec_type.from_string("/task:1/device:GPU:2"))166 self.assertEqual("/job:foo/replica:0/task:1/device:GPU:2", d.to_string())167 d = device_spec_type()168 d = d.make_merged_spec(device_spec_type.from_string("/task:1/cpu:0"))169 self.assertEqual("/task:1/device:CPU:0", d.to_string())170 d = d.make_merged_spec(171 device_spec_type.from_string("/job:boo/device:GPU:0"))172 self.assertEqual("/job:boo/task:1/device:GPU:0", d.to_string())173 d = d.make_merged_spec(device_spec_type.from_string("/job:muu/cpu:2"))174 self.assertEqual("/job:muu/task:1/device:CPU:2", d.to_string())175 d = d.make_merged_spec(device_spec_type.from_string(176 "/job:muu/device:MyFunnyDevice:2"))177 self.assertEqual("/job:muu/task:1/device:MyFunnyDevice:2", d.to_string())178if __name__ == "__main__":...

Full Screen

Full Screen

device_setter_test.py

Source:device_setter_test.py Github

copy

Full Screen

...29 "worker": ["worker0:2222", "worker1:2222", "worker2:2222"]30 })31 @test_util.run_deprecated_v132 def testCPUOverride(self):33 with ops.device(34 device_setter.replica_device_setter(cluster=self._cluster_spec)):35 with ops.device("/cpu:0"):36 v = variables.Variable([1, 2])37 w = variables.Variable([2, 1])38 with ops.device("/cpu:0"):39 a = v + w40 self.assertDeviceEqual("/job:ps/task:0/cpu:0", v.device)41 self.assertDeviceEqual("/job:ps/task:0/cpu:0", v.initializer.device)42 self.assertDeviceEqual("/job:ps/task:1", w.device)43 self.assertDeviceEqual("/job:ps/task:1", w.initializer.device)44 self.assertDeviceEqual("/job:worker/cpu:0", a.device)45 @test_util.run_deprecated_v146 def testResource(self):47 with ops.device(48 device_setter.replica_device_setter(cluster=self._cluster_spec)):49 v = resource_variable_ops.ResourceVariable([1, 2])50 self.assertDeviceEqual("/job:ps/task:0", v.device)51 @test_util.run_deprecated_v152 def testPS2TasksWithClusterSpecClass(self):53 with ops.device(54 device_setter.replica_device_setter(cluster=self._cluster_spec)):55 v = variables.Variable([1, 2])56 w = variables.Variable([2, 1])57 a = v + w58 self.assertDeviceEqual("/job:ps/task:0", v.device)59 self.assertDeviceEqual("/job:ps/task:0", v.initializer.device)60 self.assertDeviceEqual("/job:ps/task:1", w.device)61 self.assertDeviceEqual("/job:ps/task:1", w.initializer.device)62 self.assertDeviceEqual("/job:worker", a.device)63 @test_util.run_deprecated_v164 def testPS2TasksPinVariableToJob(self):65 with ops.device(66 device_setter.replica_device_setter(cluster=self._cluster_spec)):67 v = variables.Variable([1, 2])68 with ops.device("/job:moon"):69 w = variables.Variable([2, 1])70 with ops.device("/job:ps"): # Explicit PS job will get task set.71 x = variables.Variable([0, 1])72 a = v + w + x73 self.assertDeviceEqual("/job:ps/task:0", v.device)74 self.assertDeviceEqual("/job:ps/task:0", v.initializer.device)75 self.assertDeviceEqual("/job:moon", w.device)76 self.assertDeviceEqual("/job:moon", w.initializer.device)77 self.assertDeviceEqual("/job:ps/task:1", x.device)78 self.assertDeviceEqual("/job:ps/task:1", x.initializer.device)79 self.assertDeviceEqual("/job:worker", a.device)80 @test_util.run_deprecated_v181 def testPS2TasksUseCpuForPS(self):82 with ops.device(83 device_setter.replica_device_setter(ps_tasks=1, ps_device="/cpu:0")):84 v = variables.Variable([1, 2])85 with ops.device("/job:moon"):86 w = variables.Variable([2, 1])87 a = v + w88 self.assertDeviceEqual("/cpu:0", v.device)89 self.assertDeviceEqual("/cpu:0", v.initializer.device)90 self.assertDeviceEqual("/job:moon/cpu:0", w.device)91 self.assertDeviceEqual("/job:moon/cpu:0", w.initializer.device)92 self.assertDeviceEqual("/job:worker", a.device)93 @test_util.run_deprecated_v194 def testPS2TasksNoMerging(self):95 with ops.device(96 device_setter.replica_device_setter(97 cluster=self._cluster_spec, merge_devices=False)):98 v = variables.Variable([1, 2])99 with ops.device("/job:ps"): # Won't assign task when merge_devices=False.100 w = variables.Variable([2, 1])101 a = v + w102 self.assertDeviceEqual("/job:ps/task:0", v.device)103 self.assertDeviceEqual("/job:ps/task:0", v.initializer.device)104 self.assertDeviceEqual("/job:ps", w.device)105 self.assertDeviceEqual("/job:ps", w.initializer.device)106 self.assertDeviceEqual("/job:worker", a.device)107 @test_util.run_deprecated_v1108 def testPS2TasksWithClusterSpecDict(self):109 with ops.device(110 device_setter.replica_device_setter(cluster=self._cluster_spec.as_dict(111 ))):112 v = variables.Variable([1, 2])113 w = variables.Variable([2, 1])114 a = v + w115 self.assertDeviceEqual("/job:ps/task:0", v.device)116 self.assertDeviceEqual("/job:ps/task:0", v.initializer.device)117 self.assertDeviceEqual("/job:ps/task:1", w.device)118 self.assertDeviceEqual("/job:ps/task:1", w.initializer.device)119 self.assertDeviceEqual("/job:worker", a.device)120 @test_util.run_deprecated_v1121 def testPS2TasksWithClusterDef(self):122 with ops.device(123 device_setter.replica_device_setter(124 cluster=self._cluster_spec.as_cluster_def())):125 v = variables.Variable([1, 2])126 w = variables.Variable([2, 1])127 a = v + w128 self.assertDeviceEqual("/job:ps/task:0", v.device)129 self.assertDeviceEqual("/job:ps/task:0", v.initializer.device)130 self.assertDeviceEqual("/job:ps/task:1", w.device)131 self.assertDeviceEqual("/job:ps/task:1", w.initializer.device)132 self.assertDeviceEqual("/job:worker", a.device)133 @test_util.run_deprecated_v1134 def testPS2TasksWithDevice(self):135 cluster_spec = server_lib.ClusterSpec({136 "sun": ["sun0:2222", "sun1:2222", "sun2:2222"],137 "moon": ["moon0:2222", "moon1:2222"]138 })139 with ops.device(140 device_setter.replica_device_setter(141 ps_device="/job:moon",142 worker_device="/job:sun",143 cluster=cluster_spec.as_cluster_def())):144 v = variables.Variable([1, 2])145 w = variables.Variable([2, 1])146 a = v + w147 self.assertDeviceEqual("/job:moon/task:0", v.device)148 self.assertDeviceEqual("/job:moon/task:0", v.initializer.device)149 self.assertDeviceEqual("/job:moon/task:1", w.device)150 self.assertDeviceEqual("/job:moon/task:1", w.initializer.device)151 self.assertDeviceEqual("/job:sun", a.device)152 @test_util.run_deprecated_v1153 def testPS2TasksWithCPUConstraint(self):154 cluster_spec = server_lib.ClusterSpec({155 "sun": ["sun0:2222", "sun1:2222", "sun2:2222"],156 "moon": ["moon0:2222", "moon1:2222"]157 })158 with ops.device(159 device_setter.replica_device_setter(160 ps_device="/job:moon/cpu:0",161 worker_device="/job:sun",162 cluster=cluster_spec.as_cluster_def())):163 v = variables.Variable([1, 2])164 w = variables.Variable([2, 1])165 a = v + w166 self.assertDeviceEqual("/job:moon/task:0/cpu:0", v.device)167 self.assertDeviceEqual("/job:moon/task:0/cpu:0", v.initializer.device)168 self.assertDeviceEqual("/job:moon/task:1/cpu:0", w.device)169 self.assertDeviceEqual("/job:moon/task:1/cpu:0", w.initializer.device)170 self.assertDeviceEqual("/job:sun", a.device)171if __name__ == "__main__":172 test.main()

Full Screen

Full Screen

devices.ts

Source:devices.ts Github

copy

Full Screen

1import { AudioDeviceInfo, VideoDeviceInfo, DeviceManager } from '@azure/communication-calling';2const SET_DEVICE_MANAGER = 'SET_DEVICE_MANAGER';3const SET_AUDIO_DEVICE_INFO = 'SET_AUDIO_DEVICE_INFO';4const SET_VIDEO_DEVICE_INFO = 'SET_VIDEO_DEVICE_INFO';5const SET_AUDIO_DEVICE_LIST = 'SET_AUDIO_DEVICE_LIST';6const SET_VIDEO_DEVICE_LIST = 'SET_VIDEO_DEVICE_LIST';7const SET_MICROPHONE_PERMISSION = 'SET_MICROPHONE_PERMISSION';8const SET_CAMERA_PERMISSION = 'SET_CAMERA_PERMISSION';9interface SetDeviceManagerAction {10 type: typeof SET_DEVICE_MANAGER;11 deviceManager: DeviceManager;12}13interface SetMicrophonePermission {14 type: typeof SET_MICROPHONE_PERMISSION;15 microphonePermission: string;16}17interface SetCameraPermission {18 type: typeof SET_CAMERA_PERMISSION;19 cameraPermission: string;20}21interface SetAudioDeviceAction {22 type: typeof SET_AUDIO_DEVICE_INFO;23 audioDeviceInfo: AudioDeviceInfo | undefined;24}25interface SetVideoDeviceAction {26 type: typeof SET_VIDEO_DEVICE_INFO;27 videoDeviceInfo: VideoDeviceInfo | undefined;28}29interface SetAudioDeviceListAction {30 type: typeof SET_AUDIO_DEVICE_LIST;31 audioDeviceList: AudioDeviceInfo[];32}33interface SetVideoDeviceListAction {34 type: typeof SET_VIDEO_DEVICE_LIST;35 videoDeviceList: VideoDeviceInfo[];36}37export const setDeviceManager = (deviceManager: DeviceManager): SetDeviceManagerAction => {38 return {39 type: SET_DEVICE_MANAGER,40 deviceManager41 };42};43export const setMicrophonePermission = (microphonePermission: string): SetMicrophonePermission => {44 return {45 type: SET_MICROPHONE_PERMISSION,46 microphonePermission47 };48};49export const setCameraPermission = (cameraPermission: string): SetCameraPermission => {50 return {51 type: SET_CAMERA_PERMISSION,52 cameraPermission53 };54};55export const setAudioDeviceInfo = (audioDeviceInfo: AudioDeviceInfo | undefined): SetAudioDeviceAction => {56 return {57 type: SET_AUDIO_DEVICE_INFO,58 audioDeviceInfo59 };60};61export const setVideoDeviceInfo = (videoDeviceInfo: VideoDeviceInfo | undefined): SetVideoDeviceAction => {62 return {63 type: SET_VIDEO_DEVICE_INFO,64 videoDeviceInfo65 };66};67export const setAudioDeviceList = (audioDeviceList: AudioDeviceInfo[]): SetAudioDeviceListAction => {68 return {69 type: SET_AUDIO_DEVICE_LIST,70 audioDeviceList71 };72};73export const setVideoDeviceList = (videoDeviceList: VideoDeviceInfo[]): SetVideoDeviceListAction => {74 return {75 type: SET_VIDEO_DEVICE_LIST,76 videoDeviceList77 };78};79export {80 SET_DEVICE_MANAGER,81 SET_AUDIO_DEVICE_INFO,82 SET_VIDEO_DEVICE_INFO,83 SET_VIDEO_DEVICE_LIST,84 SET_AUDIO_DEVICE_LIST,85 SET_CAMERA_PERMISSION,86 SET_MICROPHONE_PERMISSION87};88export type DeviceTypes =89 | SetDeviceManagerAction90 | SetAudioDeviceAction91 | SetVideoDeviceAction92 | SetMicrophonePermission93 | SetCameraPermission94 | SetAudioDeviceListAction...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var device = require('./device.js');2var device = require('./device.js');3var device = require('./device.js');4var device = require('./device.js');5var device = require('./device.js');6var device = require('./device.js');7var device = require('./device.js');8var device = require('./device.js');9var device = require('./device.js');10var device = require('./device.js');11var device = require('./device.js');12var device = require('./device.js');13var device = require('./device.js');14var device = require('./device.js');

Full Screen

Using AI Code Generation

copy

Full Screen

1var DeviceFarmer = require('devicefarmer-stf').DeviceFarmer;2deviceFarmer.device('serialNumber').then(function(device) {3 device.method('method', 'params').then(function(result) {4 console.log(result);5 });6});7var DeviceFarmer = require('devicefarmer-stf').DeviceFarmer;8deviceFarmer.device('serialNumber').then(function(device) {9 device.method('method', 'params').then(function(result) {10 console.log(result);11 });12});13var DeviceFarmer = require('devicefarmer-stf').DeviceFarmer;14deviceFarmer.device('serialNumber').then(function(device) {15 device.method('method', 'params').then(function(result) {16 console.log(result);17 });18});19var DeviceFarmer = require('devicefarmer-stf').DeviceFarmer;20deviceFarmer.device('serialNumber').then(function(device) {21 device.method('method', 'params').then(function(result) {22 console.log(result);23 });24});25var DeviceFarmer = require('devicefarmer-stf').DeviceFarmer;26deviceFarmer.device('serialNumber').then(function(device) {27 device.method('method', 'params').then(function(result) {28 console.log(result);29 });30});31var DeviceFarmer = require('devicefarmer-stf').DeviceFarmer;32deviceFarmer.device('serialNumber').then(function(device) {33 device.method('method', 'params').then(function

Full Screen

Using AI Code Generation

copy

Full Screen

1var Device = require('devicefarmer-stf-client');2var device = new Device({ serial: '0123456789ABCDEF' });3device.method('shell', 'input keyevent 82', function(err, data) {4 if (err) {5 console.log(err);6 } else {7 console.log(data);8 }9});

Full Screen

Using AI Code Generation

copy

Full Screen

1var device = require('devicefarmer-stf').device;2var d = new device();3d.method('getDevices', function(err, data) {4 if(err) {5 console.log(err);6 return;7 }8 console.log(data);9});10var device = require('devicefarmer-stf').device;11var d = new device();12d.method('getDevices', function(err, data) {13 if(err) {14 console.log(err);15 return;16 }17 console.log(data);18});19var device = require('devicefarmer-stf').device;20var d = new device();21d.method('getDevices', function(err, data) {22 if(err) {23 console.log(err);24 return;25 }26 console.log(data);27});28var device = require('devicefarmer-stf').device;29var d = new device();30d.method('getDevices', function(err, data) {31 if(err) {32 console.log(err);33 return;34 }35 console.log(data);36});37var device = require('devicefarmer-stf').device;38var d = new device();39d.method('getDevices', function(err, data) {40 if(err) {41 console.log(err);42 return;43 }44 console.log(data);45});46var device = require('devicefarmer-stf').device;47var d = new device();48d.method('getDevices', function(err, data) {49 if(err) {50 console.log(err);51 return;52 }53 console.log(data);54});55var device = require('devicefarmer-stf').device;56var d = new device();57d.method('getDevices', function(err, data) {58 if(err) {59 console.log(err);60 return;61 }62 console.log(data);63});

Full Screen

Using AI Code Generation

copy

Full Screen

1const DeviceFarm = require('devicefarmer-stf').DeviceFarm;2DeviceFarm.getDevices().then(function(devices) {3 console.log(devices);4});5DeviceFarm.getDevices({manufacturer: 'Samsung', model: 'Galaxy S5'}).then(function(devices) {6 console.log(devices);7});8DeviceFarm.getDevices({manufacturer: 'Samsung', model: 'Galaxy S5'}).then(function(devices) {9 console.log(devices);10});11DeviceFarm.getDevices({manufacturer: 'Samsung', model: 'Galaxy S5'}).then(function(devices) {12 console.log(devices);13});14DeviceFarm.getDevices({manufacturer: 'Samsung', model: 'Galaxy S5'}).then(function(devices) {15 console.log(devices);16});17DeviceFarm.getDevices({manufacturer: 'Samsung', model: 'Galaxy S5'}).then(function(devices) {18 console.log(devices);19});20DeviceFarm.getDevices({manufacturer: 'Samsung', model: 'Galaxy S5'}).then(function(devices) {21 console.log(devices);22});23DeviceFarm.getDevices({manufacturer: 'Samsung', model: 'Galaxy S5'}).then(function(devices) {24 console.log(devices);25});26DeviceFarm.getDevices({manufacturer: 'Samsung', model: 'Galaxy S5'}).then(function(devices) {27 console.log(devices);28});29DeviceFarm.getDevices({manufacturer: 'Samsung', model: 'Galaxy S5'}).then(function(devices) {30 console.log(devices);31});32DeviceFarm.getDevices({manufacturer: 'Samsung', model: 'Galaxy S5'}).then(function(devices) {33 console.log(devices);34});35DeviceFarm.getDevices({manufacturer: 'Samsung', model: 'Galaxy S5'}).then(function(devices) {36 console.log(devices);37});

Full Screen

Using AI Code Generation

copy

Full Screen

1var df = require('devicefarmer-stf-client');2var client = new df.Client();3client.device('serialnumber').method('methodname', 'parameter').then(function (result) {4});5var df = require('devicefarmer-stf-client');6var client = new df.Client();7client.device('serialnumber').method('methodname', 'parameter').then(function (result) {8});9var df = require('devicefarmer-stf-client');10var client = new df.Client();11client.device('serialnumber').method('methodname', 'parameter').then(function (result) {12});13var df = require('devicefarmer-stf-client');14var client = new df.Client();15client.device('serialnumber').method('methodname', 'parameter').then(function (result) {16});17var df = require('devicefarmer-stf-client');18var client = new df.Client();19client.device('serialnumber').method('methodname', 'parameter').then(function (result) {20});21var df = require('devicefarmer-stf-client');22var client = new df.Client();23client.device('serialnumber').method('methodname', 'parameter').then(function (result) {24});25var df = require('devicefarmer-stf-client');26var client = new df.Client();27client.device('serialnumber').method('methodname', 'parameter').then(function (result) {28});29var df = require('devicefarmer-stf-client');30var client = new df.Client();

Full Screen

Using AI Code Generation

copy

Full Screen

1var device = require('devicefarmer-stf').device;2var device = new device();3device.useDevice('deviceID', 'appPackage', 'appActivity', 'appWaitActivity', function(err, result) {4 if (err) {5 console.log(err);6 } else {7 console.log(result);8 }9});10var device = require('devicefarmer-stf').device;11var device = new device();12device.useDevice('deviceID', 'appPackage', 'appActivity', 'appWaitActivity', function(err, result) {13 if (err) {14 console.log(err);15 } else {16 console.log(result);17 }18});19var device = require('devicefarmer-stf').device;20var device = new device();21device.useDevice('deviceID', 'appPackage', 'appActivity', 'appWaitActivity', function(err, result) {22 if (err) {23 console.log(err);24 } else {25 console.log(result);26 }27});28var device = require('devicefarmer-stf').device;29var device = new device();30device.useDevice('deviceID', 'appPackage', 'appActivity', 'appWaitActivity', function(err, result) {31 if (err) {32 console.log(err);33 } else {34 console.log(result);35 }36});37var device = require('devicefarmer-stf').device;38var device = new device();39device.useDevice('deviceID', 'appPackage', 'appActivity', 'appWaitActivity', function(err, result) {40 if (err) {41 console.log(err);42 } else {43 console.log(result);44 }45});46var device = require('devicefarmer-stf').device;47var device = new device();48device.useDevice('deviceID', 'appPackage', 'appActivity', 'appWaitActivity', function(err, result) {49 if (err) {50 console.log(err);51 } else {

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run devicefarmer-stf automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful