Skip to content

Commit 8a6b2cd

Browse files
committed
Use moved implementation inside mbed-os-tools
1 parent 2800a66 commit 8a6b2cd

File tree

6 files changed

+28
-1797
lines changed

6 files changed

+28
-1797
lines changed

legacy/mbed-ls/mbed_lstools/darwin.py

Lines changed: 1 addition & 164 deletions
Original file line numberDiff line numberDiff line change
@@ -15,167 +15,4 @@
1515
limitations under the License.
1616
"""
1717

18-
import re
19-
import subprocess
20-
import platform
21-
try:
22-
from plistlib import loads
23-
except ImportError:
24-
from plistlib import readPlistFromString as loads
25-
from xml.parsers.expat import ExpatError
26-
27-
from .lstools_base import MbedLsToolsBase
28-
29-
import logging
30-
logger = logging.getLogger("mbedls.lstools_darwin")
31-
logger.addHandler(logging.NullHandler())
32-
DEBUG = logging.DEBUG
33-
del logging
34-
35-
mbed_volume_name_match = re.compile(r'\b(mbed|SEGGER MSD|ATMEL EDBG Media)\b', re.I)
36-
37-
38-
def _plist_from_popen(popen):
39-
out, _ = popen.communicate()
40-
if not out:
41-
return []
42-
try:
43-
return loads(out)
44-
except ExpatError:
45-
return []
46-
47-
def _find_TTY(obj):
48-
''' Find the first tty (AKA IODialinDevice) that we can find in the
49-
children of the specified object, or None if no tty is present.
50-
'''
51-
try:
52-
return obj['IODialinDevice']
53-
except KeyError:
54-
for child in obj.get('IORegistryEntryChildren', []):
55-
found = _find_TTY(child)
56-
if found:
57-
return found
58-
return None
59-
60-
61-
def _prune(current, keys):
62-
""" Reduce the amount of data we have to sift through to only
63-
include the specified keys, and children that contain the
64-
specified keys
65-
"""
66-
pruned_current = {k: current[k] for k in keys if k in current}
67-
pruned_children = list(
68-
filter(None, [_prune(c, keys) for c in
69-
current.get('IORegistryEntryChildren', [])]))
70-
keep_current = any(k in current for k in keys) or pruned_children
71-
if keep_current:
72-
if pruned_children:
73-
pruned_current['IORegistryEntryChildren'] = pruned_children
74-
return pruned_current
75-
else:
76-
return {}
77-
78-
79-
def _dfs_usb_info(obj, parents):
80-
""" Find all of the usb info that we can from this particular IORegistry
81-
tree with depth first search (and searching the parent stack....)
82-
"""
83-
output = {}
84-
if ('BSD Name' in obj and obj['BSD Name'].startswith('disk') and
85-
mbed_volume_name_match.search(obj['IORegistryEntryName'])):
86-
disk_id = obj['BSD Name']
87-
usb_info = {
88-
'serial':None,
89-
'vendor_id':None,
90-
'product_id':None,
91-
'tty':None,
92-
}
93-
for parent in [obj] + parents:
94-
if 'USB Serial Number' in parent:
95-
usb_info['serial'] = parent['USB Serial Number']
96-
if 'idVendor' in parent and 'idProduct' in parent:
97-
usb_info['vendor_id'] = format(parent['idVendor'], '04x')
98-
usb_info['product_id'] = format(parent['idProduct'], '04x')
99-
if usb_info['serial']:
100-
usb_info['tty'] = _find_TTY(parent)
101-
if all(usb_info.values()):
102-
break
103-
logger.debug("found usb info %r", usb_info)
104-
output[disk_id] = usb_info
105-
for child in obj.get('IORegistryEntryChildren', []):
106-
output.update(_dfs_usb_info(child, [obj] + parents))
107-
return output
108-
109-
110-
class MbedLsToolsDarwin(MbedLsToolsBase):
111-
""" mbed-enabled platform detection on Mac OS X
112-
"""
113-
114-
def __init__(self, **kwargs):
115-
MbedLsToolsBase.__init__(self, **kwargs)
116-
self.mac_version = float('.'.join(platform.mac_ver()[0].split('.')[:2]))
117-
118-
def find_candidates(self):
119-
# {volume_id: {serial:, vendor_id:, product_id:, tty:}}
120-
volumes = self._volumes()
121-
122-
# {volume_id: mount_point}
123-
mounts = self._mount_points()
124-
return [
125-
{
126-
'mount_point': mounts[v],
127-
'serial_port': volumes[v]['tty'],
128-
'target_id_usb_id': volumes[v].get('serial'),
129-
'vendor_id': volumes[v].get('vendor_id'),
130-
'product_id': volumes[v].get('product_id')
131-
} for v in set(volumes.keys()) and set(mounts.keys())
132-
if v in mounts and v in volumes
133-
]
134-
135-
def _mount_points(self):
136-
''' Returns map {volume_id: mount_point} '''
137-
diskutil_ls = subprocess.Popen(['diskutil', 'list', '-plist'], stdout=subprocess.PIPE)
138-
disks = _plist_from_popen(diskutil_ls)
139-
140-
if logger.isEnabledFor(DEBUG):
141-
import pprint
142-
logger.debug("disks dict \n%s", pprint.PrettyPrinter(indent=2).pformat(disks))
143-
return {disk['DeviceIdentifier']: disk.get('MountPoint', None)
144-
for disk in disks['AllDisksAndPartitions']}
145-
146-
def _volumes(self):
147-
''' returns a map {volume_id: {serial:, vendor_id:, product_id:, tty:}'''
148-
149-
# to find all the possible mbed volumes, we look for registry entries
150-
# under all possible USB tree which have a "BSD Name" that starts with
151-
# "disk" # (i.e. this is a USB disk), and have a IORegistryEntryName that
152-
# matches /\cmbed/
153-
# Once we've found a disk, we can search up for a parent with a valid
154-
# serial number, and then search down again to find a tty that's part
155-
# of the same composite device
156-
# ioreg -a -r -n <usb_controller_name> -l
157-
usb_controllers = ['AppleUSBXHCI', 'AppleUSBUHCI', 'AppleUSBEHCI',
158-
'AppleUSBOHCI', 'IOUSBHostDevice']
159-
160-
cmp_par = '-n'
161-
# For El Captain we need to list all the instances of (-c) rather than
162-
# compare names (-n)
163-
if self.mac_version >= 10.11:
164-
cmp_par = '-c'
165-
166-
for usb_controller in usb_controllers:
167-
ioreg_usb = subprocess.Popen(['ioreg', '-a', '-r', cmp_par, usb_controller, '-l'], stdout=subprocess.PIPE)
168-
usb_tree = _plist_from_popen(ioreg_usb)
169-
170-
r = {}
171-
172-
for name, obj in enumerate(usb_tree):
173-
pruned_obj = _prune(obj, ['USB Serial Number', 'idVendor', 'BSD Name',
174-
'IORegistryEntryName', 'idProduct', 'IODialinDevice'])
175-
if logger.isEnabledFor(DEBUG):
176-
import pprint
177-
logger.debug("finding in \n%s", pprint.PrettyPrinter(indent=2).pformat(pruned_obj))
178-
r.update(_dfs_usb_info(pruned_obj, []))
179-
180-
logger.debug("_volumes return %r", r)
181-
return r
18+
from mbed_os_tools.detect.darwin import MbedLsToolsDarwin

legacy/mbed-ls/mbed_lstools/linux.py

Lines changed: 1 addition & 143 deletions
Original file line numberDiff line numberDiff line change
@@ -15,146 +15,4 @@
1515
limitations under the License.
1616
"""
1717

