lukasroegner / homebridge-apple-tv-remote

Plugin for controlling Apple TVs in homebridge.
MIT License
132 stars 13 forks source link

No longer working in tvOS 15 #105

Open KibosJ opened 3 years ago

KibosJ commented 3 years ago

I know it's a beta, just wanted to give a heads up that this doesn't work in tvOS 15

shemege commented 3 years ago

@matcik890 OK try this:

Many operations performed by Homebridge Config UI X, such as installing plugins, upgrading Homebridge and viewing the logs can require root permissions. You can run the Homebridge service as root or you can enable the sudo option in the config.

"platforms": [ { "platform": "config", "name": "Config", "port": 8080, "sudo": true } ]

When sudo mode is enabled Homebridge Config UI X will use sudo when executing installing, removing or upgrading plugins, viewing the logs using the Logs From File or Logs From Systemd method, and when upgrading Homebridge. It will not be used for Logs From Custom Command or custom restart commands.

Password-less sudo required

For sudo mode to work password-less sudo is required. You can enable password-less sudo by adding this entry to the bottom of your /etc/sudoers file (use visudo to edit the file!):

homebridge ALL=(ALL) NOPASSWD: ALL or pi ALL=(ALL) NOPASSWD: ALL Replace homebridge with the actual user you are running Homebridge as.

matcik890 commented 3 years ago

homebridge ALL=(ALL) NOPASSWD: ALL

@matcik890 ХОРОШО, попробуй это:

Многие операции, выполняемые Homebridge Config UI X, такие как установка плагинов, обновление Homebridge и просмотр журналов, могут потребовать прав суперпользователя. Вы можете запустить службу Homebridge от имени root или включить опцию sudo в конфигурации.

"platforms": [ { "platform": "config", "name": "Config", "port": 8080, "sudo": true } ]

Когда включен режим sudo, Конфигурация домашнего моста UI X будет использовать sudo при установке, удалении или обновлении подключаемых модулей, просмотре журналов с использованием журналов Из файла или журналов Из метода Systemd, а также при обновлении домашнего моста. Он не будет использоваться для журналов Пользовательских команд или пользовательских команд перезапуска.

Судо без пароля требуется

Для работы в режиме sudo требуется sudo без пароля. Вы можете включить sudo без пароля, добавив эту запись в нижнюю часть /etc/sudoersфайла (используйте visudo для редактирования файла!):

homebridge ALL=(ALL) NOPASSWD: ALL или pi ALL=(ALL) NOPASSWD: ALL замените homebridge фактическим пользователем, от имени которого вы запускаете Homebridge.

Thanks for the advice! But I do not know if I understood you correctly. I added the string "sudo" to the homebridge configuration: true,

