GithubHelp home page GithubHelp logo

jefflirion / python-androidtv Goto Github PK

View Code? Open in Web Editor NEW
157.0 157.0 57.0 744 KB

Communicate with an Android TV or Fire TV device via ADB over a network.

License: MIT License

Python 97.48% Makefile 1.54% Shell 0.98%
adb androidtv firetv python

python-androidtv's Introduction

python-androidtv

Build Status

Coverage Status

Downloads

Contributions Only

I no longer have the time to actively work on this project, and so all future development will be from pull requests submitted by the community. What I will do is:

  • review pull requests that pass all of the CI checks
  • publish new releases upon request

About

Documentation for this package can be found at https://androidtv.readthedocs.io.

androidtv is a Python package that provides state information and control of Android TV and Fire TV devices via ADB. This package is used by the Android TV integration in Home Assistant.

Installation

pip install androidtv

To utilize the async version of this code, you must install into a Python 3.7+ environment via:

pip install androidtv[async]

ADB Intents and Commands

A collection of useful intents and commands can be found here (credit: mcfrojd).

Acknowledgments

This is based on python-firetv by happyleavesaoc and the androidtv component for Home Assistant by a1ex4, and it depends on the Python packages adb-shell (which is based on python-adb) and pure-python-adb.

python-androidtv's People

Contributors

a1ex4 avatar aav7fl avatar achupryn avatar agneevx avatar apaperclip avatar bdraco avatar deviant-aut avatar diosdog avatar glassbase avatar grimpy avatar imduffy15 avatar jefflirion avatar jeffresc avatar jherby2k avatar kevin-kraus avatar lolouk44 avatar martomo avatar matejdro avatar nortonko avatar ofalvai avatar ollo69 avatar ppanagiotis avatar raman325 avatar sergeknystautas avatar shawnheide avatar stephengoodall avatar thezoker avatar tungmeister avatar victor4x avatar vlebourl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-androidtv's Issues

Nokia Streaming Box 8000 (Android 10) not working ... ?!

Hi all,

I know, this library is set to "contribution only" - and I cannot expect a fix "soon"... but maybe, someone will have an idea and can support with my issues?

I do have an Nokia Streaming Box 8000 - which is using Andorid 10.
Unfortunately, on HomeAssistant, the MediaPlayer component is not able to change the input source - nor to show any other state than "idle"...

I can switch the Box on / and off... but that's all :-(
When I play something, that won't be shown on the mediaplayer...

I've already reported an issue in the HA Core:
home-assistant/core#90360 ...

I am already testing some "remote control" cards - and these are working... and after going through the issues here, I saw, most cases have been reported for Android 11 or 12...

Since I am completely new to this whole Android TV stuff, any step by step support would be much appreciated :)

MiBox power issue (maybe other devices as well?)

When I use the HA media_player.turn_off or off button on the card, my MiBox(es) go into some "deep?" sleep where they drop off the network (cannot ping, cannot power on via ADB / HA).

Yet if I use the power button on the remote, the box goes to sleep, but does not drop the network connection and therefore, can be controlled via HA / ADB.
(I have 4 MiBox and happens for all)

** does this issue belong here or over at HA github?

Missing connection state awareness results in endless connection attempt loops (Android TV powered off) and log flooding

I discovered the same as this user here, unfortunately it seems he didn't raise an issue in this repo as recommended at the end of the issue:

Android TV integration very chatty in log when configured Android TV device is not available (turned off)
home-assistant/core#69672
(here the problem is already described)

Problem: python-androidtv constantly (every 80 seconds) trys to connect to the tv. If it is powered off, it will go on like forever. On every failed connect attempt an error is written to the log. This floods logs pretty fast pretty heavily.

This is what Home Assistant log contains for ONE single failed connection attempt:

Logger: androidtv.adb_manager.adb_manager_async
Source: /usr/local/lib/python3.9/site-packages/androidtv/adb_manager/adb_manager_async.py:298
First occurred: 30. Mai 2022, 16:21:17 (1445 occurrences)
Last logged: 00:50:11

Couldn't connect to xxx.xxx.xxx.xxx:5555. TcpTimeoutException: Connecting to xxx.xxx.xxx.xxx:5555 timed out (1.0 seconds)

This is what HA's GUI presents:
grafik

The experts from HA (see referenced issue) told this is nothing HA can fix but this only can to be done in this library repo.

By the way: Not related to #15

Toshiba Fire TV

Support for embedded Fire TV units such as insignia and toshiba where the fire tv version controls the input select etc... its embedded.

Looking for support or insight to control On/Off and Input changes...

Different versions of Android TV / Fire TV - help with adb commands for this project

I am not super familiar with adb commands needed for this project other than what I have quickly read in the current issue of Android TV 9 (vs 10) vs 11.

Would it beneficial for this project for everyone with different devices and OSes to run certain commands to help build out the required commands required to parse out data?

What would those commands be?

