Git Product home page Git Product logo

ha-google-home's Introduction

GitHub Workflow Status GitHub Release hacs GitHub Activity Installs

Logo

Home Assistant Google Home community integration

This custom integration aims to provide plug-and-play Google Home experience for Home Assistant enthusiasts.

Table of Contents
  1. About The Project
  2. Sensors
  3. Switches
  4. Numbers
  5. Services
  6. Getting Started
  7. Lovelace Cards
  8. Node-RED Flows
  9. Troubleshooting
  10. Contribution
  11. Localization
  12. Credits

About

This is a custom component that is emerging from the community discussion of a need to be able to retrieve local google assistant device (like Google Home/Nest etc) authentication tokens and use those tokens making API calls to Google Home devices.

IMPORTANT

With version 1.6 we have changed the update interval from 10 seconds to 180 seconds. This is due to #202. Some people are experiencing devices timing out when trying to fetch data from them.

You can manually change the update interval by pressing the configure button on the integration page. Default is 180 seconds. Change this at your own risk! If your devices are timing out, please increase this until it is stable again.

Sensors

This component will set up the following sensors:

Platform Sample sensor Description
sensor sensor.living_room_alarms Sensor with a list of alarms from the device
sensor sensor.living_room_timers Sensor with a list of timers from the device
sensor sensor.living_room_device Sensor with the IP address for the device, as well as some info attributes

Alarms

You can have multiple alarms on your Google Home device. Home Assistant alarms sensor will represent all of them in the state attributes as a list alarms. Each of the alarms has the following keys:

Key Value type Description
alarm_id Google Home corresponding ID Used to identify the alarm
fire_time Seconds Raw value coming from Google Home device until the alarm goes off
local_time Time Time when the alarm goes off, in respect to the Home Assistant's timezone
local_time_iso Time in ISO 8601 standard Useful for automations
status Status (string) The current status of the alarm, either none, set, ringing, snoozed or inactive
label Name Name of the alarm, this can be set when making the alarm
recurrence List of integers Days of the week when the alarm will go off. Please note, respecting Google set standard, the week starts from Sunday, therefore is denoted by 0. Correspondingly, Monday is 1, Saturday is 6 and so on

The state value shows the next alarm as a timestring (i.e.: 2021-03-07T15:26:17+01:00) if there is at least one alarm set, otherwise it is set to unavailable. This matches state format of standard next alarm sensor provided by mobile_app.

This sensor is formatted to be compatible with the mobile app sensor, e.g. sensor.phone_next_alarm.

Timers

You can have multiple timers on your Google Home device. Home Assistant timers sensor will represent all of them in the state attributes as a list timers. Each of the timers has the following keys:

Key Value type Description
timer_id Google Home corresponding ID Used to identify the timer
fire_time Seconds Raw value coming from Google Home device until the timer goes off
local_time Time Time when the timer goes off, in respect to the Home Assistant's timezone
local_time_iso Time in ISO 8601 standard Useful for automations
duration Seconds Timer duration in seconds
status Status (string) The current status of the timer, either none, set, ringing or paused
label Name Name of the timer, this can be set when making the timer

The state value shows the next timer as a timestring (i.e.: 2021-03-07T15:26:17+01:00) if there is at least one timer set, otherwise it is set to unavailable.

Alarm/Timer status

Both alarms and timers have a property called status. The status of the next alarm/timer (which is used as sensor state value) is also available through sensor state attributes next_alarm_status and next_timer_status respectively.

Status Meaning
none Alarm or timer does not exist
set Alarm or timer has been set
ringing Alarm or timer is ringing right now
snoozed Alarm was ringing and has been snoozed (only available for alarms)
inactive Alarm is inactive (only available for alarms)
missed Alarm was missed (only available for alarms)

Note that timers lack the additional snoozed state due to a limitation of the API. If you actually snooze a timer it will just reset itself to the state set again.

Switches

This component will set up the following switches:

Platform Sample switch Description
switch switch.living_room_do_not_disturb Toggle Do Not Disturb mode on a Google Home device

Numbers

This component will set up the following numbers:

Platform Sample number Description
number number.living_room_alarm_volume Control the alarm volume on a Google Home device

Services

It is possible to delete an alarm or a timer with the google_home.delete_alarm or google_home.delete_timer services. You can check it out in Home Assistant Developer Services Tool.

See below for the more detailed information.

Delete alarm

Example

service: google_home.delete_alarm
data:
  entity_id: sensor.kitchen_alarms
  timer_id: alarm/47dc1fa0-5ec0-2cc7-9ead-a94b85e22769
  skip_refresh: true

Key Descriptions

Key Example Description
entity_id sensor.kitchen_alarms Entity name of a Google Home alarms sensor.
alarm_id alarm/6ed06a56-8a58-c6e3-a7d4-03f92c9d8a51 ID of an alarm. See alarms description above.
skip_refresh true Boolean to skip refreshing Google Home devices.

Delete timer

Example

service: google_home.delete_timer
data:
  entity_id: sensor.kitchen_timers
  timer_id: timer/47dc1fa0-5ec0-2cc7-9ead-a94b85e22769
  skip_refresh: true

Key Descriptions

Key Example Description
entity_id sensor.kitchen_timers Entity name of a Google Home timers sensor.
timer_id timer/6ed06a56-8a58-c6e3-a7d4-03f92c9d8a51 ID of a timer. See timers description above.
skip_refresh true Boolean to skip refreshing Google Home devices.

Reboot device