"bridge": { "name": "Homebridge 34C1", "username": "0E:87:6D:97:34:C1", "port": 51248, "sudo": true, "ping": "999-99-999"

and also I checked /etc/sudoers, but it already contains pi ALL=(ALL) NOPASSWD: ALL

Maybe I didn't understand something, I'm not very good at subtleties 1345 .

shemege commented 3 years ago

@matcik890 I checked your posts, but owner of your atvremote binaries is user homebridge Finaly try change owner for your atv* binaries sudo chown pi.pi -R /home/pi/.local/bin/

matcik890 commented 3 years ago

@matcik890 Я проверил ваши сообщения, но владельцем ваших двоичных файлов atvremote является пользовательhomebridge, Наконец, попробуйте сменить владельца для ваших двоичных файлов atv* sudo chown pi.pi -R /home/pi/.local/bin/

Changing the user to pi didn't help either. I tried to run the command from the homebridge user via the sudo -u homebridge command /var/lib/homebridge/tvremote/appletv_on.sh , but in response I get this message /var/lib/homebridge/tvremote/appletv_on.sh: 1: /var/lib/homebridge/tvremote/appletv_on.sh: atvremote: not found. How can this be fixed? Access to the directory and all files in it is provided by chmod 777, the user and the homebridge group.

andypburke commented 3 years ago

@MatGriffin your workaround works for me, thanks for posting. One odd thing though is the power state isn't recognised properly in homebridge. Even when it is true it shows false and then changes the switch state even when the Apple TV is on. Any ideas on that one?

MatGriffin commented 3 years ago

@MatGriffin your workaround works for me, thanks for posting. One odd thing though is the power state isn't recognised properly in homebridge. Even when it is true it shows false and then changes the switch state even when the Apple TV is on. Any ideas on that one?

Hi Andy, Good to hear it's working. My button state is the same, I've not paid too much attention to fixing as I tend to operate via voice commands. If I get time I'll have a look.

andypburke commented 3 years ago

@MatGriffin your workaround works for me, thanks for posting. One odd thing though is the power state isn't recognised properly in homebridge. Even when it is true it shows false and then changes the switch state even when the Apple TV is on. Any ideas on that one?

Hi Andy, Good to hear it's working. My button state is the same, I've not paid too much attention to fixing as I tend to operate via voice commands. If I get time I'll have a look.

Yes I do the same with Alexa but looked to see how I could fix it anyway. It seems to be related to the script1.flag file so I added the following lines to the appletv_on.sh and appletv_off.sh. It is a bit crude but seems to work

Added to appletv_on.sh an extra line touch /var/lib/homebridge/script1.flag

Added to appletv_off.sh an extra line rm /var/lib/homebridge/script1.flag

NorthernMan54 commented 3 years ago

100% agreed on the alexa voice control as the way to go here. Is your wording with Alexa clumsy now based on the workaround?

In my setup, turning off/on and pause/resume were one of the highest used functions.

MatGriffin commented 3 years ago

Using Alexa as well, just have it in a routine.

andypburke commented 3 years ago

Yes same. Use routines to make it easier to control multiple devices.

DarKOrange75 commented 3 years ago

@matcik890 Я проверил ваши сообщения, но владельцем ваших двоичных файлов atvremote является пользовательhomebridge, Наконец, попробуйте сменить владельца для ваших двоичных файлов atv* sudo chown pi.pi -R /home/pi/.local/bin/

Changing the user to pi didn't help either. I tried to run the command from the homebridge user via the sudo -u homebridge command /var/lib/homebridge/tvremote/appletv_on.sh , but in response I get this message /var/lib/homebridge/tvremote/appletv_on.sh: 1: /var/lib/homebridge/tvremote/appletv_on.sh: atvremote: not found. How can this be fixed? Access to the directory and all files in it is provided by chmod 777, the user and the homebridge group.

I fixed the issue by sudoing the pi user in all the 3 scripts:

sudo -u pi /home/pi/.local/bin/atvremote -s 192.168.1.11 --airplay-credentials

Now everything is working, hope it will help you.

cristian5th commented 3 years ago

Hi. In my case I use it more as a trigger to control other things. Like switching the lights off when Apple TV starts playing, or switching off the subwoofer when Apple TV turns off. Does this workaround provide the play and on/off status as the original plugin? Thanks.

andypburke commented 3 years ago

Hi. In my case I use it more as a trigger to control other things. Like switching the lights off when Apple TV starts playing, or switching off the subwoofer when Apple TV turns off. Does this workaround provide the play and on/off status as the original plugin? Thanks.

I am sure you can if you create specific scripts to perform those functions. You need to check the instructions on how to do this via atvremote https://pyatv.dev/documentation/atvremote/ and then add them to the Script2 plugin

matcik890 commented 3 years ago

@matcik890 Я проверил ваши сообщения, но владельцем ваших двоичных файлов atvremote является пользовательhomebridge, Наконец, попробуйте сменить владельца для ваших двоичных файлов atv* sudo chown pi.pi -R /home/pi/.local/bin/

Изменение пользователя на pi тоже не помогло. Я попытался выполнить команду от пользователя homebridge с помощью команды sudo-u homebridge /var/lib/homebridge/tvremote/appletv_on.sh , но в ответ я получаю это сообщение /var/lib/homebridge/tvremote/appletv_on.sh: 1: /var/lib/homebridge/tvremote/appletv_on.sh: примечание: не найдено. Как это можно исправить? Доступ к каталогу и всем файлам в нем предоставляется chmod 777, пользователем и группой homebridge.

Я исправил проблему, отправив пользователя pi во всех 3 сценариях:

sudo -u pi /home/pi/.local/bin/atvremote -s 192.168.1.11 --airplay-учетные данные

Теперь все работает, надеюсь, это вам поможет. Yeah, great, it helped me! thank you!!

cristian5th commented 3 years ago

@MatGriffin your workaround works for me, thanks for posting. One odd thing though is the power state isn't recognised properly in homebridge. Even when it is true it shows false and then changes the switch state even when the Apple TV is on. Any ideas on that one?

Hi Andy, Good to hear it's working. My button state is the same, I've not paid too much attention to fixing as I tend to operate via voice commands. If I get time I'll have a look.

Hi. I believe the issue is within the configuration of the Script 2 plugin. For the previously posted shell scripts to work properly, the plugin should be configured like this:

{
    "accessory": "Script2",
    "name": "ATV",
    "on": "/var/lib/homebridge/appletv_on.sh",
    "off": "/var/lib/homebridge/appletv_off.sh",
    "state": "/var/lib/homebridge/appletv_state.sh",
    "on_value": "PowerState.On"
}

Either the "state" or the "fileState" option is used, but not both at the same time. Because the stdout of the _appletvstate.sh is PowerState.On or PowerState.Off, the one that you want the plugin to consider to be the "on_value" is PowerState.On. This will give you the right state of the Apple TV power.

Regretfully, the state is only updating upon request. That is, when you open the Home app or when you execute any of the two other scripts. This means that, if you use your remote to power on the Apple TV, the state will not switch automatically and your automations, like turning on the subwoofer, will not be executed either. I keep on looking for a solution.

cristian5th commented 3 years ago

I finally made it work the way I want it. I will share here how to do it in case somebody is interested. Of course, all is based on @njuart's proposal to use @postlund's pyatv. The solution to call the shell scripts with Script2 Ventrilo plugin as proposed by @MatGriffin is not updating the status of the Apple TV if you do not open the Home app, and because I want some automations to work even when the Home app is not in use, then I had to use another option.

@shemege had originally proposed to use homebridge-cmd4 plugin and this plugin has some polling capabilities that make it all work. Let's have a look at it.

First, the configuration for the homebridge-cmd4 plugin. This plugin brings you infinite possibilities. I stick to the classic switch. There are two switches, one for power on/off and one for play/pause. Interval is the number of seconds for a new execution of the scripts; as I configured, the scripts will run every 5 seconds.

{
    "platform": "Cmd4",
    "name": "Cmd4",
    "interval": 5,
    "timeout": 4000,
    "stateChangeResponseTime": 3,
    "queueTypes": [
        {
            "queue": "A",
            "queueType": "WoRm"
        }
    ],
    "accessories": [
        {
            "type": "Switch",
            "displayName": "Apple TV Power",
            "on": "FALSE",
            "queue": "A",
            "polling": [
                {
                    "characteristic": "on"
                }
            ],
            "state_cmd": "bash /var/lib/homebridge/appletv_powerstate.sh"
        },
        {
            "type": "Switch",
            "displayName": "Apple TV Play State",
            "on": "FALSE",
            "queue": "A",
            "polling": [
                {
                    "characteristic": "on"
                }
            ],
            "state_cmd": "bash /var/lib/homebridge/appletv_playstate.sh"
        }
    ]
}

Now let's have a look at the scripts. You will see that they are exactly the same and the only change is the call sent to atvremote. Of course, you will need to change ATV_id and airplay_credentials to suit your Apple TV identifier for the first one, and your airplay pairing credentials for the second one.

appletv_powerstate.sh

#!/bin/bash

set -e

# Exit immediately for unbound variables.
set -u

length=$#
device=""
io=""
characteristic=""
option=""
ATV_id="50:27:37:43:F0:07"
airplay_credentials="c559e2a53e289609d0107d13f4892a655a1344d8d81:054ece2d7c4b95a3618abc51492adf79eb2ecc8d00:32433042313d344630442d413233322d453734354236343133373039:37663863313232622d633865662d346463322d613230392d64303562"

if [ $length -le 1 ]; then
   printf "Usage: $0 Get < AccessoryName > < Characteristic >\n"
   printf "Usage: $0 Set < AccessoryName > < Characteristic > < Value >\n"
   exit -1
fi

# printf "args =$#\n"   # debug
# printf "arg1 =$1\n"   # debug

if [ $length -ge 1 ]; then
    io=$1
   #  printf "io=$io\n"   # debug
fi
if [ $length -ge 2 ]; then
    device=$2
   #  printf "device = ${device}\n"   # debug
fi
if [ $length -ge 3 ]; then
    characteristic=$3
   #  printf "Characteristic = ${characteristic}\n"   # debug
fi
if [ $length -ge 4 ]; then
    option=$4
   #  printf "option = ${option}\n"   # debug
fi

if [ "${io}" == "Get" ]; then
   case $characteristic in
      'On')
         # Get Apple TV power state
         ATV_POWER_STATE=$(/home/pi/.local/bin/atvremote --id ${ATV_id} --airplay-credentials ${airplay_credentials} power_state)
         if [ "${ATV_POWER_STATE}" = "PowerState.On" ]
         then
            printf "1\n"
         else
            printf "0\n"
         fi
         exit 0
         ;;
      *)
         printf "UnHandled Get ${device}  Characteristic ${characteristic}\n"
         exit -1
         ;;
    esac
