Home assistant подключение bluetooth колонки

Добавляем поддержку BLE (bluetooth) устройств в Home Assistant

В последней публикации из своей трилогии я расскажу, как добавить поддержку Bluetooth устройств в умный дом на Home Assistant, а также напомню способ установки кастомных компонентов.

Translation to English is here . Также основной канал в telegram .

Первая часть заключалась в том, что я описал купленный стик:

Во второй части я описал как добавить поддержку сервисов Bluetooth в Linux, если таковой у Вас еще нет:

И вот — настало время все соединить воедино. Как я уже объяснил в прошлой статье, на сайте Home Assistant есть как минимум три интеграции, но они нам не нужны. Мы будем использовать интеграцию Passive BLE Monitor integration . Она себя зарекомендовала и множество (тысячи) пользователей установили ее себе и отметили ее на GitHub звездой.

Есть 2 способа установить эту интеграцию: а) Через HACS: писал про это тут:

б) Создаем рядом с файлом конфигурации Home Assistant папку custom_components и копируем в него интеграцию прямо с GItHub из этой папки .

Для копирования файлов на сервер очень удобно использовать ftp. Как его настроить, например, на Windows — писал тут:

1. Копируем файлы в папку или ставим из HACS (↑ описано выше ↑).

2. Далее перезагружаем HA и переходим в интеграции и набираем в поиске BLE. Если пункт №1 выполнен правильно, то найдется интеграция Passive BLE monitor

3. Выберем ее и нажмем «установить»

4. Как только установка закончится, появится менюшка. Если Bluetooth адаптер настроен верно, то мы увидим его в списке ниже(hcl0). Проверим что на нем стоит галка.

4. Я дополнительно установил галку на пункте «авто рестарт», но не уверен, что это требуется — скорее перестраховался.

5. После того, как я нажал кнопку «ок», в квартире мгновенно нашлись 4 устройства. Все устройства были от Xiaomi.

6. Нажимаем «финиш». Интеграция отображается в общем списке. Также показываются устройства и сущности.

Читайте также:  Touch screen radio with bluetooth

7. Давайте нажмем на «устройства»:

8. Давайте нажмем на сущности:

Устройства заведенные в HA таким образом работают точно также как и WiFi или ZigBee устройства. За 2 недели у меня не было пока никаких проблем ни с одним из них. Не требуются никакие сопряжения устройств и прочие танцы с бубном, что я нахожу очень удобным. Всем добра!

Подпишитесь , чтобы не пропускать следующий контент.
Нажмите лайк , если интересно, так я пойму какие публикации больше нужны моей публике.
Также публикации можно найти на других площадках: Instagram , telegram ( RU , EN , DE ), Medium , LiveJournal , YouTube .

Мой блог является некоммерческим, поэтому позитивный комментарий, лайк или репост поможет публикациям выходить чаще ☺.

Источник

Using Bluetooth Speaker and White noise with Home Assistant

So since the child was born my wife had this idea that we need white noise in bedroom. I’ve made a quick dirty implementation with small speakers + usb-bluetooth AUX adapter and Android phone connected over bluetooth.

Problem being that if you had to stop/start or change volume you had to carry phone with you (and charge it) or keep it on charger constantly and reach over to it to change sounds and volume.

I was looking into solution from my Smart Home standpoint — a way to play using Home Assistant . I had some experience using MPD and PI MusicBox with playing radio stations on my Rpi Zero W, but it was too laggy for 1 CPU.

I recommend reading GUIDE for detailed instructions on installation. I will just provide high level guide.

Building all pre-requesites (checklist)

We would need few tools/packages for it to work:

Installing bluez

If you don’t have already — grab latest distributive (or one that is known to be bug-free) from http://www.bluez.org. (Follow GUIDE for details)

Installing bluealsa

For me bluealsa was not available as a package so I had to grab a source code, compile and install it. After that I had to create service to be able to start it with os and control it:

[Unit] Description=BluezALSA proxy Requires=bluetooth.service After=bluetooth.service [Service] Type=simple User=root ExecStart=/usr/bin/bluealsa --device=hci0 

Checking your bluetooth hardware

Check if your adapter is connected and is up and working:

hciconfig list hciconfig hci0 -a sudo hciconfig hci0 up 

Connecting speaker and testing it:

You would need to use bluetoothctl utility in order for all bluetooth-pairing stuff.

list # lists your BT devices select # select your BT device (adapter) power on agent on scan on # find your device mac in list scan off pair trust connect exit 

Check if everything is ok:

aplay -D bluealsa:HCI=hci,DEV=,PROFILE=a2dp /usr/share/sounds/alsa/Front_Center.wav 

If you can hear sound continue.

Читайте также:  Пропал звук блютуз наушниках

Now let’s save this speaker for permanent use inside /etc/asound.conf so you would not need to specify it each time you play music:

pcm.!default < type asym playback.pcm "btspeaker" >pcm.btspeaker < type plug slave.pcm < type bluealsa device "00:11:22:33:44:55" profile "a2dp" >hint < show on description "My Bluetooth Speaker" >> 

if everything goes fine you can run script and hear music:

