Как вручную обрабатывать все USB-устройства, подключенные к MacBook

Моя проблема в том, что я хочу вручную обрабатывать, как обрабатываются USB-устройства, когда они подключены. Я не хочу, чтобы операционная система делала что-либо с подключенными USB-устройствами, кроме как уведомлять меня об их типе и их идентификаторе, когда они подключены in. Затем я могу выбрать соответствующий драйвер, который будет применяться к нему, или вручную что-то сделать с ним с помощью специального кода.

Я читал это о том, как MacOS обрабатывает USB-накопители, и там говорится:

If you want your driver selected above others, all you need to do is add key value pairs for the device your driver is for which cause your driver to get a really high score. Usually it's enough to just put keys in for your vendor id/model. However, I think you can override the matching method (device drivers are written in a restricted set of C++) to give your driver a really high score.

Я также нашел эти 3 библиотеки для получения уведомлений о вещах на USB-накопителе:

Я просто не уверен, что эти библиотеки будут выполнять прерывать всю обработку USB-устройств операционной системой. до что-либо происходит (до того, как какой-либо драйвер устройства будет выбран и применен автоматически). Я бы хотел, чтобы ничего не происходило, кроме как получить доступ к устройству и его типу в одной из вышеуказанных библиотек, но я не уверен, что они это сделают.

У меня пока мало кода, кроме этого:

var usb = require('usb')
usb.getDeviceList()

Но я предполагаю, что это разрешит подключенные устройства после, которые ОС уже выбрала и применила к нему драйвер по умолчанию. Я хочу сделать что-то вроде этого:

usb.blockDefaultOSDeviceHandler()
usb.on('device:plugged_in', function(data){
  if (data.type == 'keyboard') {
    if (data.modelNumber == '123') {
      // allow
      usb.applyKeyboardDriver('abc', data.modelNumber)
      usb.on('keyboard:event', logKeyboardEvent)
    } else {
      throw new Error('Unrecognized device')
    }
  } 
})

Я надеюсь, что библиотека будет прерывать для всего поведения операционной системы по умолчанию, чтобы я мог сам справиться с тем, что должно быть сделано, когда подключено USB-устройство. Причина в том, что, возможно, USB-устройство является клавиатурой, и оно автоматически начинает печатать в некоторых ключи. Я хотел бы знать, что это клавиатура, и для нее требуется пароль и конкретный драйвер, который я предварительно одобрил. Вроде того.

Я хотел бы получить доступ к любому недавно подключенному USB-устройству до, операционная система применяет свои правила обработки по умолчанию. А затем у вас есть возможность написать код, чтобы вручную обрабатывать, что делать с каждым подключенным устройством.

Если это возможно только в C, то, зная, как это сделать, было бы хорошо вместо node.js.

Возможно, вы стреляете из-за чего-то, для чего узел не создан. Вам нужно будет пойти намного глубже (подумайте о C).

basic 05.01.2019 01:37

Если это возможно только в C, то, зная, как это сделать, было бы хорошо вместо node.js.

user10869858 05.01.2019 01:39

Человек, которого вы процитировали, говорил о написании драйвера (он же «kext»). Для этого вам, вероятно, придется написать драйвер USB на уровне ядра. Итак, вы начали и есть ли у вас какие-либо конкретные вопросы о том, как заставить драйвер работать? В противном случае это, вероятно, слишком широко.

David Grayson 05.01.2019 08:55

Кроме того, почему вы вообще хотите это делать? Похоже, вы довольно часто наносите вред своему компьютеру, случайно отключая USB-клавиатуру и мышь. Может быть, есть лучшее решение, которое решает вашу проблему действительный, которую вы не указали.

David Grayson 05.01.2019 08:58

Актуальная проблема указана в заголовке.

user10869858 09.01.2019 23:56
Стоит ли изучать PHP в 2026-2027 годах?
Стоит ли изучать PHP в 2026-2027 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
2
5
566
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Ответ находится в документации Apple по USB-устройствам. По сути, вы хотите переопределить функцию probe в настраиваемом драйвере, чтобы она возвращала наивысший балл, чтобы переопределить все другие драйверы, и реализовать драйвер как обычно. Здесь - это некоторая полезная документация по процессу выбора драйвера и создания экземпляра.

