File: usb_transport.py

package info (click to toggle)
python-adb-shell 0.4.4-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 760 kB
  • sloc: python: 3,860; makefile: 191; sh: 124
file content (647 lines) | stat: -rw-r--r-- 20,258 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
# Copyright (c) 2021 Jeff Irion and contributors
#
# This file is part of the adb-shell package.  It incorporates work
# covered by the following license notice:
#
#
#   Copyright 2014 Google Inc. All rights reserved.
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

"""A class for creating a USB connection with the device and sending and receiving data.

.. warning::

   USB support is an experimental feature.


* :func:`get_interface`
* :func:`interface_matcher`
* :class:`UsbTransport`

    * :meth:`UsbTransport._find`
    * :meth:`UsbTransport._find_and_open`
    * :meth:`UsbTransport._find_devices`
    * :meth:`UsbTransport._find_first`
    * :meth:`UsbTransport._flush_buffers`
    * :meth:`UsbTransport._open`
    * :meth:`UsbTransport._port_path_matcher`
    * :meth:`UsbTransport._serial_matcher`
    * :meth:`UsbTransport._timeout`
    * :meth:`UsbTransport.bulk_read`
    * :meth:`UsbTransport.bulk_write`
    * :meth:`UsbTransport.close`
    * :meth:`UsbTransport.connect`
    * :attr:`UsbTransport.port_path`
    * :attr:`UsbTransport.serial_number`
    * :attr:`UsbTransport.usb_info`

"""


import logging
import platform
import re
import threading
import warnings
import weakref

import usb1

from .base_transport import BaseTransport

from .. import exceptions


#: Default timeout
DEFAULT_TIMEOUT_S = 10

SYSFS_PORT_SPLIT_RE = re.compile("[,/:.-]")

_LOGGER = logging.getLogger(__name__)

CLASS = usb1.CLASS_VENDOR_SPEC  # pylint: disable=no-member
SUBCLASS = 0x42
PROTOCOL = 0x01


def get_interface(setting):  # pragma: no cover
    """Get the class, subclass, and protocol for the given USB setting.

    Parameters
    ----------
    setting : TODO
        TODO

    Returns
    -------
    TODO
        TODO
    TODO
        TODO
    TODO
        TODO

    """
    return (setting.getClass(), setting.getSubClass(), setting.getProtocol())


def interface_matcher(clazz, subclass, protocol):   # pragma: no cover
    """Returns a matcher that returns the setting with the given interface.

    Parameters
    ----------
    clazz : TODO
        TODO
    subclass : TODO
        TODO
    protocol : TODO
        TODO

    Returns
    -------
    matcher : function
        TODO

    """
    interface = (clazz, subclass, protocol)

    def matcher(device):
        """TODO

        Parameters
        ----------
        device : TODO
            TODO

        Returns
        -------
        TODO, None
            TODO

        """
        for setting in device.iterSettings():
            if get_interface(setting) == interface:
                return setting
        return None

    return matcher