fi
if [ "${io}" == 'Set' ]; then
   case $characteristic in
      'On')
         # Get Apple TV current power state and switch accordingly
         ATV_POWER_STATE=$(/home/pi/.local/bin/atvremote --id ${ATV_id} --airplay-credentials ${airplay_credentials} power_state)
         if [ "${ATV_POWER_STATE}" = "PowerState.On" ]
         then
            /home/pi/.local/bin/atvremote --id ${ATV_id} --airplay-credentials ${airplay_credentials} turn_off
         else
            /home/pi/.local/bin/atvremote --id ${ATV_id} --airplay-credentials ${airplay_credentials} turn_on
         fi
         exit 0
         ;;
      *)
         printf "UnHandled Set ${device} Characteristic ${characteristic}"
         exit -1
         ;;
    esac
fi
printf "Unknown io command ${io}\n"
exit -1

Just one note for the second script: if you request the playing status when the Apple TV is off, this will turn on the Apple TV and you don't want it. That is the reason why I first check if the Apple TV is on, and then I request the playing status. Same as before, you will need to change ATV_id and airplay_credentials again.

appletv_playstate.sh

#!/bin/bash

set -e

# Exit immediately for unbound variables.
set -u

length=$#
device=""
io=""
characteristic=""
option=""
ATV_id="50:27:37:43:F0:07"
airplay_credentials="c559e2a53e289609d0107d13f4892a655a1344d8d81:054ece2d7c4b95a3618abc51492adf79eb2ecc8d00:32433042313d344630442d413233322d453734354236343133373039:37663863313232622d633865662d346463322d613230392d64303562"

if [ $length -le 1 ]; then
   printf "Usage: $0 Get < AccessoryName > < Characteristic >\n"
   printf "Usage: $0 Set < AccessoryName > < Characteristic > < Value >\n"
   exit -1
fi

# printf "args =$#\n"   # debug
# printf "arg1 =$1\n"   # debug

if [ $length -ge 1 ]; then
    io=$1
   #  printf "io=$io\n"   # debug