18-
import re
19-
from os.path import join, isdir, dirname, abspath
20-
import os
21-
22-
from .lstools_base import MbedLsToolsBase
23-
24-
import logging
25-
logger = logging.getLogger("mbedls.lstools_linux")
26-
logger.addHandler(logging.NullHandler())
27-
del logging
28-
29-
SYSFS_BLOCK_DEVICE_PATH = '/sys/class/block'
30-
31-
def _readlink(link):
32-
content = os.readlink(link)
33-
if content.startswith(".."):
34-
return abspath(join(dirname(link), content))
35-
else:
36-
return content
37-
38-
39-
class MbedLsToolsLinuxGeneric(MbedLsToolsBase):
40-
""" mbed-enabled platform for Linux with udev
41-
"""
42-
def __init__(self, **kwargs):
43-
"""! ctor
44-
"""
45-
MbedLsToolsBase.__init__(self, **kwargs)
46-
self.nlp = re.compile(
47-
r'(pci|usb)-[0-9a-zA-Z:_-]*_(?P<usbid>[0-9a-zA-Z]*)-.*$')
48-
self.mmp = re.compile(
49-
r'(?P<dev>(/[^/ ]*)+) on (?P<dir>(/[^/ ]*)+) ')
50-
self.udp = re.compile(r'^[0-9]+-[0-9]+[^:\s]*$')
51-
52-
def find_candidates(self):
53-
disk_ids = self._dev_by_id('disk')
54-
serial_ids = self._dev_by_id('serial')
55-
mount_ids = dict(self._fat_mounts())
56-
usb_info = self._sysfs_block_devices(disk_ids.values())
57-
logger.debug("Mount mapping %r", mount_ids)
58-
59-
return [
60-
{
61-
'mount_point' : mount_ids.get(disk_dev),
62-
'serial_port' : serial_ids.get(disk_uuid),
63-
'target_id_usb_id' : disk_uuid,
64-
'vendor_id': usb_info.get(disk_dev, {}).get('vendor_id'),
65-
'product_id': usb_info.get(disk_dev, {}).get('product_id')
66-
} for disk_uuid, disk_dev in disk_ids.items()
67-
]
68-
69-
def _dev_by_id(self, device_type):
70-
"""! Get a dict, USBID -> device, for a device class
71-
@param device_type The type of devices to search. For exmaple, "serial"
72-
looks for all serial devices connected to this computer
73-
@return A dict: Device USBID -> device file in /dev
74-
"""
75-
dir = join("/dev", device_type, "by-id")
76-
if isdir(dir):
77-
to_ret = dict(self._hex_ids([join(dir, f) for f in os.listdir(dir)]))
78-
logger.debug("Found %s devices by id %r", device_type, to_ret)
79-
return to_ret
80-
else:
81-
logger.error("Could not get %s devices by id. "
82-
"This could be because your Linux distribution "
83-
"does not use udev, or does not create /dev/%s/by-id "
84-
"symlinks. Please submit an issue to github.com/"
85-
"armmbed/mbed-ls.", device_type, device_type)
86-
return {}
87-
88-
def _fat_mounts(self):
89-
"""! Lists mounted devices with vfat file system (potential mbeds)
90-
@result Returns list of all mounted vfat devices
91-
@details Uses Linux shell command: 'mount'
92-
"""
93-
_stdout, _, retval = self._run_cli_process('mount')
94-
if not retval:
95-
for line in _stdout.splitlines():
96-
if b'vfat' in line:
97-
match = self.mmp.search(line.decode('utf-8'))
98-
if match:
99-
yield match.group("dev"), match.group("dir")
100-
101-
def _hex_ids(self, dev_list):
102-
"""! Build a USBID map for a device list
103-
@param disk_list List of disks in a system with USBID decoration
104-
@return Returns map USBID -> device file in /dev
105-
@details Uses regular expressions to get a USBID (TargeTIDs) a "by-id"
106-
symbolic link
107-
"""
108-
logger.debug("Converting device list %r", dev_list)
109-
for dl in dev_list:
110-
match = self.nlp.search(dl)
111-
if match:
112-
yield match.group("usbid"), _readlink(dl)
113-
114-
def _sysfs_block_devices(self, block_devices):
115-
device_names = { os.path.basename(d): d for d in block_devices }
116-
sysfs_block_devices = set(os.listdir(SYSFS_BLOCK_DEVICE_PATH))
117-
common_device_names = sysfs_block_devices.intersection(set(device_names.keys()))
118-
result = {}
119-
120-
for common_device_name in common_device_names:
121-
sysfs_path = os.path.join(SYSFS_BLOCK_DEVICE_PATH, common_device_name)
122-
full_sysfs_path = os.readlink(sysfs_path)
123-
path_parts = full_sysfs_path.split('/')
124-
125-
end_index = None
126-
for index, part in enumerate(path_parts):
127-
if self.udp.search(part):
128-
end_index = index
129-
130-
if end_index == None:
131-
logger.debug('Did not find suitable usb folder for usb info: %s', full_sysfs_path)
132-
continue
133-
134-
usb_info_rel_path = path_parts[:end_index + 1]
135-
usb_info_path = os.path.join(SYSFS_BLOCK_DEVICE_PATH, os.sep.join(usb_info_rel_path))
136-
137-
vendor_id = None
138-
product_id = None
139-
140-
vendor_id_file_paths = os.path.join(usb_info_path, 'idVendor')
141-
product_id_file_paths = os.path.join(usb_info_path, 'idProduct')
142-
143-
try:
144-
with open(vendor_id_file_paths, 'r') as vendor_file:
145-
vendor_id = vendor_file.read().strip()
146-
except OSError as e:
147-
logger.debug('Failed to read vendor id file %s weith error:', vendor_id_file_paths, e)
148-
149-
try:
150-
with open(product_id_file_paths, 'r') as product_file:
151-
product_id = product_file.read().strip()
152-
except OSError as e:
153-
logger.debug('Failed to read product id file %s weith error:', product_id_file_paths, e)
154-
155-
result[device_names[common_device_name]] = {
156-
'vendor_id': vendor_id,
157-
'product_id': product_id
158-
}
159-
160-
return result
18+
from mbed_os_tools.detect.linux import MbedLsToolsLinuxGeneric

0 commit comments

Comments
 (0)