tzh
2024-08-22 c7d0944258c7d0943aa7b2211498fd612971ce27
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
# Copyright 2016 The Android Open Source Project
#
# 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.
 
import os
import re
 
 
class Device(object):
    """Create dict object for relay usb connection.
 
       This class provides an interface to locate lab equipment without encoding
       knowledge of the USB bus topology in the lab equipment device drivers.
    """
 
    KEY_VID = 'vendor_id'
    KEY_PID = 'product_id'
    KEY_SN = 'serial_no'
    KEY_INF = 'inf'
    KEY_CFG = 'config'
    KEY_NAME = 'name'
    KEY_TTY = 'tty_path'
    KEY_MFG = 'mfg'
    KEY_PRD = 'product'
    KEY_VER = 'version'
 
    _instance = None
 
    _USB_DEVICE_SYS_ROOT = '/sys/bus/usb/devices'
    _DEV_ROOT = '/dev'
 
    _SYS_VENDOR_ID = 'idVendor'
    _SYS_PRODUCT_ID = 'idProduct'
    _SYS_SERIAL_NO = 'serial'
    _INF_CLASS = 'bInterfaceClass'
    _INF_SUB_CLASS = 'bInterfaceSubClass'
    _INF_PROTOCOL = 'bInterfaceProtocol'
    _MFG_STRING = 'manufacturer'
    _PRODUCT_STRING = 'product'
    _VERSION_STRING = 'version'
 
    _USB_CDC_ACM_CLASS = 0x02
    _USB_CDC_ACM_SUB_CLASS = 0x02
    _USB_CDC_ACM_PROTOCOL = 0x01
 
    def __init__(self, name, vid, pid, cfg, inf):
        self._device_list = []
 
        self._build_device(name, vid, pid, cfg, inf)
 
        self._walk_usb_tree(self._init_device_list_callback, None)
 
    def __new__(cls, *args, **kwargs):
        # The Device class should be a singleton.  A lab test procedure may
        # use multiple pieces of lab equipment and we do not want to have to
        # create a new instance of the Device for each device.
        if not cls._instance:
            cls._instance = super(Device, cls).__new__(cls, *args, **kwargs)
        return cls._instance
 
    def __enter__(self):
        return self
 
    def __exit__(self, exception_type, exception_value, traceback):
        pass
 
    def _build_device(self, name, vid, pid, cfg, inf):
        """Build relay device information.
 
        Args:
            name:   device
            vid:    vendor ID
            pid:    product ID
            cfg:    configuration
            inf:    interface
 
        Returns:
            Nothing
        """
        entry = {}
        entry[self.KEY_NAME] = name
        entry[self.KEY_VID] = int(vid, 16)
        entry[self.KEY_PID] = int(pid, 16)
 
        # The serial number string is optional in USB and not all devices
        # use it.  The relay devices do not use it then we specify 'None' in
        # the lab configuration file.
        entry[self.KEY_SN] = None
        entry[self.KEY_CFG] = int(cfg)
        entry[self.KEY_INF] = int(inf)
        entry[self.KEY_TTY] = None
 
        self._device_list.append(entry)
 
    def _find_lab_device_entry(self, vendor_id, product_id, serial_no):
        """find a device in the lab device list.
 
        Args:
            vendor_id: unique vendor id for device
            product_id: unique product id for device
            serial_no: serial string for the device (may be None)
 
        Returns:
            device entry or None
        """
        for device in self._device_list:
            if device[self.KEY_VID] != vendor_id:
                continue
            if device[self.KEY_PID] != product_id:
                continue
            if device[self.KEY_SN] == serial_no:
                return device
 
        return None
 
    def _read_sys_attr(self, root, attr):
        """read a sysfs attribute.
 
        Args:
            root: path of the sysfs directory
            attr: attribute to read
 
        Returns:
            attribute value or None
        """
        try:
            path = os.path.join(root, attr)
            with open(path) as f:
                return f.readline().rstrip()
        except IOError:
            return None
 
    def _read_sys_hex_attr(self, root, attr):
        """read a sysfs hexadecimal integer attribute.
 
        Args:
            root: path of the sysfs directory
            attr: attribute to read
 
        Returns:
            attribute value or None
        """
        try:
            path = os.path.join(root, attr)
            with open(path) as f:
                return int(f.readline(), 16)
        except IOError:
            return None
 
    def _is_cdc_acm(self, inf_path):
        """determine if the interface implements the CDC ACM class.
 
        Args:
            inf_path: directory entry for the inf under /sys/bus/usb/devices
 
        Returns:
            True if the inf is CDC ACM, false otherwise
        """
        cls = self._read_sys_hex_attr(inf_path, self._INF_CLASS)
        sub_cls = self._read_sys_hex_attr(inf_path, self._INF_SUB_CLASS)
        proto = self._read_sys_hex_attr(inf_path, self._INF_PROTOCOL)
        if self._USB_CDC_ACM_CLASS != cls:
            return False
        if self._USB_CDC_ACM_SUB_CLASS != sub_cls:
            return False
        if self._USB_CDC_ACM_PROTOCOL != proto:
            return False
 
        return True
 
    def _read_tty_name(self, dir_entry, inf, cfg):
        """Get the path to the associated tty device.
 
        Args:
            dir_entry: directory entry for the device under /sys/bus/usb/devices
            inf: Interface number of the device
            cfg: Configuration number of the device
 
        Returns:
            Path to a tty device or None
        """
        inf_path = os.path.join(self._USB_DEVICE_SYS_ROOT,
                                '%s:%d.%d' % (dir_entry, cfg, inf))
 
        # first determine if this is a CDC-ACM or USB Serial device.
        if self._is_cdc_acm(inf_path):
            tty_list = os.listdir(os.path.join(inf_path, 'tty'))
 
            # Each CDC-ACM interface should only have one tty device associated
            # with it so just return the first item in the list.
            return os.path.join(self._DEV_ROOT, tty_list[0])
        else:
            # USB Serial devices have a link to their ttyUSB* device in the inf
            # directory
            tty_re = re.compile(r'ttyUSB\d+$')
 
            dir_list = os.listdir(inf_path)
            for entry in dir_list:
                if tty_re.match(entry):
                    return os.path.join(self._DEV_ROOT, entry)
 
        return None
 
    def _init_device_list_callback(self, _, dir_entry):
        """Callback function used with _walk_usb_tree for device list init.
 
        Args:
            _: Callback context (unused)
            dir_entry: Directory entry reported by _walk_usb_tree
 
        """
        path = os.path.join(self._USB_DEVICE_SYS_ROOT, dir_entry)
 
        # The combination of vendor id, product id, and serial number
        # should be sufficient to uniquely identify each piece of lab
        # equipment.
        vendor_id = self._read_sys_hex_attr(path, self._SYS_VENDOR_ID)
        product_id = self._read_sys_hex_attr(path, self._SYS_PRODUCT_ID)
        serial_no = self._read_sys_attr(path, self._SYS_SERIAL_NO)
 
        # For each device try to match it with a device entry in the lab
        # configuration.
        device = self._find_lab_device_entry(vendor_id, product_id, serial_no)
        if device:
            # If the device is in the lab configuration then determine
            # which tty device it associated with.
            device[self.KEY_TTY] = self._read_tty_name(dir_entry,
                                                       device[self.KEY_INF],
                                                       device[self.KEY_CFG])
 
    def _list_all_tty_devices_callback(self, dev_list, dir_entry):
        """Callback for _walk_usb_tree when listing all USB serial devices.
 
        Args:
            dev_list: Device list to fill
            dir_entry: Directory entry reported by _walk_usb_tree
 
        """
        dev_path = os.path.join(self._USB_DEVICE_SYS_ROOT, dir_entry)
 
        # Determine if there are any interfaces in the sys directory for the
        # USB Device.
        inf_re = re.compile(r'\d+-\d+(\.\d+){0,}:(?P<cfg>\d+)\.(?P<inf>\d+)$')
        inf_dir_list = os.listdir(dev_path)
 
        for inf_entry in inf_dir_list:
            inf_match = inf_re.match(inf_entry)
            if inf_match is None:
                continue
 
            inf_dict = inf_match.groupdict()
            inf = int(inf_dict['inf'])
            cfg = int(inf_dict['cfg'])
 
            # Check to see if there is a tty device associated with this
            # interface.
            tty_path = self._read_tty_name(dir_entry, inf, cfg)
            if tty_path is None:
                continue
 
            # This is a TTY interface, create a dictionary of the relevant
            # sysfs attributes for this device.
            entry = {}
            entry[self.KEY_TTY] = tty_path
            entry[self.KEY_INF] = inf
            entry[self.KEY_CFG] = cfg
            entry[self.KEY_VID] = self._read_sys_hex_attr(dev_path,
                                                          self._SYS_VENDOR_ID)
            entry[self.KEY_PID] = self._read_sys_hex_attr(dev_path,
                                                          self._SYS_PRODUCT_ID)
            entry[self.KEY_SN] = self._read_sys_attr(dev_path,
                                                     self._SYS_SERIAL_NO)
            entry[self.KEY_MFG] = self._read_sys_attr(dev_path,
                                                      self._MFG_STRING)
            entry[self.KEY_PRD] = self._read_sys_attr(dev_path,
                                                      self._PRODUCT_STRING)
            entry[self.KEY_VER] = self._read_sys_attr(dev_path,
                                                      self._VERSION_STRING)
 
            # If this device is also in the lab device list then add the
            # friendly name for it.
            lab_device = self._find_lab_device_entry(entry[self.KEY_VID],
                                                     entry[self.KEY_PID],
                                                     entry[self.KEY_SN])
            if lab_device is not None:
                entry[self.KEY_NAME] = lab_device[self.KEY_NAME]
 
            dev_list.append(entry)
 
    def _walk_usb_tree(self, callback, context):
        """Walk the USB device and locate lab devices.
 
           Traverse the USB device tree in /sys/bus/usb/devices and inspect each
           device and see if it matches a device in the lab configuration.  If
           it does then get the path to the associated tty device.
 
        Args:
            callback: Callback to invoke when a USB device is found.
            context: Context variable for callback.
 
        Returns:
            Nothing
        """
        # Match only devices, exclude interfaces and root hubs
        file_re = re.compile(r'\d+-\d+(\.\d+){0,}$')
        dir_list = os.listdir(self._USB_DEVICE_SYS_ROOT)
 
        for dir_entry in dir_list:
            if file_re.match(dir_entry):
                callback(context, dir_entry)
 
    def get_tty_path(self, name):
        """Get the path to the tty device for a given lab device.
 
        Args:
            name: lab device identifier, e.g. 'rail', or 'bt_trigger'
 
        Returns:
            Path to the tty device otherwise None
        """
        for dev in self._device_list:
            if dev[self.KEY_NAME] == name and dev[self.KEY_NAME] is not None:
                return dev[self.KEY_TTY]
 
        return None
 
    def get_tty_devices(self):
        """Get a list of all USB based tty devices attached to the machine.
 
        Returns:
            List of dictionaries where each dictionary contains a description of
            the USB TTY device.
        """
        all_dev_list = []
        self._walk_usb_tree(self._list_all_tty_devices_callback, all_dev_list)
 
        return all_dev_list