Note: Not all devices this integration supports can be rebooted, even if you get the message "Successfully asked xxxxx to reboot."

Example

service: google_home.reboot_device
data:
  entity_id: sensor.kitchen_device

Key Descriptions

Key Example Description
entity_id sensor.kitchen_device Entity name of a Google Home device sensor.

Refresh devices

Note: Resets the timer for automatic polling to refresh devices.

Example

service: google_home.refresh_devices

Getting Started

Prerequisites

Use Home Assistant v2023.2.0 or above.

Google Account security

This integration uses your google account username and app password. See 2 Factor Authentication section for tips how to setup app password. However, we strongly recommend protection your main google account by not exposing it to the Home Assistant for automation purposes. We encourage you to create a separate Google account and add it to your Google Home. Your second account would not have access to anything other than Google Home, so even if it gets compromised, it's not as severe as losing your main google account. See more discussion here

Master token

Due to authentication issues with google credentials alone it may be required to get the master token separately and provide it during the setup process. This can be done using this script or glocaltokens package.

Since there are several issues getting the token reliable on different environments, you can use a docker container which was created solely for this use: https://hub.docker.com/r/breph/ha-google-home_get-token. If you choose to use this container, run the following command:

$ docker run --rm -it breph/ha-google-home_get-token

HACS Installation

You can find it in the default HACS repo. Just search Google Home.

Manual Installation

  1. Open the directory with your Home Assistant configuration (where you find configuration.yaml, usually ~/.homeassistant/).
  2. If you do not have a custom_components directory there, you need to create it.

Git clone method

This is a preferred method of manual installation, because it allows you to keep the git functionality, allowing you to manually install updates just by running git pull origin master from the created directory.

Now you can clone the repository somewhere else and symlink it to Home Assistant like so:

  1. Clone the repo.
git clone https://github.com/leikoilja/ha-google-home.git
  1. Create the symlink to google_home in the configuration directory. If you have non standard directory for configuration, use it instead.
ln -s ha-google-home/custom_components/google_home ~/.homeassistant/custom_components/google_home

Copy method

  1. Download ZIP with the code.
  2. Unpack it.
  3. Copy the custom_components/google_home/ from the unpacked archive to custom_components in your Home Assistant configuration directory.

Integration Setup

  • Browse to your Home Assistant instance.
  • In the sidebar click on Configuration.
  • From the configuration menu select: Integrations.
  • In the bottom right, click on the Add Integration button.
  • From the list, search and select β€œGoogle Home”.
  • Follow the instruction on screen to complete the set up.
  • After completing, the Google Home integration will be immediately available for use.

Running in Home Assistant Docker container

Make sure that you have your Home Assistant Container network set to host, as perscribed in the official docker installation for Home Assistant.

ARM Docker Container Dependencies Workaround

If you are installing this integration on an ARM based device (Like Raspberry Pi, Synology, etc), you may need to do the following if you get this error:

ERROR: Cannot install glocaltokens==0.3.1

Please run the following command in the Home Assistant container to add the missing dependencies for glocaltokens:

apk add gcc g++

then you can install glocaltokens manually like this:

pip3 install glocaltokens

Unfortunately, this will need to be done each time the image is updated. Alternatively you can add the command to the container startup:

command: /bin/bash -c "apk add gcc g++; pip3 install --upgrade pip; pip3 install glocaltokens; /init"

Lovelace Cards

Open a PR to add your card here!

Node-RED Flows

Open a PR to add your flow here!

Troubleshooting

Collecting useful log data

Here are the steps to generate useful log data:

  1. Temporary log level change.
    1. Visit Home Assistant Developer Services Tool.
    2. Choose Logger: Set level from the Service menu. (the Logger service needs to be enabled for this)
    3. Go to YAML mode and paste the following (starting on line 2):
      data:
        custom_components.google_home: debug
        glocaltokens: debug
    4. Click Call Service.
  2. Read the log information.
    1. Visit Home Assistant Logs.
    2. Click Load Full Home Assistant Log.
    3. Look for all google_home and glocaltokens entries.
  3. Requesting help with the log information.
    1. Copy the log entries.
    2. Paste them into a discussion forum or bug report. Make sure to use quotation block.

"Username/Password is incorrect"

If you get this error:

  1. First verify you are using the correct Username and Password combination for that Google account.
  2. Have you enabled 2 Factor Authentication on that Google account? If so read the 2 Factor Authentication section to continue.
  3. We have seen some other custom components break the dependencies causing google_home to fail authentication process. For more information please see this issue.
  4. After ruling out #1, #2 and #3 collect relevant logs and open a new issue.

2 Factor Authentication / App Passwords

The error "The setting you are looking for is not available for your account" will occur if you do not have 2 Factor Authentication (2FA) enabled on your Google account.

Here are the steps to resolve this issue:

  1. Open Google Account settings.
  2. On the top right corner click the profile photo and select the account which you would like to use.
  3. Go to Security page and make sure you have 2-Step Verification turned on in Signing in to Google section.
  4. Then visit App passwords.
    1. Click Select app and enter a descriptive name such as Google Home Integration for Home Assistant.
    2. Click the Generate button.
    3. Copy the password and return to the Google Home Configuration screen.
  5. Return to Integrations.
    1. Click Configure on the Google Home integration.
    2. Enter your Google account username.
    3. Paste the password into the Google account app password field.
    4. Click Submit.

Devices found, but not initialized

If the debug logs list your devices, but then show Successfully initialized 0 Google Home devices make sure you are logged into the correct Google account. The account you are using with the integration must have access to your Home. If unsure, please check what account you are using in the Google Home app and if your devices are listed there.