Just myself - I have Mi Box 3 with OS 8, Mi Box 3 with OS 9. Shield 2019 with OS 9, Onn with OS 10, random Fire TV devices with OS 5, 6, 7.

Thanks @JeffLIrion for all the hard work on this over the years, been using since it was a beta component.

Wake on LAN

Started using HA Android TV component after I bought my new Android TV a week ago.

Reading through the HA community forum revealed that many users have issues with waking the TV from sleep because the adb connection is terminated when the TV is powered off

Same goes for my TV but it does support wake on LAN. Unfortunately though the component does not support that but it would be a nice addition.

Change scan interval

Since 2022.2 with automatic configuration via UI seem to have lost ability to change scan_interval in homeassistant. Would be nice to be able to change this attribute as the default is too long.

Why does the firetv platform allow you to get a list of apps and launch an app but the androidtv platform doesn't?

Hi,

Curious as to why the FireTV class supports getting a list of apps as well as launching an app, but the AndroidTV class does not? Per some googling, ps -A | grep u0_a will get you a list of running apps on any Android device (similar to what you are using for the FireTV platform), and pm list packages -f | sed -e 's/.*=//' | sed 's/\r//g' | sort (found here: https://gist.github.com/davidnunez/1404789#gistcomment-1220924) will get you a list of all apps, whether running or not. Both of these lists could be filtered using your static app list to determine a list of available media apps to launch. I also tested the monkey adb shell command monkey -c android.intent.category.LAUNCHER -p com.netflix.ninja 1 on my Shield and that successfully launched Netflix.

Also, can you explain why you are looking at running apps instead of all installed apps? Just trying to understand the motivation behind it.

Thanks in advance!

Select source does not work after boot

The media_player.select_source on my Fire TV does only work after I opened any application. So right after starting the device, this does not have any affect. When I start netflix for example, I can then also start spotify and all other applications.
I'm not sure of this is a issue of the library or is a bug on the Fire TV itself.
Same applies when the device is in Idle mode (screensaver on the Fire TV).

Maybe someone can test this and we can narrow it down.

Android TV 12 devices not working properly

Hello.

After my Chromecast with Google TV received an update from Android 10 to Android 12 the state of the device is always only "off".
ADB commands seems to be working at least for me however the key states like idle, playing, paused, etc. does not. Automations depends on those.

This is common issue for Android 12 devices, other users already reported this in different threads for example:
home-assistant/core#80555
home-assistant/core#79154

@ollo69 recommends the issue should be opened here instead of HA/core as this problem is inside AndroidTV library.

@JeffLIrion Could you please check this issue?
If you need logs or something let me know I can collect and provide them once I am home.

ADB连接

ABD一般都不开启了 意思是需要数据线连接吗

FireTV Cube Unable to Retrieve List of Running Apps

FireTV Cube running Fire OS 7.2.4.2
In Home Assistant, the Source List in the Media Card only shows the current running App.
I had the same problem with a FireTV Stick (which I no longer use).

In my looking around at the code, what I think is the problem is the ADB Shell command
that FireTV uses (from constants.py):

#: Get the running apps for a Fire TV device
CMD_RUNNING_APPS_FIRETV = "ps | grep u0_a"

When I change this to the following (which is the same as for the Android Device):

#: Get the running apps for a Fire TV device
CMD_RUNNING_APPS_FIRETV = "ps -A | grep u0_a"

The running Apps list is actually retrieved!!!

Key Command Request - NOT AN ISSUE

Hi, any chance you can add an "ESC" key command?, my android tv box only exits running apps via the return key on the traditional remote, or esc key on a keyboard.

Thanks
image
image

Want to try

Please start try and error forum / topin in community so that thiscan be discussed,
I want to try
but dont know the configuration and how to install it.
do i need to pip install androitv.py in hass.io installed on raspbianstrech
i want to try androidtv for my Mini M8s2 android box with androidxperiencetv rom 7.1
If i puy platfrom as android tv error platform androidtv not found appears,
but if i put platform as firetv no error, why?
Please guide and start a topic so that we can try.
Thanks

TypeError: __init__() got an unexpected keyword argument 'default_timeout_s'

Hi,
I tried to setup a quick PoC but I couldn't get very far.

I always get TypeError: __init__() got an unexpected keyword argument 'default_timeout_s'

import androidtv
from androidtv.androidtv import AndroidTV

if __name__ == '__main__':
    atv = AndroidTV('HOST', 5555)
    atv.adb_connect()

I couldn't find any code snippets so I just went with the submodule reference.

Any ideas what I'm doing wrong?

Media session title

Hello @JeffLIrion! Thx for work!

dumpsys media_session return the title of the content being played in the metadata:description field for apps that use media_session API (YouTube, Spotify, ViMu, Netflix, TiviMate etc..).

Is it possible to make this information used in HA media_title, media_artist, media_album if it provided and active? Like Google Cast integration do. Also i see current media position meta.


  6 sessions listeners.
  Global priority session is null
  User Records:
  Record for full_user=0
    Volume key long-press listener: null
    Volume key long-press listener package: 
    Media key listener: null
    Media key listener package: 
    Callback: android.media.session.ICallback$Stub$Proxy@7f2bc79
    Last MediaButtonReceiver: null
    Restored MediaButtonReceiver: null
    Media button session is com.google.android.youtube.tv/starboard_media (userId=0)
    Sessions Stack - have 4 sessions:
      starboard_media com.google.android.youtube.tv/starboard_media (userId=0)
        ownerPid=25681, ownerUid=10048, userId=0
        package=com.google.android.youtube.tv
        launchIntent=null
        mediaButtonReceiver=null
        active=true
        flags=3
        rating type=0
        controllers: 12
        state=PlaybackState {state=3, position=1980379, buffered position=0, speed=1.0, updated=38059080, actions=379, custom actions=[], active item id=-1, error=null}
        audioAttrs=AudioAttributes: usage=USAGE_MEDIA content=CONTENT_TYPE_UNKNOWN flags=0x0 tags= bundle=null
        volumeType=1, controlType=2, max=0, current=0
        metadata:size=5, description=Introducing iPad Pro | Apple, Apple, null
        queueTitle=null, size=0

      spotify-android-tv-media-session com.spotify.tv.android/spotify-android-tv-media-session (userId=0)
        ownerPid=4636, ownerUid=10071, userId=0
        package=com.spotify.tv.android
        launchIntent=null
        mediaButtonReceiver=PendingIntent{8775afa: PendingIntentRecord{fe618ab com.spotify.tv.android broadcastIntent}}
        active=false
        flags=3
        rating type=0
        controllers: 0
        state=PlaybackState {state=0, position=30357, buffered position=0, speed=1.0, updated=36002007, actions=2368383, custom actions=[], active item id=-1, error=null}
        audioAttrs=AudioAttributes: usage=USAGE_MEDIA content=CONTENT_TYPE_UNKNOWN flags=0x0 tags= bundle=null
        volumeType=1, controlType=2, max=0, current=0
        metadata:size=7, description=Counting Days Till Suicide, REDZED, Ecstasy
        queueTitle=null, size=0

      Netflix media session com.netflix.ninja/Netflix media session (userId=0)
        ownerPid=5525, ownerUid=10063, userId=0
        package=com.netflix.ninja
        launchIntent=null
        mediaButtonReceiver=null
        active=false
        flags=3
        rating type=0
        controllers: 0
        state=null
        audioAttrs=AudioAttributes: usage=USAGE_MEDIA content=CONTENT_TYPE_UNKNOWN flags=0x0 tags= bundle=null
        volumeType=1, controlType=2, max=0, current=0
        metadata:size=0, description=null
        queueTitle=null, size=0

      starboard_media com.google.android.youtube.tv/starboard_media (userId=0)
        ownerPid=25681, ownerUid=10048, userId=0
        package=com.google.android.youtube.tv
        launchIntent=null
        mediaButtonReceiver=null
        active=false
        flags=3
        rating type=0
        controllers: 0
        state=PlaybackState {state=0, position=0, buffered position=0, speed=0.0, updated=0, actions=0, custom actions=[], active item id=-1, error=null}
        audioAttrs=AudioAttributes: usage=USAGE_MEDIA content=CONTENT_TYPE_UNKNOWN flags=0x0 tags= bundle=null
        volumeType=1, controlType=2, max=0, current=0
        metadata:size=0, description=null, null, null
        queueTitle=null, size=0

  Audio playback (lastly played comes first)
    uid=10048 packages=com.google.android.youtube.tv

Getting HDMI input from the device

For my (Home Assistant) setup, I only care about the HDMI input of the device. I have found out that this value changes as the HDMI input changes:

$ adb shell dumpsys activity starter | grep "HW[0-9]"
   Intent { act=android.intent.action.VIEW dat=content://android.media.tv/passthrough/com.mediatek.tvinput%2F.hdmi.HDMIInputService%2FHW5 flg=0x10000000 cmp=org.droidtv.playtv/.PlayTvActivity (has extras) }
  mIntent=Intent { act=android.intent.action.VIEW dat=content://android.media.tv/passthrough/com.mediatek.tvinput/.hdmi.HDMIInputService/HW5 flg=0x10000000 cmp=org.droidtv.playtv/.PlayTvActivity (has extras) }

Specifically, for my two HDMI inputs, you'd either get HW5 or HW6. So a neater solution is:

$ adb shell dumpsys activity starter | grep -o "HW[0-9]" | head -n 1

Now I can do some magic and run a script that calls androidtv.adb_command every 5 seconds or so and then grab the output from the device's adb_response. I then also have to take in to account whether the device is turned on, etc (not that the command fails otherwise, but it makes little sense querying an inactive device).

But ideally this would be integrated in to this repo, so the state can be returned in home assistant and it can be used by more people. The thing is, I have no idea whether this works for everyone.

Otherwise, it would be nice if we could do something like this to automatically include custom states in the entity's attributes:

media_player:
  - platform: androidtv
    name: Philips TV
    host: 10.0.0.100
    adb_server_ip: 127.0.0.1
    get_sources: false
    track:
      - name: hdmi_input
        command: dumpsys activity starter | grep -o "HW[0-9]" | head -n 1

My TV is a Philips 55POS9002 by the way.

Continuous getevent monitoring

I put together this little script: https://pastebin.com/RJ3J2nb3, which I use to monitor key presses on my chromecrast with googletv's remote, and forward/trigger Hass actions.

The reasoning behind it is that the TV I have the chromecast plugged into doesn't have HDMI-CEC, but I am able to control it using IR via Hass. The chromecast remote has volume -+ and a source button that do literally nothing on the chromecast device, they are designed 100% to be passed through to the TV using HDMI-CEC.

The flow is:
remote keypress -> adb getevent -> hass action -> IR to TV

After a small discussion here: https://www.reddit.com/r/homeassistant/comments/o709m7/is_there_a_way_to_use_an_android_tv_controller/h2xrq66/?context=3, user pjrt cleaned up the script and wrote a simple dockerfile: https://github.com/pjrt/androidtv-homeassistant-input-reader and confirmed that it worked for them, allowing them control Hass automations with unused remote buttons.

I had intended to turn it into either a HACS or HA addon, but now I'm wondering if this functionality could potentially be added to this library and the core androidtv component.

I see that you already use getevent for the learn_event functionality, but only call it for an 8 second window.
I am unfamiliar with python's async, so, is having a 'thread' constantly listening to 'getevent' and forwarding keypresses possible within the architecture of this library?

nexus player state incorrect

I've just setup the component for use with my nexux player and I've an issue that the state is always shown as 'playing' other than when the ambient display mode is on at which point it switches to 'idle'. I believe the issue is because the state is being reported based on the audo_state property always reporting as 'playing'.

looking at the 'GET_PROPERTIES' it looks as though the state would work better if derived from the 'media_session_state' attribute as this a 0 when nothing is playing a 1 or 3 when playing and a 2 when paused. see my responses:

{
"entity_id": "media_player.living_room_display","command": "GET_PROPERTIES"
}

adb_response: {'screen_on': True, 'awake': True, 'wake_lock_size': 4, 'media_session_state': 0, 'current_app': 'com.google.android.tvlauncher', 'audio_state': 'playing', 'device': 'hdmi', 'is_volume_muted': False, 'volume': None}

adb_response: {'screen_on': True, 'awake': True, 'wake_lock_size': 5, 'media_session_state': 3, 'current_app': 'com.google.android.youtube.tv', 'audio_state': 'playing', 'device': 'hdmi', 'is_volume_muted': False, 'volume': None}

adb_response: {'screen_on': True, 'awake': True, 'wake_lock_size': 5, 'media_session_state': 3, 'current_app': 'com.netflix.ninja', 'audio_state': 'playing', 'device': 'hdmi', 'is_volume_muted': False, 'volume': None}

adb_response: {'screen_on': True, 'awake': True, 'wake_lock_size': 6, 'media_session_state': 1, 'current_app': 'de.cyberdream.dreamepg.tvh.tv.player', 'audio_state': 'playing', 'device': 'hdmi', 'is_volume_muted': False, 'volume': None}

adb_response: {'screen_on': True, 'awake': True, 'wake_lock_size': 5, 'media_session_state': 2, 'current_app': 'com.google.android.youtube.tv', 'audio_state': 'playing', 'device': 'hdmi', 'is_volume_muted': False, 'volume': None}

adb_response: {'screen_on': True, 'awake': True, 'wake_lock_size': 5, 'media_session_state': 2, 'current_app': 'com.netflix.ninja', 'audio_state': 'playing', 'device': 'hdmi', 'is_volume_muted': False, 'volume': None}

Unable to browse through other videos while weatching a video

Hi,
I used to be able to push "down" button (twice) and see other videos/cards while watching something.
Now, when I press the down button once, player buttons come up, when I press again- nothing happens.
Sometimes, I'd like to listen to the audio only, without watching a video and be able to search through other videos.
What happened to this future?

[Feature Request] Add inputid attribute to differentiate cable vs HDMI/app input

Hey! The ADB commands work like magic and it's great -- good job and thank you so much for this integration 🙏🏻

One thing I'm struggling with is differentiating between an active HDMI input and watching via cable.
The hdmi_input stays the same, and the source is always the org.droidtv.playtv app.
I've looked at the various state detection (as suggested in #12), but the response for GET_PROPERTIES is identical in both cases.

Could we add some property to recognize cable vs HDMI input?

EDIT: As a starting point, I found getprop | grep persist.sys to be useful, and particularly persist.sys.inputid.
EDIT 2: That solved it for me! Changed the issue to a feature request, would be great to have this perhaps in the default properties as inputid

sendevent not working until remote is used once

I have a firetv cube connected to my Visio tv.. Using home assistant to send adb commands to the firecube. I have collected the key command using learn sendevent to power off the tv.. If I use the adb command "HOME" to power on the cube and set the TV input it works perfect, but when I send the cube a command(any learned command) back it does not work, unless I first use the actual remote then all commands work perfect..

Implement a better method for setting volume

You can use the command:

media volume --show --stream 3 --set X

... to change the volume where X is 0 - 15

@i00 thanks for posting that command, I was unaware of it. I've got a few questions. Why is --show necessary? Is it always --stream 3 or is it sometimes a different number? And you said that x is 0 - 15, but some devices have a max volume of 40, I believe, so I assume that the range would be 0 - 40?

Could you post the output from this command:

dumpsys audio | grep 'STREAM_MUSIC:' -A 12

FireTV (Integrated in Smart TV) Power On functionality

One of my main annoyances with this integration has been with powering on my device. The default is for the device to send the power button followed by home if it is off.

await self._adb.shell(constants.CMD_SCREEN_ON + " || (input keyevent {0} && input keyevent {1})".format(constants.KEY_POWER, constants.KEY_HOME))
and
self._adb.shell(constants.CMD_SCREEN_ON + " || (input keyevent {0} && input keyevent {1})".format(constants.KEY_POWER, constants.KEY_HOME))
this effectively breaks the television turning on the last input if it is configured to do so.

While this can easily be fixed by adding:
turn_on_command: "input keyevent 26"
to the configuration, in order to override the default... I was curious if it might be feasible to make the default functionality follow what the television settings are set to. This can be determined by:
adb shell settings get secure power_on_launch_mode
where
0 = home
1 = last input

I'm not really sure if there's anything being stored in this implementation that would determine that dynamically though.

thanks in advance.

List source in home assistant uses "running apps" list doesn't contain all apps

The list sources option in home assistant uses the list returned by "running apps" however, this doesn't include all apps, only running ones.

For me, on a nvidia shield this means that many apps to not appear.

It would make more sense to use "installed apps" as provided by:

pm list packages | awk -F : '{print $2}'

For my own personal use I've forked this library and made this change imduffy15@c4e1558 it would be great to see it upstream or understand the reasoning for listing running apps only.

Fire TV Select source doesn't work right after "POWER" ADB command

I am trying to make some scripts on HA 0.114.0.dev0,
so, I'm using androidtv[async] 0.0.48 module.

The script didn't work as I wanted, so I looked into it.
And I guess there are some bugs on this project.

media_player.select_source service never work right after POWER adb command,
and the log is,
2020-08-07 23:32:53 INFO (MainThread) [homeassistant.components.androidtv.media_player] ADB command not executed because the connection is currently in use

In this situation, push any button on remote controller, after then select_source works again.

I think there will be a bug in the adb_manager_async.py related to _adb_lock, so please look for it.

How to help with state detection!

State detection diagnostics

Assuming you're using the Home Assistant Android TV component, here's how you can help improve state detection.

This package determines the state in the AndroidTV.update / FireTV.update methods using a collection of properties and reports that state to Home Assistant. You can see what those properties are by using the HA service androidtv.adb_command with "GET_PROPERTIES" as the command argument -- they will be logged at the INFO level and they will be stored in the media player's adb_response attribute (HA 0.94+), which can easily be viewed on the States tab. You can read more about the androidtv.adb_command service at the bottom of the Android TV documentation.

The state detection logic will differ depending on the app. So open an app, send the "GET_PROPERTIES" command a few times while it's idle / on standby, playing, and paused, and try to figure out a better way to determine the state. Pull requests are welcome!

Android TV 11 showing only Off, Idle or Standby, not recognizing running apps

I have a TCL TV with Android TV 11 installed running on latest release HA (2021.9.7) and I the only states HA receives are Off,Idle and Standby with adb response: null in Developer - States tab.

I ran the commands through adb shell and these are the results:

~$ adb shell dumpsys power | grep 'Display Power' | grep 'state=ON' || dumpsys power | grep 'mScreenOn=true'
Display Power: state=ON
~$ adb shell getprop ro.product.manufacturer
TCL
~$ adb shell getprop ro.product.model
Smart TV Pro
~$ adb shell getprop ro.build.version.release
11
adb shell dumpsys window windows | grep -E 'mCurrentFocus|mFocusedApp'

gives no response

this works

~$ adb shell dumpsys window windows | grep Window\ #1
  Window #1 Window{f978c53 u0 com.google.android.youtube.tv/com.google.android.apps.youtube.tv.activity.MainActivity}:
~$ adb shell ps -A | grep u0_a
u0_a39          410   4071       0      0 0                   0 Z [com.tcl.usercen]
u0_a72         1029    274 1270008  83388 0                   0 S com.android.systemui
u0_a78         1229    274 1237900  48308 0                   0 S com.google.android.ext.services
u0_a22         1279    274 1303284  39828 0                   0 S com.google.android.tv.remote.service
u0_a70         1302    274 1223912  39352 0                   0 S com.google.android.partnersetup
u0_a15         1361    274 1353364  75584 0                   0 S com.google.android.gms.persistent
u0_a37         1433    274 1266488  51476 0                   0 S com.google.android.inputmethod.latin
u0_a15         1566    274 1238860  41872 0                   0 S com.google.process.gservices
u0_a77         1628    274 1240776  39884 0                   0 S com.android.providers.media.module
u0_a23         1751    274 1277568  76200 0                   0 S com.google.android.tvrecommendations
u0_a27         1772    274 1318284  55712 0                   0 S com.google.android.tvlauncher
u0_a12         1912    274 1255744  42656 0                   0 S com.android.providers.tv
u0_a6          2106    274 1219396  37888 0                   0 S com.android.externalstorage
u0_a59         2593    274 1906136  49788 0                   0 S com.tcl.bi:service
u0_a16         2653    274 2034692  39224 0                   0 S com.google.android.katniss:search
u0_a55         2783    274 1900044  55384 0                   0 S com.netflix.ninja
u0_a80         2859    274 1265992  54496 0                   0 S tv.twitch.android.app
u0_a16         3028    274 1991444  38792 0                   0 S com.google.android.katniss:interactor
u0_a19         3090    274 1252588  41664 0                   0 S com.google.android.tungsten.setupwraith
u0_a15         3147    274 1296252 102184 0                   0 S com.google.android.gms
u0_a11         3218    274 1375284 107356 0                   0 S com.google.android.apps.mediashell
u0_a79         3630    274 1807528 341556 0                   0 S org.xbmc.kodi
u0_a39         4071    274 1278092  43744 0                   0 S com.tcl.usercenter
~$ CURRENT_APP=$(adb shell dumpsys activity a . | grep -E 'mResumedActivity' | cut -d ' ' -f 8) && CURRENT_APP=${CURRENT_APP%%/*} && echo $CURRENT_APP
com.netflix.ninja
~$ CURRENT_APP=$(adb shell dumpsys activity a . | grep -E 'mResumedActivity' | cut -d ' ' -f 8) && CURRENT_APP=${CURRENT_APP%%/*} && echo $CURRENT_APP
com.tcl.waterfall.overseas
~$ CURRENT_APP=$(adb shell dumpsys activity a . | grep -E 'mResumedActivity' | cut -d ' ' -f 8) && CURRENT_APP=${CURRENT_APP%%/*} && echo $CURRENT_APP
com.android.vending
~$ CURRENT_APP=$(adb shell dumpsys activity a . | grep -E 'mResumedActivity' | cut -d ' ' -f 8) && CURRENT_APP=${CURRENT_APP%%/*} && echo $CURRENT_APP
tv.twitch.android.app

Here's full output of dumpsys window and dumpsys activity starter in a gist link

Hulu app ID

For me the app ID of Hulu is com.hulu.livingroomplus, not com.hulu.plus. Would it be possible to have both?

File Collision between required modules

install_requires=['rsa', 'adb-homeassistant', 'pure-python-adb-homeassistant']

but cannot merge 'adb-homeassistant-1.3.2' and 'pure-python-adb-homeassistant-0.1.6' at the same time, both have

 * 	/usr/lib64/python3.6/site-packages/adb/__init__.py
 * 	/usr/lib64/python3.6/site-packages/adb/__pycache__/__init__.cpython-36.opt-1.pyc
 * 	/usr/lib64/python3.6/site-packages/adb/__pycache__/__init__.cpython-36.opt-2.pyc
 * 	/usr/lib64/python3.6/site-packages/adb/__pycache__/__init__.cpython-36.pyc

With only adb-homeassistant installed i get

  File "/usr/lib64/python3.6/site-packages/androidtv/basetv.py", line 15, in <module>
    from adb_messenger.client import Client as AdbClient
ModuleNotFoundError: No module named 'adb_messenger'

and with only pure-python-adb-0.1.6 installed

  File "/usr/lib64/python3.6/site-packages/androidtv/basetv.py", line 13, in <module>
    from adb import adb_commands
ImportError: cannot import name 'adb_commands'

from homeassistant-0.91.1

State is idle when an app is playing

I use it with Philips TV 55POS900212 and it partly works: on/off, mute/unmute, change volume and correctly shows which app is running but it doesn’t change idle status to playing when an app is actually playing. I can provide details if it helps to debug it.

Android Debug Bridge (AndroidTV) app_id frequently shows "Failed to write while dumping service window: Broken pipe

The problem

I have an automation (below) that triggers based on the app_Id from the device via Android Debug Bridge. Since Home Assistant
/2023.10.4, the platform state attributes often responds with:

app_id: Failed to write while dumping service window: Broken pipe
app_name: Failed to write while dumping service window: Broken pipe
source: Failed to write while dumping service window: Broken pipe
adb_response: null

This causes automations to trigger based on the state change away from the expected values (testing for com.valvesoftware.steamlink).

Additional information

A few other users have reported this via the Home Assistant integrations github - home-assistant/core#104652

Suppress debug messages from connection.py

How can we suppress the spamming of debug messages?

I used to just comment them out of config/deps/adb_messenger/connection.py but now that the deps folder is no longer used, what can we do?

Proposal: Read known apps from local or remote json file.

As the title suggest, I believe reading the known apps titles from a local/remote json file instead of using constants might be an improvement as it may be more maintainable and also auto updated with some custom scripts (parse app store for example). What do you think?

question: determine state of connected tv/display

Hello,

is it possible to determine the state of the display/tv where the Fire TV is connected to? Or do you know the corresponding adb commands?

I would need to check if the TV/display is powered regardless if the TV is displaying data from the Fire TVs HDMI port or any other port.

Best regards,
wewa

Idea: implement input via monkeyrunner for low latency remote control

I'm currently searching for a good solution to control both my android devices: a slower Bravia and a Shield TV Pro.

Of course we have adb input but it is slow as heck on both my devices (~2s) because it spawns a new jvm process for each sent command- it's good enough for single commands like pause or volume control but it sucks for d-pad navigation for instance.
I'm disabled and have to use all my devices without any physical control so all my remotes should be exposed in some way in Home Assistant (lovelace cards, services, alexa commands etc).

For Bravia specifically we already have three different API's but even those have it's flaws (ie: actually harder to keep the server alive and responsive than adb mostly due to TVs lack of memory). If you've ever had to power cycle or reboot your TV because sony PSK API refuses to answer because it crashed you know what I mean.

So, after some github searching I've found this neat java app called ADBKeyMonkey that uses the native monkeyrunner API to forward local input (which is a different thing than monkey, usually used to launch intents/app).
It just requires a normal adb connection, and it's very low latency.

I don't wanna mess with java and the official monkeyrunner python module only works with pre-historic Jython 2.5. I played with it a bit and was set on writing a tiny websocket server script as a demo but the Jython requirement still sounded bad. Luckily someone made this compatibility layer and after a bit of fiddling I'm now writing a few sample scripts in Python 3 and figuring out how to properly keep the connection alive based on ideas from the ADBKeyMonkey.

I'm a newbie coder but I hope this gives some ideas for the brighter minds, so drop your thoughts.

I would like to help with adding support for the new Chromecast with Google TV

GET_PROPERTIES returns mostly values of none.

I have found that the normal command to get the current app does not work but this command does.
"dumpsys activity a . | grep -E 'mResumedActivity' | cut -d ' ' -f 8"
It returns
adb_response: com.google.android.apps.tv.launcherx/.home.HomeActivity

I'd love to learn more about adb/linux/python and in the process, I would like to give you a hand with getting this Add-On working with the new chromecast.

Please let me know however I can help!

Thanks for the awesome Add-On. I love using it on my nVidia Shield

Use USB for adb connection

Would this be possible? I have an Android TV that only supports adb over usb, and I am currently using an USB-A male to male cable to use adb and it works fine. Would it be possible to use this with home assistant over usb?

Sony TV HDMI input detection

Issue 202 added HDMI input info, but that doesn't appear to work on current Sony Android TV implementations.

This command appears to work on my X950H, returning just the port number (ports are 1 indexed, when the routing is 0x0000 internal apps are in use).:

'dumpsys hdmi_control | grep -o 'mActiveRoutingPath: 0x[1-9]' | grep -o [1-9]'

There are several other fields in dumpsys that could be used, but this seemed cleanest to me.

Not sure what the right pattern is for multiple variants of CMD_HDMI_INPUT or detection of subtypes of Android TV so I'm not proposing a patch.

Select source wont work on firetv

{
  "entity_id": "media_player.firetv",
  "source": "com.netflix.ninja"
}

and

{
  "entity_id": "media_player.firetv",
  "source": "com.netflix.ninja"
}

isnt working

state_detection_rules doesn't seems to work

Hi, I see a problem with state_detection_rules... I wanted to add support for player (one of Polish services with VOD). I figrued out that it changes wake lock size depending on state of the media, while media_session_state is none and audio_state is paused. I prepared this code for my configuration.yaml:

media_player:
  - platform: androidtv
    name: AndroidTV_Philips
    host: 192.168.0.11
    device_class: androidtv
    scan_interval: 1
    apps: {}
    state_detection_rules:
      'pl.tvn.player.pl':
        - 'playing':
            'audio_state': paused
            'wake_lock_size': 3
        - 'paused':
            'audio_state': paused
            'wake_lock_size': 2 
        - 'idle'

This code not working, I don't know if there is some information how to exlude one of the parameters, because in my case media_session_state is always none...

Split `update()` / `get_properties()` into multiple ADB commands

When I first created this package, the ADB library was not very reliable for newer devices. In an effort to make it work better, I used a single ADB command for the update function. This wasn't so bad at first, the command was reasonably short. But as more info got collected by the update function, this ADB command grew in complexity.

Now that the Python ADB library that this package uses (adb-shell) is pretty reliable, it would simplify things a lot to split the update function into multiple ADB commands. First, check simple stuff, like if the device is on and awake. Then, if the device is on and awake, check stuff like the current app and additional fields. And maybe instead of using a complicated grep command to parse the dumpsys output on the device, just return the full output and parse it in this package.

lots of logs when device is turn off

when device is turnoff
the error floods the log file
error shown

2019-03-20 10:31:58 ERROR (MainThread) [homeassistant.helpers.entity] Update for media_player.minim8s2 fails
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/homeassistant/helpers/entity.py", line 220, in async_update_ha_state
    await self.async_device_update()
  File "/usr/local/lib/python3.7/site-packages/homeassistant/helpers/entity.py", line 348, in async_device_update
    await self.hass.async_add_executor_job(self.update)
  File "/usr/local/lib/python3.7/concurrent/futures/thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/config/custom_components/androidtv/media_player.py", line 186, in _adb_exception_catcher
    return func(self, *args, **kwargs)
  File "/config/custom_components/androidtv/media_player.py", line 342, in update
    self.aftv.update()
  File "/config/deps/lib/python3.7/site-packages/androidtv/androidtv.py", line 100, in update
    screen_on, awake, wake_lock_size, media_session_state, _current_app, audio_state, device, muted, volume_level = self.get_properties(lazy=True)
  File "/config/deps/lib/python3.7/site-packages/androidtv/androidtv.py", line 341, in get_properties
    "dumpsys audio")
  File "/config/deps/lib/python3.7/site-packages/androidtv/basetv.py", line 122, in _adb_shell_pure_python_adb
    return self._adb_device.shell(cmd)
  File "/usr/local/lib/python3.7/site-packages/adb_messenger/command/transport/__init__.py", line 20, in shell
    conn = self.create_connection(timeout=timeout)
  File "/usr/local/lib/python3.7/site-packages/adb_messenger/device.py", line 45, in create_connection
    self.transport(conn)
  File "/usr/local/lib/python3.7/site-packages/adb_messenger/command/transport/__init__.py", line 15, in transport
    connection.send(cmd)
  File "/usr/local/lib/python3.7/site-packages/adb_messenger/connection.py", line 77, in send
    return self._check_status()
  File "/usr/local/lib/python3.7/site-packages/adb_messenger/connection.py", line 83, in _check_status
    raise RuntimeError("ERROR: {} {}".format(repr(recv), error))
RuntimeError: ERROR: 'FAIL' 0025device '192.168.11.37:5555' not found
2019-03-20 10:32:09 ERROR (MainThread) [homeassistant.helpers.entity] Update for media_player.minim8s2 fails
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/homeassistant/helpers/entity.py", line 220, in async_update_ha_state
    await self.async_device_update()
  File "/usr/local/lib/python3.7/site-packages/homeassistant/helpers/entity.py", line 348, in async_device_update
    await self.hass.async_add_executor_job(self.update)
  File "/usr/local/lib/python3.7/concurrent/futures/thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/config/custom_components/androidtv/media_player.py", line 186, in _adb_exception_catcher
    return func(self, *args, **kwargs)
  File "/config/custom_components/androidtv/media_player.py", line 342, in update
    self.aftv.update()
  File "/config/deps/lib/python3.7/site-packages/androidtv/androidtv.py", line 100, in update
    screen_on, awake, wake_lock_size, media_session_state, _current_app, audio_state, device, muted, volume_level = self.get_properties(lazy=True)
  File "/config/deps/lib/python3.7/site-packages/androidtv/androidtv.py", line 341, in get_properties
    "dumpsys audio")
  File "/config/deps/lib/python3.7/site-packages/androidtv/basetv.py", line 122, in _adb_shell_pure_python_adb
    return self._adb_device.shell(cmd)
  File "/usr/local/lib/python3.7/site-packages/adb_messenger/command/transport/__init__.py", line 20, in shell
    conn = self.create_connection(timeout=timeout)
  File "/usr/local/lib/python3.7/site-packages/adb_messenger/device.py", line 45, in create_connection
    self.transport(conn)
  File "/usr/local/lib/python3.7/site-packages/adb_messenger/command/transport/__init__.py", line 15, in transport
    connection.send(cmd)
  File "/usr/local/lib/python3.7/site-packages/adb_messenger/connection.py", line 77, in send
    return self._check_status()
  File "/usr/local/lib/python3.7/site-packages/adb_messenger/connection.py", line 83, in _check_status
    raise RuntimeError("ERROR: {} {}".format(repr(recv), error))
RuntimeError: ERROR: 'FAIL' 0025device '192.168.11.37:5555' not found

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.