Linux emulate bluetooth mouse

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Emulate a Bluetooth HID device with bluez on linux

Alkaid-Benetnash/EmuBTHID

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

This tool emulates a simple bluetooth HID device (keyboard + mouse) based on bluez and xserver from linux. It was orignally designed for a poor student cannot afford a bluetooth keyboard. That poor student used laptop keyboard/mouse to control an android phone via bluetooth.

Via bluez, EmuBTHID registers a special bluetooth service («00001124-0000-1000-8000-00805f9b34fb») which can serve as a HID device and be discoverable by other users.

Via Xlib, EmuBTHID creates a X window, which grabs keyboard/mouse input and send them to remote.

This tool requires «root» to listen to priviledged bluetooth ports, which communicate with remote devices.

This tool is recently tested under Archlinux:

python-xlib 0.27 dbus-python 1.2.16

The client who uses the emulated HID device is an android 9 phone.

Update the bluetooth controller MAC in main.py

Edit main.py and change the CONTROLLER_MAC variable in the beginning to your own MAC. You can find the MAC of the bluetooth controller in bluetoothctl . E.g. the «5C:87:9C:96:BE:5E» shown in the screenshot below is the MAC.

  1. make sure that bluetoothd has the plugin input disabled (i.e. «-P input»).
  2. For example, refer to ArchWiki
sudo systemctl edit bluetooth 
### Editing /etc/systemd/system/bluetooth.service.d/override.conf ### Anything between here and the comment below will become the contents > [Service] ExecStart= ExecStart=/usr/lib/bluetooth/bluetoothd -P input 
sudo systemctl restart bluetooth 

In bluetoothctl, it should look like this, where a lot of UUIDs are registered

bluetoothctl_1

And you can find this specific Class value and UUID for a «Human Interface Device» appears in show

bluetoothctl-2

On the other hand, you should be able to see the main window of EmuBTHID which will capture your keyboard/mouse input:

MainWindow

  1. Now go back to bluetoothctl, enable discoverable bluetoothctl-3
  2. Now you should be able to discover a new HID device on other devices (e.g. an android phone). Now pair or re-connect. You should finish the pairing procedure in bluetoothctl (there will be a prompt). It looks like this: bluetoothctl-4
  3. Final step, go back to the main window. enter «Ctrl+Alt+Shift+B» as shown in the window to grab keyboard as well as mouse input. Press the same combination again to un-grab.

bluetoothctl-authorize-prompt

  1. The xhost + is pretty hacky and may raise security concerns. But I am personally fine with that.
  2. After pairing or connecting to this emulated HID device, bluetoothctl will show a lot of authorize prompt, which I normally ignore.
  3. Even though the keyboard usually works pretty well, the mouse sometimes becomes lagging. But I normally only use the keyboard feature.

About

Emulate a Bluetooth HID device with bluez on linux

Источник

Bluetooth mouse (Русский)

Состояние перевода: На этой странице представлен перевод статьи Bluetooth mouse. Дата последней синхронизации: 25 сентября 2021. Вы можете помочь синхронизировать перевод, если в английской версии произошли изменения.

Эта статья описывает настройку Bluetooth-мышей и решение связанных с ними проблем. Информация базируется на основной статье Bluetooth, и предполагается, что вы уже изучили её.

Настройки

Скорость прокрутки на Apple Magic Mouse

Если прокрутка слишком медленная, попробуйте

# modprobe -r hid_magicmouse # modprobe hid_magicmouse scroll_acceleration=1 scroll_speed=55

Можно установить значение от 0 до 63.

Когда вы найдёте подходящее вам значение, можно сделать это изменение постоянным в /etc/modprobe.d/

/etc/modprobe.d/hid_magicmouse.conf
options hid_magicmouse scroll_acceleration=1 scroll_speed=55

Щелчок средней кнопкой на Apple Magic Mouse

Если вы считаете, что средний щелчок слишком привередлив, вы можете отключить его

# modprobe -r hid_magicmouse # modprobe hid_magicmouse emulate_3button=0

