Repository: pkozul/ha-tts-bluetooth-speaker Branch: master Commit: 40c75d4c5d15 Files: 8 Total size: 19.2 KB Directory structure: gitextract_9q7f_eeh/ ├── README.md ├── configuration.yaml └── custom_components/ ├── bluetooth_tracker/ │ ├── __init__.py │ ├── device_tracker.py │ └── manifest.json └── tts_bluetooth_speaker/ ├── __init__.py ├── manifest.json └── media_player.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: README.md ================================================ # TTS Bluetooth Speaker for Home Assistant This project provides a media player (custom component) for Home Assistant that plays TTS (text-to-speech) via a Bluetooth speaker. If you're using HA's Bluetooth device tracker (for presence detection), this project also provides a replacement Bluetooth tracker that allows both components to play nicely together. Since the Bluetooth tracker constantly scans for devices, playback of audio on the Bluetooth speaker may be disrupted / become choppy while scanning. These custom components work together to ensure only one of them is accessing Bluetooth at any given time. The flow is something like this: - Bluetooth tracker component continually scans for devices (presence detection) - TTS service gets called to play something on the Bluetooth speaker - TTS Bluetooth speaker component disables Bluetooth tracker component - Bluetooth tracker component terminates any running Bluetooth scans - TTS Bluetooth speaker component plays the TTS MP3 file - TTS Bluetooth speaker component enables Bluetooth tracker component - Bluetooth tracker component continues scanning for devices (presence detection) ## Getting Started ### 1) Install Pulse Audio (with Bluetooth support), MPlayer and SoX (with MP3 support) ``` sudo apt-get install pulseaudio pulseaudio-module-bluetooth bluez mplayer sox libsox-fmt-mp3 ``` ### 2) Add HA and pi user to 'pulse-access' group (pi user for testing, homeassistant for the service) ``` sudo adduser pi pulse-access sudo adduser homeassistant pulse-access ``` ### 3) Add Bluetooth discovery to Pulse Audio In `/etc/pulse/system.pa`, add the following to the bottom of the file: ``` ### Bluetooth Support .ifexists module-bluetooth-discover.so load-module module-bluetooth-discover .endif #set-card-profile bluez_card.00_2F_AD_12_0D_42 a2dp_sink ``` The last part is to persist the setting for a2dp, in case your bluetooth seems to default to a different profile. I have commented it out because it seems to be flakey. You may want to uncomment this line if your audio is getting cut off: ``` ### Automatically suspend sinks/sources that become idle for too long #load-module module-suspend-on-idle ``` ### 4) Create a service to run Pulse Audio at startup Create the file `/etc/systemd/system/pulseaudio.service` and add the following to it: ``` [Unit] Description=Pulse Audio [Service] Type=simple Environment=DBUS_SESSION_BUS_ADDRESS=unix:path=/run/dbus/system_bus_socket ExecStart=/usr/bin/pulseaudio --system --disallow-exit --disable-shm --exit-idle-time=-1 [Install] WantedBy=multi-user.target ``` Enable the service to start at boot time. ``` sudo systemctl daemon-reload sudo systemctl enable pulseaudio.service ``` Give pulse user access to bluetooth interfaces edit `/etc/dbus-1/system.d/bluetooth.conf` add the following lines: ``` ``` ### 5) Create a script to pair the Bluetooth speaker at startup ``` sudo bluetoothctl scan on pair 00:2F:AD:12:0D:42 trust 00:2F:AD:12:0D:42 connect 00:2F:AD:12:0D:42 quit ``` Create the file `[PATH_TO_YOUR_HOME_ASSSISTANT]/scripts/pair_bluetooth.sh` and add the following to it. Make sure to replace the Bluetooth address with that of your Bluetooth speaker. ``` #!/bin/bash bluetoothctl << EOF connect 00:2F:AD:12:0D:42 EOF ``` Make sure to grant execute permissions for the script. ``` sudo chmod a+x [PATH_TO_YOUR_HOME_ASSSISTANT]/scripts/pair_bluetooth.sh ``` In `/etc/rc.local`, add the following to the end of the file to run the script at startup: ``` # Pair Bluetooth devices [PATH_TO_YOUR_HOME_ASSSISTANT]/scripts/pair_bluetooth.sh exit 0 ``` ### 6) Add the TTS Bluetooth Speaker to HA Copy the TTS Bluetooth Speaker component (from this GitHub repo) and save it to your Home Assistant config directory. ``` custom_components/tts_bluetooth_speaker/media_player.py ``` ### 7) Optional - Add the (new) Bluetooth Tracker to HA This step only applies if you're using the Bluetooth tracker. Copy the Bluetooth Tracker component and save it to your Home Assistant config directory. ``` custom_components/bluetooth_tracker/device_tracker.py ``` ### 8) Validate audio sink is available `pactl list sinks` You should see something like: ``` Sink #1 State: SUSPENDED Name: bluez_sink.00_2F_AD_12_0D_42.a2dp_sink ``` If it instead says headset_head_unit, you can switch to a2dp profile as follows: ``` pactl set-card-profile bluez_card.00_2F_AD_12_0D_42 a2dp_sink ``` Check again and validate it is using a2dp. Test using command line if mplayer can stream to a2dp ``` mplayer -ao pulse::bluez_sink.00_2F_AD_12_0D_42.a2dp_sink -channels 2 -volume 100 /some/mp3file.mp3 ``` ### 9) Start using it in HA By this stage (after a reboot), you should be able to start using the TTS Bluetooth speaker in HA. Below is an example of how the component is configured. You need to specify the Bluetooth address of your speaker, and optionally set the `volume` level (must be between 0 and 1). If you find your speaker is not playing the first part of the audio (i.e. first second is missing when played back), then you can optionally add some silence before and/or after the original TTS audio hsing the `pre_silence_duration` and `post_silence_duration` options (must be between 0 and 60 seconds). If you've change your TTS cache directory (in your TTS config), then you should set the `cache_dir` here to match. ``` media_player: - platform: tts_bluetooth_speaker address: [BLUETOOTH_ADDRESS] # Required - for example, 00:2F:AD:12:0D:42 volume: 0.45 # Optional - default is 0.5 # pre_silence_duration: 1 # Optional - No. of seconds silence before the TTS (default is 0) # post_silence_duration: 0.5 # Optional - No. of seconds silence after the TTS (default is 0) # cache_dir: /tmp/tts # Optional - make sure it matches the same setting in TTS config ``` If you're using the Bluetooth tracker, you probably already have this in your config: ``` device_tracker: - platform: bluetooth_tracker ``` To test that it's all working, you can use **Developer Tools > Services** in the HA frontend to play a TTS message through your Bluetooth speaker: ![image](https://user-images.githubusercontent.com/8870047/57437834-b773ef00-7296-11e9-891e-9a181ebb6520.png) `{ "entity_id": "media_player.tts_bluetooth_speaker", "message": "Hello" }` Another way to test it is to add an automation that plays a TTS message whenever HA is started: ``` automation: - alias: Home Assistant Start trigger: platform: homeassistant event: start action: - delay: '00:00:10' - service: tts.google_translate_say data: entity_id: media_player.tts_bluetooth_speaker message: 'Home Assistant has started' ``` ================================================ FILE: configuration.yaml ================================================ device_tracker: - platform: bluetooth_tracker media_player: - platform: tts_bluetooth_speaker address: 00:2F:AD:12:0D:42 volume: 0.45 # cache_dir: /tmp/tts # Optional - make sure it matches the same setting in TTS config ================================================ FILE: custom_components/bluetooth_tracker/__init__.py ================================================ ================================================ FILE: custom_components/bluetooth_tracker/device_tracker.py ================================================ """ Tracking for bluetooth devices. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/device_tracker.bluetooth_tracker/ """ import logging import os import subprocess import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.core import callback from homeassistant.helpers.event import track_point_in_utc_time from homeassistant.const import STATE_OFF, STATE_STANDBY, STATE_ON from homeassistant.components.device_tracker import ( YAML_DEVICES, CONF_TRACK_NEW, CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL, load_config, PLATFORM_SCHEMA, DEFAULT_TRACK_NEW) from homeassistant.const import ( ATTR_ENTITY_ID) import homeassistant.util.dt as dt_util _LOGGER = logging.getLogger(__name__) BT_PREFIX = 'BT_' DOMAIN = 'device_tracker' ENTITY_ID = 'bluetooth_tracker' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_TRACK_NEW): cv.boolean }) BLUETOOTH_TRACKER_SERVICE_SCHEMA = vol.Schema({ vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, }) BLUETOOTH_TRACKER_SERVICE_TURN_ON = 'bluetooth_tracker_turn_on' BLUETOOTH_TRACKER_SERVICE_TURN_OFF = 'bluetooth_tracker_turn_off' def setup_scanner(hass, config, see, discovery_info=None): """Set up the Bluetooth Scanner.""" # pylint: disable=import-error import bluetooth import bluetooth._bluetooth as bluez hass.states.set(DOMAIN + '.' + ENTITY_ID, STATE_ON) def turn_on(call): """Turn Bluetooth tracker on.""" _LOGGER.info("Turning on Bluetooth") hass.states.set(DOMAIN + '.' + ENTITY_ID, STATE_ON) def turn_off(call): """Turn Bluetooth tracker off.""" _LOGGER.info("Turning off Bluetooth") try: sock = bluez.hci_open_dev(0) bluez.hci_send_cmd(sock, bluez.OGF_LINK_CTL, bluez.OCF_INQUIRY_CANCEL) sock.close() _LOGGER.info("Turned off Bluetooth") hass.states.set(DOMAIN + '.' + ENTITY_ID, STATE_OFF) except Exception as err: _LOGGER.error("Error turning off Bluetooth: %s", err) sock.close() def see_device(device): """Mark a device as seen.""" see(mac=BT_PREFIX + device[0], host_name=device[1]) def discover_devices(): if hass.states.get(DOMAIN + '.' + ENTITY_ID).state != STATE_ON: return [] _LOGGER.debug("Discovering Bluetooth devices") """Discover Bluetooth devices.""" result = bluetooth.discover_devices( duration=8, lookup_names=True, flush_cache=True, lookup_class=False) _LOGGER.debug("Bluetooth devices discovered = " + str(len(result))) return result hass.services.register( DOMAIN, BLUETOOTH_TRACKER_SERVICE_TURN_ON, turn_on, schema=BLUETOOTH_TRACKER_SERVICE_SCHEMA) hass.services.register( DOMAIN, BLUETOOTH_TRACKER_SERVICE_TURN_OFF, turn_off, schema=BLUETOOTH_TRACKER_SERVICE_SCHEMA) # Ensure the Bluetooth tracker is on (if that state has been set) if hass.states.get(DOMAIN + '.' + ENTITY_ID).state == STATE_ON: turn_on(None) yaml_path = hass.config.path(YAML_DEVICES) devs_to_track = [] devs_donot_track = [] # Load all known devices. # We just need the devices so set consider_home and home range # to 0 for device in load_config(yaml_path, hass, 0): # Check if device is a valid bluetooth device if device.mac and device.mac[:3].upper() == BT_PREFIX: if device.track: devs_to_track.append(device.mac[3:]) else: devs_donot_track.append(device.mac[3:]) # If track new devices is true discover new devices on startup. track_new = config.get(CONF_TRACK_NEW, DEFAULT_TRACK_NEW) if track_new: for dev in discover_devices(): if dev[0] not in devs_to_track and \ dev[0] not in devs_donot_track: devs_to_track.append(dev[0]) see_device(dev) interval = config.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) def update_bluetooth(now): """Lookup Bluetooth device and update status.""" try: if track_new: for dev in discover_devices(): if dev[0] not in devs_to_track and \ dev[0] not in devs_donot_track: devs_to_track.append(dev[0]) for mac in devs_to_track: if hass.states.get(DOMAIN + '.' + ENTITY_ID).state != STATE_ON: continue _LOGGER.debug("Scanning %s", mac) result = bluetooth.lookup_name(mac, timeout=5) if not result: # Could not lookup device name continue see_device((mac, result)) except bluetooth.BluetoothError: _LOGGER.exception("Error looking up Bluetooth device") track_point_in_utc_time( hass, update_bluetooth, dt_util.utcnow() + interval) update_bluetooth(dt_util.utcnow()) return True ================================================ FILE: custom_components/bluetooth_tracker/manifest.json ================================================ { "domain": "bluetooth_tracker", "name": "BT Tracker", "documentation": "https://github.com/pkozul/ha-tts-bluetooth-speaker", "dependencies": [], "codeowners": ["@pkozul"], "requirements": ["pybluez==0.22"] } ================================================ FILE: custom_components/tts_bluetooth_speaker/__init__.py ================================================ ================================================ FILE: custom_components/tts_bluetooth_speaker/manifest.json ================================================ { "domain": "tts_bluetooth_speaker", "name": "BT Speaker", "documentation": "https://github.com/pkozul/ha-tts-bluetooth-speaker", "dependencies": [], "codeowners": ["@pkozul"], "requirements": [] } ================================================ FILE: custom_components/tts_bluetooth_speaker/media_player.py ================================================ """ Support for TTS on a Bluetooth Speaker """ import voluptuous as vol from homeassistant.components.media_player import ( SUPPORT_PLAY_MEDIA, SUPPORT_VOLUME_SET, PLATFORM_SCHEMA, MediaPlayerDevice) from homeassistant.const import ( CONF_NAME, STATE_OFF, STATE_PLAYING) import homeassistant.helpers.config_validation as cv try: from ..device_tracker import bluetooth_tracker except ImportError: pass import subprocess import logging import os import re import sys import time DEFAULT_NAME = 'TTS Bluetooth Speaker' DEFAULT_VOLUME = 0.5 DEFAULT_CACHE_DIR = "tts" DEFAULT_SILENCE_DURATION = 0.0 DEFAULT_ADDRESS = '' SUPPORT_BLU_SPEAKER = SUPPORT_PLAY_MEDIA | SUPPORT_VOLUME_SET CONF_ADDRESS = 'address' CONF_VOLUME = 'volume' CONF_CACHE_DIR = 'cache_dir' CONF_PRE_SILENCE_DURATION = 'pre_silence_duration' CONF_POST_SILENCE_DURATION = 'post_silence_duration' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_ADDRESS, default=DEFAULT_ADDRESS): cv.string, vol.Optional(CONF_VOLUME, default=DEFAULT_VOLUME): vol.All(vol.Coerce(float), vol.Range(min=0, max=1)), vol.Optional(CONF_PRE_SILENCE_DURATION, default=DEFAULT_SILENCE_DURATION): vol.All(vol.Coerce(float), vol.Range(min=0, max=60)), vol.Optional(CONF_POST_SILENCE_DURATION, default=DEFAULT_SILENCE_DURATION): vol.All(vol.Coerce(float), vol.Range(min=0, max=60)), vol.Optional(CONF_CACHE_DIR, default=DEFAULT_CACHE_DIR): cv.string, }) _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the Bluetooth Speaker platform.""" name = config.get(CONF_NAME) address = config.get(CONF_ADDRESS) volume = float(config.get(CONF_VOLUME)) pre_silence_duration = float(config.get(CONF_PRE_SILENCE_DURATION)) post_silence_duration = float(config.get(CONF_POST_SILENCE_DURATION)) cache_dir = get_tts_cache_dir(hass, config.get(CONF_CACHE_DIR)) add_devices([BluetoothSpeakerDevice(hass, name, address, volume, pre_silence_duration, post_silence_duration, cache_dir)]) return True def get_tts_cache_dir(hass, cache_dir): """Get cache folder.""" if not os.path.isabs(cache_dir): cache_dir = hass.config.path(cache_dir) return cache_dir class BluetoothSpeakerDevice(MediaPlayerDevice): """Representation of a Bluetooth Speaker on the network.""" def __init__(self, hass, name, address, volume, pre_silence_duration, post_silence_duration, cache_dir): """Initialize the device.""" self._hass = hass self._name = name self._is_standby = True self._current = None self._address = address self._volume = volume self._pre_silence_duration = pre_silence_duration self._post_silence_duration = post_silence_duration self._cache_dir = self.get_tts_cache_dir(cache_dir) self._tracker = 'custom_components.device_tracker.bluetooth_tracker' in sys.modules _LOGGER.debug('Bluetooth tracker integration: {}'.format(str(self._tracker))) def get_tts_cache_dir(self, cache_dir): """Get cache folder.""" if not os.path.isabs(cache_dir): cache_dir = hass.config.path(cache_dir) return cache_dir def update(self): """Retrieve latest state.""" if self._is_standby: self._current = None else: self._current = True @property def name(self): """Return the name of the device.""" return self._name # MediaPlayerDevice properties and methods @property def state(self): """Return the state of the device.""" if self._is_standby: return STATE_OFF else: return STATE_PLAYING @property def supported_features(self): """Flag media player features that are supported.""" return SUPPORT_BLU_SPEAKER @property def volume_level(self): """Volume level of the media player (0..1).""" return self._volume def set_volume_level(self, volume): """Set volume level, range 0..1.""" # self._vlc.audio_set_volume(int(volume * 100)) self._volume = volume def play_media(self, media_type, media_id, **kwargs): """Send play commmand.""" _LOGGER.info('play_media: %s', media_id) self._is_standby = False media_file = self._cache_dir + '/' + media_id[media_id.rfind('/') + 1:]; sink = 'pulse::bluez_sink.' + re.sub(':', '_', self._address) + '.a2dp_sink' volume = str(self._volume * 100) pre_silence_file = "" post_silence_file = "" media_file_to_play = media_file if (self._pre_silence_duration > 0) or (self._post_silence_duration > 0): media_file_to_play = "/tmp/tts_{}".format(os.path.basename(media_file)) if (self._pre_silence_duration > 0): pre_silence_file = "/tmp/pre_silence.mp3" command = "sox -c 1 -r 24000 -n {} synth {} brownnoise gain -50".format(pre_silence_file, self._pre_silence_duration) _LOGGER.debug('Executing command: %s', command) subprocess.call(command, shell=True) if (self._post_silence_duration > 0): post_silence_file = "/tmp/post_silence.mp3" command = "sox -c 1 -r 24000 -n {} synth {} brownnoise gain -50".format(post_silence_file, self._post_silence_duration) _LOGGER.debug('Executing command: %s', command) subprocess.call(command, shell=True) command = "sox {} {} {} {}".format(pre_silence_file, media_file, post_silence_file, media_file_to_play) _LOGGER.debug('Executing command: %s', command) subprocess.call(command, shell=True) if self._tracker: self._hass.services.call(bluetooth_tracker.DOMAIN, bluetooth_tracker.BLUETOOTH_TRACKER_SERVICE_TURN_OFF, None) while self._hass.states.get(bluetooth_tracker.DOMAIN + '.' + bluetooth_tracker.ENTITY_ID).state == bluetooth_tracker.STATE_ON: _LOGGER.debug('Waiting for Bluetooth tracker to turn off') time.sleep(0.5) command = "mplayer -ao {} -quiet -channels 2 -volume {} {}".format(sink, volume, media_file_to_play); _LOGGER.debug('Executing command: %s', command) subprocess.call(command, shell=True) if (self._pre_silence_duration > 0) or (self._post_silence_duration > 0): command = "rm {} {} {}".format(pre_silence_file, media_file_to_play, post_silence_file); _LOGGER.debug('Executing command: %s', command) subprocess.call(command, shell=True) if self._tracker: self._hass.services.call(bluetooth_tracker.DOMAIN, bluetooth_tracker.BLUETOOTH_TRACKER_SERVICE_TURN_ON, None) self._is_standby = True