- Android TV
- Device preparation
- Configuration
- Configuration Variables
- Full Configuration
- ADB Setup
- 1. Python ADB Implementation
- 2. ADB Server
- ADB Troubleshooting
- Services
- media_player.select_source
- androidtv.adb_command
- androidtv.learn_sendevent (for faster ADB commands)
- androidtv.download and androidtv.upload
- Custom State Detection
- Сервер для HomeAssistant на бывшей Android TV приставке
- Media Player: управляем SmartTV и Kodi через HomeAssistant
- Подключение приставки на Android (AndroidTV)
- Подключение Kodi
- Плейлисты в Kodi
- Автоматизация на основе контента Kodi
Android TV
The androidtv platform allows you to control an Android TV device or Amazon Fire TV device.
When setting up this integration, it is recommended that you do NOT use an ADB server and instead use the built-in Python ADB implementation. This simplifies the setup and makes it easier to troubleshoot issues. If there are stability issues with this approach, then you may wish to try using an ADB server. See the ADB Setup section for more information.
Device preparation
To set up your device, you will need to find its IP address and enable ADB debugging. For Android TV devices, please consult the documentation for your device.
For Fire TV devices, the instructions are as follows:
- Turn on ADB Debugging on your Amazon Fire TV:
- From the main (Launcher) screen, select Settings.
- Select My Fire TV > Developer Options.
- Select ADB Debugging.
- Find Amazon Fire TV device IP address:
- From the main (Launcher) screen, select Settings.
- Select My Fire TV > About > Network.
Configuration
Configuration Variables
The IP address for your Android TV / Fire TV device.
The friendly name of the device.
The port for your Android TV / Fire TV device.
The path to your adbkey file; if not provided, Home Assistant will generate a key for you (if necessary).
The IP address of the ADB server. If this is provided, the integration will utilize an ADB server to communicate with the device.
The port for the ADB server.
Whether or not to retrieve the running apps as the list of sources.
A dictionary where the keys are app IDs and the values are app names that will be displayed in the UI; see example below. If a name is not provided, the app will never be shown in the sources list. (These app names are configured in the backend package and do not need to be included in your configuration.)
If this is true, then only the apps you specify in the apps configuration parameter and those specified in the backend library will be shown in the sources list.
The type of device: auto (detect whether it is an Android TV or Fire TV device), androidtv , or firetv .
A dictionary whose keys are app IDs and whose values are lists of state detection rules; see the section Custom State Detection for more info.
An ADB shell command that will override the default turn_on command.
An ADB shell command that will override the default turn_off command.
Determines if album art should be pulled from what is shown onscreen.
Full Configuration
ADB Setup
This integration works by sending ADB commands to your Android TV / Fire TV device. There are two ways to accomplish this.
1. Python ADB Implementation
The default approach is to connect to your device using the adb-shell Python package. As of Home Assistant 0.101, if a key is needed for authentication and it is not provided by the adbkey configuration option, then Home Assistant will generate a key for you.
Prior to Home Assistant 0.101, this approach did not work well for newer devices. Efforts have been made to resolve these issues, but if you experience problems then you should use the ADB server option.
2. ADB Server
The second option is to use an ADB server to connect to your Android TV and Fire TV devices.
Using this approach, Home Assistant will send the ADB commands to the server, which will then send them to the Android TV / Fire TV device and report back to Home Assistant. To use this option, add the adb_server_ip option to your configuration. If you are running the server on the same machine as Home Assistant, you can use 127.0.0.1 for this value.
ADB Troubleshooting
If the setup for your Android TV or Fire TV device fails, then there is probably an issue with your ADB connection. Here are some possible causes.
You have the wrong IP address for the device.
ADB is not enabled on your device.
You are already connected to the Android TV / Fire TV via ADB from another device. Only one device can be connected, so disconnect the other device, restart the Android TV / Fire TV (for good measure), and then restart Home Assistant.
You need to approve the ADB connection; see the note in the ADB Setup section above.
Some Android TV devices (e.g., Philips TVs running Android TV) only accept the initial ADB connection request over their Wi-Fi interface. If you have the TV wired, you need to connect it to Wi-Fi and try the initial connection again. Once the authentication has been granted via Wi-Fi, you can connect to the TV over the wired interface as well.
If your device drops off WiFi, breaking the ADB connection and causing the entity to become unavailable in Home Assistant, you could install a wake lock utility (such as Wakelock) to prevent this from happening. Some users have reported this problem with Xiaomi Mi Box devices.
If you are using the Python ADB implementation approach, as mentioned above, there may be some issues with newer devices. In this case, you should use the ADB server approach instead.
Services
media_player.select_source
You can launch an app on your device using the media_player.select_source command. Simply provide the app ID as the source . You can also stop an app by prefixing the app ID with a ! . For example, you could define scripts to start and stop Netflix as follows:
androidtv.adb_command
The service androidtv.adb_command allows you to send either keys or ADB shell commands to your Android TV / Fire TV device. If there is any output, it will be stored in the ‘adb_response’ attribute (i.e., state_attr(‘media_player.android_tv_living_room’, ‘adb_response’) in a template) and logged at the INFO level.
Service data attribute | Optional | Description |
---|---|---|
entity_id | no | Name(s) of Android TV / Fire TV entities. |
command | no | Either a key command or an ADB shell command. |
In an action of your automation setup it could look like this:
Available key commands include:
The full list of key commands can be found here.
You can also use the command GET_PROPERTIES to retrieve the properties used by Home Assistant to update the device’s state. These will be stored in the media player’s ‘adb_response’ attribute and logged at the INFO level. This information can be used to help improve state detection in the backend androidtv package, and also to define your own custom state detection rules.
A list of various intents can be found here.
androidtv.learn_sendevent (for faster ADB commands)
When sending commands like UP, DOWN, HOME, etc. via ADB, the device can be slow to respond. The problem isn’t ADB, but rather the Android command input that is used to perform those actions. A faster way to send these commands is using the Android sendevent command. The challenge is that these commands are device-specific. To assist users in learning commands for their device, the Android TV integration provides the androidtv.learn_sendevent service. Its usage is as follows:
Service data attribute | Optional | Description |
---|---|---|
entity_id | no | Name(s) of Android TV / Fire TV entities. |
- Call the androidtv.learn_sendevent service.
- Within 8 seconds, hit a single button on your Android TV / Fire TV remote.
- After 8 seconds, a persistent notification will appear that contains the equivalent command that can be sent via the androidtv.adb_command service. This command can also be found in the adb_response attribute of the media player in Home Assistant, and it will be logged at the INFO level.
As an example, a service call in a script could be changed from this:
androidtv.download and androidtv.upload
You can use the androidtv.download service to download a file from your Android TV / Fire TV device to your Home Assistant instance.
Service data attribute | Optional | Description |
---|---|---|
entity_id | no | Name of Android TV / Fire TV entity. |
device_path | no | The filepath on the Android TV / Fire TV device. |
local_path | no | The filepath on your Home Assistant instance. |
Similarly, you can use the androidtv.upload service to upload a file from Home Assistant instance to Android TV / Fire TV devices.
Service data attribute | Optional | Description |
---|---|---|
entity_id | no | Name(s) of Android TV / Fire TV entities. |
device_path | no | The filepath on the Android TV / Fire TV device. |
local_path | no | The filepath on your Home Assistant instance. |
Custom State Detection
The Android TV integration works by polling the Android TV / Fire TV device at a regular interval and collecting a handful of properties. Unfortunately, there is no standard API for determining the state of the device to which all apps adhere. Instead, the backend androidtv package uses three of the properties that it collects to determine the state: audio_state , media_session_state , and wake_lock_size . The correct logic for determining the state differs depending on the current app, and the backend androidtv package implements app-specific state detection logic for a handful of apps. Of course, it is not feasible to implement custom logic for each and every app in the androidtv package. Moreover, the correct state detection logic may differ across devices and device configurations.
The solution to this problem is the state_detection_rules configuration parameter, which allows you to provide your own rules for state detection. The keys are app IDs, and the values are lists of rules that are evaluated in order. Valid rules are:
- ‘standby’ , ‘playing’ , ‘paused’ , ‘idle’ , or ‘off’
- If this is not a map, then this state will always be reported when this app is the current app
- If this is a map, then its entries are conditions that will be checked. If all of the conditions are true, then this state will be reported. Valid conditions pertain to 3 properties (see the example configuration above):
- ‘media_session_state’
- ‘audio_state’
- ‘wake_lock_size’
- ‘media_session_state’ = try to use the media_session_state property to determine the state
- ‘audio_state’ = try to use the audio_state property to determine the state
Источник
Сервер для HomeAssistant на бывшей Android TV приставке
Случайно обнаружил данное сообщество.
В силу работы и увлечений, я тоже близок к нему. Почитал все, мало, но понравилось, решил внести свою лепту.
Весь пост будет по части сервера HA.
Когда решил поставить дома IOT, появился вопрос, какой и где будет сервер. Облака сразу отмёл, так как при прекращении инета работа устройств под сомнением, плюс часто, привязка к вендору. Хотя и свои удобства у данного сервера есть.
Читал-читал — остановился на HomeAssistant (в связке с ESPHome). Только по моему мнению — система самая удобная и функциональная.
Правда до сих пор не могу конфигурировать панель для пульта ИК телевизора, но это вопрос времени.
Так как работаю в основном в *NIX системах, привык к их подходу — программа должна выполнять только свою функцию но выполнять ее хорошо.
В связи с подходом — не приобретаю SmartTV. Дома только обычные TV + Smart приставка. Устаревает приставка — меняю на новую, до 4К телевизора — у меня нет контента, что бы регулярно его смотреть, поэтому FullHD телек остается.
К тому времени, как я увлекся IOT, пара приставок, отслуживших свой срок уже валялась, и при выборе сервера для HA, я ими заинтересовался.
Одной из последних, рабочих, оказалась noname X96. В схему особо вписалось, что питание у нее 5В DC.
Так как дома практически везде Linux, на нее был найден и установлен порт armbian. Дальше, по обычному гайду для Debian, установлен HA. Добавлена карта памяти на 64Гб с того же Ali для логов в шатный разъем. Получилось малопотребляющее устройство, при этом, достаточно мощное (для своих целей, нагрузка на процессор не превышает 30%). Дополнительное удобство было в потреблении этой приставкой 5В .
Так как серверу необходимо непрерывное питание, был закуплен на Ali корпус для Powerbank, за 200 руб, на 6 мест 18650, плюс, эти 6*18650*3,4 АЧ. Не помню точную сумму, но не более 2000 руб обошелся мне этот бесперебойник. Запитывается от от зарядника даво почившего смартфона.
Дополнительно, пропилил «крышу» приставки и установил на нее вентилятор от древнего ноута, который подключен прямо к питанию X96.
В такой конфигурации бесперебойника (
20АЧ), «сервер» HA работает более 24 часов без внешнего электричества (задолбался проверять, оставалось 15% на момент прекращения эксперимента, если отключить вентилятор, то и поболее будет).
На данный момент ищу недорогую и хорошую антену для WiFi, что бы подпаять ее вместо встроенной в X96 и использовать именно ее для WiFi IOT. Понятно, что «бесперебойника» хватит на меньшее время, но будет, думаю, правильнее — не надо поддерживать питание внешнего роутера и свича.
Источник
Media Player: управляем SmartTV и Kodi через HomeAssistant
К сожалению, телевизор у меня не «умный» ни разу, в нём не то, что бы SmartTV, вообще никаких интерфейсов нет. Логичным шагом в своё время стала покупка ТВ-бокса с Android на борту. На бокс был установлен медиа-комбайн Kodi, установленный лончером по умолчанию, кроме которого, в общем-то, запускается только YouTube. Вот такой аскетизм.
И вот пришла пора всем этим рулить из HomeAssistant.
Подключение приставки на Android (AndroidTV)
Для управления медиасистемами в HomeAssistant предусмотрена штатная интеграция Media Player . Тем, у кого, например, Philips или Samsung — повезло больше, поскольку созданы отдельные компоненты под телевизоры этих марок, для всех остальных — есть штатная реализация Media Player под Android TV (которая, в общем-то, работает и с обычным Android).
Первое, что нам нужно для подключения — это знать IP-адрес нашей коробочки. Второе — убедиться, что с сервера, на котором крутится HomeAssistant, наша коробочка доступна и слушается через adb:
Если сервер начнёт ругаться, что не знает команду adb — нужно поставить библиотеки. Для Ubuntu это выглядит так:
sudo apt-get install android-tools-adb
Если соединение прошло успешно — можно настраивать плагин (в configuration.yaml):
media_player:
— platform: androidtv
host: !secret tvbox_ip
adb_server_ip: 127.0.0.1
name: TV BOX
apps:
«kodi»: «Kodi»
«com.liskovsoft.videomanager»: «YouTube»
, здесь tvbox_ip — адрес нашей коробочки, adb_server_ip — адрес сервера, с которого мы подключаемся к боксу через adb, name — название устройства, которое будет отображаться в HomeAssistant, apps — список приложений, названия которых будут отображаться в карточке Media Player (у меня в качестве YouTube используется приложение Smart YouTube TV с телевизионным интерфейсом). Список apps нужен в первую очередь для того, чтобы превратить длинные наименования приложений в короткие и понятные названия, которыми проще будет оперировать при управлении и создании автоматизаций.
После создания конфигурации и перезапуска HomeAssistant можно добавить карточку MediaPlayer к себе на панель управления:
Кроме стандартной карточки проигрывателя есть ещё кастомный плагин Mini Media Player с широкими возможностями. Эти возможности и примеры карточек можно увидеть на странице плагина на GitHub . Я вынес кнопки в отдельную панель и сейчас моя карточка выглядит так:
Подключение Kodi
Интеграция Media Player, кроме управления устройствами, имеет возможность управлять отдельными распространёнными приложениями, : iTunes, Spotify, Plex или Kodi. Все виды интеграций можно посмотреть тут , меня же интересует (пока что) только Kodi .
Чтобы подключить Kodi, нужно активировать в настройках Kodi доступ через веб-интерфейс, а затем прописать доступ в configuration.yaml:
media_player:
— platform: kodi
host: !secret kodi_ip
port: !secret kodi_port
Перезапускаем HomeAssistant и добавляем стандартную карточку:
Или кастомный плагин:
Плейлисты в Kodi
Зачем вообще городить Kodi отдельно от общего Android TV? Плагин для Kodi умеет больше, чем общий плагин для управления боксами — он определяет источник медиа (музыка, сериалы, фильмы), показывает обложки, позволяет синхронизировать медиатеку из HomeAssistant и всякое другое.
Мне в первую очередь от плагина нужен был запуск музыки из панели управления, чтобы не вставать лишний раз в поисках пульта. Делается это с помощью сервиса media_player.play_media.
Поскольку плейлистов у меня организовано никогда не было а музыку я запускал исключительно по исполнителю, то первым моим шагом было создание отдельных папок с исполнителями на диске, откуда играется музыка и вызов сервиса play_media с указанием папки, откуда играть. У такого подхода есть существенный минус — при запуске проигрывателя сначала вся папка сканируется и собирается плейлист, что создаёт большую задержку между нажатием кнопки и, собственно, музыкой.
Я отказался от такого подхода и решил собрать смарт-плейлисты. Вкратце: смарт-плейлисты в Kodi — это фильтры, с помощью которых из всей медиатеки выбирается нужная музыка, например, по исполнителю, по ключевым словам или по любому другому параметру. Недостаток смарт-плейлистов тот же, что и при проигрывании папки с музыкой — чем больше музыки попадает под фильтры, тем больше времени нужно для подготовки плейлиста при каждом запуске.
В итоге я пришёл к старым добрым традиционным плейлистам, в которые я занёс самостоятельно все нужные мне композиции и сохранил в формате m3u.
Подход для запуска любого их вышеперечисленных способов одинаковый: я создал объект input_select c перечнем всех плейлистов и при выборе одного из них передавал название плейлиста в автоматизацию в виде переменной.
Объект input_select создаётся в меню Настройки — Вспомогательное — Выпадающий список:
Задаём название, иконку и добавляем опции — названия плейлистов. Важно! Плейлисты надо задавать именно в том виде, в каком они хранятся в хранилище Kodi. Одна неверная буква или лишний пробел — и плейлист запускаться не будет.
Следующий этап: создать автоматизацию запуска плейлиста при выборе одного из значений (в automations.yaml):
— alias: Играть
platform: state
entity_id: input_select.pleilist
action:
service: media_player.play_media
data_template:
entity_id: media_player.kodi
media_content_type: DIRECTORY
media_content_id: «special://profile/playlists/music/<< states('input_select.pleilist') >>.m3u»
Теперь достаточно добавить на панель в любое удобное место наш выпадающий список:
И готово, при выборе плейлиста он запускается. Аналогичным способом можно запускать любое медиа из файла (подставить нужные пути в media_content_id) или отдельными методами Kodi.
Впрочем, с тех пор как у меня дома поселилась Алиса, я слушаю музыку с Яндекс.Станции, а не через Kodi, так что эта автоматизация у меня тоже теперь закомментирована до лучших времён. Про Алису, разумеется, тоже будет отдельная статья, возможно и не одна.
Автоматизация на основе контента Kodi
Ещё одна причина, по которой стоит отдельно настроить Kodi, если вы его используете — определение типа воспроизведения для создания автоматизации. Например, включение интимного освещения при запуске кино или что-нибудь ещё при включении музыки.
Моя автоматизация для режима «кино» (automations.yaml):
— alias: Время для фильма
trigger:
— platform: state
entity_id: media_player.kodi
to: ‘playing’
condition:
— condition: state
state: ‘below_horizon’
— condition: or
conditions:
— condition: template
value_template: ‘<< states.media_player.kodi.attributes.media_content_type == "tvshow" >>’
— condition: template
value_template: ‘<< states.media_player.kodi.attributes.media_content_type == "movie" >>’
action:
— service: script.cinema
Тут самое сложное — это разобраться с условиями (conditions). Триггер срабатывает, когда состояние media_player.kodi переходит в playing и выполнены условия: солнце за горизонтом (зачем нам свет включать, если и так светло?) и (media_content_type = tvshow или media_content_type = movie). Условия в HomeAssistant записываются именно так, с этим ничего не поделать. Когда срабатывает триггер — запускается action, в моём случае заранее заданный скрипт (scripts.yaml):
sequence:
— service: remote.send_command
data:
entity_id: remote.broadlink
device: Ceiling
command: Darken
num_repeats: 10
Поскольку у меня пока управлять особо нечем, то режим «кино» подразумевает просто убавление яркости потолочного светильника до минимума. При первой же возможности куплю торшер и переделаю автоматизацию на выключение потолочного светильника и включение торшера. Ну или ещё чего-нибудь.
На этом всё. Шер, лайк, подписки, комментарии. Бложик я веду не ради монетизации, но всё равно приятно знать, что кто-то читает и интересуется.
Источник