Можно сделать это изменение постоянным в /etc/modprobe.d/

/etc/modprobe.d/hid_magicmouse.conf
options hid_magicmouse emulate_3button=0

Сопряжение мыши и dual boot

При использовании нескольких операционным систем вам придётся настраивать сопряжение с мышью каждый раз снова и снова при переходе в другую ОС. Это связано с тем, что при сопряжении Bluetooth-служба генерирует уникальный набор ключей сопряжения.

Во-первых, ваш компьютер хранит MAC-адрес устройства Bluetooth и ключ сопряжения. Во-вторых, ваше Bluetooth-устройство хранит MAC-адрес компьютера и соответствующий ключ. Это обычно работает нормально, но MAC-адрес вашего Bluetooth-порта одинаковый во всех ОС (он прописан на аппаратном уровне), а при сопряжении каждый раз генерируется новый ключ. Этот ключ перезаписывает старый, хранящийся на Bluetooth-устройстве. Windows перезаписывает Linux-ключ и наоборот.

Вы можете перенести ключи сопряжения из другой системы в Linux; смотрите Bluetooth (Русский)#Сопряжение при Dual boot.

Если у вас устройство Bluetooth LE, используйте этот Python-скрипт, слегка адаптированный для Arch (оригинальное обсуждение [1]).

Решение проблем

Тормоза мыши

Если вы наблюдаете тормоза мыши, вы можете попробовать увеличить частоту опроса. Смотрите Mouse polling rate для дополнительной информации.

Можно попробовать установить минимальную/максимальную задержку для мыши в BlueZ [2]:

Попробуйте изменить файл /var/lib/bluetooth/mac-адрес-адаптера/mac-адрес-мыши//info , добавив туда следующие строки:

[ConnectionParameters] MinInterval=6 MaxInterval=9 Latency=44 Timeout=216

Также можно использовать hcitool (из bluez-utils-compat AUR ) для изменения параметров задержки:

# HANDLE="$(hcitool con | grep '' | awk '')" # get the device handle # hcitool lecup --handle $HANDLE --latency 0 --min 6 --max 8

Это применится только для текущего соединения; после переподключения мыши команду нужно будет выполнить снова.

Ещё можно попробовать изменить настройки задержки через debugfs. Смотрите /sys/kernel/debug/bluetooth/hci0/conn__interval> .

This example will solve the lag problems, but you must un pair and pair the mouse:

# echo 0 > /sys/kernel/debug/bluetooth/hci0/conn_latency # echo 6 > /sys/kernel/debug/bluetooth/hci0/conn_min_interval # echo 7 > /sys/kernel/debug/bluetooth/hci0/conn_max_interval

Проблемы с bluetooth-адаптером USB

Если у вас проблемы с адаптером USB, можете попробовать выполнить:

Сейчас вы должны получить устройство hci0 с помощью команды:

Иногда устройство не активируется автоматически. Попробуйте поднять интерфейс с помощью:

и выполнить поиск устройств, как описано выше.

Мышь постоянно отключается

Если мышь перестаёт работать, но снова работает после перезапуска Bluetooth, или постоянно засыпает через несколько секунд неактивности (что случается как минимум с некоторыми модулями Dell XPS 13 [3] [устаревшая ссылка 2022-09-17 ⓘ] ), вам может понадобиться отключить USB autosuspend для выбранного устройства.

Проблема также может быть в таймауте устройства и настройках HID. Смотрите #Проблемы с Thinkpad Bluetooth Laser Mouse.

Если у вас Logitech, проблема может быть решена процедурой, описанной в #Проблемы с Logitech BLE мышами (M557, M590, Anywhere 2 и т.д.).

Проблемы с Thinkpad Bluetooth Laser Mouse

Если у вас Thinkpad Bluetooth Laser Mouse подключается и быстро (спустя несколько миллисекунд) отключается каждые несколько секунд (когда вы её двигаете или нажимаете кнопку), попробуйте выполнить сопряжения с кодом 0000 вместо сопряжения без кода.

