Repository: JeffLIrion/python-androidtv (language: python)

Issue:
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:
https://github.com/home-assistant/core/issues/80555
https://github.com/home-assistant/core/issues/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.
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:
https://github.com/home-assistant/core/issues/80555
https://github.com/home-assistant/core/issues/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.


Discussion / hints:
Hi @Dillton 

In readme of this repo owner said that he have no time to work on this project.
I would not expect any fix soon. 
Someone from community need to check this.
I think if HA officially use this repo should be take care by HA ;) but this is only my dream for perfect world 
> In readme of this repo owner said that he have no time to work on this project.

@JeffLIrion  clear explain that he will not have time to work on fix, but PR are welcome. Anyone with some programming competence and a valid device for test can create PR on this repo, and I think that @JeffLIrion will found the time to review them. HA architecture is base on the fact that communication with devices are based on external and open source python library. This can be strength and weakness at the same time of this architecture, but that's it. I think that HA team will never work on external library, but this doesn't means that fix will not be implemented, this is just based on goodwill of the community.
I think I might have found a fix for this already, but haven't had time to fully test & open a PR yet. It seems that the `CMD_SCREEN_ON` checks aren't sufficient for Android 12 on the Chromecast with Google TV. Adding a check for `mScreenState=ON` in the `display` output of `dumpsys` looks to correctly report the screen state, e.g.
```
CMD_SCREEN_ON = (
    "(dumpsys power | grep 'Display Power' | grep -q 'state=ON' || dumpsys power | grep -q 'mScreenOn=true' || dumpsys display | grep -q 'mScreenState=ON')"
)
```
From there, since the screen is on, the rest of the logic seems to work so far. But once again, I haven't tested *everything* yet, and also haven't regression tested other devices (e.g. my Nvidia Shield).

I recall reading up a bit on a major architectural shift for this project during the last major Android version bump, but am not sure specifically what changed to make it easier to add more device-specific commands (perhaps something to do with custom commands???)

In the long-run, it would seem better to have device profiles (something like ZWaveJS does I think) instead of a lot of `if android version == TARGET_VERSION then command x, else command y"`. E.g. have a base profile with the most common/standard adb commands that each device profile entry would inherit from and override any specific commands necessary for that device/version combo. I'm not a Python dev though, so an undertaking like that might be a bit more for me to attempt.

I can help test this ;) I have valid device ;)
> I can help test this ;) I have valid device ;)

What type of install do you have? I'm running docker, so I had to shell into the container and manually make the edit to `/usr/local/lib/python3.10/site-packages/androidtv/constants.py` and restart the container afterwards. I'm not sure how different that would be for a supervised install (which I think also runs in a docker container?)

In any event, if you can get to that file in your install and change https://github.com/JeffLIrion/python-androidtv/blob/b1425b1b0d1d826e25948fad15ca3650433e3d5d/androidtv/constants.py#L179-L182
to the code snippet in my prior comment (here it is again):
```
CMD_SCREEN_ON = (
    "(dumpsys power | grep 'Display Power' | grep -q 'state=ON' || dumpsys power | grep -q 'mScreenOn=true' || dumpsys display | grep -q 'mScreenState=ON')"
)
```
That should be the extent of the fix. At that point, once the state is being correctly derived, it will be much easier to test other parts of the AndroidTV integration to see if further Android 12 changes are needed in addition to the device state.
> What type of install do you have? I'm running docker, so I had to shell into the container and manually make the edit to `/usr/local/lib/python3.10/site-packages/androidtv/constants.py` and restart the container afterwards

@breakthestatic, I suggest you to setup a HA dev environment as explained [here](https://developers.home-assistant.io/docs/development_environment/). It's quite simple (it works with windows, linux or mac), will simplify your tests and will avoid to hack your default HA installation.
> > What type of install do you have? I'm running docker, so I had to shell into the container and manually make the edit to `/usr/local/lib/python3.10/site-packages/androidtv/constants.py` and restart the container afterwards
> 
> @breakthestatic, I suggest you to setup a HA dev environment as explained [here](https://developers.home-assistant.io/docs/development_environment/). It's quite simple (it works with windows, linux or mac), will simplify your tests and will avoid to hack your default HA installation.

I already have that set up but am not sure how to make the needed change since it's in this library, not HA core. To test the fix, I was already using the dev env, but still manually changing the python-androidtv file in site-packages. 
> > I can help test this ;) I have valid device ;)
> 
> What type of install do you have? I'm running docker, so I had to shell into the container and manually make the edit to `/usr/local/lib/python3.10/site-packages/androidtv/constants.py` and restart the container afterwards. I'm not sure how different that would be for a supervised install (which I think also runs in a docker container?)
> 
> In any event, if you can get to that file in your install and change
> 
> https://github.com/JeffLIrion/python-androidtv/blob/b1425b1b0d1d826e25948fad15ca3650433e3d5d/androidtv/constants.py#L179-L182
> 
> 
> to the code snippet in my prior comment (here it is again):
> ```
> CMD_SCREEN_ON = (
>     "(dumpsys power | grep 'Display Power' | grep -q 'state=ON' || dumpsys power | grep -q 'mScreenOn=true' || dumpsys display | grep -q 'mScreenState=ON')"
> )
> ```
> 
> That should be the extent of the fix. At that point, once the state is being correctly derived, it will be much easier to test other parts of the AndroidTV integration to see if further Android 12 changes are needed in addition to the device state.

