Получение точки монтирования при подключении USB-устройства Mac OS X и Linux

Я пытаюсь разработать программу в Mac OS и Linux, в которой перечислены файлы и папки на USB-накопителе. Мне нужно получить некоторые события, когда USB-устройство подключено и удалено. Я знаю, что в Mac OS X я могу использовать IOKit. Но я не знаю, как получить точку монтирования, где установлено устройство. Могу ли я получить его с помощью IOkit? Есть ли кроссплатформенное решение для Linux и Mac?


person wantro    schedule 11.12.2009    source источник


Ответы (2)


Нет, нет. Под Linux вы можете использовать HAL или DeviceKit-диски с интерфейсами D-Bus. Обратите внимание, что это необязательные компоненты, которые могут отсутствовать. HAL старше, а DeviceKit-диски — более новые реализации, а DK-d заменяет HAL.

person dottedmag    schedule 12.12.2009
comment
Большое спасибо за ответ. В общем, как мне получить путь монтирования USB-устройства (я использую iPod) в Mac. Я использую IOServiceMatching(kIOUSBDeviceClassName) и IOServiceAddMatchingNotification для прослушивания уведомлений о добавлении/удалении USB-устройства. Как только я получаю уведомление, я использую IORegistryEntryCreateCFProperty (device, CFSTR(kIOBSDNameKey), kCFAllocatorDefault,0); чтобы получить имя устройства. Но этот вызов возвращает NULL. - person wantro; 12.12.2009
comment
Продолжая комментарий выше... Когда я использовал IORegistryEntrySearchCFProperty(e, kIOServicePlane, CFSTR(kIOBSDNameKey), NULL, bits); Я получаю имя BSD как disk2. Это как я должен получить имя BSD? Поскольку системный профилировщик показывает устройство как /dev/disk2s1 - person wantro; 12.12.2009

Подход, который я использовал для получения доступных точек монтирования (с Java), направляет вывод команды system_profiler SPUSBDataType -xml в dd-plist. Впоследствии он рекурсивно проходит по иерархии USB, сопоставляя те, у которых есть ключ «тома». Для каждого элемента в этом массиве извлеките ключ «mount_point», чтобы получить место, где он смонтирован. См. пример кода ниже:

/*
Copyright © 2014 Edwin de Jong. All Rights Reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY [LICENSOR] "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/
package nl.topicuszorg.laos.util.osx;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;

import nl.topicuszorg.laos.model.response.MountState;
import nl.topicuszorg.laos.model.response.MountedDevice;

import org.xml.sax.SAXException;

import com.dd.plist.NSArray;
import com.dd.plist.NSDictionary;
import com.dd.plist.NSObject;
import com.dd.plist.NSString;
import com.dd.plist.PropertyListFormatException;
import com.dd.plist.PropertyListParser;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;

public class USBHelpers
{
  private static final String SYSTEM_PROFILER_COMMAND = "/usr/sbin/system_profiler";

  private static final String SPUSB_DATA_TYPE = "SPUSBDataType";

  private interface SpUSBDataTypeIdentifiers
  {
    String ITEMS = "_items";

    String VOLUMES = "volumes";

    String VENDOR_ID = "vendor_id";

    String MOUNT_POINT = "mount_point";

    String NAME = "_name";
  }

  public static List<MountedDevice> findMountedDevicesOsX() throws IOException, PropertyListFormatException,
    ParseException, ParserConfigurationException, SAXException
  {
    final Process process = new ProcessBuilder(SYSTEM_PROFILER_COMMAND, SPUSB_DATA_TYPE, "-xml")
      .start();
    return findMountedDevicesInConfiguration(process.getInputStream());
  }

  private static List<MountedDevice> findMountedDevicesInConfiguration(final InputStream processInputStream)
    throws IOException, PropertyListFormatException, ParseException, ParserConfigurationException, SAXException
  {
    // Root is an array, the USB devices are hierarchical in _items (and eg. _items(0)._items)
    final NSArray array = (NSArray) (PropertyListParser.parse(processInputStream));
    final NSDictionary dict = (NSDictionary) array.objectAtIndex(0);
    final NSArray itemsArray = (NSArray) dict.get(SpUSBDataTypeIdentifiers.ITEMS);
    return recurseUSBDevices(itemsArray);
  }

  public static List<MountedDevice> recurseUSBDevices(NSArray items)
  {
    final Builder<MountedDevice> builder = ImmutableList.builder();
    for (NSObject item : items.getArray())
    {
      builder.addAll(recurseUSBDevice((NSDictionary) item));
    }

    return builder.build();
  }

  private static List<MountedDevice> recurseUSBDevice(final NSDictionary dict)
  {
    final Builder<MountedDevice> builder = ImmutableList.builder();
    for (final Map.Entry<String, NSObject> entry : dict.entrySet())
    {
      if (entry.getKey().equals(SpUSBDataTypeIdentifiers.ITEMS))
      {
        // The USB device is a hub
        builder.addAll(recurseUSBDevices((NSArray) entry.getValue()));
      }
      if (entry.getKey().equals(SpUSBDataTypeIdentifiers.VOLUMES))
      {
        // This is a mountable device. We need to get the volumes, and for each volume, return it.
        List<MountedDevice> mountedDeviceOpt = parseVolumes((NSArray) (entry.getValue()));
        for (MountedDevice mountedDevice : mountedDeviceOpt)
        {
          mountedDevice.setVendorId(((NSString) dict.get(SpUSBDataTypeIdentifiers.VENDOR_ID)).toString());
          builder.add(mountedDevice);
        }
      }
    }
    return builder.build();
  }

  private static List<MountedDevice> parseVolumes(final NSArray nsArray)
  {
    final Builder<MountedDevice> builder = ImmutableList.builder();
    for (final NSObject item : nsArray.getArray())
    {
      builder.add(parseVolume((NSDictionary) item));
    }
    return builder.build();

  }

  private static MountedDevice parseVolume(final NSDictionary item)
  {
    final String mountPoint = ((NSString) item.get(SpUSBDataTypeIdentifiers.MOUNT_POINT)).toString();
    final String name = ((NSString) item.get(SpUSBDataTypeIdentifiers.NAME)).toString();
    return new MountedDevice(mountPoint, name, null, null, MountState.MOUNTED);
  }

}
person Dibbeke    schedule 01.10.2014