aplay -D bluealsa:DEV=,PROFILE=a2dp /usr/share/sounds/alsa/Rear_Left.wav 

Installing mopidy

If you are lucky enough and have latest installation of OS, you can try (and probably would be sucesfull):

Otherwise you can visit my Mopidy installation and issues article and do.

pip2 install --upgrade --force-reinstall mopidy==2.1.0 

Troubleshooting

Check logs before doing anything — it would give you hints on what’s wrong:

journalctl -u bluetooth -b journalctl -u bluealsa -b journalctl -u mopidy -b dmesg -w 

a2dp-sink profile connect failed for : Protocol not available

Reason: bluealsa not started properly, or is misconfigured

If you have more than one bluetooth adapter (or even if you have one, just to be sure) put device parameter into bluealsa.service . See installing bluealsa section for example.

To find out which adapter id to use — list them using

/usr/bin/bluealsa: E: Couldn’t release transport: GDBus.Error:org.freedesktop.DBus.Error.UnknownObject: Method “Release” with signature “” on interface “org.bluez.MediaTransport1” doesn’t exist

I just restart bluealsa here — usually it helps.

“Operation not possible due to RF-kill (132)” or something is fishy with adapter

1) I would check if it’s not blocked with rfkill application. Unblock it if it was blocked:

rfkill list all rfkill unblock

restart your bluealsa and bluetooth services.

Bluetooth device is disconnected after some timeout if no music is playing

I ended up using this script to re-connect (thankfully bluetoothctl can be ran as bash script):

#!/usr/bin/env bash sudo bluetoothctl disconnect sudo bluetoothctl agent off sudo bluetoothctl power off sleep 3 sudo bluetoothctl power on sudo bluetoothctl agent on sudo bluetoothctl connect 00:11:22:33:44:55 

New tracks added to mopidy local folder cannot be played

Run local scan and restart mopidy (without restart it would not see those tracks):

sudo mopidyctl local scan systemctl restart mopidy 

also ensure that your media files belong to mopidy:audio user and group.

Tracks are not looped

mpc single on mpc repeat on 

Integrating into Home Assistant

First — you need to configure Media player (mopidy in our case) — this would allow us to control speaker:

media_player: - platform: mpd name: mopidy host: 127.0.0.1 port: 6600 

If you want to play local tracks (for white noise for example) — copy them to /var/lib/mopidy/media/white_noise .

Читайте также:  Bluetooth connect and play app

Add to config file (for example track that is located in folder /var/lib/mopidy/media/white_noise/cat.m4a):

 mopidy_white_noise_cat: sequence: - service: media_player.play_media data: entity_id: media_player.mopidy media_content_type: music media_content_id: local:track:white_noise/cat.m4a 

If you want to listen to radio stations — you can also configure like this:

 mopidy_stream_rock: sequence: - service: media_player.play_media data: entity_id: media_player.mopidy media_content_type: audio/mpeg media_content_id: http://live.radioec.com.ua:8000/rock.m3u 

Also remember the script from troulbeshooting part? I’ve also added it as a button:

shell_command: restart_white_noise: /opt/white_noise/restart_speaker.sh 

Источник

Bluesound

The bluesound platform allows you to control your Bluesound HiFi wireless speakers and audio integrations from Home Assistant.

To manually add a Bluesound device to your installation, add the following to your configuration.yaml file:

# Example configuration.yaml media_player: - platform: bluesound hosts: - host: 192.168.1.100 

Configuration Variables

List with your Bluesound devices.

The IP address or hostname of the player.

The name of the device used in the frontend.

The port to communicate with the device.

Advanced configuration example

# Example configuration.yaml entry with manually specified addresses media_player: - platform: bluesound hosts: - host: 192.168.1.100 name: bluesound_kitchen port: 11000 - host: 192.168.1.131 

Service bluesound.join

Group players together under a single master speaker. That will make a new group or join an existing group.

Service data attribute Optional Description
master no A single entity_id that will become/hold the master speaker.
entity_id no String or list of a single entity_id that will group to master speaker.

Service bluesound.unjoin

Remove one or more speakers from a group of speakers. If no entity_id is provided, all speakers are unjoined.

Service data attribute Optional Description
entity_id yes String or list of entity_id s that will be separated from their master speaker.

Service bluesound.set_sleep_timer

Sets a timer that will turn off the speaker. For each time you call this it will increase the time by one step. The steps are (in minutes): 15, 30, 45, 60, 90, 0. If you increase an ongoing timer of for example 13 minutes, it will increase it to 15. If the timer is set to 90, it will remove the time (hence the 0).

Service data attribute Optional Description
entity_id no String or list of entity_id s that will have their timers set.

Service bluesound.clear_sleep_timer

Clear the sleep timer on a speaker, if one is set.

Service data attribute Optional Description
entity_id no String or list of entity_id s that will have their timers cleared.

Help us to improve our documentation

The Bluesound integration was introduced in Home Assistant 0.51, and it’s used by 260 active installations. Its IoT class is Local Polling.

Categories

On this page

Источник

Оцените статью
Adblock
detector