class UsbTransport(BaseTransport):   # pragma: no cover
    """USB communication object. Not thread-safe.

    Handles reading and writing over USB with the proper endpoints, exceptions,
    and interface claiming.

    Parameters
    ----------
    device : usb1.USBDevice
        libusb_device to connect to.
    setting : usb1.USBInterfaceSetting
        libusb setting with the correct endpoints to communicate with.
    usb_info : TODO, None
        String describing the usb path/serial/device, for debugging.
    default_transport_timeout_s : TODO, None
        Timeout in seconds for all I/O.

    Attributes
    ----------
    _default_transport_timeout_s : TODO, None
        Timeout in seconds for all I/O.
    _device : TODO
        libusb_device to connect to.
    _transport : TODO
        TODO
    _interface_number : TODO
        TODO
    _max_read_packet_len : TODO
        TODO
    _read_endpoint : TODO
        TODO
    _setting : TODO
        libusb setting with the correct endpoints to communicate with.
    _usb_info : TODO
        String describing the usb path/serial/device, for debugging.
    _write_endpoint : TODO, None
        TODO

    """
    # We maintain an idempotent `usb1` context object to ensure that device
    # objects we hand back to callers can be used while this class exists
    USB1_CTX = usb1.USBContext()
    USB1_CTX.open()

    _HANDLE_CACHE = weakref.WeakValueDictionary()
    _HANDLE_CACHE_LOCK = threading.Lock()

    def __init__(self, device, setting, usb_info=None, default_transport_timeout_s=None):
        self._setting = setting
        self._device = device
        self._transport = None

        self._interface_number = None
        self._read_endpoint = None
        self._write_endpoint = None

        self._usb_info = usb_info or ''
        self._default_transport_timeout_s = default_transport_timeout_s if default_transport_timeout_s is not None else DEFAULT_TIMEOUT_S
        self._max_read_packet_len = 0

    def close(self):
        """Close the USB connection.

        """
        if self._transport is None:
            return
        try:
            self._transport.releaseInterface(self._interface_number)
            self._transport.close()
        except usb1.USBError:
            _LOGGER.info('USBError while closing transport %s: ', self.usb_info, exc_info=True)
        finally:
            self._transport = None

    def connect(self, transport_timeout_s=None):
        """Create a USB connection to the device.

        Parameters
        ----------
        transport_timeout_s : float, None
            Set the timeout on the USB instance

        """
        read_endpoint = None
        write_endpoint = None

        for endpoint in self._setting.iterEndpoints():
            address = endpoint.getAddress()
            if address & usb1.ENDPOINT_DIR_MASK:  # pylint: disable=no-member
                read_endpoint = address
                # max_read_packet_len = endpoint.getMaxPacketSize()
            else:
                write_endpoint = address

        assert read_endpoint is not None
        assert write_endpoint is not None

        transport = self._device.open()
        iface_number = self._setting.getNumber()
        try:
            if (platform.system() != 'Windows' and transport.kernelDriverActive(iface_number)):
                transport.detachKernelDriver(iface_number)
        except usb1.USBErrorNotFound:  # pylint: disable=no-member
            warnings.warn('Kernel driver not found for interface: %s.', iface_number)

        # # When this object is deleted, make sure it's closed.
        # weakref.ref(self, self.close)

        self._transport = transport
        self._read_endpoint = read_endpoint
        self._write_endpoint = write_endpoint
        self._interface_number = iface_number

        self._transport.claimInterface(self._interface_number)

    def bulk_read(self, numbytes, transport_timeout_s=None):
        """Receive data from the USB device.

        Parameters
        ----------
        numbytes : int
            The maximum amount of data to be received
        transport_timeout_s : float, None
            When the timeout argument is omitted, ``select.select`` blocks until at least one file descriptor is ready. A time-out value of zero specifies a poll and never blocks.

        Returns
        -------
        bytes
            The received data

        Raises
        ------
        adb_shell.exceptions.UsbReadFailedError
            Could not receive data

        """
        if self._transport is None:
            raise exceptions.UsbReadFailedError('This transport has been closed, probably due to another being opened.', None)
        try:
            # python-libusb1 > 1.6 exposes bytearray()s now instead of bytes/str.
            # To support older and newer versions, we ensure everything's bytearray()
            # from here on out.
            return bytes(self._transport.bulkRead(self._read_endpoint, numbytes, timeout=self._timeout_ms(transport_timeout_s)))
        except usb1.USBError as e:
            raise exceptions.UsbReadFailedError('Could not receive data from %s (timeout %sms)' % (self.usb_info, self._timeout_ms(transport_timeout_s)), e)

    def bulk_write(self, data, transport_timeout_s=None):
        """Send data to the USB device.

        Parameters
        ----------
        data : bytes
            The data to be sent
        transport_timeout_s : float, None
            When the timeout argument is omitted, ``select.select`` blocks until at least one file descriptor is ready. A time-out value of zero specifies a poll and never blocks.

        Returns
        -------
        int
            The number of bytes sent

        Raises
        ------
        adb_shell.exceptions.UsbWriteFailedError
            This transport has been closed, probably due to another being opened
        adb_shell.exceptions.UsbWriteFailedError
            Could not send data

        """
        if self._transport is None:
            raise exceptions.UsbWriteFailedError('This transport has been closed, probably due to another being opened.', None)

        try:
            return self._transport.bulkWrite(self._write_endpoint, data, timeout=self._timeout_ms(transport_timeout_s))

        except usb1.USBError as e:
            raise exceptions.UsbWriteFailedError('Could not send data to %s (timeout %sms)' % (self.usb_info, self._timeout_ms(transport_timeout_s)), e)

    def _open(self):
        """Opens the USB device for this setting, and claims the interface.

        """
        # Make sure we close any previous transport open to this usb device.
        port_path = tuple(self.port_path)
        with self._HANDLE_CACHE_LOCK:
            old_transport = self._HANDLE_CACHE.get(port_path)
            if old_transport is not None:
                old_transport.Close()

        self._read_endpoint = None
        self._write_endpoint = None

        for endpoint in self._setting.iterEndpoints():
            address = endpoint.getAddress()
            if address & usb1.USB_ENDPOINT_DIR_MASK:  # pylint: disable=no-member
                self._read_endpoint = address
                self._max_read_packet_len = endpoint.getMaxPacketSize()
            else:
                self._write_endpoint = address

        assert self._read_endpoint is not None
        assert self._write_endpoint is not None

        transport = self._device.open()
        iface_number = self._setting.getNumber()
        try:
            if (platform.system() != 'Windows' and transport.kernelDriverActive(iface_number)):
                transport.detachKernelDriver(iface_number)
        except usb1.USBErrorNotFound:  # pylint: disable=no-member
            warnings.warn('Kernel driver not found for interface: %s.', iface_number)
        transport.claimInterface(iface_number)
        self._transport = transport
        self._interface_number = iface_number

        with self._HANDLE_CACHE_LOCK:
            self._HANDLE_CACHE[port_path] = self
        # When this object is deleted, make sure it's closed.
        weakref.ref(self, self.close)

    def _timeout_ms(self, transport_timeout_s):
        """TODO

        Returns
        -------
        TODO
            TODO

        """
        return int(transport_timeout_s * 1000 if transport_timeout_s is not None else self._default_transport_timeout_s * 1000)

    def _flush_buffers(self):
        """TODO

        Raises
        ------
        adb_shell.exceptions.UsbReadFailedError
            TODO

        """
        while True:
            try:
                self.bulk_read(self._max_read_packet_len, transport_timeout_s=10)
            except exceptions.UsbReadFailedError as e:
                if isinstance(e.usb_error, usb1.USBErrorTimeout):  # pylint: disable=no-member
                    break
                raise

    # ======================================================================= #
    #                                                                         #
    #                               Properties                                #
    #                                                                         #
    # ======================================================================= #
    @property
    def port_path(self):
        """TODO

        Returns
        -------
        TODO
            TODO

        """
        return [self._device.getBusNumber()] + self._device.getPortNumberList()

    @property
    def serial_number(self):
        """TODO

        Returns
        -------
        TODO
            TODO

        """
        return self._device.getSerialNumber()

    @property
    def usb_info(self):
        """TODO

        Returns
        -------
        TODO
            TODO

        """
        try:
            sn = self.serial_number
        except usb1.USBError:
            sn = ''
        if sn and sn != self._usb_info:
            return '%s %s' % (self._usb_info, sn)
        return self._usb_info

    # ======================================================================= #
    #                                                                         #
    #                                Matchers                                 #
    #                                                                         #
    # ======================================================================= #
    @classmethod
    def _port_path_matcher(cls, port_path):
        """Returns a device matcher for the given port path.

        Parameters
        ----------
        port_path : TODO
            TODO

        Returns
        -------
        function
            TODO

        """
        if isinstance(port_path, str):
            # Convert from sysfs path to port_path.
            port_path = [int(part) for part in SYSFS_PORT_SPLIT_RE.split(port_path)]
        return lambda device: device.port_path == port_path

    @classmethod
    def _serial_matcher(cls, serial):
        """Returns a device matcher for the given serial.

        Parameters
        ----------
        serial : TODO
            TODO

        Returns
        -------
        function
            TODO

        """
        return lambda device: device.serial_number == serial

    # ======================================================================= #
    #                                                                         #
    #                                 Finders                                 #
    #                                                                         #
    # ======================================================================= #
    @classmethod
    def _find(cls, setting_matcher, port_path=None, serial=None, default_transport_timeout_s=None):
        """Gets the first device that matches according to the keyword args.

        Parameters
        ----------
        setting_matcher : TODO
            TODO
        port_path : TODO, None
            TODO
        serial : TODO, None
            TODO
        default_transport_timeout_s : TODO, None
            TODO

        Returns
        -------
        TODO
            TODO

        """
        if port_path:
            device_matcher = cls._port_path_matcher(port_path)
            usb_info = port_path
        elif serial:
            device_matcher = cls._serial_matcher(serial)
            usb_info = serial
        else:
            device_matcher = None
            usb_info = 'first'
        return cls._find_first(setting_matcher, device_matcher, usb_info=usb_info, default_transport_timeout_s=default_transport_timeout_s)

    @classmethod
    def _find_and_open(cls, setting_matcher, port_path=None, serial=None, default_transport_timeout_s=None):
        """TODO

        Parameters
        ----------
        setting_matcher : TODO
            TODO
        port_path : TODO, None
            TODO
        serial : TODO, None
            TODO
        default_transport_timeout_s : TODO, None
            TODO

        Returns
        -------
        dev : TODO
            TODO

        """
        dev = cls._find(setting_matcher, port_path=port_path, serial=serial, default_transport_timeout_s=default_transport_timeout_s)
        dev._open()  # pylint: disable=protected-access
        dev._flush_buffers()  # pylint: disable=protected-access
        return dev

    @classmethod
    def _find_devices(cls, setting_matcher, device_matcher=None, usb_info='', default_transport_timeout_s=None):
        """_find and yield the devices that match.

        Parameters
        ----------
        setting_matcher : TODO
            Function that returns the setting to use given a ``usb1.USBDevice``, or ``None``
            if the device doesn't have a valid setting.
        device_matcher : TODO, None
            Function that returns ``True`` if the given ``UsbTransport`` is
            valid. ``None`` to match any device.
        usb_info : str
            Info string describing device(s).
        default_transport_timeout_s : TODO, None
            Default timeout of commands in seconds.

        Yields
        ------
        TODO
            UsbTransport instances

        """
        for device in cls.USB1_CTX.getDeviceIterator(skip_on_error=True):
            setting = setting_matcher(device)
            if setting is None:
                continue

            transport = cls(device, setting, usb_info=usb_info, default_transport_timeout_s=default_transport_timeout_s)
            if device_matcher is None or device_matcher(transport):
                yield transport

    @classmethod
    def _find_first(cls, setting_matcher, device_matcher=None, usb_info='', default_transport_timeout_s=None):
        """Find and return the first matching device.

        Parameters
        ----------
        setting_matcher : TODO
            Function that returns the setting to use given a ``usb1.USBDevice``, or ``None``
            if the device doesn't have a valid setting.
        device_matcher : TODO
            Function that returns ``True`` if the given ``UsbTransport`` is
            valid. ``None`` to match any device.
        usb_info : str
            Info string describing device(s).
        default_transport_timeout_s : TODO, None
            Default timeout of commands in seconds.

        Returns
        -------
        TODO
            An instance of `UsbTransport`

        Raises
        ------
        adb_shell.exceptions.DeviceNotFoundError
            Raised if the device is not available.

        """
        try:
            return next(cls._find_devices(setting_matcher, device_matcher=device_matcher, usb_info=usb_info, default_transport_timeout_s=default_transport_timeout_s))
        except StopIteration:
            raise exceptions.UsbDeviceNotFoundError('No device available, or it is in the wrong configuration.')

    @classmethod
    def find_adb(cls, serial=None, port_path=None, default_transport_timeout_s=None):
        """TODO

        Parameters
        ----------
        serial : TODO
            TODO
        port_path : TODO
            TODO
        default_transport_timeout_s : TODO, None
            Default timeout of commands in seconds.

        Returns
        -------
        UsbTransport
            TODO

        """
        return cls._find(
            interface_matcher(CLASS, SUBCLASS, PROTOCOL),
            serial=serial,
            port_path=port_path,
            default_transport_timeout_s=default_transport_timeout_s
        )

    @classmethod
    def find_all_adb_devices(cls, default_transport_timeout_s=None):
        """Find all ADB devices attached via USB.

        Parameters
        ----------
        default_transport_timeout_s : TODO, None
            Default timeout of commands in seconds.

        Returns
        -------
        generator
            A generator which yields each ADB device attached via USB.

        """
        for dev in cls._find_devices(interface_matcher(CLASS, SUBCLASS, PROTOCOL), default_transport_timeout_s=default_transport_timeout_s):
            yield dev