Linux bluetooth headphones battery level

Заряд аккумулятора блютус устройств. Как посмотреть?

Подскажите, каким образом можно посмотреть заряд аккумулятора в блютус устройстве? В андроиде готовых приложений — вагон и маленькая вагонетка, а вот в GNU/Linux системах я не нашел, ни приложений, ни консольных вариантов.

Видел у местных на скриншотах такое. В гнум3 точно есть, за KDE не ручаюсь.

Он обычно либо виден через upower, либо нет.

19 минт cinnamon.

Если можно, подробнее.

Есть стандартный фреймворк для отображения заряда всего, что можно. У меня он показывает заряд двух батарей ноутбука и bluetooth-клавиатуры производства еще покойной Palm.

Графические смотрелки есть как минимум в комплекте с GNOME и XFCE.

Выполни, пожалуйста, команду upower -d с подключенными устройствами и покажи вывод (например выложив на pastebin). Также укажи модели устройств, заряд которых пытаешься выяснить.

bluetooth-клавиатуры производства еще покойной Palm.

Херасе. Дай посмотреть, аж интересно стало

Есть стандартный фреймворк для отображения заряда всего, что можно

Главное, чтобы само устройство желало отдавать такую информацию. У меня есть очень дешевая bluetooth-клавиатура производства defender, и она никакую информацию не отдает. Но судя по ее устройству, она когда-то была клавиатурой на одноразовых батарейках, а потом китайцы сбоку приделали к ней литий-ионный аккумулятор со своим собственным контроллером заряда.

Естественно, но только вот батарейки или нет — не решающий фактор, та пальмовая как раз на батарейках.

Выполни, пожалуйста, команду upower -d с подключенными устройствами и покажи вывод (например выложив на pastebin).

Также укажи модели устройств, заряд которых пытаешься выяснить.

Наушники(Гарнитура) SVEN SEB-B270MV

  • [NEW] Controller B0:35:9F:08:76:B7 X-System [default]
  • [NEW] Device 20:13:08:12:03:3B Bluetooth Mouse
  • [NEW] Device 00:00:00:07:32:B7 SVEN SEB-B270MV
  • Agent registered
  • [CHG] Device 20:13:08:12:03:3B Connected: yes
  • [SVEN SEB-B270MV ]#

Графические смотрелки есть как минимум в комплекте с GNOME и XFCE.

Беглый поиск по синаптику ничего не дал, кроме того что к upower, установлен сам и к оному библиотека. Документацию доустановил, но толку не дало.

Тогда если тебе только посмотреть, то, похоже, не судьба.

Если ты решителен и хочешь добавить поддержку нового устройства несмотря ни на что, то придется освоить много нового и интересного, но я сам этого никогда не делал и особо не помогу.

Источник

Arch Linux

You are not logged in.

#1 2018-04-24 13:32:17

Bluetooth Headset Battery Status

I want to get the battery status from my Bluetooth headset.
It seems it does not support the GATT-Profile, but my android phone shows the battery status (LinageOS and Stock 8.1).

Its a: «Marshall Monitor Bluetooth» witch is advertised with «Bluetooth v4.0 aptX».

I connected it using «A2DP» and it plays the music without any problems:

using bluetoothctl (Version 5.49).