fi
if [ $length -ge 2 ]; then
    device=$2
   #  printf "device = ${device}\n"   # debug
fi
if [ $length -ge 3 ]; then
    characteristic=$3
   #  printf "Characteristic = ${characteristic}\n"   # debug
fi
if [ $length -ge 4 ]; then
    option=$4
   #  printf "option = ${option}\n"   # debug
fi

if [ "${io}" == "Get" ]; then
   case $characteristic in
      'On')
         # Get Apple TV play status
         # If requested when Apple TV is off, it will switch on and this is unwanted
         ATV_POWER_STATE=$(/home/pi/.local/bin/atvremote --id ${ATV_id} --airplay-credentials ${airplay_credentials} power_state)
         if [ "${ATV_POWER_STATE}" = "PowerState.On" ]
         then
            ATV_PLAYING_STATE=$(/home/pi/.local/bin/atvremote --id ${ATV_id} --airplay-credentials ${airplay_credentials} playing | grep -oP '(?<=Device state: ).*')
            if [ "${ATV_PLAYING_STATE}" = "Playing" ]
            then
               printf "1\n"
            else
               printf "0\n"
            fi
         else
            printf "0\n"
         fi
         exit 0
         ;;
      *)
         printf "UnHandled Get ${device}  Characteristic ${characteristic}\n"
         exit -1
         ;;
    esac
fi
if [ "${io}" == 'Set' ]; then
   case $characteristic in
      'On')
         # Toggle between play and pause
         /home/pi/.local/bin/atvremote --id ${ATV_id} --airplay-credentials ${airplay_credentials} play_pause
         exit 0
         ;;
      *)
         printf "UnHandled Set ${device} Characteristic ${characteristic}"
         exit -1
         ;;
    esac
fi
printf "Unknown io command ${io}\n"
exit -1

And then you can go to your Home app and create your automations like turning on the subwoofer when the Apple TV power is ON, closing the blinds when the Apple TV play state is ON, turning ON the lights when the Apple TV play state is OFF, etc...

Thank you to all that brought here the information that helped me get it working. And big thank you to @postlund for his pyatv app.

Any improvement will be welcome.

njuart commented 3 years ago

Wow, amazing! @cristian5th How do I obtain credentials to put in script? If I have it since last pair attempt when Apple TV Remote plugin was working, will it fit? Or I need to re-pair ATV? Do we also need to install something else, besides Cmd4 plugin and creating scripts in order your solution to work properly? Thx! Wanna give it a try.

cristian5th commented 3 years ago

Wow, amazing! @cristian5th How do I obtain credentials to put in script? If I have it since last pair attempt when Apple TV Remote plugin was working, will it fit? Or I need to re-pair ATV? Do we also need to install something else, besides Cmd4 plugin and creating scripts in order your solution to work properly? Thx! Wanna give it a try.

Yes, you need to install @postlund's pyatv. But I thought you already have it because this was originally your idea :)

Once installed, you can execute atvremote scan to find all Apple TV devices in your network. You will see the MAC and IP address. There are different ways to pair. I used the command atvremote -s 192.168.0.57 --protocol airplay pair with the IP address of my Apple TV. You just follow instructions and you will get the airplay credentials.

NorthernMan54 commented 3 years ago

FYI - I'm playing with this as well, as not having pause/play support has been painful in my house. My initial work in progress so far is here, at this point in time it has not been fully tested so please don't install it yet. - https://github.com/NorthernMan54/homebridge-cmd-television

I will be continuing to work on this in the near future, so expect a formal release shortly, including any updates needed to homebridge-alexa.

njuart commented 3 years ago

@cristian5th Looks like I'm almost there, but getting this error while loading HB after configuring Cmd4, even though script is there for sure

image

matcik890 commented 3 years ago

Ух ты, потрясающе! @cristian5th Как мне получить учетные данные для ввода в скрипт? Если он у меня с последней попытки сопряжения, когда работал плагин Apple TV Remote, подойдет ли он? Или мне нужно перепарковать квадроцикл? Нужно ли нам также устанавливать что-то еще, кроме плагина Cmd4 и создания сценариев, чтобы ваше решение работало должным образом? Тх! Хочу попробовать.

Да, вам необходимо установить @постлунд. Но я думал, что у вас это уже есть, потому что изначально это была ваша идея :)

После установки вы можете выполнить atvremote scan чтобы найти все устройства Apple TV в вашей сети. Вы увидите MAC-адрес и IP-адрес. Существуют разные способы спаривания. Я использовал команду atvremote -s 192.168.0.57 --protocol airplay pair с IP - адресом моего Apple TV. Вы просто следуете инструкциям, и вы получите учетные данные airplay.

Tell me in this line you need to make changes in the configuration file appletv_playstate.sh ATV_POWER_STATE=$(/home/pi/.local/bin/a tv remote --id ${tv_id} --airplay-credentials ${airplay_credentials} power_state)

cristian5th commented 3 years ago

@cristian5th Looks like I'm almost there, but getting this error while loading HB after configuring Cmd4, even though script is there for sure

image

@njuart, that will depend on your install, but if it is something like mine, the homebridge folder is not where you have written it. What you have at /home/pi/ is a link called .homebridge that is pointing to /var/lib/homebridge/.

