- Заряд аккумулятора блютус устройств. Как посмотреть?
- Проверьте уровень заряда батареи подключенного устройства Bluetooth на Linux
- 8 ответов
- Arch Linux
- #1 2018-04-24 13:32:17
- Bluetooth Headset Battery Status
- #2 2018-08-11 07:58:06
- Re: Bluetooth Headset Battery Status
- #3 2018-08-11 14:44:36
- Re: Bluetooth Headset Battery Status
- #4 2018-08-13 05:34:48
- Re: Bluetooth Headset Battery Status
- Check battery level of connected bluetooth device on linux
- 9 Answers 9
Заряд аккумулятора блютус устройств. Как посмотреть?
Подскажите, каким образом можно посмотреть заряд аккумулятора в блютус устройстве? В андроиде готовых приложений — вагон и маленькая вагонетка, а вот в 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, установлен сам и к оному библиотека. Документацию доустановил, но толку не дало.
Тогда если тебе только посмотреть, то, похоже, не судьба.
Если ты решителен и хочешь добавить поддержку нового устройства несмотря ни на что, то придется освоить много нового и интересного, но я сам этого никогда не делал и особо не помогу.
Источник
Проверьте уровень заряда батареи подключенного устройства 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, сделайте это.
Длинный ответ , но это скорее рекомендуемая отправная точка:
- Тони Д: https://youtu.be/5fQR2PHMDWE?t=4644 удалось использовать << X0>> для чтения атрибутов и отправки данных на устройство Bluetooth. Обязательно проверьте видео информацию, вы найдете отличные ссылки и ссылки: https: / /learn.adafruit.com/introduction-to-bluetooth-low-energy/gatt
- Сжимон Янк: 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 .
Из командной строки:
- Подключитесь к целевому BLE-устройству с помощью bluetoothctl
- А затем запросите 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
Источник
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.
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.
I think you can find the same info that I did without too much Googling given the above.
Источник
Check battery level of connected bluetooth device on linux
How can I check the battery level of a connected bluetooth device? The device shows the battery level on Android so I’m assuming the device supports the GATT-based Battery Service. However, by entering «menu gatt» in bluetoothctl and then listing the GATT attributes of the device with «list-attributes [dev]», nothing shows up.
A similar question was posted to SO but the OP seems to have found a solution that doesn’t work for me. When I run «info [dev]» in bluetoothctl I don’t see the UUID for Battery Service.
I would prefer a solution that runs on the command line and is distro-agnostic.
Please let me know if this question should be posted on SuperUser instead.
9 Answers 9
This might be a bit late to the party but for me this Python project has worked fine:
I only had to change the port in line 57 to 3 for my no-name X5 headset. If it hangs or errors with «connection refused» try a different port.
The Python program uses AT commands via RFCOMM and should work while Pulseaudio is using the A2DP sink (mine reconnects). Python 3 is needed as 2 doesn’t have BT-Serial sockets. Windows will probably not work as it lacks bluez. It basically does the same thing as the Pulseaudio hack here: https://stackoverflow.com/a/56390625/920122
If you want to look at the commands as they are exchanged, try my debug fork: https://github.com/clst/Bluetooth_Headset_Battery_Level
This is such a great question, ahead of development and tools that are available at the moment.
The short answer (in October 2018)
you have to write it yourself! It won’t be a one liner in the terminal. I am going to write this for myself in Python, but C has a little more documentation, so if you are skilled with C go for it.
The long answer, but it’s more a recommended starting point:
- Tony D: https://youtu.be/5fQR2PHMDWE?t=4644 managed to use bluetoothctl to read attributes and send data to a bluetooth device. Definitely check the video information, you will find great links and references: https://learn.adafruit.com/introduction-to-bluetooth-low-energy/gatt
- Szymon Janc: https://youtu.be/VMDyebKT5c4 developer and contributer to the LINUX Bluetooth Stack
Definitely check out how this question is answered on Mobile devices. For Android it’s the BAS (Battery Service): https://android.stackexchange.com/questions/106073/displaying-bluetooth-gadgets-battery-status-on-the-phone
You don’t see Battery Level in the list of GATT characteristics since Bluez v5.48 because this specific GATT characteristic was moved into DBUS org.bluez.Battery1 interface.
From the command line:
- Connect to your target BLE device with bluetoothctl
- And then request DBUS by running: dbus-send —print-reply=literal —system —dest=org.bluez /org/bluez/hci0/dev_ org.freedesktop.DBus.Properties.Get string:»org.bluez.Battery1″ string:»Percentage»
In my case with my BLE peripheral with the following MAC address C3:41:A6:C8:93:42 :
Note: You could potentially scan and connect to your device using Bluez DBUS API.
For me running this in terminal worked- upower —dump
Here is a way to get battery level via pulseaudio logs with some hack. My bluetooth headset uses proprietary Apple HFP AT commands, HFP/A2DP protocols are handled by pulseaudio directly. It seems the only way to get those values is through pulse.
By default Bluez ‘hides’ the Battery Service UUID. This is because there is a ‘battery plugin’ loaded at startup of bluetoothd.
If you don’t want the battery plugin to be activated and make the Battery Service UUID visible again to bluetoothctl or any other application, then change the startup command for bluetoothd to be like this: ‘bluetoothd -P battery’. That will make sure the battery plugin is not loaded. On a Raspberry Pi the bluetooth.service is located in /lib/systemd/system/bluetooth.service so you need to make the change in that file.
(This answer is specific to headphones/headsets)
I’d been using the Python program from clst’s answer for some time and although it worked, it required me to connect, then disconnect and run it again. If I understand the problem correctly, that happens because only one program can open a socket to talk to the bluetooth device, so it ends up fighting with PulseAudio over it.
I’ve recently found out about hsphfpd.
hsphfpd is specification with some prototype implementation used for connecting Bluetooth devices with HSP and HFP profiles on Linux operating system.
Basically, since only one program can communicate with the headset at once and it wouldn’t make sense to implement battery level reporting in an audio server, nor implement audio in a power management software, it moves that functionality to an external daemon. That way, PulseAudio and whatever can both use the headset at the same time. There is a version of PulseAudio patched to use hsphfpd. Even though these are both still prototypes, they seem to work very well.
hsphfpd reports battery status (and other stuff) through DBus, so to get it from the command line, you can just do
or even call it from a program.
Both of these are available in the AUR, if you use Arch Linux.
Источник