If GATT is found there should be more output from the Device (says: https://docs.ubuntu.com/core/en/stacks/ … t-services ).
But this is all i got.

info gives me this:

I assume the UUID’s are services/features of the device. But there is no «Battery Service».
I read that there are some proprietary ways to submit the battery status, but when android it get’s it should be possible for me as well, or?

I’am tring on gathering more information’s about these services.
With D-Feet I find some interfaces of the device, but now I’am stuck and don’t know what i can do next.

Читайте также:  Менеджер файлов windows это

Here a Screenshot of D-Feet: https://ibb.co/mzcKPH


So any ideas are appreciated

#2 2018-08-11 07:58:06

Re: Bluetooth Headset Battery Status

I’ve just looked into this way too much and while you probably don’t care at this point and I don’t have a firm answer yet, let me tell you what I’ve found out in case anyone else wants to take a look.

I’m guessing Android is using the hands free profile to get battery information. According to Wikipedia the Hands free protocol supports sending battery information and there is a spec sheet that seems to confirm it (https://www.bluetooth.org/docman/handle … _id=292287). I’m still very unclear about a bunch of how bluetooth works, but I’m going to be continuing to pursue this a bit and so maybe I’ll be able to update with more information.

#3 2018-08-11 14:44:36

Re: Bluetooth Headset Battery Status

You may look into Wireshark. It now handles Bluetooth traffic and has a nice protocol analyzer to allow you to see what are being transmitted and received.

Nothing is too wonderful to be true, if it be consistent with the laws of nature — Michael Faraday
Sometimes it is the people no one can imagine anything of who do the things no one can imagine. — Alan Turing

How to Ask Questions the Smart Way

#4 2018-08-13 05:34:48

Re: Bluetooth Headset Battery Status

As promised I did some more searching. Actually a lot more searching.

I’ve found 4 ways to get battery levels only one of which works on my headphones.

* GATT
* Hands Free AG
* A/V Remote Control Target
* And the one that worked: Headset AG with apple specific command

The search started with finding that the Hands Free Profile can report battery info. To find out if my device supported it I had to write a python script with Bluez’s d-bus integration. to get my headphones connect so I could log the info. I went through implementing a lot of the connection procedure before I realized that my device didn’t support the relevant feature.

The A/V Remote Control Target should also in theory support devices reporting battery level, but I don’t think my device supports it. I didn’t go into much detail to confirm though.

The headset profile was pure luck though. I was looking at Wireshark and happened to see

. I’d missed it before because it was only sent when first connecting, but a bit after the initial negotiation. The Bluetooth headset profile doesn’t support battery reporting, but it looks like Apple has their own command for iphones. It seems that in recent version Android supports it too. If you want to interact with it through code though you may have problems since PulseAudio implements their own support for this profile. I have to confess now that I’m not actually on Arch at the moment, so I’m not sure what the config for the Arch version looks like, but for me I had to compile from source with the

set. This means there won’t be any support for pulse audio hooking into the volume control on the device. I don’t really care, but you might.

If anyone else wants any info about this I’d be happy to share, but I suspect the interest isn’t probably all that great.

Читайте также:  Hack ios kali linux

I think you can find the same info that I did without too much Googling given the above.

Источник

Проверьте уровень заряда батареи подключенного устройства Bluetooth на Linux

Как я могу проверить уровень заряда батареи подключенного устройства Bluetooth? Устройство показывает уровень заряда батареи в Android, поэтому я предполагаю, что устройство поддерживает Служба батарей на основе GATT. Однако после ввода «menu gatt» в bluetoothctl и последующего перечисления атрибутов GATT устройства с помощью «list-attribute [dev]» ничего не появляется.

A аналогичный вопрос был отправлен на SO, но ОП, кажется, нашел решение, которое не работает для меня. Когда я запускаю «info [dev]» в bluetoothctl, я не вижу UUID для обслуживания батареи.

Я бы предпочел решение, которое работает в командной строке и является дистроагностичным.

Пожалуйста, дайте мне знать, если этот вопрос должен быть размещен на SuperUser вместо.

8 ответов

Это может быть немного поздно для вечеринки, но для меня этот проект Python работал нормально:

Мне нужно было только изменить порт в строке 57 на 3 для моей безымянной гарнитуры X5. Если он зависает или ошибки с «отказано в соединении», попробуйте другой порт.

Программа Python использует AT-команды через RFCOMM и должна работать, пока Pulseaudio использует приемник A2DP (мои переподключения). Python 3 необходим, так как 2 не имеет BT-Serial сокетов. Windows, вероятно, не будет работать, так как ей не хватает bluez. Он в основном делает то же самое, что и взлом Pulseaudio здесь: https://stackoverflow.com/a/56390625/920122

Если вы хотите посмотреть на команды, которыми они обмениваются, попробуйте мой ответвление: https://github.com/clst / Bluetooth_Headset_Battery_Level

Вот способ получить уровень заряда батареи с помощью журналов pulseaudio с помощью некоторого хака. Моя Bluetooth-гарнитура использует запатентованные команды Apple HFP AT, протоколы HFP / A2DP обрабатываются с помощью pulseaudio напрямую. Кажется, что единственный способ получить эти значения — через импульс.

В версии bluez вы можете использовать экспериментальные атрибуты Gatt. Если вам нужно включить экспериментальные характеристики, запустив команду bluetoothd deamon по ключевому слову -E, как «/ usr / libexec / bluetooth / bluetoothd -E», это сработало для меня.

По умолчанию Bluez «скрывает» UUID службы батареи. Это связано с тем, что при запуске bluetoothd загружается «плагин батареи».

Если вы не хотите, чтобы плагин батареи активировался и чтобы UUID службы батареи снова становился видимым для bluetoothctl или любого другого приложения, измените команду запуска для bluetoothd следующим образом: «bluetoothd -P battery». Это позволит убедиться, что плагин батареи не загружен. На Raspberry Pi служба bluetooth.service находится в /lib/systemd/system/bluetooth.service, поэтому вам нужно внести изменения в этот файл.

Как сказано выше @OlivierM, UUID фильтруется через bluetoothd. Вы можете отменить это и экспортировать UUID так же, как любые другие характеристики сервиса, удалив следующее из функции export_service() в src/gatt-client.c

Это такой большой вопрос, опережающий разработку и инструменты, которые доступны на данный момент.

Краткий ответ (в октябре 2018 года)

ты должен написать это сам! Это не будет один лайнер в терминале. Я собираюсь написать это для себя на Python, но у C есть немного больше документации, так что если вы разбираетесь в C, сделайте это.

Длинный ответ , но это скорее рекомендуемая отправная точка:

  1. Тони Д: https://youtu.be/5fQR2PHMDWE?t=4644 удалось использовать << X0>> для чтения атрибутов и отправки данных на устройство Bluetooth. Обязательно проверьте видео информацию, вы найдете отличные ссылки и ссылки: https: / /learn.adafruit.com/introduction-to-bluetooth-low-energy/gatt
  2. Сжимон Янк: https://youtu.be/VMDyebKT5c4 разработчик и участник Bluetooth-стека LINUX

Определенно . Узнайте, как на этот вопрос отвечают мобильные устройства. Для Android это BAS (Battery Battery): https: // android.stackexchange.com/questions/106073/displaying-bluetooth-gadgets-battery-status-on-the-phone

Вы не видите Уровень заряда батареи в списке характеристик GATT начиная с Bluez v5.48, потому что эта особая характеристика GATT была перемещена в Интерфейс DBUS org.bluez.Battery1 .

Из командной строки:

  1. Подключитесь к целевому BLE-устройству с помощью bluetoothctl
  2. А затем запросите DBUS, запустив: dbus-send —print-reply=literal —system —dest=org.bluez /org/bluez/hci0/dev_ org.freedesktop.DBus.Properties.Get string:»org.bluez.Battery1″ string:»Percentage»

В моем случае с моим периферийным устройством BLE со следующим MAC-адресом C3:41:A6:C8:93:42 :

Примечание. Вы можете сканировать и подключаться к своему устройству с помощью API Bluez DBUS.

Для меня запуск этого в терминале работал upower —dump

Источник

Linux bluetooth headphones battery level

🔋 🎧 Bluetooth Headset Battery Level

This is a python script to fetch the battery charge level of some Bluetooth headsets.

You need python 3.6 or newer to run the script.

There are three options:

Option 1: Install from PyPI

Please ensure you have the BlueZ and python libraries and header files if you are using Ubuntu/Debian based distros:

If you are using OpenSUSE, you will need to install bluez , bluez-devel , python3-devel , python3-pybluez

Then, install with pip:

You can input addresses for as many devices as you want separated by space.

the dependency pybluez should be installed automatically, but if not, you may need to install it manually

Option 2: Download this repository

make sure you have python-pybluez or python3-pybluez or python3-bluez installed on your system.

Option 3: Docker

You must have docker installed on your system. Clone the repository using git clone command. Then run:

Once the build is complete you can use the below command to run the program:

There is also a GNOME extension for integrating this program with GNOME desktop environment: https://extensions.gnome.org/extension/3991/bluetooth-battery/

Finding MAC address

There are a variety of utilities that can find the MAC address of your bluetooth device. Here is one, this command is in the bluez package, and the given argument gets a list of all devices it knows about, even if not currently available.

The 1st and 3rd would be relevant here, as those are headsets.

This shows devices that are actually connected.

to query the battery of all connected devices.

You can set the port number manually by adding a dot at the end of mac address, like this: 00:00:00:00:00:00.3

Try port numbers 1 to 30 to find the one that works for your device. (wait a few seconds between each try)

If that didn’t work, disconnect your device first, and then try again.

Still doesn’t work?

Please consider that this script doesn’t guarantee to support every bluetooth device.

You can open a new issue for discussion or check the existing ones for more information.

  • ArchLinux (5.6.14)
  • NixOS 20.09 (20.09.2386.ae1b121d9a6)
  • Debian GNU/Linux (bullseye 5.9)
  • Ubuntu/Linux (Focal Fossa 20.04.1)

Special thanks to:

@clst: For spreading the word!

@bhepple: For his research on fixing the important bug

@balsoft: For thinking outside the box (finding my big mistake)

@martin-beran: For making it easy to set the port number

@Bobo1239: For adding support for Samsung galaxy buds

@keystroke3: For adding multiple device support to the script

@jadia: For docker container support

@cheriimoya: For refactoring the code and providing NixOS packages

@MichalW: For making the GNOME shell extension

❤️ And everyone else that pointed out the issues or helped me with writing the code or testing it.

This project is a free software licensed under GPL-3.0 or newer. For more information see LICENSE

About

A python script to get battery level from Bluetooth headsets

Источник

Читайте также:  Radeon x300se драйвер windows 10
Оцените статью