I also tried to put directly the link at the plugin configuration, but I got the same error as you. That is why I changed it for the absolute path which is /var/lib/homebridge/. Try it.

cristian5th commented 3 years ago

Ух ты, потрясающе! @cristian5th Как мне получить учетные данные для ввода в скрипт? Если он у меня с последней попытки сопряжения, когда работал плагин Apple TV Remote, подойдет ли он? Или мне нужно перепарковать квадроцикл? Нужно ли нам также устанавливать что-то еще, кроме плагина Cmd4 и создания сценариев, чтобы ваше решение работало должным образом? Тх! Хочу попробовать.

Да, вам необходимо установить @постлунд. Но я думал, что у вас это уже есть, потому что изначально это была ваша идея :) После установки вы можете выполнить atvremote scan чтобы найти все устройства Apple TV в вашей сети. Вы увидите MAC-адрес и IP-адрес. Существуют разные способы спаривания. Я использовал команду atvremote -s 192.168.0.57 --protocol airplay pair с IP - адресом моего Apple TV. Вы просто следуете инструкциям, и вы получите учетные данные airplay.

Tell me in this line you need to make changes in the configuration file appletv_playstate.sh ATV_POWER_STATE=$(/home/pi/.local/bin/a tv remote --id ${tv_id} --airplay-credentials ${airplay_credentials} power_state)

@matcik890, I'm sorry but I don't fully understand your question.

What the line of the script that you have written is doing, is execute the atvremote command with the given variables $ATV_id and $airplay_credentials, and storing the stdout of this execution into a new variable named $ATV_POWER_STATE.

The only thing that you may need to change in that line, could be the path to the atvremote executable. As I installed it into a Raspberry Pi, the path is /home/pi/.local/bin/atvremote, where pi is a username. Maybe you need to change that?

njuart commented 3 years ago

@cristian5th Looks like I'm almost there, but getting this error while loading HB after configuring Cmd4, even though script is there for sure image

@njuart, that will depend on your install, but if it is something like mine, the homebridge folder is not where you have written it. What you have at /home/pi/ is a link called .homebridge that is pointing to /var/lib/homebridge/.

I also tried to put directly the link at the plugin configuration, but I got the same error as you. That is why I changed it for the absolute path which is /var/lib/homebridge/. Try it.

Still no luck, tried different options, can't get rid of this error. I'm running HB in docker, maybe this somehow related, maybe something with permissions. If I execute script in Terminal btw, I see response

image

cristian5th commented 3 years ago

@cristian5th Looks like I'm almost there, but getting this error while loading HB after configuring Cmd4, even though script is there for sure image

@njuart, that will depend on your install, but if it is something like mine, the homebridge folder is not where you have written it. What you have at /home/pi/ is a link called .homebridge that is pointing to /var/lib/homebridge/. I also tried to put directly the link at the plugin configuration, but I got the same error as you. That is why I changed it for the absolute path which is /var/lib/homebridge/. Try it.

Still no luck, tried different options, can't get rid of this error. I'm running HB in docker, maybe this somehow related, maybe something with permissions. If I execute script in Terminal btw, I see response

image

It seems to be working correctly when you execute it on the Terminal. Try on the terminal: /home/pi/homebridge/appletv_playstate.sh Get 'Apple TV' 'On'

This should give you back 0 if ATV is not playing and 1 if it is playing. You will confirm if atvremote is correctly working.

Finally, on the cmd4 plugin configuration, you can add the debug option and you will get execution messages at the Homebridge log. You should be able to see what could be your issues.

