Bluetooth Speakers Pulseaudio Bluez VLC, Disconnecting resolved, jack and bluetooth output, Hassbian bluetoothctl

Hi

Thought I’d post this as it took a while to find the relevant files to have success and have my Bluetooth speakers staying permanently connected for tts and playing media on my Pi3 with Hass. I am now using Bluetooth and the audio jack with amplified speakers and can connect to either speakers with tts or to play media via shell_command

Lisited below is the process I followed, I ran in this order but if your getting disconnection issues and have your bluetooth connected (pulse/bluez, possibly others), you may want to jump straight to the emojis and the file changes for bluetooth for the ones you have… although some of the stuff listed below may have helped my connection…

I started with a backup of my Hassbian as an image via Win32Diskimager, I’ve been stung before with loss of the work on my config. As it turned out in the end I did restore back to my previous image and starting again to get everything working. WinSCP is invaluable for quick editing of system files. I also backed up all my .homeassistant folder and all config files, just in case.

I followed the great guide here first;

https://github.com/pkozul/ha-tts-bluetooth-speaker

After that made sure I ran sudo apt-get update and sudo apt-get upgrade before continuing.

I uninstalled sudo apt-get remove bluez and reinstalled installed latest Bluez from instructions here;

https://learn.adafruit.com/install-bluez-on-the-raspberry-pi/installation

Uninstalled and reinstalled pulseaudio sudo apt-get remove pulseaudio sudo apt-get install pulseaudio and installed volume control for pulse audio sudo apt-get install pavucontrol

I also installed this if memory serves; sudo apt-get install alsa-utils bluez-tools pulseaudio-module-bluetooth
the last module was already installed in the instructions in the first post above

Not sure if it changed anything but I uninstalled and reinstalled vlc-nox, I also installed omxplayer.

sudo apt-get remove vlc-nox
sudo apt-get install vlc-nox
sudo apt-get install omxplayer

Ran this for vlc;

    sudo usermod -a -G audio homeassistant

This was important
sudo chmod a+x /home/homeassistant/.homeassistant/scripts/pair_bluetooth.sh
(thats the directory my file is installed).

I have this in /etc/sudoers file (for the time being but I will close this down to the files as needed for media);

#includedir /etc/sudoers.d
hass ALL=(ALL) NOPASSWD: ALL

This was useful for checking sinks were working with bluetooth and my card;

pactl list short sinks

(mine lists two sinks, one for the Alsa card and one for the Bluez bluetooth speaker followed by the Mac address of connected speaker)