Devices found and initialized, but no alarms/timers sensor (#231)

If you can see your devices, and they all seem correct, but the alarms/timers sensors do not appear, or appear empty try restarting the Google Home device, Home Assistant, and reinstalling the integration.

Device offline or not compatible message (#402)

If you get the following error for all of your devices:

2021-11-28 16:13:20 DEBUG (MainThread) [custom_components.google_home] Failed to fetch timers/alarms information from device xxx. We could not determine its IP address, the device is either offline or is not compatible Google Home device. Will try again later.

It may be that your device and Home Assistant installation are not on the same network.

The integration works by connecting to the Google's servers to authenticate and get the authorisation keys for controlling these devices, but after that, all the requests are made locally, so it's required that the server and devices are on the same network. You can use a VPN or setup routing between each network to overcome this issue.

"version GLIBC_2.34 not found"

Your system has old version of GLIBC and therefore not compatible with pre-compiled version of grpcio. But you can build it from sources for your system. For that in HA virtualenv run (use the version of grpcio from glocaltokens):

pip install -U grpcio==1.46.1 --no-binary=grpcio --force-reinstall

Contribution

If you encounter issues or have any suggestions consider opening issues and contributing through PR. If you are ready to contribute to this please read the Contribution guidelines.

Localization

Currently the integration supports the following languages:

  • Catalan
  • Danish
  • Dutch
  • English
  • French
  • German (Germany)
  • Italian (Italy)
  • Norwegian (bokmΓ₯l and nynorsk)
  • Polish
  • Portuguese (Brazil)
  • Portuguese (Portugal)
  • Russian
  • Slovak
  • Spanish (Spain)
  • Ukrainian

If you want to translate the project to your own language, follow the Localization guide.

Credits

ha-google-home's People

Contributors

arnyminerz avatar astroviking avatar brephlas avatar brianhanifin avatar cdemi avatar denysdovhan avatar dependabot[bot] avatar durgnomis-drol avatar emile-bodin avatar gaworskirafal avatar heehoo59 avatar jaspers2307 avatar jlsjonas avatar jumping2000 avatar kapji avatar leandroissa avatar leikoilja avatar leoledmag avatar mattieha avatar mdegat01 avatar mdiazgoncalves avatar morphy99 avatar petrepa avatar pschneider87 avatar rounndel avatar scop avatar skgsergio avatar viper5000 avatar williamg97 avatar zaprodk avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ha-google-home's Issues

More options for config flow

Is your feature request related to a problem? Please describe.
We currently only ask for login and password on config flow. However some people might have issue with BadAuthentication cause by different custom components as #95 for example. As an alternative solution we could provide master_token input on config UI.
Also we discuss to have error catching for which we need to provide an option to 'opt out' from diagnostic data collection.

Describe the solution you'd like
More versatile config flow UI that allows to enter master token and opt in / opt out from diagnotic data collection

Simplify manual installation

Is your feature request related to a problem? Please describe.
Copying files from repo folder to custom_components is not very convenient.

Describe the solution you'd like
I think it'd be much simpler if repo can be just cloden inside custom_components without any extra actions. This will simplify interating for contributor as well.

It just needs putting __init__.py in the repo root, all other sources can be placed in subfolder for cleaner repo structure.

Issue with token local_auth_token

Version of the custom_component

  • ha-google-home v1.0.0
  • core-2021.3.3
  • supervisor-2021.03.4

Configuration

Installed through HACS

Created app password since I use 2FA

Describe the bug

No error during initial configuration (when I enter my Google account and app password), but I don't see any sensors. Seems like it's trying again and again to connect (without success). My Google account on other devices has been signing out due to the repeated attempts...

Debug log


2021-03-12 17:44:22 ERROR (SyncWorker_1) [glocaltokens.client] local_auth_token doesn't follow the correct format.
2021-03-12 17:44:22 ERROR (MainThread) [custom_components.google_home] Unexpected error fetching sensor data: 'Device' object has no attribute 'ip'
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/update_coordinator.py", line 151, in async_refresh
    self.data = await self._async_update_data()
  File "/usr/src/homeassistant/homeassistant/helpers/update_coordinator.py", line 139, in _async_update_data
    return await self.update_method()
  File "/config/custom_components/google_home/api.py", line 164, in update_google_devices_information
    devices = await self.get_google_devices()
  File "/config/custom_components/google_home/api.py", line 74, in get_google_devices
    self.google_devices = [
  File "/config/custom_components/google_home/api.py", line 78, in <listcomp>
    ip_address=device.ip,
AttributeError: 'Device' object has no attribute 'ip'

Next alarm/timer should be device_class timestamp

I would like to use some blueprints that use timestamps but was surprised to find that I could not use the next alarm or or timers sensor because they are not device_class timestamp. Since these sensor provide a timestamp, they should have this device class

Relax requirements for account name

Is your feature request related to a problem? Please describe.
Requiring stripping of @gmail.com is too restrictive. Also note that Google accounts can be on custom domains with G Suite and they probably also should be supported.

Describe the solution you'd like
This can be done programatically.

AttributeError: 'NoneType' object has no attribute 'get_sorted_alarms

Version of the custom_component

Latest

Configuration

2021-03-21 09:41:29 ERROR (MainThread) [homeassistant] Error doing job: Task exception was never retrieved
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/update_coordinator.py", line 126, in _handle_refresh_interval
    await self.async_refresh()
  File "/usr/src/homeassistant/homeassistant/helpers/update_coordinator.py", line 200, in async_refresh
    update_callback()
  File "/usr/src/homeassistant/homeassistant/helpers/update_coordinator.py", line 260, in _handle_coordinator_update
    self.async_write_ha_state()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 295, in async_write_ha_state
    self._async_write_ha_state()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 319, in _async_write_ha_state
    sstate = self.state
  File "/config/custom_components/google_home/sensor.py", line 141, in state
    alarms = self._get_alarms_data()
  File "/config/custom_components/google_home/sensor.py", line 156, in _get_alarms_data
    return self.as_dict(device.get_sorted_alarms())
AttributeError: 'NoneType' object has no attribute 'get_sorted_alarms'

Describe the bug

It does not appear immediately, but shows up after my HA installation have been running for some hours.

@leikoilja Have also had this error show up in his logs

Debug log

Repo/Integration renaming -> ha-google-home

Now that we are adding more features like alarms/timers fetching, this repo is no longer makes sense to be called ha-glocaltokens, cause it's not just tokens we are fetching. How about we rename this repo into something like ha-google-home? Or is it too big of a shot? Anyways, let's discuss it here, @DurgNomis-drol, @ArnyminerZ

Invalid timestamp

Describe the bug

I was getting "Unavailable" on v.1 on alarms and timers but now get "Invalid Timestamp" on v1.1.0

Version of the integration

V1.1.0

Glocaltokens Version (Underlying package)

Add pip information here.

Logs


2021-03-25 20:15:37 WARNING (MainThread) [homeassistant.components.cloud.google_config] Error reporting state - 5: Requested entity was not found.
2021-03-25 20:15:43 WARNING (MainThread) [homeassistant.components.switch] Setup of switch platform meross_cloud is taking over 10 seconds.
2021-03-25 20:16:37 WARNING (MainThread) [homeassistant.bootstrap] Waiting on integrations to complete setup: google_home
2021-03-25 20:16:47 WARNING (MainThread) [homeassistant.components.cloud.google_config] Error reporting state - 5: Requested entity was not found.
2021-03-25 20:16:47 WARNING (MainThread) [homeassistant.components.cloud.google_config] Error reporting state - 5: Requested entity was not found.
2021-03-25 20:16:47 WARNING (MainThread) [homeassistant.components.cloud.google_config] Error reporting state - 5: Requested entity was not found.
2021-03-25 20:16:47 WARNING (MainThread) [homeassistant.components.cloud.google_config] Error reporting state - 5: Requested entity was not found.
2021-03-25 20:16:47 WARNING (MainThread) [homeassistant.components.cloud.google_config] Error reporting state - 5: Requested entity was not found.
2021-03-25 20:16:47 WARNING (MainThread) [homeassistant.components.cloud.google_config] Error reporting state - 5: Requested entity was not found.
2021-03-25 20:16:47 WARNING (MainThread) [homeassistant.components.cloud.google_config] Error reporting state - 5: Requested entity was not found.

Debug log

logger:
  default: debug
  logs:
    custom_components.google_home: debug

Add your debug logs here.

Implement UI device setup

Is your feature request related to a problem? Please describe.
I have been developing another integration with more or less the same idea in mind, it would be nice to join the two in this one, and not have multiple integrations with the same purpose laying around.

Describe the solution you'd like
Add the config_flow device setup and features of ArnyminerZ/HomeAssistant-GoogleHome.

I'm working on implementing it, but there's quite a lot to adapt.

Do not hammer Google Oauth API

Describe the solution you'd like
Make sure that we are not hammering the Google Oauth when trying to retrieve master_token, access_token and localAuthToken.

Alarm state format

Problem

In #47 alarm state format was changed from unix timestamp to formatted string which is nice and makes it more readable. But I think it should also include time zone because it's a local time.

Before March 28 I live in UTC and can't check this but Sweden uses CET and I believe if in template editor in developer tools you try this, these timestampts won't be equal:

Converted timestamp: {{ as_timestamp(states("sensor.<google_home_name>_alarms")) }}
Fire time: {{ state_attr("sensor.<google_home_name>_alarms", "alarms")[0]["fire_time"] }}

This makes it harder to use state in automations.

Solution

Add time zone to TIME_STR_FORMAT. %z should be compatible with ISO datetime format. It should look like 2021-03-04 13:41:04+0100

Fails to fetch IP through zeroconf

Version of the custom_component

Latest master

Configuration

2021-03-04 17:12:47 DEBUG (MainThread) [custom_components.ha-google-home] Failed to fetch timers/alarms information from device Kitchen. We could not determine it's IP address, the device is either offline or is not compatable Google Home device. Will try again later.

Describe the bug

It fails to fetch IP through zeroconf. Device is on and a timer is set. Device is a Google Nest Mini

While setting up the integration it finds my device, but i does not when trying to fetch data from it.

Debug log

See above

No sensors created - SSL handshake failure

This might be similar to #100, but since the error message differs I've created a new issue for this.

Version of the custom_component

1.0.0

Configuration

via integrations panel in UI.

Describe the bug

No sensors are created after setting up the integration and rebooting a few times.

Debug log

Logger: custom_components.google_home
Source: helpers/update_coordinator.py:160
Integration: Google Home (documentation, issues)
First occurred: 12:53:12 (8 occurrences)
Last logged: 13:01:03

Error requesting sensor data: Cannot connect to host 192.168.2.201:8443 ssl:default [[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:1125)]

The issue stays after reboot, sensors are not created. I've installed the latest version of this integration via HACS on a Raspberry Pi 3b.

Cannot configure integration

Version of the custom_component

Latest on master

Configuration

configuration.yaml

...
ha-glocaltokens:
...

Describe the bug

When trying to configure the integration through the add integration UI (config_flow), the window goes back to the integrations list.

Debug log

In the browser, I get:

{
"body": { "message": "Invalid handler specified" },
"error": "Response error: 404",
"status_code": "404"
}

More request info:
Contents:

{"handler":"ha-glocaltokens","show_advanced_options":false}

Cookies:

Idea-48b7ff8d | "41ae16d5-eebc-40f1-9a3b-c035f087e00b"

Headers:

XHRPOSThttp://localhost:8123/api/config/config_entries/flow
[HTTP/1.1 404 Not Found 1ms]

POST
	http://localhost:8123/api/config/config_entries/flow
Estado 404 Not Found
VersiΓ³n HTTP/1.1
Transferido 224 B (tamaΓ±o 40 B)
PolΓ­tica de referencia same-origin

    Content-Encoding
    	deflate
    Content-Length
    	48
    Content-Type
    	application/json
    Date
    	Sat, 13 Feb 2021 12:30:55 GMT
    Server
    	Python/3.8 aiohttp/3.7.3
    	
    POST /api/config/config_entries/flow HTTP/1.1

    Host: localhost:8123

    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:85.0) Gecko/20100101 Firefox/85.0

    Accept: */*

    Accept-Language: es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3

    Accept-Encoding: gzip, deflate

    Content-Type: application/json;charset=UTF-8

    Content-Length: 59

    HA-Frontend-Base: http://localhost:8123

    Origin: http://localhost:8123

    DNT: 1

    Sec-GPC: 1

    authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhYWQxMGNjZGVjMjI0MGNhOGFjNzBiNmQ4Y2IyZDY0MiIsImlhdCI6MTYxMzIxODk4NywiZXhwIjoxNjEzMjIwNzg3fQ.u7W9c4EF_kLZHWwd4bJQO1tW0rG1k-EwjCYc_AfoCS4

    Referer: http://localhost:8123/config/integrations

    Connection: keep-alive

    Cookie: Idea-48b7ff8d=41ae16d5-eebc-40f1-9a3b-c035f087e00b

Add missing docstrings

Problem

Let's enforce better documentation and add missing docstrings.

How to do this

Remove these lines from pyproject.yaml and make sure poetry run pylint custom_components/google_home finished with no warnings.

    "missing-class-docstring",
    "missing-function-docstring",
    "missing-module-docstring",

Can anyone take this?

Error requesting sensor data

Version of the custom_component

1.0

Configuration

Add your logs here.

Describe the bug

I've installed the custom component and I was able to add it in the integration page. However, I'm not getting the sensors in my HA. I might be missing something, but I don't know what.

Debug log


Logger: custom_components.google_home
Source: helpers/update_coordinator.py:160
Integration: Google Home (documentation, issues)
First occurred: 10:53:42 (3 occurrences)
Last logged: 10:55:19

Error requesting sensor data: Cannot connect to host 192.168.xx.xx:8443 ssl:default [None]

Problems during first login

Versions

Configuration

Google Account

Since I have 2FA enabled, I have created an application password.

Home Assistant

This component does not need configuration in yaml format but you can check how to install it or the complete configuration in my repository:

All the configuration and plugins work perfectly, only this one fails.

Describe the bug

After installing the plugin, I tried to configure it but, after entering my login details, it fails with the following error:

 Username/Password is incorrect. If your google account has 2FA enabled please generate app password (https://myaccount.google.com/apppasswords) 

and in the home-assistant logs I can see the following:

Logger: glocaltokens.client
Source: /usr/local/lib/python3.8/site-packages/glocaltokens/client.py:169
First occurred: 8:42:50 PM (1 occurrences)
Last logged: 8:42:50 PM

[!] Could not get master token.

Debug log

I tried to debug a bit more and discovered that here the variable res contain the value Error=BadAuthentication.

I can probe further but first I wanted to know if this is a known bug since it seems to be related to simon-weber/gpsoauth#24.

GitHub issue/pr templates

As we start encountering issues with glocaltokens package and different release versions of google-home we need to update the github issue template to include instructions on how one finds and specifies what version of both packages is used when opening the issue. That will greatly help us to debug and help one another

  • Edit issue template to hold a comment how to find the versions of package/integration
  • Edit issue template to have a reference of glocaltokens package version
  • Edit issue template to have a reference of google-home integration version
  • Add a reference to glocaltokens on how to try and test credentials for those who can't even login (@leikoilja can do that)

Change attribute time_left to duration instead

Version of the custom_component

Latest master

Configuration

timers:
  - fire_time: 1614879264
    date_time_utc: '2021-03-04 17:34:24'
    local_time: '2021-03-04 18:34:24'
    time_left: '0:30:00'
device: Kitchen timers
integration: ha-google-home
friendly_name: Kitchen timers
icon: 'mdi:timer-sand'

Describe the bug

time_left should be duration instead. It does not count down, so i think the name is misleading

Add next alarm sensor

Is your feature request related to a problem? Please describe.
Add a alarm sensor that only shows the next alarm as it's state.

I use the sensor from the mobil app to trigger things when i wake up and i think this would be very useful for those people who use there's as an alarm clock.

Describe the solution you'd like
This sensor should mimic the same sensor in the mobile app for android. Next alarm sensor

Failing to install due to glocaltokens dependancy (grpcio-tools)

Hi.

Im having trouble installing your addon, which btw is amazing work.
I followed the guide provided but when i launch homeassistant and try to setup the integration nothing happens. Multiple errors show up in the logs.

2021-02-08 14:54:18 ERROR (SyncWorker_1) [homeassistant.util.package] Unable to install package glocaltokens==0.1.4: ERROR: Command errored out with exit status 1:
command: /usr/local/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-2u_2xggr/grpcio-tools/setup.py'"'"'; __file__='"'"'/tmp/pip-install-2u_2xggr/grpcio-tools/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-iz62u3yg
cwd: /tmp/pip-install-2u_2xggr/grpcio-tools/
Complete output (11 lines):
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/pip-install-2u_2xggr/grpcio-tools/setup.py", line 151, in <module>
if check_linker_need_libatomic():
File "/tmp/pip-install-2u_2xggr/grpcio-tools/setup.py", line 80, in check_linker_need_libatomic
cpp_test = subprocess.Popen([cxx, '-x', 'c++', '-std=c++11', '-'],
File "/usr/local/lib/python3.8/subprocess.py", line 854, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/local/lib/python3.8/subprocess.py", line 1702, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'c++'

Not sure if this last error is regarding glocaltokens.

ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
WARNING: You are using pip version 20.2.4; however, version 21.0.1 is available.
You should consider upgrading via the '/usr/local/bin/python3 -m pip install --upgrade pip' command.
2021-02-08 14:54:18 ERROR (MainThread) [aiohttp.server] Error handling request
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/aiohttp/web_protocol.py", line 422, in _handle_request
resp = await self._request_handler(request)
File "/usr/local/lib/python3.8/site-packages/aiohttp/web_app.py", line 499, in _handle
resp = await handler(request)
File "/usr/local/lib/python3.8/site-packages/aiohttp/web_middlewares.py", line 118, in impl
return await handler(request)
File "/usr/src/homeassistant/homeassistant/components/http/security_filter.py", line 56, in security_filter_middleware
return await handler(request)
File "/usr/src/homeassistant/homeassistant/components/http/request_context.py", line 18, in request_context_middleware
return await handler(request)
File "/usr/src/homeassistant/homeassistant/components/http/ban.py", line 72, in ban_middleware
return await handler(request)
File "/usr/src/homeassistant/homeassistant/components/http/auth.py", line 127, in auth_middleware
return await handler(request)
File "/usr/src/homeassistant/homeassistant/components/http/view.py", line 129, in handle
result = await result
File "/usr/src/homeassistant/homeassistant/components/config/config_entries.py", line 136, in post
return await super().post(request)
File "/usr/src/homeassistant/homeassistant/components/http/data_validator.py", line 60, in wrapper
result = await method(view, request, *args, **kwargs)
File "/usr/src/homeassistant/homeassistant/helpers/data_entry_flow.py", line 69, in post
result = await self._flow_mgr.async_init(
File "/usr/src/homeassistant/homeassistant/data_entry_flow.py", line 119, in async_init
flow = await self.async_create_flow(handler, context=context, data=data)
File "/usr/src/homeassistant/homeassistant/config_entries.py", line 541, in async_create_flow
await async_process_deps_reqs(self.hass, self._hass_config, integration)
File "/usr/src/homeassistant/homeassistant/setup.py", line 343, in async_process_deps_reqs
await requirements.async_get_integration_with_requirements(
File "/usr/src/homeassistant/homeassistant/requirements.py", line 79, in async_get_integration_with_requirements
await async_process_requirements(
File "/usr/src/homeassistant/homeassistant/requirements.py", line 136, in async_process_requirements
raise RequirementsNotFound(name, [req])

Any suggestions? Could very well be my fault.

Unknown error occurred

Just installed this new component via HACS method and going through the configuration flow.

I did notice that Google local authentication token fetching shows up as the name, not Google Home as per your docs. But I know your only changing the name in the last day or so.

However, when I put my username and password in, I get an "unknown error occured".

This happens with my main password but also with an app password I created also. My HA log shows

021-03-11 15:56:31 ERROR (MainThread) [aiohttp.server] Error handling request
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/aiohttp/web_protocol.py", line 422, in _handle_request
    resp = await self._request_handler(request)
  File "/usr/local/lib/python3.8/site-packages/aiohttp/web_app.py", line 499, in _handle
    resp = await handler(request)
  File "/usr/local/lib/python3.8/site-packages/aiohttp/web_middlewares.py", line 119, in impl
    return await handler(request)
  File "/usr/src/homeassistant/homeassistant/components/http/security_filter.py", line 56, in security_filter_middleware
    return await handler(request)
  File "/usr/src/homeassistant/homeassistant/components/http/forwarded.py", line 172, in forwarded_middleware
    return await handler(request)
  File "/usr/src/homeassistant/homeassistant/components/http/request_context.py", line 18, in request_context_middleware
    return await handler(request)
  File "/usr/src/homeassistant/homeassistant/components/http/ban.py", line 72, in ban_middleware
    return await handler(request)
  File "/usr/src/homeassistant/homeassistant/components/http/auth.py", line 129, in auth_middleware
    return await handler(request)
  File "/usr/src/homeassistant/homeassistant/components/http/view.py", line 129, in handle
    result = await result
  File "/usr/src/homeassistant/homeassistant/components/config/config_entries.py", line 150, in post
    return await super().post(request, flow_id)
  File "/usr/src/homeassistant/homeassistant/components/http/data_validator.py", line 60, in wrapper
    result = await method(view, request, *args, **kwargs)
  File "/usr/src/homeassistant/homeassistant/helpers/data_entry_flow.py", line 106, in post
    result = await self._flow_mgr.async_configure(flow_id, data)
  File "/usr/src/homeassistant/homeassistant/data_entry_flow.py", line 158, in async_configure
    result = await self._async_handle_step(flow, cur_step["step_id"], user_input)
  File "/usr/src/homeassistant/homeassistant/data_entry_flow.py", line 216, in _async_handle_step
    result: Dict = await getattr(flow, method)(user_input)
  File "/config/custom_components/glocaltokens/config_flow.py", line 46, in async_step_user
    CONF_ANDROID_ID: client.get_android_id(),
  File "/config/custom_components/glocaltokens/api.py", line 48, in get_android_id
    return self._client._get_android_id()
AttributeError: 'GLocalAuthenticationTokens' object has no attribute '_get_android_id'

If I use the wrong password, I do get a correct message "Username/Password is incorrect wrong. If your google account has 2FA enabled please generate app password (https://myaccount.google.com/apppasswords)"

Looking forward to being able to try this properly.

Kind regards

HACS Documentation

Super happy to announce that the integration has aired in the default HACS repo, so one should not need to add custom repo anymore πŸ’₯

We would need to update the README documentation about installation and try it ourselves :)

Is this message generated from your custom component? '[glocaltokens.client] [!] Could not get access token.'

Your custom component had been running fine for a couple days. Then this morning, my home assistant log showed this error and then the error and warning shown below started filling the log every second until I shut down the server. Are these messages from your custom component?

2021-03-15 02:07:36 ERROR (MainThread) [custom_components.google_home] Timeout fetching sensor data

2021-03-15 02:08:16 ERROR (SyncWorker_8) [glocaltokens.client] [!] Could not get access token.
2021-03-15 02:08:16 WARNING (SyncWorker_8) [glocaltokens.client] The access token has expired. Getting a new one.
2021-03-15 02:08:16 ERROR (SyncWorker_8) [glocaltokens.client] [!] Could not get access token.
2021-03-15 02:08:16 WARNING (SyncWorker_8) [glocaltokens.client] The access token has expired. Getting a new one.
2021-03-15 02:08:16 ERROR (SyncWorker_8) [glocaltokens.client] [!] Could not get access token.

Add refresh setting to configuration

Is your feature request related to a problem? Please describe.
Currently the integration updates timers/alarms at a hardcoded period (15 seconds or 5 minutes).

Describe the solution you'd like
A configuration UI setting where the user can set a custom update rate. Maybe with some reasonable limits.

Reuse android_id

Version of the custom_component

Latest master branch

Describe the bug

When performing google requests to fetch tokens we should provide one and the same android_id, without generating a new id every time. If we do - it will look like dozens of different devices are connected to the same account that might lead to unexpected authentication problems.
We already have some mitigation in the underlying glocaltokens python package, but we need a more robust mechanism, because now when Homeassistant restarts it will also restart glocaltokens instance wiping away stored android_id that will lead to fetching a new one.

We are already saving android_id in the integration config flow (CONF_ANDROID_ID: await client.get_android_id()), but we never use it. We should either introduce set_android_id() method in underlying glocaltokens that we would call every sensor update cycle (just to be sure) or pass that value when calling get_google_devices.

@ArnyminerZ, would you have any interest in picking it? πŸ™ πŸ₯‡ πŸ˜„

Get rid of SUPPORTED_HARDWARE_LIST

Problem

Maintaining that list is burden you don't really want to have. New devices will be released and other manufacturers will release compatible devices.

Proposal

If device is discovered from Foyer API, it's probably good. Then we can check if it returns alarms list correctly, otherwise mark sensor unavailable.

Make updates faster

Problem

Updates now are unreasonably slow and take around 20 seconds.

Solution

  • Run zeroconf only for setup
  • Reuse tokens and don't refresh them for every update, they should be valid at least for 1 hour.
  • Query alarms and timers from devices in parallel (probably already done)

Basically we can always assume that token is still valid and if request fails, only then we need to fetch the new one and retry the request.

With this update interval can be pretty small like 10 or 15 seconds and there is no need in #58

[dev] Implement IP address autodiscovery (zeroconf)

Discovery should be implemented, in order to detect the Google Home device's IP. By using the pychromecast API, this can be achieved, for example, with the following snippet:

import pychromecast

VALID_GOOGLE_HOME_MODELS = [
    "Google Home",
    "Google Home Mini",
    "Lenovo Smart Clock"
]


def discover_google_home():
    print("Discovering Google Homes...")
    services, browser = pychromecast.discovery.discover_chromecasts()
    for service in services:
        model = service[2]
        name = service[3]
        ip = service[4]
        access_port = service[5]
        if model in VALID_GOOGLE_HOME_MODELS:
            print(f"{name} ({ip}:{access_port}) - {model}")
            print()

The port is more or less useless, since as far as I know, for every Google Home the port is the same: 8009, but, who knows.

This should be added to the integration in the discovery.py file, as stated by the Home Assistant documentation.

I will start working on that, and see if we can make the device configuration easier.

Device discovery using HomeAssistant zeroconf

Is your feature request related to a problem? Please describe.
We need to implement zeroconf device autodiscovery to be able to fetch google device IP addresses using HomeAssistant zeroconf

Describe the solution you'd like
Getting IP addresses and matching them to the existing google devices in the integration

Retry alarms/timers fetching from every discovered device on every coordinator update

Describe the bug

Google Home devices are mistakenly filtered:
Devices that actually contain alarms/timers are filtered out if the API request fails to establish because of underlying issues of pychromcast.
Please see there two log entries where my Google Home devices were filtered out because the API request to them unexpectedly returned 404.

Version of the integration

If you are unsure about the version check the github release here.

Google Home v1.0.1

Logs

Screenshot 2021-03-27 at 08 32 23

Screenshot 2021-03-27 at 08 33 33

From these logs, you see that I used to have a working Kitchen device that got filtered out and no more data fetched from it (1st screenshot) and Living Room device that also got filtered out (2nd screenshot)

Expected behaviour

Retry fetching alarms/timers from device(s) on every coordinator update

Support Bluetooth Scan / Scan Results

Back at the start of the GHLocalApi several of us where starting to build a triangulation based presence system based on bluetooth results. Would love to help get this working again as we now have access again.

Get Scan Results
Initiate Scan

This would likely require creating new entities as each rescan interval potentially identifies new devices, it all depends.

[dev] Implement timers/alarms updates

Describe the bug

You still have to reload the integration to update timers and alarms, i dont know why and have tried a lot to fix it but it is over my skill level ;)

Introduce periodic Foyer device fetching

Is your feature request related to a problem? Please describe.
We need to fetch Foyer devices every 10 mins instead of 24h as it is right now. The problem is when a new device is plugged in the user expects the device to appear in Google Home integration, however, with a current setup, we only fetch Foyer devices every time the access token goes off (~24h).
We will need to dynamically create HA sensor if a new device has appeared and it's initialized as HA sensors

Describe the solution you'd like
Introduce a constant parameter to adjust how often the integration refreshes Foyer devices (does a force fetching of all google devices when calling glocaltokens.get_devices).

Enable strict typing

Problem

Having types and type checks helps to:

  • Check that all functions exist and called with correct arguments.
  • Make the code more robust.
  • Allow to refactor code simpler and safer.

The plan

I'll enable mypy checks soon and will gradually enable stricter checks as more parts are covered with types.

Let me know what do you think!

[dev] Implement multiple timer/alarm instances

Discuss and implement timer/alarm instances

See some ideas at #11 (comment)

I am not sure what's the best way for us to ultimately go with that but what if we end up implementing generic "GlocaltokenAlarm" for each of the alarms for each of the devices? And inside of the alarm, we can have attributes like: recurring and reccurring_days. For recurring alarms they will be recurring = True; recurring_days = "..." and for single alarms recuring = False; recurring_days = None. And then on top of it all we can have a service that will be called something like get_next_alarm, with input argument of google home's name. Which will go through all Alarm sensors in that particular Google Home's alarms and find the next alarm by comparing them all?

But even if so, let's just keep it as you have already implemented and we can take that discussion as a whole separate ticket afterwards :)

Some comments about sorting here

Use poetry for dependency management

Poetry is a modern way to manage python projects. Right now dependency management is a bit messy with 2 separate dependency lists in requirements and .github/workflows/constraints.txt. And you need to manually create virtualenv if you don't want to mess with system packages.

  • Poetry can install all project dependencies in virtualenv with poetry install and it manages dependency versions.
  • It separates between normal dependencies and dev dependencies (black, flake8, etc)
  • Then you can run any tools with poetry run, e.g. poetry run black, can be integrated with pre-commit as well.
  • Some extra configuration is required for dependabot.

I want to switch everything (pre-commit config, github actions) to use poetry.
Any objections?

Introduce services to delete/modify alarms or timers

Is your feature request related to a problem? Please describe.
When one wants to make automation he needs to know what is the soonest timer/alarm to go off. Also when the user wants to delete/modify an alarm/timer how does one do that?

Describe the solution you'd like
We should probably look into introducing HA services with a separate service for each task, like:

@DurgNomis-drol , @ArnyminerZ, @KapJI what do you think about that idea? Would any of you have an interest in implementing that? πŸ₯³

Uninstall

On Uninstall, Home Assistant complains that cannot find component in setup.py even though integration was removed and also removed from HACS.
Work-around is to uninstall integration and leave it installed in HACS

Rename component

Problem

ha-google-home is not PEP8 compliant name for python module. It should use _ for spaces.

This is only 1 of 2 custom components with - here: https://github.com/home-assistant/wheels-custom-integrations/tree/master/components

All components in home assistant follow this rule: https://github.com/home-assistant/core/tree/dev/homeassistant/components

Can we rename the whole thing?

I understand it's quite a huge change but it's better to do this earlier.
But this is also an opportunity to choose a better name. Can we use just google_home or it's too bold? πŸ™‚
There is no official google_home component anymore, so this name should be free.

What needs to be renamed

Filter chromecast devices

Since the integration provides alarms and timers, chromecast should be filtered from list ofdiscovered devices since they do not support either of the two features.

401 Unauthorised error handling

Describe the bug

We cache local authentication token in glocaltokens package, but if the token expires - we don't know and requests fail with 401.
There is a new feature in glocaltokens to force reload homegraph that will provide new local auth tokens. See here. What we need to do is introduce 401 error handling to our session.get request that will re-run get_google_devices method with force_homegraph_reload=True

Recommend Projects

  • React photo React

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

  • Vue.js photo Vue.js

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

  • Typescript photo Typescript

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

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

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

  • web

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

  • server

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

  • Machine learning

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

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

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

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.