Evening. I can also help with testing with my Chromecast and so far I can say this seems to be the trick, thank you.
Modifyed my container and did some real life usage:
![image](https://user-images.githubusercontent.com/68992112/197410386-2e25aaab-c107-4d4f-bf0f-57b7f8bbf84b.png)
![image](https://user-images.githubusercontent.com/68992112/197410429-585a4475-3fb1-46bc-ae8a-d2d5254f52af.png)
![image](https://user-images.githubusercontent.com/68992112/197411625-a9b9037a-1d8c-4224-a9f4-9771afb65a88.png)

I will keep it modifyed like that and see.
@breakthestatic Do you need some specific testing?

I can confirm that this fixes the issue for me too (CCwGTV Android TV 12). Thanks!
Hi All 

i looking this path on my instance 
/usr/local/lib/python3.10/site-packages/androidtv/constants.py

But i cannot find it 

first of all i don't have python 3.10 folder i have only 3.9
also don't have folder site-packages 
i have only dist-packages

My installation is on virtual machine and up to date
> Hi All
> 
> i looking this path on my instance /usr/local/lib/python3.10/site-packages/androidtv/constants.py
> 
> But i cannot find it
> 
> first of all i don't have python 3.10 folder i have only 3.9 also don't have folder site-packages i have only dist-packages
> 
> My installation is on virtual machine and up to date

If it's Hass os in a VM you need to access home assistant core docker container shell. 
`docker exec -it $(docker ps -f name=homeassistant -q) bash` 
@breakthestatic Found an additional problem so there might be needed additional modification of the code.
The device goes off for 10 seconds sometimes as you can see on screen below:
![image](https://user-images.githubusercontent.com/68992112/197581673-c00eb782-4086-47e6-aaef-fc615b21f517.png)

> @breakthestatic Found an additional problem so there might be needed additional modification of the code. The device goes off for 10 seconds sometimes as you can see on screen below: ![image](https://user-images.githubusercontent.com/68992112/197581673-c00eb782-4086-47e6-aaef-fc615b21f517.png)

Not saying you are definitely wrong about needing some additional fixes, but I recall seeing behavior like this with the Nvidia Shield recently as well. I believe the integration polls the device every 10 seconds, so perhaps there is some logic that defaults the playing state to `off` if an individual poll result fails?

So far I haven't seen this myself on the Chromecast, but I have also not done much testing. I'll see if I can reproduce it if/when I have some spare time over the next few days. Also, if you are somewhat familiar w/ ADB as well, you could manually set up an ADB session on another computer and see if `mScreenState` actually changes its value during the time periods that HA is reporting it to be off.
Just a quick follow-up regarding the intermittent `off` state... I ran through several states over the past ~ 45minutes (idle to standby, then playing through a full episode in Plex, back to idle after the episode ended & back to playing once the next episode started):
![Screen Shot 2022-10-24 at 12 46 53 PM](https://user-images.githubusercontent.com/9346314/197613630-05dfb534-249b-4548-9f9c-2572b7806e14.png)

Once again, I'm not really familiar with the actual functionality of this library beyond the basic ADB commands used to determine state, but it seems like the `off` state is only set in a single place:
https://github.com/JeffLIrion/python-androidtv/blob/b1425b1b0d1d826e25948fad15ca3650433e3d5d/androidtv/androidtv/base_androidtv.py#L112-L114
Looking at this piece of code, it seems that only two things can trigger it, either an incorrect `screen_on` value or when the `current_app` is set to `off`. I'm still not 100% sure if a failed poll could return what is eventually interpreted as an incorrect `screen_on` state. I tried faking it by pulling my ethernet cable for ~20 seconds, but HA correctly interpreted that as "unavailable" in that case (not `off` as is seen in your screenshot), so it seems unlikely that a dropped poll can cause it.  That leaves either a truly incorrect reading of screen state (i.e if, for some reason your `mScreenState` isn't `ON` for that particular poll response), or an invalid `current_app`.

There's a bit more logic surrounding the state of `current_app` that I wasn't able to fully step through, but it seems like you could get a bad state via the custom state detection logic.  Do you know what app was running when you saw this (and do you possibly have any custom state detection rules configured)? Without being able to reproduce this myself, & not having deep-enough knowledge of this library (or language for that matter 😆), I'm not sure how much further I could get with this.
I was about to report this intermittent `off` state as well. For context I was watching HotD on hbomax 😅  and got some automations triggered based on the off state a couple of times. I'll try to reproduce it again although it seemed to be rather random.
![Screenshot_2022-10-25-00-18-20](https://user-images.githubusercontent.com/40600040/197635728-e6d1a851-5f3e-4c0b-bc36-2af5fd50f899.png)

@breakthestatic Really does not matter which application I think. I was watching youtube and netflix yesterday and with both the same behaviour. Sometimes also state changed to standby even when it should be playing.
Not really sure what's going on there :( My two Chromecasts have been very consistent with their state reporting since putting in the fix.

In Twitch, I noticed that whenever the stream goes from actively playing to buffering (doesn't happen often, but still), the state switches from `playing` to `idle`, so perhaps some of the logic I noted in my prior comment (the stuff concerning the app-specific state & fallback detection rules) is the cause. I believe at the bottom of `base_androidtv.py`, there's a single extra location where state is not explicitly set to pre-determined values (besides a couple app-specific rules for Bell Fibe & VRV, whatever those are):
https://github.com/JeffLIrion/python-androidtv/blob/b1425b1b0d1d826e25948fad15ca3650433e3d5d/androidtv/androidtv/base_androidtv.py#L208-L210
It seems that condition is rather open-ended, in that as long as none of the app-specific rules above it trigger, and there is no `media_session_state`, it will try to get the overall state from the current audio state (as long as it isn't `idle`). If `audio_state` is `off`, that could also seemingly lead to what you guys are seeing.

Maybe you could try adding extra logging at the bottom to see what all the various state variables look like at the time the problem occurs (i.e. put it right before line 228 in base_androidtv.py):
```
_LOGGER.debug("screen_on: %s", screen_on)
_LOGGER.debug("current_app: %s", current_app)
_LOGGER.debug("media_session_state: %s", media_session_state)
_LOGGER.debug("audio_state: %s", audio_state)
```
> ![Screen Shot 2022-10-24 at 12 46 53 PM](https://user-images.githubusercontent.com/9346314/197613630-05dfb534-249b-4548-9f9c-2572b7806e14.png)

a side-question @breakthestatic : did you reinstall/re-add your CCwGTV in HomeAssistant? I can see that the firmware shows "12" - mine CCwGTV upgraded itself over the night [probably - yesterday it was Android 10, today it's 12, and I didn't do anything ;)] but it still shows "10" in the firmware info in HA. of course all my automations stopped working [and I was using different ones according to which app is running with what state], but I'm too afraid to fiddle "with system" or try your hot fixes. I'll just wait patiently :)

also I've noticed that service `androidtv.adb_command` with command `GET_PROPERTIES` - doesn't give any new response, it just shows something old, not changed according to current state. it probably won't help you, but I didn't wanted to come here only with questions :)

Hey @pejotigrek, I didn't reinstall my Chromecast, but I have both reloaded the integration, as well as completely restarted HA. I'm not sure which (or both) of those might have updated the firmware version, but I would definitely be sure that you are seeing the updated version before doing further debugging. When my Chromecast was updated to 12 (already said fw12 in HA), doing the `GET_PROPERTIES` call correctly populated the `adb_response` (just with the incorrect `screen_on` state).
> Hey @pejotigrek, I didn't reinstall my Chromecast, but I have both reloaded the integration, as well as completely restarted HA. I'm not sure which (or both) of those might have updated the firmware version, but I would definitely be sure that you are seeing the updated version before doing further debugging. When my Chromecast was updated to 12 (already said fw12 in HA), doing the `GET_PROPERTIES` call correctly populated the `adb_response` (just with the incorrect `screen_on` state).

ok checked now, reloading did the trick! thanks! :) also looks like `GET_PROPERTIES` was populated with updated info, but as I am away from home [which is empty right now] - I'll check the whole feedback little bit later [I assume that wakelocks etc. should work good].
thank you!
ok, tested, my `adb_response` isn't correctly populated. from the whole feedback line:
`{'screen_on': False, 'awake': True, 'audio_state': None, 'wake_lock_size': 2, 'current_app': None, 'media_session_state': None, 'audio_output_device': None, 'is_volume_muted': None, 'volume': None, 'running_apps': None, 'hdmi_input': None}` only the _wake_lock_size_ changes with different integers [1-4] depending on what streaming app is used and what state it is.
I suppose it's because I didn't made any changes to the python files.
Yeah, I believe that *most* of the values are dependent on `screen_on` being correctly populated. Regrettably, without others contributing to debugging their specific issues, not sure when this will get fixed. I can definitely open a PR for the change, but I'm not sure it will get merged with several people still reporting abnormal state.
I'm also affected by this. I applied the `CMD_SCREEN_ON` fix and restarted HA, everything seems to be working fine (thanks @breakthestatic). The state is reported correctly, and a few automations I have the rely on the `app_id` attribute and `androidtv/adb_command` look good (although I didn't do any extensive testing).

Let me know if you want me to test anything specific.

If the change works for some people and is unlikely to break anything, maybe it's worth releasing it so that others can test more easily without having to manually to edit code inside containers.




> If the change works for some people and is unlikely to break anything, maybe it's worth releasing it so that others can test more easily without having to manually to edit code inside containers.

maybe I'm too naive, but I guess that it won't be worse than "not working" as it is without fixes, so yeah, release would be cool :)

but maybe there's an relatively easy way to put it as custom integration - just for testing? so it could be checked without fiddling within dockers?
> Not really sure what's going on there :( My two Chromecasts have been very consistent with their state reporting since putting in the fix.
> 
> In Twitch, I noticed that whenever the stream goes from actively playing to buffering (doesn't happen often, but still), the state switches from `playing` to `idle`, so perhaps some of the logic I noted in my prior comment (the stuff concerning the app-specific state & fallback detection rules) is the cause. I believe at the bottom of `base_androidtv.py`, there's a single extra location where state is not explicitly set to pre-determined values (besides a couple app-specific rules for Bell Fibe & VRV, whatever those are):
> 
> https://github.com/JeffLIrion/python-androidtv/blob/b1425b1b0d1d826e25948fad15ca3650433e3d5d/androidtv/androidtv/base_androidtv.py#L208-L210
> 
> 
> It seems that condition is rather open-ended, in that as long as none of the app-specific rules above it trigger, and there is no `media_session_state`, it will try to get the overall state from the current audio state (as long as it isn't `idle`). If `audio_state` is `off`, that could also seemingly lead to what you guys are seeing.
> Maybe you could try adding extra logging at the bottom to see what all the various state variables look like at the time the problem occurs (i.e. put it right before line 228 in base_androidtv.py):
> 
> ```
> _LOGGER.debug("screen_on: %s", screen_on)
> _LOGGER.debug("current_app: %s", current_app)
> _LOGGER.debug("media_session_state: %s", media_session_state)
> _LOGGER.debug("audio_state: %s", audio_state)
> ```

Hi @breakthestatic I just added extra logging and will watch some movie today so hopefully we will learn something more about the states.

EDIT1: So far HA is not able to load the integration with added logging.
EDIT2: Solved, cant use tabs only spaces in editor, oh my...
> > Not really sure what's going on there :( My two Chromecasts have been very consistent with their state reporting since putting in the fix.
> > In Twitch, I noticed that whenever the stream goes from actively playing to buffering (doesn't happen often, but still), the state switches from `playing` to `idle`, so perhaps some of the logic I noted in my prior comment (the stuff concerning the app-specific state & fallback detection rules) is the cause. I believe at the bottom of `base_androidtv.py`, there's a single extra location where state is not explicitly set to pre-determined values (besides a couple app-specific rules for Bell Fibe & VRV, whatever those are):
> > https://github.com/JeffLIrion/python-androidtv/blob/b1425b1b0d1d826e25948fad15ca3650433e3d5d/androidtv/androidtv/base_androidtv.py#L208-L210
> > 
> > It seems that condition is rather open-ended, in that as long as none of the app-specific rules above it trigger, and there is no `media_session_state`, it will try to get the overall state from the current audio state (as long as it isn't `idle`). If `audio_state` is `off`, that could also seemingly lead to what you guys are seeing.
> > Maybe you could try adding extra logging at the bottom to see what all the various state variables look like at the time the problem occurs (i.e. put it right before line 228 in base_androidtv.py):
> > ```
> > _LOGGER.debug("screen_on: %s", screen_on)
> > _LOGGER.debug("current_app: %s", current_app)
> > _LOGGER.debug("media_session_state: %s", media_session_state)
> > _LOGGER.debug("audio_state: %s", audio_state)
> > ```
> 
> Hi @breakthestatic I just added extra logging and will watch some movie today so hopefully we will learn something more about the states.
> 
> EDIT1: So far HA is not able to load the integration with added logging. EDIT2: Solved, cant use tabs only spaces in editor, oh my...

@breakthestatic Ok got some logs, you can check below.
When state changes to off:
2022-10-28 21:09:19.164 DEBUG (MainThread) [androidtv.androidtv.base_androidtv] screen_on: False
2022-10-28 21:09:19.165 DEBUG (MainThread) [androidtv.androidtv.base_androidtv] current_app: None
2022-10-28 21:09:19.165 DEBUG (MainThread) [androidtv.androidtv.base_androidtv] media_session_state: None
2022-10-28 21:09:19.165 DEBUG (MainThread) [androidtv.androidtv.base_androidtv] audio_state: None

When state changes to standby:
2022-10-28 21:07:09.204 DEBUG (MainThread) [androidtv.androidtv.base_androidtv] screen_on: True
2022-10-28 21:07:09.204 DEBUG (MainThread) [androidtv.androidtv.base_androidtv] current_app: None
2022-10-28 21:07:09.204 DEBUG (MainThread) [androidtv.androidtv.base_androidtv] media_session_state: None
2022-10-28 21:07:09.204 DEBUG (MainThread) [androidtv.androidtv.base_androidtv] audio_state: None

![image](https://user-images.githubusercontent.com/68992112/198714472-4bc447cc-4d9b-4a56-a28d-584d243c2bcd.png)

Seems like no data available at that time?
Hmm, so it seems *likely* the actual dumpsys response is incorrect when the problem occurs. The only extra logic that is performed before it gets to the state logic is an inversion.  The actual ADB command performs a silent grep for the commands, which returns a `0` exit code when found (meaning it found one of the screen on strings), and an exit code of `1` when the grep fails. Since normal boolean logic treats `0` as false and `1` as true, there's a bit of code that *flips* the adb command response and returns `1` if the screen is on and `0` if it's off:
https://github.com/JeffLIrion/python-androidtv/blob/b1425b1b0d1d826e25948fad15ca3650433e3d5d/androidtv/constants.py#L72-L73

Are you familiar with ADB at all? If so, perhaps you could set up an ADB connection to your Chromecast, and then either set up an automation to alert you when the media player's state changes to `off` and immediately issue the following command in your ADB shell (using whatever filename/location you want to output to):
```
adb shell dumpsys display > debug.log
```

**or** run a small loop that automatically saves the output every N seconds, e.g. (sorry for my likely poor shell scripting abilities):
```
while sleep 5; do date >> debug.log && adb shell dumpsys display >> debug.log; done
```

From there you can open the file and inspect all the various display state info at the time HA saw the errant state to see if maybe `mScreenState` isn't `ON`, and if that's the case, if there's another parameter that could be targeted instead.
@breakthestatic Got the logs when HA sees OFF however mScreenState is ON in logs. You can check if you find something else.
[debug.log](https://github.com/JeffLIrion/python-androidtv/files/9895587/debug.log)
[debug2.log](https://github.com/JeffLIrion/python-androidtv/files/9895588/debug2.log)

Were these just manual dumps after noticing the player status switching to `off`? If that's the case (and even with the logging loop) there is a chance that the single call was different than one that occurred just before it.

@ollo69 or @JeffLIrion, are you familiar with the flow of data from the ADB commands in constants.py through to the HA state? I'm trying to see if we can get the raw data that ADB returns to determine if the ADB state is incorrect, or if it's something further downstream. I *believe* that it's something later on, or perhaps some different (but related) ADB call that is failing, but I'm not very well-versed in this and without being able to reproduce it myself, am having a hard time trying to get any data to help debug.
> Were these just manual dumps after noticing the player status switching to `off`? If that's the case (and even with the logging loop) there is a chance that the single call was different than one that occurred just before it.

Yes manual right after state changed. I didn't managed to get the loop work and had very little time this weekend so at least I got the manual log however I will take a look at the loop in the following days.
Confirming the fix below works for me as well (CCWGTV updated to Android 12 last night), with the same issue of "off status" being reported every several minutes. I have an automation set to update status of my CCWGTV every 3 seconds and that is the duration of the off status

![Screenshot 2022-11-12 10 42 46](https://user-images.githubusercontent.com/25775578/201482127-c565eb7b-d703-411c-a507-319b73053aa6.png)

It appears this problem only occurs when the playstate is "Playing" or "Paused". Not an issue when device is standby or idle.

**I am happy to help with debugging. Let me know what I can do.**



> I think I might have found a fix for this already, but haven't had time to fully test & open a PR yet. It seems that the `CMD_SCREEN_ON` checks aren't sufficient for Android 12 on the Chromecast with Google TV. Adding a check for `mScreenState=ON` in the `display` output of `dumpsys` looks to correctly report the screen state, e.g.
> 
> ```
> CMD_SCREEN_ON = (
>     "(dumpsys power | grep 'Display Power' | grep -q 'state=ON' || dumpsys power | grep -q 'mScreenOn=true' || dumpsys display | grep -q 'mScreenState=ON')"
> )
> ```
> 
> From there, since the screen is on, the rest of the logic seems to work so far. But once again, I haven't tested _everything_ yet, and also haven't regression tested other devices (e.g. my Nvidia Shield).
> 
> I recall reading up a bit on a major architectural shift for this project during the last major Android version bump, but am not sure specifically what changed to make it easier to add more device-specific commands (perhaps something to do with custom commands???)
> 
> In the long-run, it would seem better to have device profiles (something like ZWaveJS does I think) instead of a lot of `if android version == TARGET_VERSION then command x, else command y"`. E.g. have a base profile with the most common/standard adb commands that each device profile entry would inherit from and override any specific commands necessary for that device/version combo. I'm not a Python dev though, so an undertaking like that might be a bit more for me to attempt.


Hello @breakthestatic.
Finally had time to loop the logging but unfortunatelly as you mentioned before there is no difference as with manual log.
Below you can find collected logs so you can double check if I missed something.
Log while state was playing starts on line 6556 changed to off line 6901.
[debug.log](https://github.com/JeffLIrion/python-androidtv/files/9997136/debug.log)
![image](https://user-images.githubusercontent.com/68992112/201521014-7d0fc7d5-ed05-4c93-a380-504f6b949076.png)

How Can I attempt this fix on Hassio?
Is anyone successfully using Android's `sendevent` command with the latest Android 12 based CCwGTV? `sendevent` replaces the default `input` command for those with a remote on Home Assistant and stopped working Android 10. My device is in another room so I can't use the Google remote
> > I can help test this ;) I have valid device ;)
> 
> What type of install do you have? I'm running docker, so I had to shell into the container and manually make the edit to `/usr/local/lib/python3.10/site-packages/androidtv/constants.py` and restart the container afterwards. I'm not sure how different that would be for a supervised install (which I think also runs in a docker container?)
> 
> In any event, if you can get to that file in your install and change
> 
> https://github.com/JeffLIrion/python-androidtv/blob/b1425b1b0d1d826e25948fad15ca3650433e3d5d/androidtv/constants.py#L179-L182
> 
> to the code snippet in my prior comment (here it is again):
> 
> ```
> CMD_SCREEN_ON = (
>     "(dumpsys power | grep 'Display Power' | grep -q 'state=ON' || dumpsys power | grep -q 'mScreenOn=true' || dumpsys display | grep -q 'mScreenState=ON')"
> )
> ```
> 
> That should be the extent of the fix. At that point, once the state is being correctly derived, it will be much easier to test other parts of the AndroidTV integration to see if further Android 12 changes are needed in addition to the device state.

I could confirm that helped me to recover my Google TV with android 12 as well on home-assistant integration.
Are we aware of any official release notes or documentation from Google mentioning this change to `dumpsys` or the underlying system it queries in Android TV 12? This might give us more confidence in the change we're making. Here are some docs that might be valuable to review:

https://developer.android.com/about/versions/12/behavior-changes-12
https://developer.android.com/about/versions/12/behavior-changes-all
I can also confirm that the CMD_SCREEN_ON fix corrects the hassio integration.
Hello, when this can be implemented into HA?
> Hello, when this can be implemented into HA?

I'll make a PR with the mentioned CMD_SCREEN_ON change.

I have confirmed that this works to regain get_properties() functionality, but there are probably still changes that need to be made to address the dropout issues people are having: https://github.com/JeffLIrion/python-androidtv/issues/323#issuecomment-1312511072

I am not running this in HASS, as I wanted to have a good development environment, so I cannot confirm whether or not I see the dropout-issue. I will do some more testing on this today, however.
Hi @Dillton 

In readme of this repo owner said that he have no time to work on this project.
I would not expect any fix soon. 
Someone from community need to check this.
I think if HA officially use this repo should be take care by HA ;) but this is only my dream for perfect world 
> In readme of this repo owner said that he have no time to work on this project.

@JeffLIrion  clear explain that he will not have time to work on fix, but PR are welcome. Anyone with some programming competence and a valid device for test can create PR on this repo, and I think that @JeffLIrion will found the time to review them. HA architecture is base on the fact that communication with devices are based on external and open source python library. This can be strength and weakness at the same time of this architecture, but that's it. I think that HA team will never work on external library, but this doesn't means that fix will not be implemented, this is just based on goodwill of the community.
I think I might have found a fix for this already, but haven't had time to fully test & open a PR yet. It seems that the `CMD_SCREEN_ON` checks aren't sufficient for Android 12 on the Chromecast with Google TV. Adding a check for `mScreenState=ON` in the `display` output of `dumpsys` looks to correctly report the screen state, e.g.
```
CMD_SCREEN_ON = (
    "(dumpsys power | grep 'Display Power' | grep -q 'state=ON' || dumpsys power | grep -q 'mScreenOn=true' || dumpsys display | grep -q 'mScreenState=ON')"
)
```
From there, since the screen is on, the rest of the logic seems to work so far. But once again, I haven't tested *everything* yet, and also haven't regression tested other devices (e.g. my Nvidia Shield).

I recall reading up a bit on a major architectural shift for this project during the last major Android version bump, but am not sure specifically what changed to make it easier to add more device-specific commands (perhaps something to do with custom commands???)

In the long-run, it would seem better to have device profiles (something like ZWaveJS does I think) instead of a lot of `if android version == TARGET_VERSION then command x, else command y"`. E.g. have a base profile with the most common/standard adb commands that each device profile entry would inherit from and override any specific commands necessary for that device/version combo. I'm not a Python dev though, so an undertaking like that might be a bit more for me to attempt.

I can help test this ;) I have valid device ;)
> I can help test this ;) I have valid device ;)

What type of install do you have? I'm running docker, so I had to shell into the container and manually make the edit to `/usr/local/lib/python3.10/site-packages/androidtv/constants.py` and restart the container afterwards. I'm not sure how different that would be for a supervised install (which I think also runs in a docker container?)

In any event, if you can get to that file in your install and change https://github.com/JeffLIrion/python-androidtv/blob/b1425b1b0d1d826e25948fad15ca3650433e3d5d/androidtv/constants.py#L179-L182
to the code snippet in my prior comment (here it is again):
```
CMD_SCREEN_ON = (
    "(dumpsys power | grep 'Display Power' | grep -q 'state=ON' || dumpsys power | grep -q 'mScreenOn=true' || dumpsys display | grep -q 'mScreenState=ON')"
)
```
That should be the extent of the fix. At that point, once the state is being correctly derived, it will be much easier to test other parts of the AndroidTV integration to see if further Android 12 changes are needed in addition to the device state.
> What type of install do you have? I'm running docker, so I had to shell into the container and manually make the edit to `/usr/local/lib/python3.10/site-packages/androidtv/constants.py` and restart the container afterwards

@breakthestatic, I suggest you to setup a HA dev environment as explained [here](https://developers.home-assistant.io/docs/development_environment/). It's quite simple (it works with windows, linux or mac), will simplify your tests and will avoid to hack your default HA installation.
> > What type of install do you have? I'm running docker, so I had to shell into the container and manually make the edit to `/usr/local/lib/python3.10/site-packages/androidtv/constants.py` and restart the container afterwards
> 
> @breakthestatic, I suggest you to setup a HA dev environment as explained [here](https://developers.home-assistant.io/docs/development_environment/). It's quite simple (it works with windows, linux or mac), will simplify your tests and will avoid to hack your default HA installation.

I already have that set up but am not sure how to make the needed change since it's in this library, not HA core. To test the fix, I was already using the dev env, but still manually changing the python-androidtv file in site-packages. 
> > I can help test this ;) I have valid device ;)
> 
> What type of install do you have? I'm running docker, so I had to shell into the container and manually make the edit to `/usr/local/lib/python3.10/site-packages/androidtv/constants.py` and restart the container afterwards. I'm not sure how different that would be for a supervised install (which I think also runs in a docker container?)
> 
> In any event, if you can get to that file in your install and change
> 
> https://github.com/JeffLIrion/python-androidtv/blob/b1425b1b0d1d826e25948fad15ca3650433e3d5d/androidtv/constants.py#L179-L182
> 
> 
> to the code snippet in my prior comment (here it is again):
> ```
> CMD_SCREEN_ON = (
>     "(dumpsys power | grep 'Display Power' | grep -q 'state=ON' || dumpsys power | grep -q 'mScreenOn=true' || dumpsys display | grep -q 'mScreenState=ON')"
> )
> ```
> 
> That should be the extent of the fix. At that point, once the state is being correctly derived, it will be much easier to test other parts of the AndroidTV integration to see if further Android 12 changes are needed in addition to the device state.

Evening. I can also help with testing with my Chromecast and so far I can say this seems to be the trick, thank you.
Modifyed my container and did some real life usage:
![image](https://user-images.githubusercontent.com/68992112/197410386-2e25aaab-c107-4d4f-bf0f-57b7f8bbf84b.png)
![image](https://user-images.githubusercontent.com/68992112/197410429-585a4475-3fb1-46bc-ae8a-d2d5254f52af.png)
![image](https://user-images.githubusercontent.com/68992112/197411625-a9b9037a-1d8c-4224-a9f4-9771afb65a88.png)

I will keep it modifyed like that and see.
@breakthestatic Do you need some specific testing?

I can confirm that this fixes the issue for me too (CCwGTV Android TV 12). Thanks!
Hi All 

i looking this path on my instance 
/usr/local/lib/python3.10/site-packages/androidtv/constants.py

But i cannot find it 

first of all i don't have python 3.10 folder i have only 3.9
also don't have folder site-packages 
i have only dist-packages

My installation is on virtual machine and up to date
> Hi All
> 
> i looking this path on my instance /usr/local/lib/python3.10/site-packages/androidtv/constants.py
> 
> But i cannot find it
> 
> first of all i don't have python 3.10 folder i have only 3.9 also don't have folder site-packages i have only dist-packages
> 
> My installation is on virtual machine and up to date

If it's Hass os in a VM you need to access home assistant core docker container shell. 
`docker exec -it $(docker ps -f name=homeassistant -q) bash` 
@breakthestatic Found an additional problem so there might be needed additional modification of the code.
The device goes off for 10 seconds sometimes as you can see on screen below:
![image](https://user-images.githubusercontent.com/68992112/197581673-c00eb782-4086-47e6-aaef-fc615b21f517.png)

> @breakthestatic Found an additional problem so there might be needed additional modification of the code. The device goes off for 10 seconds sometimes as you can see on screen below: ![image](https://user-images.githubusercontent.com/68992112/197581673-c00eb782-4086-47e6-aaef-fc615b21f517.png)

Not saying you are definitely wrong about needing some additional fixes, but I recall seeing behavior like this with the Nvidia Shield recently as well. I believe the integration polls the device every 10 seconds, so perhaps there is some logic that defaults the playing state to `off` if an individual poll result fails?

So far I haven't seen this myself on the Chromecast, but I have also not done much testing. I'll see if I can reproduce it if/when I have some spare time over the next few days. Also, if you are somewhat familiar w/ ADB as well, you could manually set up an ADB session on another computer and see if `mScreenState` actually changes its value during the time periods that HA is reporting it to be off.
Just a quick follow-up regarding the intermittent `off` state... I ran through several states over the past ~ 45minutes (idle to standby, then playing through a full episode in Plex, back to idle after the episode ended & back to playing once the next episode started):
![Screen Shot 2022-10-24 at 12 46 53 PM](https://user-images.githubusercontent.com/9346314/197613630-05dfb534-249b-4548-9f9c-2572b7806e14.png)

Once again, I'm not really familiar with the actual functionality of this library beyond the basic ADB commands used to determine state, but it seems like the `off` state is only set in a single place:
https://github.com/JeffLIrion/python-androidtv/blob/b1425b1b0d1d826e25948fad15ca3650433e3d5d/androidtv/androidtv/base_androidtv.py#L112-L114
Looking at this piece of code, it seems that only two things can trigger it, either an incorrect `screen_on` value or when the `current_app` is set to `off`. I'm still not 100% sure if a failed poll could return what is eventually interpreted as an incorrect `screen_on` state. I tried faking it by pulling my ethernet cable for ~20 seconds, but HA correctly interpreted that as "unavailable" in that case (not `off` as is seen in your screenshot), so it seems unlikely that a dropped poll can cause it.  That leaves either a truly incorrect reading of screen state (i.e if, for some reason your `mScreenState` isn't `ON` for that particular poll response), or an invalid `current_app`.

There's a bit more logic surrounding the state of `current_app` that I wasn't able to fully step through, but it seems like you could get a bad state via the custom state detection logic.  Do you know what app was running when you saw this (and do you possibly have any custom state detection rules configured)? Without being able to reproduce this myself, & not having deep-enough knowledge of this library (or language for that matter 😆), I'm not sure how much further I could get with this.
I was about to report this intermittent `off` state as well. For context I was watching HotD on hbomax 😅  and got some automations triggered based on the off state a couple of times. I'll try to reproduce it again although it seemed to be rather random.
![Screenshot_2022-10-25-00-18-20](https://user-images.githubusercontent.com/40600040/197635728-e6d1a851-5f3e-4c0b-bc36-2af5fd50f899.png)

@breakthestatic Really does not matter which application I think. I was watching youtube and netflix yesterday and with both the same behaviour. Sometimes also state changed to standby even when it should be playing.
Not really sure what's going on there :( My two Chromecasts have been very consistent with their state reporting since putting in the fix.

In Twitch, I noticed that whenever the stream goes from actively playing to buffering (doesn't happen often, but still), the state switches from `playing` to `idle`, so perhaps some of the logic I noted in my prior comment (the stuff concerning the app-specific state & fallback detection rules) is the cause. I believe at the bottom of `base_androidtv.py`, there's a single extra location where state is not explicitly set to pre-determined values (besides a couple app-specific rules for Bell Fibe & VRV, whatever those are):
https://github.com/JeffLIrion/python-androidtv/blob/b1425b1b0d1d826e25948fad15ca3650433e3d5d/androidtv/androidtv/base_androidtv.py#L208-L210
It seems that condition is rather open-ended, in that as long as none of the app-specific rules above it trigger, and there is no `media_session_state`, it will try to get the overall state from the current audio state (as long as it isn't `idle`). If `audio_state` is `off`, that could also seemingly lead to what you guys are seeing.

Maybe you could try adding extra logging at the bottom to see what all the various state variables look like at the time the problem occurs (i.e. put it right before line 228 in base_androidtv.py):
```
_LOGGER.debug("screen_on: %s", screen_on)
_LOGGER.debug("current_app: %s", current_app)
_LOGGER.debug("media_session_state: %s", media_session_state)
_LOGGER.debug("audio_state: %s", audio_state)
```
> ![Screen Shot 2022-10-24 at 12 46 53 PM](https://user-images.githubusercontent.com/9346314/197613630-05dfb534-249b-4548-9f9c-2572b7806e14.png)

a side-question @breakthestatic : did you reinstall/re-add your CCwGTV in HomeAssistant? I can see that the firmware shows "12" - mine CCwGTV upgraded itself over the night [probably - yesterday it was Android 10, today it's 12, and I didn't do anything ;)] but it still shows "10" in the firmware info in HA. of course all my automations stopped working [and I was using different ones according to which app is running with what state], but I'm too afraid to fiddle "with system" or try your hot fixes. I'll just wait patiently :)

also I've noticed that service `androidtv.adb_command` with command `GET_PROPERTIES` - doesn't give any new response, it just shows something old, not changed according to current state. it probably won't help you, but I didn't wanted to come here only with questions :)

Hey @pejotigrek, I didn't reinstall my Chromecast, but I have both reloaded the integration, as well as completely restarted HA. I'm not sure which (or both) of those might have updated the firmware version, but I would definitely be sure that you are seeing the updated version before doing further debugging. When my Chromecast was updated to 12 (already said fw12 in HA), doing the `GET_PROPERTIES` call correctly populated the `adb_response` (just with the incorrect `screen_on` state).
> Hey @pejotigrek, I didn't reinstall my Chromecast, but I have both reloaded the integration, as well as completely restarted HA. I'm not sure which (or both) of those might have updated the firmware version, but I would definitely be sure that you are seeing the updated version before doing further debugging. When my Chromecast was updated to 12 (already said fw12 in HA), doing the `GET_PROPERTIES` call correctly populated the `adb_response` (just with the incorrect `screen_on` state).

ok checked now, reloading did the trick! thanks! :) also looks like `GET_PROPERTIES` was populated with updated info, but as I am away from home [which is empty right now] - I'll check the whole feedback little bit later [I assume that wakelocks etc. should work good].
thank you!
ok, tested, my `adb_response` isn't correctly populated. from the whole feedback line:
`{'screen_on': False, 'awake': True, 'audio_state': None, 'wake_lock_size': 2, 'current_app': None, 'media_session_state': None, 'audio_output_device': None, 'is_volume_muted': None, 'volume': None, 'running_apps': None, 'hdmi_input': None}` only the _wake_lock_size_ changes with different integers [1-4] depending on what streaming app is used and what state it is.
I suppose it's because I didn't made any changes to the python files.
Yeah, I believe that *most* of the values are dependent on `screen_on` being correctly populated. Regrettably, without others contributing to debugging their specific issues, not sure when this will get fixed. I can definitely open a PR for the change, but I'm not sure it will get merged with several people still reporting abnormal state.
I'm also affected by this. I applied the `CMD_SCREEN_ON` fix and restarted HA, everything seems to be working fine (thanks @breakthestatic). The state is reported correctly, and a few automations I have the rely on the `app_id` attribute and `androidtv/adb_command` look good (although I didn't do any extensive testing).

Let me know if you want me to test anything specific.

If the change works for some people and is unlikely to break anything, maybe it's worth releasing it so that others can test more easily without having to manually to edit code inside containers.




> If the change works for some people and is unlikely to break anything, maybe it's worth releasing it so that others can test more easily without having to manually to edit code inside containers.

maybe I'm too naive, but I guess that it won't be worse than "not working" as it is without fixes, so yeah, release would be cool :)

but maybe there's an relatively easy way to put it as custom integration - just for testing? so it could be checked without fiddling within dockers?
> Not really sure what's going on there :( My two Chromecasts have been very consistent with their state reporting since putting in the fix.
> 
> In Twitch, I noticed that whenever the stream goes from actively playing to buffering (doesn't happen often, but still), the state switches from `playing` to `idle`, so perhaps some of the logic I noted in my prior comment (the stuff concerning the app-specific state & fallback detection rules) is the cause. I believe at the bottom of `base_androidtv.py`, there's a single extra location where state is not explicitly set to pre-determined values (besides a couple app-specific rules for Bell Fibe & VRV, whatever those are):
> 
> https://github.com/JeffLIrion/python-androidtv/blob/b1425b1b0d1d826e25948fad15ca3650433e3d5d/androidtv/androidtv/base_androidtv.py#L208-L210
> 
> 
> It seems that condition is rather open-ended, in that as long as none of the app-specific rules above it trigger, and there is no `media_session_state`, it will try to get the overall state from the current audio state (as long as it isn't `idle`). If `audio_state` is `off`, that could also seemingly lead to what you guys are seeing.
> Maybe you could try adding extra logging at the bottom to see what all the various state variables look like at the time the problem occurs (i.e. put it right before line 228 in base_androidtv.py):
> 
> ```
> _LOGGER.debug("screen_on: %s", screen_on)
> _LOGGER.debug("current_app: %s", current_app)
> _LOGGER.debug("media_session_state: %s", media_session_state)
> _LOGGER.debug("audio_state: %s", audio_state)
> ```

Hi @breakthestatic I just added extra logging and will watch some movie today so hopefully we will learn something more about the states.

EDIT1: So far HA is not able to load the integration with added logging.
EDIT2: Solved, cant use tabs only spaces in editor, oh my...
> > Not really sure what's going on there :( My two Chromecasts have been very consistent with their state reporting since putting in the fix.
> > In Twitch, I noticed that whenever the stream goes from actively playing to buffering (doesn't happen often, but still), the state switches from `playing` to `idle`, so perhaps some of the logic I noted in my prior comment (the stuff concerning the app-specific state & fallback detection rules) is the cause. I believe at the bottom of `base_androidtv.py`, there's a single extra location where state is not explicitly set to pre-determined values (besides a couple app-specific rules for Bell Fibe & VRV, whatever those are):
> > https://github.com/JeffLIrion/python-androidtv/blob/b1425b1b0d1d826e25948fad15ca3650433e3d5d/androidtv/androidtv/base_androidtv.py#L208-L210
> > 
> > It seems that condition is rather open-ended, in that as long as none of the app-specific rules above it trigger, and there is no `media_session_state`, it will try to get the overall state from the current audio state (as long as it isn't `idle`). If `audio_state` is `off`, that could also seemingly lead to what you guys are seeing.
> > Maybe you could try adding extra logging at the bottom to see what all the various state variables look like at the time the problem occurs (i.e. put it right before line 228 in base_androidtv.py):
> > ```
> > _LOGGER.debug("screen_on: %s", screen_on)
> > _LOGGER.debug("current_app: %s", current_app)
> > _LOGGER.debug("media_session_state: %s", media_session_state)
> > _LOGGER.debug("audio_state: %s", audio_state)
> > ```
> 
> Hi @breakthestatic I just added extra logging and will watch some movie today so hopefully we will learn something more about the states.
> 
> EDIT1: So far HA is not able to load the integration with added logging. EDIT2: Solved, cant use tabs only spaces in editor, oh my...

@breakthestatic Ok got some logs, you can check below.
When state changes to off:
2022-10-28 21:09:19.164 DEBUG (MainThread) [androidtv.androidtv.base_androidtv] screen_on: False
2022-10-28 21:09:19.165 DEBUG (MainThread) [androidtv.androidtv.base_androidtv] current_app: None
2022-10-28 21:09:19.165 DEBUG (MainThread) [androidtv.androidtv.base_androidtv] media_session_state: None
2022-10-28 21:09:19.165 DEBUG (MainThread) [androidtv.androidtv.base_androidtv] audio_state: None

When state changes to standby:
2022-10-28 21:07:09.204 DEBUG (MainThread) [androidtv.androidtv.base_androidtv] screen_on: True
2022-10-28 21:07:09.204 DEBUG (MainThread) [androidtv.androidtv.base_androidtv] current_app: None
2022-10-28 21:07:09.204 DEBUG (MainThread) [androidtv.androidtv.base_androidtv] media_session_state: None
2022-10-28 21:07:09.204 DEBUG (MainThread) [androidtv.androidtv.base_androidtv] audio_state: None

![image](https://user-images.githubusercontent.com/68992112/198714472-4bc447cc-4d9b-4a56-a28d-584d243c2bcd.png)

Seems like no data available at that time?
Hmm, so it seems *likely* the actual dumpsys response is incorrect when the problem occurs. The only extra logic that is performed before it gets to the state logic is an inversion.  The actual ADB command performs a silent grep for the commands, which returns a `0` exit code when found (meaning it found one of the screen on strings), and an exit code of `1` when the grep fails. Since normal boolean logic treats `0` as false and `1` as true, there's a bit of code that *flips* the adb command response and returns `1` if the screen is on and `0` if it's off:
https://github.com/JeffLIrion/python-androidtv/blob/b1425b1b0d1d826e25948fad15ca3650433e3d5d/androidtv/constants.py#L72-L73

Are you familiar with ADB at all? If so, perhaps you could set up an ADB connection to your Chromecast, and then either set up an automation to alert you when the media player's state changes to `off` and immediately issue the following command in your ADB shell (using whatever filename/location you want to output to):
```
adb shell dumpsys display > debug.log
```

**or** run a small loop that automatically saves the output every N seconds, e.g. (sorry for my likely poor shell scripting abilities):
```
while sleep 5; do date >> debug.log && adb shell dumpsys display >> debug.log; done
```

From there you can open the file and inspect all the various display state info at the time HA saw the errant state to see if maybe `mScreenState` isn't `ON`, and if that's the case, if there's another parameter that could be targeted instead.
@breakthestatic Got the logs when HA sees OFF however mScreenState is ON in logs. You can check if you find something else.
[debug.log](https://github.com/JeffLIrion/python-androidtv/files/9895587/debug.log)
[debug2.log](https://github.com/JeffLIrion/python-androidtv/files/9895588/debug2.log)

Were these just manual dumps after noticing the player status switching to `off`? If that's the case (and even with the logging loop) there is a chance that the single call was different than one that occurred just before it.

@ollo69 or @JeffLIrion, are you familiar with the flow of data from the ADB commands in constants.py through to the HA state? I'm trying to see if we can get the raw data that ADB returns to determine if the ADB state is incorrect, or if it's something further downstream. I *believe* that it's something later on, or perhaps some different (but related) ADB call that is failing, but I'm not very well-versed in this and without being able to reproduce it myself, am having a hard time trying to get any data to help debug.
> Were these just manual dumps after noticing the player status switching to `off`? If that's the case (and even with the logging loop) there is a chance that the single call was different than one that occurred just before it.

Yes manual right after state changed. I didn't managed to get the loop work and had very little time this weekend so at least I got the manual log however I will take a look at the loop in the following days.
Confirming the fix below works for me as well (CCWGTV updated to Android 12 last night), with the same issue of "off status" being reported every several minutes. I have an automation set to update status of my CCWGTV every 3 seconds and that is the duration of the off status

![Screenshot 2022-11-12 10 42 46](https://user-images.githubusercontent.com/25775578/201482127-c565eb7b-d703-411c-a507-319b73053aa6.png)

It appears this problem only occurs when the playstate is "Playing" or "Paused". Not an issue when device is standby or idle.

**I am happy to help with debugging. Let me know what I can do.**



> I think I might have found a fix for this already, but haven't had time to fully test & open a PR yet. It seems that the `CMD_SCREEN_ON` checks aren't sufficient for Android 12 on the Chromecast with Google TV. Adding a check for `mScreenState=ON` in the `display` output of `dumpsys` looks to correctly report the screen state, e.g.
> 
> ```
> CMD_SCREEN_ON = (
>     "(dumpsys power | grep 'Display Power' | grep -q 'state=ON' || dumpsys power | grep -q 'mScreenOn=true' || dumpsys display | grep -q 'mScreenState=ON')"
> )
> ```
> 
> From there, since the screen is on, the rest of the logic seems to work so far. But once again, I haven't tested _everything_ yet, and also haven't regression tested other devices (e.g. my Nvidia Shield).
> 
> I recall reading up a bit on a major architectural shift for this project during the last major Android version bump, but am not sure specifically what changed to make it easier to add more device-specific commands (perhaps something to do with custom commands???)
> 
> In the long-run, it would seem better to have device profiles (something like ZWaveJS does I think) instead of a lot of `if android version == TARGET_VERSION then command x, else command y"`. E.g. have a base profile with the most common/standard adb commands that each device profile entry would inherit from and override any specific commands necessary for that device/version combo. I'm not a Python dev though, so an undertaking like that might be a bit more for me to attempt.


Hello @breakthestatic.
Finally had time to loop the logging but unfortunatelly as you mentioned before there is no difference as with manual log.
Below you can find collected logs so you can double check if I missed something.
Log while state was playing starts on line 6556 changed to off line 6901.
[debug.log](https://github.com/JeffLIrion/python-androidtv/files/9997136/debug.log)
![image](https://user-images.githubusercontent.com/68992112/201521014-7d0fc7d5-ed05-4c93-a380-504f6b949076.png)

How Can I attempt this fix on Hassio?
Is anyone successfully using Android's `sendevent` command with the latest Android 12 based CCwGTV? `sendevent` replaces the default `input` command for those with a remote on Home Assistant and stopped working Android 10. My device is in another room so I can't use the Google remote
> > I can help test this ;) I have valid device ;)
> 
> What type of install do you have? I'm running docker, so I had to shell into the container and manually make the edit to `/usr/local/lib/python3.10/site-packages/androidtv/constants.py` and restart the container afterwards. I'm not sure how different that would be for a supervised install (which I think also runs in a docker container?)
> 
> In any event, if you can get to that file in your install and change
> 
> https://github.com/JeffLIrion/python-androidtv/blob/b1425b1b0d1d826e25948fad15ca3650433e3d5d/androidtv/constants.py#L179-L182
> 
> to the code snippet in my prior comment (here it is again):
> 
> ```
> CMD_SCREEN_ON = (
>     "(dumpsys power | grep 'Display Power' | grep -q 'state=ON' || dumpsys power | grep -q 'mScreenOn=true' || dumpsys display | grep -q 'mScreenState=ON')"
> )
> ```
> 
> That should be the extent of the fix. At that point, once the state is being correctly derived, it will be much easier to test other parts of the AndroidTV integration to see if further Android 12 changes are needed in addition to the device state.

I could confirm that helped me to recover my Google TV with android 12 as well on home-assistant integration.
Are we aware of any official release notes or documentation from Google mentioning this change to `dumpsys` or the underlying system it queries in Android TV 12? This might give us more confidence in the change we're making. Here are some docs that might be valuable to review:

https://developer.android.com/about/versions/12/behavior-changes-12
https://developer.android.com/about/versions/12/behavior-changes-all
I can also confirm that the CMD_SCREEN_ON fix corrects the hassio integration.
Hello, when this can be implemented into HA?
> Hello, when this can be implemented into HA?

I'll make a PR with the mentioned CMD_SCREEN_ON change.

I have confirmed that this works to regain get_properties() functionality, but there are probably still changes that need to be made to address the dropout issues people are having: https://github.com/JeffLIrion/python-androidtv/issues/323#issuecomment-1312511072

I am not running this in HASS, as I wanted to have a good development environment, so I cannot confirm whether or not I see the dropout-issue. I will do some more testing on this today, however.

Fix patch:
diff --git a/androidtv/constants.py b/androidtv/constants.py
index 325270e..175e4d8 100644
--- a/androidtv/constants.py
+++ b/androidtv/constants.py
@@ -177,9 +177,7 @@ class DeviceEnum(IntEnum):
 CMD_INSTALLED_APPS = "pm list packages"
 
 #: Determine if the device is on
-CMD_SCREEN_ON = (
-    "(dumpsys power | grep 'Display Power' | grep -q 'state=ON' || dumpsys power | grep -q 'mScreenOn=true')"
-)
+CMD_SCREEN_ON = "(dumpsys power | grep 'Display Power' | grep -q 'state=ON' || dumpsys power | grep -q 'mScreenOn=true' || dumpsys display | grep -q 'mScreenState=ON')"
 
 #: Get the "STREAM_MUSIC" block from ``dumpsys audio``
 CMD_STREAM_MUSIC = r"dumpsys audio | grep '\- STREAM_MUSIC:' -A 11"


Test patch:
diff --git a/tests/test_constants.py b/tests/test_constants.py
index 57034c6..5f3fb45 100644
--- a/tests/test_constants.py
+++ b/tests/test_constants.py
@@ -185,13 +185,13 @@ def test_constants(self):
         # CMD_SCREEN_ON
         self.assertCommand(
             constants.CMD_SCREEN_ON,
-            r"(dumpsys power | grep 'Display Power' | grep -q 'state=ON' || dumpsys power | grep -q 'mScreenOn=true')",
+            r"(dumpsys power | grep 'Display Power' | grep -q 'state=ON' || dumpsys power | grep -q 'mScreenOn=true' || dumpsys display | grep -q 'mScreenState=ON')",
         )
 
         # CMD_SCREEN_ON_AWAKE_WAKE_LOCK_SIZE
         self.assertCommand(
             constants.CMD_SCREEN_ON_AWAKE_WAKE_LOCK_SIZE,
-            r"(dumpsys power | grep 'Display Power' | grep -q 'state=ON' || dumpsys power | grep -q 'mScreenOn=true') && echo -e '1\c' || echo -e '0\c' && dumpsys power | grep mWakefulness | grep -q Awake && echo -e '1\c' || echo -e '0\c' && dumpsys power | grep Locks | grep 'size='",
+            r"(dumpsys power | grep 'Display Power' | grep -q 'state=ON' || dumpsys power | grep -q 'mScreenOn=true' || dumpsys display | grep -q 'mScreenState=ON') && echo -e '1\c' || echo -e '0\c' && dumpsys power | grep mWakefulness | grep -q Awake && echo -e '1\c' || echo -e '0\c' && dumpsys power | grep Locks | grep 'size='",
         )
 
         # CMD_SERIALNO
@@ -203,25 +203,25 @@ def test_constants(self):
         # CMD_TURN_OFF_ANDROIDTV
         self.assertCommand(
             constants.CMD_TURN_OFF_ANDROIDTV,
-            r"(dumpsys power | grep 'Display Power' | grep -q 'state=ON' || dumpsys power | grep -q 'mScreenOn=true') && input keyevent 26",
+            r"(dumpsys power | grep 'Display Power' | grep -q 'state=ON' || dumpsys power | grep -q 'mScreenOn=true' || dumpsys display | grep -q 'mScreenState=ON') && input keyevent 26",
         )
 
         # CMD_TURN_OFF_FIRETV
         self.assertCommand(
             constants.CMD_TURN_OFF_FIRETV,
-            r"(dumpsys power | grep 'Display Power' | grep -q 'state=ON' || dumpsys power | grep -q 'mScreenOn=true') && input keyevent 223",
+            r"(dumpsys power | grep 'Display Power' | grep -q 'state=ON' || dumpsys power | grep -q 'mScreenOn=true' || dumpsys display | grep -q 'mScreenState=ON') && input keyevent 223",
         )
 
         # CMD_TURN_ON_ANDROIDTV
         self.assertCommand(
             constants.CMD_TURN_ON_ANDROIDTV,
-            r"(dumpsys power | grep 'Display Power' | grep -q 'state=ON' || dumpsys power | grep -q 'mScreenOn=true') || input keyevent 26",
+            r"(dumpsys power | grep 'Display Power' | grep -q 'state=ON' || dumpsys power | grep -q 'mScreenOn=true' || dumpsys display | grep -q 'mScreenState=ON') || input keyevent 26",
         )
 
         # CMD_TURN_ON_FIRETV
         self.assertCommand(
             constants.CMD_TURN_ON_FIRETV,
-            r"(dumpsys power | grep 'Display Power' | grep -q 'state=ON' || dumpsys power | grep -q 'mScreenOn=true') || (input keyevent 26 && input keyevent 3)",
+            r"(dumpsys power | grep 'Display Power' | grep -q 'state=ON' || dumpsys power | grep -q 'mScreenOn=true' || dumpsys display | grep -q 'mScreenState=ON') || (input keyevent 26 && input keyevent 3)",
         )
 
         # CMD_VERSION