Before a device—or any service provider—can be used, a driver for it must be found and loaded into the kernel. The I/O Kit defines a flexible, three-phase matching process that narrows a pool of candidate drivers down to one or more drivers. The final candidate (or, if multiple candidates, the m ost eligible one) is then loaded and given the first opportunity to manage the device or service provider.

...

Each device driver, considered as a loadable kernel extension (KEXT), must define one or more personalities that specify the kinds of devices it can support.

...

Because a driver can contain multiple matching dictionaries, each one defining a different personality for the driver, the same driver code can be loaded for different devices. For purposes of competition, the I/O Kit treats each personality as if it were a driver. If, in any single personality, all of the properties required by the family match, the driver’s code is loaded and given a chance to run for that device.

...

One common property of personalities is the probe score. A probe score is an integer that reflects how well-suited a driver is to drive a particular device. A driver may have an initial probe-score value in its personality and it may implement a probe function that allows it to modify this default value, based on its suitability to drive a device. As with other matching values, probe scores are specific to each family. That’s because once matching proceeds past the class-matching stage, only personalities from the same family compete. For more information on probe scores and what a driver does in the probe function, see Device Probing.

...

At boot time and at any time devices are added or removed, the process of driver matching occurs for each detected device (or other service provider). The process dynamically locates the most suitable driver in /System/Library/Extensions for the device or service.

...

As described in Driver Matching in the chapter Architectural Overview the matching process is triggered when a bus controller driver scans its bus and detects a new device attached to it. For each detected device the controller driver creates a nub. The I/O Kit then initiates the matching process and obtains the values from the device to use in matching (for example, examining the PCI registers). Once a suitable driver is found for the nub, the driver is registered and loaded. That driver, in turn, may create its own nub (possibly through behavior inherited from its family), which initiates the matching process to find a suitable driver.

...

The matching process proceeds as follows:

  1. In the class matching step, the I/O Kit narrows the list of potential drivers by eliminating any drivers of the wrong class for the provider service (that is, the nub). For example, all driver objects that descend from a SCSI class can be ruled out when the search is for a USB driver.
  2. In the passive matching step, the driver’s personality (specified in a driver’s XML information property list) is examined for properties specific to the provider’s family. For example, the personality might specify a particular vendor name.
  3. In the active matching step, the driver’s probe function is called with reference to the nub it is being matched against. This function allows the driver to communicate with the device and verify that it can in fact drive it. The driver returns a probe score that reflects its ability to drive the device. See Device Probing for more information. During active matching, the I/O Kit loads and probes all candidate drivers, then sorts them in order of highest to lowest probe score.

...

The I/O Kit then chooses the remaining driver with the highest probe score and starts it. If the driver successfully starts, it is added to the I/O Registry and any remaining driver candidates are discarded. If it does not start successfully, the driver with the next highest probe score is started, and so on. If more than one driver is in the pool of possible candidates, the more generic driver typically loses out to the more specific driver if both claim to be able to drive the device.

...

The probe score is a signed 32-bit integer initialized to a value specified in the driver’s personality (or to zero if not explicitly initialized).

...

A driver, in its probe function, returns a driver object (IOService *) if the probe was successful and returns zero otherwise. The returned object is usually the driver itself, but the driver can return another driver that is more suited to the provider. The probe score is an in-out parameter, which probe can modify based on what it discovers about the device.

...

After all drivers have probed the device, the one with the highest probe score is attached and its startfunction, which must be implemented by all drivers, is invoked. The start function initializes the device hardware and prepares it for operation. If the driver succeeds in starting, it returns true; the remaining candidate driver instances are discarded and the driver that started successfully continues operating. If the driver cannot initialize the hardware it must leave the hardware in the state it was in when start was invoked and return false. The failing driver is then detached and discarded, and the candidate driver with the next highest probe score is given a chance to start.

Это невозможно сделать с Node.js, если (потенциально) не используется расширение C / C++ в node.

Другие вопросы по теме