{
    "platform": "Cmd4",
    "name": "Cmd4",
    "debug": true,
    "interval": 5,
    "timeout": 4000,
    "stateChangeResponseTime": 3,
...

What I can't understand is how the Terminal can find the folder /home/pi/homebridge/ but Homebridge cannot... I personally do not have that folder, my folder is /home/pi/.homebridge/

njuart commented 3 years ago

@cristian5th Looks like I'm almost there, but getting this error while loading HB after configuring Cmd4, even though script is there for sure image

@njuart, that will depend on your install, but if it is something like mine, the homebridge folder is not where you have written it. What you have at /home/pi/ is a link called .homebridge that is pointing to /var/lib/homebridge/. I also tried to put directly the link at the plugin configuration, but I got the same error as you. That is why I changed it for the absolute path which is /var/lib/homebridge/. Try it.

Still no luck, tried different options, can't get rid of this error. I'm running HB in docker, maybe this somehow related, maybe something with permissions. If I execute script in Terminal btw, I see response image

It seems to be working correctly when you execute it on the Terminal. Try on the terminal: /home/pi/homebridge/appletv_playstate.sh Get 'Apple TV' 'On'

This should give you back 0 if ATV is not playing and 1 if it is playing. You will confirm if atvremote is correctly working.

Finally, on the cmd4 plugin configuration, you can add the debug option and you will get execution messages at the Homebridge log. You should be able to see what could be your issues.

{
    "platform": "Cmd4",
    "name": "Cmd4",
    "debug": true,
    "interval": 5,
    "timeout": 4000,
    "stateChangeResponseTime": 3,
...

What I can't understand is how the Terminal can find the folder /home/pi/homebridge/ but Homebridge cannot... I personally do not have that folder, my folder is /home/pi/.homebridge/

Thx. Just executed your command and it returned 0, an it's correct as ATV is off now. Will try with debug.

njuart commented 3 years ago

Hey @cristian5th I've managed to run plugin properly (how exactly - long story). So after finally seeing switches in Home app, I've noticed that actually nothing happens. As I understood, logic is the following, switches change its state according to state of ATV by polling every 5 seconds, so for example if ATV is on switch changes its state to on, right? So I decided to have a look at logs under debug and saw the following mess, any idea what can it be? Thx Homebridge 8D18 2021-10-28 04-36-41 I've also checked command straight from terminal, and I see that values changes between 0 and 1 in accordance to state of ATV.

cristian5th commented 3 years ago

What happens when you execute this in the Terminal? I mean in the Homebridge terminal... /var/lib/homebridge/appletv_powerstate.sh Get 'Apple TV Power' 'On'

The log just say command failed and I don't know what exactly this means.

Also, you understood it right. If the Apple TV switches ON, in no more than 5 seconds, the switch will change to ON.

njuart commented 3 years ago

What happens when you execute this in the Terminal? I mean in the Homebridge terminal... /var/lib/homebridge/appletv_powerstate.sh Get 'Apple TV Power' 'On'

The log just say command failed and I don't know what exactly this means.

Also, you understood it right. If the Apple TV switches ON, in no more than 5 seconds, the switch will change to ON.

This

image

njuart commented 3 years ago

@cristian5th Weird thing I've noticed is that when I execute in terminal Playstate script /var/lib/homebridge/appletv_playstate.sh Get 'Apple TV Play State' 'On' it changes from 1 to 0 according to playing state

But when I execute Powerstate script /var/lib/homebridge/appletv_powerstate.sh Get 'Apple TV Power' 'On' it always stays 1, no matter if ATV is on or off

cristian5th commented 3 years ago

@cristian5th Weird thing I've noticed is that when I execute in terminal Playstate script /var/lib/homebridge/appletv_playstate.sh Get 'Apple TV Play State' 'On' it changes from 1 to 0 according to playing state

But when I execute Powerstate script /var/lib/homebridge/appletv_powerstate.sh Get 'Apple TV Power' 'On' it always stays 1, no matter if ATV is on or off

Weird. That is not normal but at least we can conclude that you don't have permission issues.

What do you get in return when you execute this? You should get PowerState.On when the Apple TV is ON and PowerState.Off when the Apple TV is OFF. One detail though: Apple TV will be off when it is asleep.

/home/pi/.local/bin/atvremote --id 0.0.0.0 --airplay-credentials 0123456789abcdef power_state

njuart commented 3 years ago

@cristian5th Just checked, so executed this as you've mentioned /home/pi/.local/bin/atvremote --id 0.0.0.0 --airplay-credentials 0123456789abcdef power_state and after it also executed this /var/lib/homebridge/appletv_powerstate.sh Get 'Apple TV Power' 'On' just in case and it returned 0 which is correct, as ATV is off now

1

And also still see this in logs, and it spams so badly that after a few minutes HB goes down

2

cristian5th commented 3 years ago

@njuart, I see where the issue is coming from: atvremote cannot find your Apple TV. I believe I might have misunderstood one of the atvremote parameters.

When you execute the script appletv_powerstate.sh, you will always get 0 as answer because the Apple TV is not found. The script only returns 1 if the Apple TV is detected to be powered on.

Please, execute this command: /home/pi/.local/bin/atvremote scan

You should get some info like this example:

========================================
        Name: Living Room
    Model/SW: 4K tvOS 13.3.1 build 17K795
    Address: 10.0.0.10
        MAC: AA:BB:CC:DD:EE:FF
Identifiers:
    - 01234567-89AB-CDEF-0123-4567890ABCDE
    - 00:11:22:33:44:55
Services:
    - Protocol: MRP, Port: 49152, Credentials: None
    - Protocol: AirPlay, Port: 7000, Credentials: None

Where I told you to write the IP address of your Apple TV, I was wrong. You need to write one of the two identifiers from the previous example. Like this: /home/pi/.local/bin/atvremote --id 00:11:22:33:44:55 --airplay-credentials 0123456789abcdef power_state

If this works, then update the identifier at the two scripts with the correct value: ATV_id="00:11:22:33:44:55"

All should work now.

Also, please, execute this command when ATV is playing and when it is paused, just to confirm that the output is correct: /home/pi/.local/bin/atvremote --id 00:11:22:33:44:55 --airplay-credentials 0123456789abcdef playing

For the Homebridge going down issue: it is normal because the scripts are generating two errors every 5s and after a while Homebridge will complain hard. If errors are not solved after changing your identifier, I suggest that you set the interval to 50 or even more to avoid so many errors, until we make it work.

njuart commented 3 years ago

@cristian5th First of all, thx a lot for your time and help, much appreciated, really want this finally to work, as it's so potentially cool, really got used to it when ATV Remote plugin was working correctly.

So, now it worked, BUT the weirdest part that in scripts I already have correct identifier

image

tomjpeg commented 3 years ago

@cristian5th would it be possible for you to create a small plugin directly for Homebridge? Your script already offers almost all the functions we need ;) Thanks for the work!

cristian5th commented 3 years ago

@njuart, all this is so weird! In the latest capture that you sent, the issue is that the shell scripts cannot be found at the indicated folder. I'm afraid I don't understand why this is happening. Why don't you try to contact @ztalbot2000, owner of homebridge-cmd4? He might see easier why you are getting this strange issue.

@NewmansHub, that would be great but I do not have the knowledge. As far as I understood, @NorthernMan54 has been working exactly on that kind of solution. Maybe he is almost ready for a release.

shemege commented 3 years ago

Hi, I you have trouble with atvremote ( like me ) with version ATV 15.1.1 (lastest version TVOS) like this: ValueError: could not convert string to float: '15.1.1' try reinstall atvremote with command (devel version): pip3 install --upgrade git+https://github.com/postlund/pyatv.git

postlund commented 3 years ago

Hi, I you have trouble with atvremote ( like me ) with version ATV 15.1.1 (lastest version TVOS) like this: ValueError: could not convert string to float: '15.1.1' try reinstall atvremote with command (devel version): pip3 install --upgrade git+https://github.com/postlund/pyatv.git

That error was fixed in pyatv 0.9.3, so as long as you have that version or later you should be fine.

pip install --upgrade pyatv

Should do the trick.

njuart commented 3 years ago

@cristian5th I finally figured it out. It was lying on a surface, I've played with timeout value. So for me it worked at 10000 timeout.

cristian5th commented 3 years ago

@cristian5th I finally figured it out. It was lying on a surface, I've played with timeout value. So for me it worked at 10000 timeout.

Hmmm. 10 seconds timeout. I wonder why was this an issue. Any idea why you where experiencing this?

Anyway, I'm glad that you got it working. I hope we can enjoy it for many years before something is broken again.

njuart commented 3 years ago

@cristian5th I finally figured it out. It was lying on a surface, I've played with timeout value. So for me it worked at 10000 timeout.

Hmmm. 10 seconds timeout. I wonder why was this an issue. Any idea why you where experiencing this?

Anyway, I'm glad that you got it working. I hope we can enjoy it for many years before something is broken again.

Not sure, maybe it wasn't enough time to process. But, I went further and put Cmd4 to a child bridge, and now it works flawlessly with 4000 timeout.

lennartvava commented 3 years ago

@cristian5th thanks for your solution. I followed it and bumped into one issue. When the polling is executed I get the following error:

getValue On function failed for Apple TV Power cmd: bash /var/lib/homebridge/appletv_powerstate.sh Get 'Apple TV Power' 'On' Failed.  Generated Error: Error: Command failed: bash /var/lib/homebridge/appletv_powerstate.sh Get 'Apple TV Power' 'On'
Traceback (most recent call last):
  File "/home/pi/.local/bin/atvremote", line 6, in <module>
    from pyatv.scripts.atvremote import main
ModuleNotFoundError: No module named 'pyatv'

For some reason the pyatv module is non-existing while polling and executing atvremote. When executing the script manually in CLI, all is fine and I get good results. Any ideas?

cristian5th commented 3 years ago

@cristian5th thanks for your solution. I followed it and bumped into one issue. When the polling is executed I get the following error:

getValue On function failed for Apple TV Power cmd: bash /var/lib/homebridge/appletv_powerstate.sh Get 'Apple TV Power' 'On' Failed.  Generated Error: Error: Command failed: bash /var/lib/homebridge/appletv_powerstate.sh Get 'Apple TV Power' 'On'
Traceback (most recent call last):
  File "/home/pi/.local/bin/atvremote", line 6, in <module>
    from pyatv.scripts.atvremote import main
ModuleNotFoundError: No module named 'pyatv'

For some reason the pyatv module is non-existing while polling and executing atvremote. When executing the script manually in CLI, all is fine and I get good results. Any ideas?

I have no clue on what can happen. Maybe it is a different Python installation what is being executed from CLI and from Homebridge and pyatv is only correctly installed into one of those?

@postlund is the creator of this pyatv wonder. Maybe he has some ideas about what to do or how to look for more info.

postlund commented 3 years ago

This is a long thread now, so it's hard to get an overview of the problem. But it obviously has something to do with environments and paths. I would suggest (as the same user running homebridge):

python3 -m venv ~/pyatv_venv
source ~/pyatv_venv/bin/activate
pip install pyatv

Then call ~/pyatv_venv/bin/atvremote directly.

lennartvava commented 3 years ago

This is a long thread now, so it's hard to get an overview of the problem. But it obviously has something to do with environments and paths. I would suggest (as the same user running homebridge):

python3 -m venv ~/pyatv_venv
source ~/pyatv_venv/bin/activate
pip install pyatv

Then call ~/pyatv_venv/bin/atvremote directly.

Installing pyatv as the homebridge user did the trick. It seems this user didn't have access to it. Thanks @cristian5th and @postlund for the insane speed of response.

NorthernMan54 commented 3 years ago

@cristian5th Well, I'm finally finished my version of 'Homebridge-cmd-television', that works with homebridge-alexa. I'm finally able to control my TV again with Alexa. Working functions include, turn on, turn off, pause and play. Also on/off status in the Home App works as well.

If you want to give it a try, my code is located here - https://github.com/NorthernMan54/homebridge-cmd-television

PS No changes were required to my homebridge-alexa plugin or its configuration as well

MatGriffin commented 3 years ago

@cristian5th Well, I'm finally finished my version of 'Homebridge-cmd-television', that works with homebridge-alexa. I'm finally able to control my TV again with Alexa. Working functions include, turn on, turn off, pause and play. Also on/off status in the Home App works as well.

If you want to give it a try, my code is located here - https://github.com/NorthernMan54/homebridge-cmd-television

PS No changes were required to my homebridge-alexa plugin or its configuration as well

Thanks but on boot after installing your plug-in I get

 ERROR LOADING PLUGIN homebridge-cmd-television:
[
12/11/2021, 16:20:48] Error: Cannot find module 'request'
Require stack:
- /usr/local/lib/node_modules/homebridge-cmd-television/index.js
- /usr/local/lib/node_modules/homebridge/lib/plugin.js
- /usr/local/lib/node_modules/homebridge/lib/pluginManager.js
- /usr/local/lib/node_modules/homebridge/lib/server.js
- /usr/local/lib/node_modules/homebridge/lib/cli.js
- /usr/local/lib/node_modules/homebridge/bin/homebridge
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:902:15)
    at Function.Module._load (internal/modules/cjs/loader.js:746:27)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:93:18)
    at Object.<anonymous> (/usr/local/lib/node_modules/homebridge-cmd-television/index.js:1:15)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Module.require (internal/modules/cjs/loader.js:974:19)