:grimacing::face_with_raised_eyebrow::rofl::disappointed_relieved:
These files below were all the ones I altered to ensure Bluetooth stayed connected and I haven’t seen any issues with this (make sure that the instructions are followed in the post for the bluetooth tts speaker above for the Bluetooth speaker address to automatically connect to the Pi and the relevant permissions for that script have been run, I installed the files/folders from the post in my same directory with my .yaml 's- .homeassistant).
Listed is the file name and the section I altered, the rest of the file content was left alone, then re saved all;
.

/etc/pulse/system.pa
disable the module loading with # in front of load-module;

# Automatically suspend sinks/sources that become idle for too long
#load-module module-suspend-on-idle

.
this shoulod have already been added at the base of this file;
.
### Bluetooth Support

    .ifexists module-bluetooth-discover.so
    load-module module-bluetooth-discover
    .endif

.
.

/etc/pulse/daemon.conf
change these;

#changed below from 20 to -1 for both
; exit-idle-time =-1
; scache-idle-time =-1

.
.

/lib/systemd/system/bluetooth.target

change from yes to no;

    StopWhenUnneeded=no

.
.

/etc/bluetooth/input.conf

changed to this;

IdleTimeout=0

.

.
/etc/bluetooth/main.conf

added;
AutoConnect=true
.
.

/etc/pulse/default.pa

disable load-module with # in front;

### Automatically suspend sinks/sources that become idle for too long
#removed below#
#load-module module-suspend-on-idle

.
and add this in at the base if not there;

load-module module-switch-on-connect
# load system wide configuration
.include /etc/pulse/default.pa

.
.
and ensure this file was created as part of the tts guide/post
.
etc/systemd/system/pulseaudio.service
.

    [Unit]
    Description=Pulse Audio

    [Service]
    Type=simple
    ExecStart=/usr/bin/pulseaudio --system --disallow-exit --disable-shm --exit-idle-time=-1

    [Install]
    WantedBy=multi-user.target

.

This was helpful to understand pulse audio;

https://wiki.archlinux.org/index.php/PulseAudio

hcidump [-i hciX] was good for Bluetooth status (I kept encountering something like ‘disconnected by local host’ when monitoring the Bluetooth connection (before altering all the files)

Volume can be controlled from, with the up/down arrows;

alsamixer

I’m sure I probably didn’t need to alter all the files but I have a great consistent connection.

Bluetoothctl

For the Bluetooth control I made sure I trusted the device when pairing and used the following to access the bluetooth; $ bluetoothctl

Options once in;

         [bluetooth]#agent on
         [bluetooth]#default-agent

List devices;

           [bluetooth]#power on
           [bluetooth]#discoverable on
           [bluetooth]#pairable on           
           [bluetooth]#scan on

Devices come up with mac addresses, you need to copy/paste the one you want and try to to work it out if not obvious- this is the address you need in the files in the post at the beginning and for your .yaml

Then connect to your chose output (copy and paste MAC);

          [bluetooth]#trust xx:xx:xx:xx:xx:xx
          [bluetooth]#pair xx:xx:xx:xx:xx:xx
          [bluetooth]#connect xx:xx:xx:xx:xx:xx

[bluetooth]#info
was useful to see connection/trust/pair status.
.

exit
to exit bluetoothctl

More info on #bluetoothctl here;

https://www.npmjs.com/package/bluetoothctl

For info my configuration.yaml;

  media_player:
    - platform: vlc
      name: speaker_1
      arguments: '--alsa-audio-device=hw:0,0'
      #volume: 0.8  
    - platform: tts_bluetooth_speaker
      address: xx:xx:xx:xx:xx:xx  [Your MAC Address]
      volume: 0.8                 
      pre_silence_duration: 1
      post_silence_duration: 0.5    
      cache_dir: /tmp/tts         

  tts:
    platform: google
    cache: true
    cache_dir: /tmp/tts
    time_memory: 300

Initially I had the above ‘speaker_1’ media player set as; arguments: ‘–alsa-audio-device=plughw:0,1 as this was detailed in some other post as being potentially better via an interface but that didn’t work for the jack speakers as well, I believe my final config is direct; arguments: '--alsa-audio-device=hw:0,0'
As I was using the alsa card as well as bluetooth behind SSL I made sure this was included in my http in confiuration.yaml.

http:
  base_url: https://your https address (no need for port number)

I’m running some shell scripts to call media and automatons for tts notifications (it reads the temp when the heating turns on/off and weather), its driving everyone mad in the house with everything notified! I’ll hone this down in time, although the Muppets theme tune will probably stay… it suits the kids :crazy_face:

I hope this helps someone and saves time as it took me quite some time to get this sorted and remember it for this :neutral_face:

3 Likes

Thank you so much for your teaching. I will try this evening and keep you updated.
Further question, did you use wireless or lan for this hassbian when you attached to bluetooth speaker

Best regards,
Sun

No worries, no im not using wifi, only lan, sorry

1 Like

hmmm. Thank you very much again. I will try anyway. I’m using wifi ^^

o.O’ This time bluez error.

I reinstalled Bluez from the adafruit guide if you haven’t may be worth a go. I have it working with all the file changes but it you were patient enough some of those may not be needed.

Hi friend,
I followed the guide and was able to configure my low-cost bluetooth speakers, visible on home assistant (media_player.tts_bluetooth_speaker).
This a month ago. Now after updating home assistant (my version was very old 52.0) at the current 81.6 improvisation I no longer see the add-on and I have the following error: Error doing job: Task exception was never retrieved
File “/home/homeassistant/.homeassistant/custom_components/media_player/tts_bluetooth_speaker.py”, line 183, in <module>
self._is_standby = True
NameError: name ‘self’ is not defined
I enclose the complete log.

Error doing job: Task exception was never retrieved

Traceback (most recent call last):
File "/usr/lib/python3.5/asyncio/tasks.py", line 241, in _step
result = coro.throw(exc)
File "/srv/homeassistant/lib/python3.5/site-packages/homeassistant/setup.py", line 56, in async_setup_component
return await task  # type: ignore
File "/usr/lib/python3.5/asyncio/futures.py", line 380, in __iter__
yield self  # This tells Task to wait for completion.
File "/usr/lib/python3.5/asyncio/tasks.py", line 304, in _wakeup
future.result()
File "/usr/lib/python3.5/asyncio/futures.py", line 293, in result
raise self._exception
File "/usr/lib/python3.5/asyncio/tasks.py", line 239, in _step
result = coro.send(None)
File "/srv/homeassistant/lib/python3.5/site-packages/homeassistant/config_entries.py",   line 444, in async_forward_entry_setup
self.hass, component, self._hass_config)
File "/srv/homeassistant/lib/python3.5/site-packages/homeassistant/setup.py", line 45, in     async_setup_component
return await setup_tasks[domain]  # type: ignore
File "/usr/lib/python3.5/asyncio/futures.py", line 382, in __iter__
return self.result()  # May raise too.
File "/usr/lib/python3.5/asyncio/futures.py", line 293, in result
raise self._exception
File "/usr/lib/python3.5/asyncio/tasks.py", line 239, in _step
result = coro.send(None)
File "/srv/homeassistant/lib/python3.5/site-packages/homeassistant/setup.py", line 118, in _async_setup_component
conf_util.async_process_component_config(hass, config, domain)
File "/srv/homeassistant/lib/python3.5/site-packages/homeassistant/config.py", line 760,  in async_process_component_config
platform = get_platform(hass, domain, p_name)
File "/srv/homeassistant/lib/python3.5/site-packages/homeassistant/loader.py", line 60, in  get_platform
return get_component(hass, PLATFORM_FORMAT.format(domain, platform))
File "/srv/homeassistant/lib/python3.5/site-packages/homeassistant/loader.py", line 92, in  get_component
module = importlib.import_module(path)
File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 673, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/home/homeassistant/.homeassistant/custom_components/media_player /tts_bluetooth_speaker.py", line 183, in <module>
self._is_standby = True
NameError: name 'self' is not defined

Until a month ago everything worked now no more and I just updated homeassistant.
Please help

You probably need to read thru’ all the breaking changes between 0.52.0 and 0.81.6 to determine where the error is. It could be that the python code you are using is not compatible with the newer versions of HA.

today i try to downgrade to version 0.52.0 ant not work. ssl work, automations and sensor work but TTS Bluetooth Speaker give me same error. Any ideas? Is possible Phyton 3.5 (i updated when i updated HA). How i downgrade Phyton?

I’ve no idea how you downgrade python, but maybe @dingleydell can help?