Если это не помогло, проблема может быть в настройках таймаута устройство. Измените/создайте файл /etc/bluetooth/input.conf и пропишите в нём следующие изменения:

# Configuration file for the input service # This section contains options which are not specific to any # particular interface [General] # Set idle timeout (in minutes) before the connection will # be disconnect (defaults to 0 for no timeout) IdleTimeout=0 #Enable HID protocol handling in userspace input profile #Defaults to false(hidp handled in hidp kernel module) UserspaceHID=true

Эти изменения предотвратят таймаут устройства, чтобы оно оставалось подключенным. Вторая настройка включает userspace обработку HID. Перезапустите службу bluetooth.service для тестирования изменений. Ещё может понадобиться перезагрузиться и провести повторое сопряжение с устройством.

Проблемы с Kensington Expert Wireless Trackball

Kensington Expert Wireless Trackball имеет частоту опроса по умолчанию в районе 200мс, что создаёт ощутимые задержки. Для исправления добавьте или измените раздел [ConnectionParameters] в файле /var/lib/bluetooth/mac-адрес-адаптера/mac-адрес-мыши/info как показано выше; уменьшите задержку или вообще установите её в 0 .

Проблемы с Logitech BLE мышами (M557, M590, Anywhere 2 и т.д.)

Иногда сопряжение проходит успешно, но мышь не двигается. Устройство нужно добавить в доверенные и разблокировать. Сперва откройте терминал и выполните bluetoothctl

[bluetooth] # remove XX:XX:XX:XX:XX:XX
[bluetooth] # trust XX:XX:XX:XX:XX:XX
[bluetooth] # pair XX:XX:XX:XX:XX:XX
[bluetooth] # connect XX:XX:XX:XX:XX:XX

Если мышь не работает напрямую, выключите и снова включите её.

Иногда бывает нужно загрузить модуль ядра uhid .

Проблемы со всеми BLE мышами на ядра 5.9+

Смотрите также

Источник

Emulate a bluetooth mouse

Is it possible for my computer to pretend it is a bluetooth mouse, so another device can connect to it? An android device allow its mouse to be controlled by bluetooth without rooting it, and my computer have bluetooth, so if I could get them to speek the same language/protocol, I could send mouse-commands from the computer to the android. Is it possible, or am I just dreaming? 🙂

4 Answers 4

I know a project called Master Control which did exactly that: a program would read events from local /dev/input sources and resend those events either via Bluetooth HID profile or via USB using gadgetfs . This could effectively emulate either BT or USB mouse, keyboard or joystick.

The original project was built for ARM, and I’m not sure if the author (Roger Zoellner) has ever released the sources. You may want to ping him about it, so you don’t have to re-implement everything from scratch.

Yes, that’s possible. For example, hidclient allows you to use a Linux PC as a bluetooth keyboard and mouse for another device.

My tablet can see the computer, and its has «Audio» and «Input», but if I try to use it as «Input», it just say its unable to connect 🙁 Any ide how to find out why?

What exactly have you done (step-by-step description of commands used)? Permissions correct for the user that runs the programs? How exactly did you try to use it as input, and what’s the exact error message? What does the syslog say?

any luck getting hidclient to work on ubuntu 16.04? I tried the readme here github.com/benizi/hidclient

I don’t think you are dreaming. I think that this can be done using a programming language like Python , C , etc. For example in Python with a quick search i found this tutorial based on PyBluez: https://people.csail.mit.edu/albert/bluez-intro/c212.html

By the way, May be already available apps could fit your needs. I had been using AirDroid apps a couple of years ago and i was very happy with it since i could browse my android phone by my PC using just WiFi (not cable , not BlueTooth).

PS: AirDroid does not require root access to your phone, you can use your PC Keyboard and mouse and is still available in google play. Unfortunately i can not tell for sure if AirDroid can work with BT or if there are AirDroid BT apps.

Источник

Читайте также:  Настройка bind astra linux
Оцените статью
Adblock
detector