and lots of other plugins now no longer run

[12/11/2021, 16:20:48] No plugin was found for the platform "Hue" in your config.json. Please make sure the corresponding plugin is installed correctly.
[12/11/2021, 16:20:48] No plugin was found for the platform "TuyaLan" in your config.json. Please make sure the corresponding plugin is installed correctly.
[12/11/2021, 16:20:48] No plugin was found for the platform "zigbee2mqtt" in your config.json. Please make sure the corresponding plugin is installed correctly.
[12/11/2021, 16:20:48] No plugin was found for the platform "TuyaPlatform" in your config.json. Please make sure the corresponding plugin is installed correctly.
[12/11/2021, 16:20:48] No plugin was found for the platform "Wemo" in your config.json. Please make sure the corresponding plugin is installed correctly.
[12/11/2021, 16:20:48] No plugin was found for the accessory "HTTP-SWITCH" in your config.json. Please make sure the corresponding plugin is installed correctly

Any ideas?

NorthernMan54 commented 3 years ago

@MatGriffin pls try installing again, I changed the config around the module 'request'

This is what I get when installing

npm i -g https://github.com/NorthernMan54/homebridge-cmd-television
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated har-validator@5.1.5: this library is no longer supported
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
+ homebridge-cmd-television@2.0.0
added 48 packages from 59 contributors in 6.282s

PS For issues with plugin, pls raises issues directly against its repo.

ztalbot2000 commented 3 years ago

A clean bash environment can be had wit:

env -i bash --noprofile --norc

Run your script with that bash shell and then see what your script does when you run it from there. Scripting is painful when you realize that your bashrc file can have great influence on what you do. One of the reasons I do not do anything special with my .bashrc.

Ttyl, John

On Fri, Nov 12, 2021 at 1:26 PM Northern Man @.***> wrote:

@MatGriffin https://github.com/MatGriffin pls try installing again, I changed the config around the module 'request'

This is what I get when installing

npm i -g https://github.com/NorthernMan54/homebridge-cmd-television npm WARN deprecated @.: request has been deprecated, see https://github.com/request/request/issues/3142 npm WARN deprecated @.: this library is no longer supported npm WARN deprecated @.***: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.

  • @.*** added 48 packages from 59 contributors in 6.282s

PS For issues with plugin, pls raises issues directly against its repo.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/lukasroegner/homebridge-apple-tv-remote/issues/105#issuecomment-967325904, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABSBCX2VJ7LCERL6RRIY3ZDULVL53ANCNFSM46VORRBQ .

justinmm2 commented 2 years ago

Hi @NorthernMan54 ! Thank you for this; I'd normally try to say so in a separate forum, but wanted to comment here in case others come across with questions. I'm running the Homebridge Synology docker container, and can offer a few tips to those doing the same. (One is that you can launch a Terminal in the container from the Homebridge UI!)

But first, if anyone has issues where the "npm i" command to install the plugin from git insists on using ssh, despite git configuration overrides, this solved my issue; it no longer insisted on using ssh for cloning. $ npm config set ssl-strict=false

As for the rest of it, here are the commands I ran. (I assume you can combine apk packages into one command) # Ran inside the homebridge container on the synology (via web console) apk add gcc openssh python3-dev rust pip3 install --upgrade pip # pip3 install wheel ## can't recall if this was required or not pip3 install cryptography pip3 install pyatv atvremote scan atvremote -s --protocol companion pair npm config set ssl-strict=false npm i -g https://github.com/NorthernMan54/homebridge-cmd-television

I am experiencing a strange error where my TV turns on ~30 seconds after I turn it off sometimes, but I don't see anything in the Homebridge debug logs, so I will assume it's something else for the moment!