├── .github └── workflows │ └── combined.yaml ├── .gitignore ├── LICENSE ├── README.md ├── custom_components └── googlewifi │ ├── __init__.py │ ├── binary_sensor.py │ ├── config_flow.py │ ├── const.py │ ├── device_tracker.py │ ├── light.py │ ├── manifest.json │ ├── sensor.py │ ├── services.yaml │ ├── strings.json │ ├── switch.py │ └── translations │ ├── en.json │ ├── pt-BR.json │ └── pt-pt.json ├── hacs.json └── info.md /.github/workflows/combined.yaml: -------------------------------------------------------------------------------- 1 | name: "Validation And Formatting" 2 | on: 3 | push: 4 | pull_request: 5 | schedule: 6 | - cron: '0 0 * * *' 7 | jobs: 8 | ci: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v2 12 | name: Download repo 13 | with: 14 | fetch-depth: 0 15 | - uses: actions/setup-python@v2 16 | name: Setup Python 17 | - uses: actions/cache@v2 18 | name: Cache 19 | with: 20 | path: | 21 | ~/.cache/pip 22 | key: custom-component-ci 23 | - uses: hacs/integration/action@main 24 | with: 25 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 26 | CATEGORY: integration 27 | - uses: KTibow/ha-blueprint@stable 28 | name: CI 29 | with: 30 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Google WiFi Home Assistant Integration 2 | 3 | Buy me a coffee [![hacs_badge](https://img.shields.io/badge/HACS-Default-orange.svg?style=for-the-badge)](https://github.com/hacs/integration) 4 | 5 | 6 | This integration provides control and monitoring of the Google WiFi system within Home Assistant. 7 | 8 | ### Platforms: 9 | 10 | #### Binary Sensor: 11 | 12 | The binary_sensor platform will show the access points that are configured in your system and their connection status to the Internet (on = connected). 13 | 14 | Additionally there is a custom service to allow you to reset either a single access point or the whole wifi system: 15 | 16 | ##### Service: googlewifi.reset 17 | 18 | |Parameter|Description|Example| 19 | |-|-|-| 20 | |entity_id|Access point or system to restart.|binary_sensor.this_access_point| 21 | 22 | #### Device Tracker: 23 | 24 | The device_tracker platform will report the connected (home/away) status of all of the devices which are registered in your Google Wifi network. Note: Google Wifi retains device data for a long time so you should expect to see many duplicated devices which are not connected as part of this integration. There is no way to parse out what is current and what is old. 25 | 26 | #### Switch: 27 | 28 | The switch platform will allow you to turn on and off the internet to any connected device in your Google Wifi system. On = Internet On, Off = Internet Off / Paused. Additionally there are two custom services to allow you to set and clear device prioritization. 29 | 30 | ##### Service: googlewifi.prioritize 31 | 32 | |Parameter|Description|Example| 33 | |-|-|-| 34 | |entity_id|The entity_id of the device you want to prioritize.|switch.my_iphone| 35 | |duration|The duration in hours that you want to prioritize for.|4| 36 | 37 | ##### Service: googlewifi.prioritize_reset 38 | 39 | |Parameter|Description|Example| 40 | |-|-|-| 41 | |entity_id|The entity_id of a device on the system you want to clear.|switch.my_iphone| 42 | 43 | Note: Only one device can be prioritized at a time. If you set a second prioritization it will clear the first one first. 44 | 45 | #### Light: 46 | 47 | The light platform allows you to turn on and off and set the brightness of the lights on each of your Google Wifi hubs. (Just for fun). 48 | 49 | #### Sensor: 50 | 51 | The sensor platform adds upload and download speed monitoring to your Google Wifi system. Automatic speed testing can be enabled and disabled from the integration options (default on), as can the interval for the tests (default 24 hours). 52 | 53 | ##### Service: googlewifi.speed_test 54 | 55 | |Parameter|Description|Example| 56 | |-|-|-| 57 | |entity_id|A speed sensor entity_id of the google system.|sensor.google_wifi_system_upload_speed 58 | 59 | Note: You must select the main wifi system. Individual devices can not be tested. 60 | 61 | ### Install through HACS: 62 | 63 | Add a custom repository in HACS pointed to https://github.com/djtimca/hagooglewifi 64 | 65 | The new integration for Google WiFi should appear under your integrations tab. 66 | 67 | Click Install and restart Home Assistant. 68 | 69 | ### Install manually: 70 | 71 | Copy the contents found in https://github.com/djtimca/hagooglewifi/custom_components/googlewifi to your custom_components folder in Home Assistant. 72 | 73 | Restart Home Assistant. 74 | 75 | ## Configure the integration: 76 | 77 | To install this integration you will need a Google Refresh Token which you can get by installing the Chrome Extension directly from Github: https://github.com/AngeloD2022/onhubauthhelper 78 | 79 | Note that using the Chrome Plugin is much easier. 80 | 81 | Once installed, restart Home Assistant and go to Configuration -> Integrations and click the + to add a new integration. 82 | 83 | Search for Google WiFi and you will see the integration available. 84 | 85 | Enter the refresh token in the integration configuration screen and hit submit. 86 | 87 | Enjoy! 88 | -------------------------------------------------------------------------------- /custom_components/googlewifi/__init__.py: -------------------------------------------------------------------------------- 1 | """The Google Wifi Integration for Home Assistant.""" 2 | import asyncio 3 | import logging 4 | import time 5 | from datetime import timedelta 6 | 7 | import voluptuous as vol 8 | from googlewifi import GoogleHomeIgnoreDevice, GoogleWifi, GoogleWifiException 9 | from homeassistant.config_entries import ConfigEntry 10 | from homeassistant.const import CONF_SCAN_INTERVAL 11 | from homeassistant.core import CoreState, HomeAssistant, callback 12 | from homeassistant.exceptions import ConfigEntryNotReady, PlatformNotReady 13 | from homeassistant.helpers import aiohttp_client 14 | from homeassistant.helpers.dispatcher import async_dispatcher_send 15 | from homeassistant.helpers.update_coordinator import ( 16 | CoordinatorEntity, 17 | DataUpdateCoordinator, 18 | UpdateFailed, 19 | ) 20 | 21 | from .const import ( 22 | ADD_DISABLED, 23 | CONF_SPEEDTEST, 24 | CONF_SPEEDTEST_INTERVAL, 25 | COORDINATOR, 26 | DEFAULT_SPEEDTEST, 27 | DEFAULT_SPEEDTEST_INTERVAL, 28 | DOMAIN, 29 | GOOGLEWIFI_API, 30 | POLLING_INTERVAL, 31 | REFRESH_TOKEN, 32 | SIGNAL_ADD_DEVICE, 33 | SIGNAL_DELETE_DEVICE, 34 | ) 35 | 36 | CONFIG_SCHEMA = vol.Schema({DOMAIN: vol.Schema({})}, extra=vol.ALLOW_EXTRA) 37 | _LOGGER = logging.getLogger(__name__) 38 | 39 | PLATFORMS = ["binary_sensor", "device_tracker", "switch", "light", "sensor"] 40 | 41 | 42 | async def async_setup(hass: HomeAssistant, config: dict): 43 | """Set up the Google WiFi component.""" 44 | hass.data.setdefault(DOMAIN, {}) 45 | 46 | return True 47 | 48 | 49 | async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): 50 | """Set up Google WiFi component from a config entry.""" 51 | polling_interval = entry.options.get(CONF_SCAN_INTERVAL, POLLING_INTERVAL) 52 | 53 | conf = entry.data 54 | conf_options = entry.options 55 | 56 | session = aiohttp_client.async_get_clientsession(hass) 57 | 58 | api = GoogleWifi(refresh_token=conf[REFRESH_TOKEN], session=session) 59 | 60 | try: 61 | await api.connect() 62 | except ConnectionError as error: 63 | _LOGGER.debug(f"Google WiFi API: {error}") 64 | raise PlatformNotReady from error 65 | except ValueError as error: 66 | _LOGGER.debug(f"Google WiFi API: {error}") 67 | raise ConfigEntryNotReady from error 68 | 69 | coordinator = GoogleWiFiUpdater( 70 | hass, 71 | api=api, 72 | name="GoogleWifi", 73 | polling_interval=polling_interval, 74 | refresh_token=conf[REFRESH_TOKEN], 75 | entry=entry, 76 | add_disabled=conf.get(ADD_DISABLED, True), 77 | auto_speedtest=conf_options.get(CONF_SPEEDTEST, DEFAULT_SPEEDTEST), 78 | speedtest_interval=conf_options.get( 79 | CONF_SPEEDTEST_INTERVAL, DEFAULT_SPEEDTEST_INTERVAL 80 | ), 81 | ) 82 | 83 | await coordinator.async_refresh() 84 | 85 | if not coordinator.last_update_success: 86 | raise ConfigEntryNotReady 87 | 88 | hass.data[DOMAIN][entry.entry_id] = { 89 | COORDINATOR: coordinator, 90 | GOOGLEWIFI_API: api, 91 | } 92 | 93 | await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) 94 | 95 | return True 96 | 97 | 98 | async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry): 99 | """Unload a config entry.""" 100 | unload_ok = all( 101 | await asyncio.gather( 102 | *[ 103 | hass.config_entries.async_forward_entry_unload(entry, component) 104 | for component in PLATFORMS 105 | ] 106 | ) 107 | ) 108 | if unload_ok: 109 | hass.data[DOMAIN].pop(entry.entry_id) 110 | 111 | return unload_ok 112 | 113 | 114 | async def cleanup_device_registry(hass: HomeAssistant, device_id): 115 | """Remove device registry entry if there are no remaining entities.""" 116 | 117 | device_registry = await hass.helpers.device_registry.async_get_registry() 118 | entity_registry = await hass.helpers.entity_registry.async_get_registry() 119 | if device_id and not hass.helpers.entity_registry.async_entries_for_device( 120 | entity_registry, device_id, include_disabled_entities=True 121 | ): 122 | device_registry.async_remove_device(device_id) 123 | 124 | 125 | class GoogleWiFiUpdater(DataUpdateCoordinator): 126 | """Class to manage fetching update data from the Google Wifi API.""" 127 | 128 | def __init__( 129 | self, 130 | hass: HomeAssistant, 131 | api: str, 132 | name: str, 133 | polling_interval: int, 134 | refresh_token: str, 135 | entry: ConfigEntry, 136 | add_disabled: bool, 137 | auto_speedtest: str, 138 | speedtest_interval: str, 139 | ): 140 | """Initialize the global Google Wifi data updater.""" 141 | self.api = api 142 | self.refresh_token = refresh_token 143 | self.entry = entry 144 | self.add_disabled = add_disabled 145 | self._last_speedtest = 0 146 | self.auto_speedtest = auto_speedtest 147 | self.speedtest_interval = speedtest_interval 148 | self._force_speed_update = None 149 | self.devicelist = [] 150 | 151 | super().__init__( 152 | hass=hass, 153 | logger=_LOGGER, 154 | name=name, 155 | update_interval=timedelta(seconds=polling_interval), 156 | ) 157 | 158 | async def force_speed_test(self, system_id): 159 | """Set the flag to force a speed test.""" 160 | self._force_speed_update = system_id 161 | return True 162 | 163 | async def _async_update_data(self): 164 | """Fetch data from Google Wifi API.""" 165 | 166 | try: 167 | system_data = await self.api.get_systems() 168 | 169 | for system_id, system in system_data.items(): 170 | connected_count = 0 171 | guest_connected_count = 0 172 | main_network = system["groupSettings"]["lanSettings"].get( 173 | "dhcpPoolBegin", " " * 10 174 | ) 175 | main_network = ".".join(main_network.split(".", 3)[:3]) 176 | 177 | for device_id, device in system["devices"].items(): 178 | device_network = device.get("ipAddress", " " * 10) 179 | device_network = ".".join(device_network.split(".", 3)[:3]) 180 | 181 | if device_id not in self.devicelist: 182 | to_add = { 183 | "system_id": system_id, 184 | "device_id": device_id, 185 | "device": device, 186 | } 187 | async_dispatcher_send(self.hass, SIGNAL_ADD_DEVICE, to_add) 188 | self.devicelist.append(device_id) 189 | 190 | if device.get("connected") and main_network == device_network: 191 | connected_count += 1 192 | device["network"] = "main" 193 | elif ( 194 | device.get("connected") 195 | and device.get("unfilteredFriendlyType") != "Nest Wifi point" 196 | ): 197 | guest_connected_count += 1 198 | device["network"] = "guest" 199 | elif device.get("unfilteredFriendlyType") == "Nest Wifi point": 200 | connected_count += 1 201 | device["network"] = "main" 202 | 203 | for known_device in self.devicelist: 204 | if known_device not in system["devices"]: 205 | async_dispatcher_send( 206 | self.hass, SIGNAL_DELETE_DEVICE, known_device 207 | ) 208 | self.devicelist.remove(known_device) 209 | 210 | system_data[system_id]["connected_devices"] = connected_count 211 | system_data[system_id]["guest_devices"] = guest_connected_count 212 | system_data[system_id]["total_devices"] = ( 213 | connected_count + guest_connected_count 214 | ) 215 | 216 | if ( 217 | time.time() 218 | > (self._last_speedtest + (60 * 60 * self.speedtest_interval)) 219 | and self.auto_speedtest == True 220 | and self.hass.state == CoreState.running 221 | ): 222 | for system_id, system in system_data.items(): 223 | speedtest_result = await self.api.run_speed_test( 224 | system_id=system_id 225 | ) 226 | system_data[system_id]["speedtest"] = speedtest_result 227 | 228 | self._last_speedtest = time.time() 229 | elif self._force_speed_update: 230 | speedtest_result = await self.api.run_speed_test(system_id=system_id) 231 | system_data[system_id]["speedtest"] = speedtest_result 232 | self._force_speed_update = None 233 | 234 | return system_data 235 | except GoogleWifiException as error: 236 | session = aiohttp_client.async_create_clientsession(self.hass) 237 | self.api = GoogleWifi(refresh_token=self.refresh_token, session=session) 238 | except GoogleHomeIgnoreDevice as error: 239 | raise UpdateFailed(f"Error connecting to GoogleWifi: {error}") from error 240 | except ConnectionError as error: 241 | raise ConfigEntryNotReady( 242 | f"Error connecting to GoogleWifi: {error}" 243 | ) from error 244 | except ValueError as error: 245 | raise ConfigEntryNotReady( 246 | f"Invalid data from GoogleWifi: {error}" 247 | ) from error 248 | 249 | 250 | class GoogleWifiEntity(CoordinatorEntity): 251 | """Defines the base Google WiFi entity.""" 252 | 253 | def __init__( 254 | self, 255 | coordinator: GoogleWiFiUpdater, 256 | name: str, 257 | icon: str, 258 | system_id: str, 259 | item_id: str, 260 | ): 261 | """Initialize the Google WiFi Entity.""" 262 | super().__init__(coordinator) 263 | 264 | self._name = name 265 | self._unique_id = item_id if item_id else system_id 266 | self._icon = icon 267 | self._system_id = system_id 268 | self._item_id = item_id 269 | self._attrs = {} 270 | 271 | @property 272 | def unique_id(self) -> str: 273 | """Return a unique, Home Assistant friendly identifier for this entity.""" 274 | return self._unique_id 275 | 276 | @property 277 | def name(self) -> str: 278 | """Return the name of the entity.""" 279 | return self._name 280 | 281 | @property 282 | def icon(self): 283 | """Return the icon for the entity.""" 284 | return self._icon 285 | 286 | @property 287 | def extra_state_attributes(self): 288 | """Return the attributes.""" 289 | self._attrs["system"] = self._system_id 290 | return self._attrs 291 | 292 | @property 293 | def entity_registry_enabled_default(self): 294 | """Return option setting to enable or disable by default.""" 295 | return self.coordinator.add_disabled 296 | 297 | async def async_added_to_hass(self): 298 | """When entity is added to HASS.""" 299 | self.async_on_remove(self.coordinator.async_add_listener(self._update_callback)) 300 | 301 | @callback 302 | def _update_callback(self): 303 | """Handle device update.""" 304 | self.async_write_ha_state() 305 | 306 | async def _delete_callback(self, device_id): 307 | """Remove the device when it disappears.""" 308 | 309 | if device_id == self._unique_id: 310 | entity_registry = ( 311 | await self.hass.helpers.entity_registry.async_get_registry() 312 | ) 313 | 314 | if entity_registry.async_is_registered(self.entity_id): 315 | entity_entry = entity_registry.async_get(self.entity_id) 316 | entity_registry.async_remove(self.entity_id) 317 | await cleanup_device_registry(self.hass, entity_entry.device_id) 318 | else: 319 | await self.async_remove() 320 | -------------------------------------------------------------------------------- /custom_components/googlewifi/binary_sensor.py: -------------------------------------------------------------------------------- 1 | """Definition and setup of the Google Wifi Sensors for Home Assistant.""" 2 | 3 | from homeassistant.components.binary_sensor import BinarySensorEntity 4 | from homeassistant.const import ATTR_NAME 5 | from homeassistant.helpers import entity_platform 6 | from homeassistant.helpers.update_coordinator import UpdateFailed 7 | 8 | from . import GoogleWifiEntity, GoogleWiFiUpdater 9 | from .const import ( 10 | ATTR_IDENTIFIERS, 11 | ATTR_MANUFACTURER, 12 | ATTR_MODEL, 13 | ATTR_SW_VERSION, 14 | COORDINATOR, 15 | DEFAULT_ICON, 16 | DEV_MANUFACTURER, 17 | DOMAIN, 18 | ) 19 | 20 | SERVICE_RESET = "reset" 21 | 22 | 23 | async def async_setup_entry(hass, entry, async_add_entities): 24 | """Set up the binary sensor platforms.""" 25 | 26 | coordinator = hass.data[DOMAIN][entry.entry_id][COORDINATOR] 27 | entities = [] 28 | 29 | for system_id, system in coordinator.data.items(): 30 | entity = GoogleWifiBinarySensor( 31 | coordinator=coordinator, 32 | name=f"Google Wifi System {system_id}", 33 | icon=DEFAULT_ICON, 34 | system_id=system_id, 35 | item_id=None, 36 | ) 37 | entities.append(entity) 38 | 39 | for ap_id, access_point in system["access_points"].items(): 40 | ap_name = "Google Access Point" 41 | 42 | if access_point["accessPointSettings"].get("accessPointOtherSettings"): 43 | if access_point["accessPointSettings"]["accessPointOtherSettings"].get( 44 | "apName" 45 | ): 46 | ap_name = access_point["accessPointSettings"][ 47 | "accessPointOtherSettings" 48 | ]["apName"] 49 | 50 | if access_point["accessPointSettings"]["accessPointOtherSettings"].get( 51 | "roomData" 52 | ): 53 | if access_point["accessPointSettings"]["accessPointOtherSettings"][ 54 | "roomData" 55 | ].get("name"): 56 | ap_name = f"{access_point['accessPointSettings']['accessPointOtherSettings']['roomData']['name']} Access Point" 57 | 58 | entity = GoogleWifiBinarySensor( 59 | coordinator=coordinator, 60 | name=ap_name, 61 | icon=DEFAULT_ICON, 62 | system_id=system_id, 63 | item_id=ap_id, 64 | ) 65 | entities.append(entity) 66 | 67 | async_add_entities(entities) 68 | 69 | # register service for reset 70 | platform = entity_platform.current_platform.get() 71 | 72 | platform.async_register_entity_service( 73 | SERVICE_RESET, 74 | {}, 75 | "async_reset_device", 76 | ) 77 | 78 | 79 | class GoogleWifiBinarySensor(GoogleWifiEntity, BinarySensorEntity): 80 | """Defines a Google WiFi sensor.""" 81 | 82 | def __init__(self, coordinator, name, icon, system_id, item_id): 83 | """Initialize the sensor.""" 84 | super().__init__( 85 | coordinator=coordinator, 86 | name=name, 87 | icon=icon, 88 | system_id=system_id, 89 | item_id=item_id, 90 | ) 91 | 92 | self._state = None 93 | self._device_info = None 94 | 95 | @property 96 | def is_on(self) -> bool: 97 | """Return the on/off state of the sensor.""" 98 | 99 | try: 100 | state = False 101 | 102 | if self._item_id: 103 | if ( 104 | self.coordinator.data[self._system_id]["access_points"][ 105 | self._item_id 106 | ]["status"] 107 | == "AP_ONLINE" 108 | ): 109 | state = True 110 | else: 111 | if self.coordinator.data[self._system_id]["status"] == "WAN_ONLINE": 112 | state = True 113 | 114 | self._state = state 115 | except TypeError: 116 | pass 117 | except KeyError: 118 | pass 119 | 120 | return self._state 121 | 122 | @property 123 | def device_info(self): 124 | """Define the device as an individual Google WiFi system.""" 125 | 126 | try: 127 | device_info = { 128 | ATTR_MANUFACTURER: DEV_MANUFACTURER, 129 | ATTR_NAME: self._name, 130 | } 131 | 132 | if self._item_id: 133 | device_info[ATTR_IDENTIFIERS] = {(DOMAIN, self._item_id)} 134 | this_data = self.coordinator.data[self._system_id]["access_points"][ 135 | self._item_id 136 | ] 137 | device_info[ATTR_MANUFACTURER] = this_data["accessPointProperties"][ 138 | "hardwareType" 139 | ] 140 | device_info[ATTR_SW_VERSION] = this_data["accessPointProperties"][ 141 | "firmwareVersion" 142 | ] 143 | device_info["via_device"] = (DOMAIN, self._system_id) 144 | else: 145 | device_info[ATTR_IDENTIFIERS] = {(DOMAIN, self._system_id)} 146 | device_info[ATTR_MODEL] = "Google Wifi" 147 | device_info[ATTR_SW_VERSION] = self.coordinator.data[self._system_id][ 148 | "groupProperties" 149 | ]["otherProperties"]["firmwareVersion"] 150 | 151 | self._device_info = device_info 152 | except TypeError: 153 | pass 154 | except KeyError: 155 | pass 156 | 157 | return self._device_info 158 | 159 | async def async_reset_device(self): 160 | """Reset the network or specific access point.""" 161 | 162 | if self._item_id: 163 | success = await self.coordinator.api.restart_ap(self._item_id) 164 | 165 | if success: 166 | self.async_schedule_update_ha_state() 167 | 168 | else: 169 | raise ConnectionError("Failed to reset access point.") 170 | 171 | else: 172 | success = await self.coordinator.api.restart_system(self._system_id) 173 | 174 | if success: 175 | self.async_schedule_update_ha_state() 176 | 177 | else: 178 | raise ConnectionError("Failed to reset the Google Wifi system.") 179 | -------------------------------------------------------------------------------- /custom_components/googlewifi/config_flow.py: -------------------------------------------------------------------------------- 1 | """Config flow for Google Wifi.""" 2 | import logging 3 | 4 | import voluptuous as vol 5 | from googlewifi import GoogleWifi 6 | from homeassistant import config_entries 7 | from homeassistant.const import ( 8 | CONF_SCAN_INTERVAL, 9 | UnitOfDataRate 10 | ) 11 | from homeassistant.core import callback 12 | from homeassistant.helpers import aiohttp_client, config_entry_flow 13 | 14 | from .const import ( 15 | ADD_DISABLED, 16 | CONF_SPEED_UNITS, 17 | CONF_SPEEDTEST, 18 | CONF_SPEEDTEST_INTERVAL, 19 | DEFAULT_SPEEDTEST, 20 | DEFAULT_SPEEDTEST_INTERVAL, 21 | DOMAIN, 22 | POLLING_INTERVAL, 23 | REFRESH_TOKEN, 24 | ) 25 | 26 | _LOGGER = logging.getLogger(__name__) 27 | 28 | 29 | class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): 30 | """Handle a config flow for GoogleWifi.""" 31 | 32 | VERSION = 1 33 | CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL 34 | 35 | @staticmethod 36 | @callback 37 | def async_get_options_flow(config_entry): 38 | """Get the options flow for this handler.""" 39 | return OptionsFlowHandler(config_entry) 40 | 41 | async def async_step_user(self, user_input=None): 42 | """Handle the initial step.""" 43 | errors = {} 44 | 45 | config_entry = self.hass.config_entries.async_entries(DOMAIN) 46 | if config_entry: 47 | return self.async_abort(reason="single_instance_allowed") 48 | 49 | if user_input is not None: 50 | session = aiohttp_client.async_get_clientsession(self.hass) 51 | 52 | token = user_input[REFRESH_TOKEN] 53 | api_client = GoogleWifi(token, session) 54 | 55 | try: 56 | await api_client.connect() 57 | except ValueError: 58 | errors["base"] = "invalid_auth" 59 | except ConnectionError: 60 | errors["base"] = "cannot_connect" 61 | except Exception: # pylint: disable=broad-except 62 | _LOGGER.exception("Unexpected exception") 63 | errors["base"] = "unknown" 64 | else: 65 | await self.async_set_unique_id(user_input[REFRESH_TOKEN]) 66 | self._abort_if_unique_id_configured() 67 | return self.async_create_entry(title="Google Wifi", data=user_input) 68 | 69 | return self.async_show_form( 70 | step_id="user", 71 | data_schema=vol.Schema( 72 | { 73 | vol.Required(REFRESH_TOKEN): str, 74 | vol.Required(ADD_DISABLED, default=True): bool, 75 | } 76 | ), 77 | errors=errors, 78 | ) 79 | 80 | 81 | class OptionsFlowHandler(config_entries.OptionsFlow): 82 | """Handle options flow changes.""" 83 | 84 | def __init__(self, config_entry): 85 | """Initialize options flow.""" 86 | self.config_entry = config_entry 87 | 88 | async def async_step_init(self, user_input=None): 89 | """Manage options.""" 90 | 91 | if user_input is not None: 92 | return self.async_create_entry(title="", data=user_input) 93 | 94 | return self.async_show_form( 95 | step_id="init", 96 | data_schema=vol.Schema( 97 | { 98 | vol.Optional( 99 | CONF_SCAN_INTERVAL, 100 | default=self.config_entry.options.get( 101 | CONF_SCAN_INTERVAL, POLLING_INTERVAL 102 | ), 103 | ): vol.All( 104 | vol.Coerce(int), 105 | vol.Range(min=3), 106 | ), 107 | vol.Optional( 108 | CONF_SPEEDTEST, 109 | default=self.config_entry.options.get( 110 | CONF_SPEEDTEST, DEFAULT_SPEEDTEST 111 | ), 112 | ): bool, 113 | vol.Optional( 114 | CONF_SPEEDTEST_INTERVAL, 115 | default=self.config_entry.options.get( 116 | CONF_SPEEDTEST_INTERVAL, DEFAULT_SPEEDTEST_INTERVAL 117 | ), 118 | ): vol.Coerce(int), 119 | vol.Optional( 120 | CONF_SPEED_UNITS, 121 | default=self.config_entry.options.get( 122 | CONF_SPEED_UNITS, UnitOfDataRate.MEGABITS_PER_SECOND 123 | ), 124 | ): vol.In( 125 | { 126 | UnitOfDataRate.KILOBITS_PER_SECOND: "kbits/s", 127 | UnitOfDataRate.MEGABITS_PER_SECOND: "Mbit/s", 128 | UnitOfDataRate.GIGABITS_PER_SECOND: "Gbit/s", 129 | UnitOfDataRate.BYTES_PER_SECOND: "B/s", 130 | UnitOfDataRate.KILOBYTES_PER_SECOND: "kB/s", 131 | UnitOfDataRate.MEGABYTES_PER_SECOND: "MB/s", 132 | UnitOfDataRate.GIGABYTES_PER_SECOND: "GB/s", 133 | } 134 | ), 135 | } 136 | ), 137 | ) 138 | -------------------------------------------------------------------------------- /custom_components/googlewifi/const.py: -------------------------------------------------------------------------------- 1 | """Constants for the Google WiFi integration.""" 2 | 3 | from homeassistant.const import ( 4 | ATTR_NAME, 5 | UnitOfDataRate, 6 | ) 7 | 8 | DOMAIN = "googlewifi" 9 | COORDINATOR = "coordinator" 10 | GOOGLEWIFI_API = "googlewifi_api" 11 | ATTR_IDENTIFIERS = "identifiers" 12 | ATTR_MANUFACTURER = "manufacturer" 13 | ATTR_MODEL = "model" 14 | ATTR_SW_VERSION = "sw_version" 15 | ATTR_CONNECTIONS = "connections" 16 | POLLING_INTERVAL = 30 17 | REFRESH_TOKEN = "refresh_token" 18 | DEV_MANUFACTURER = "Google" 19 | DEV_CLIENT_MODEL = "Connected Client" 20 | DEFAULT_ICON = "mdi:wifi" 21 | PAUSE_UPDATE = 15 22 | ADD_DISABLED = "add_disabled" 23 | CONF_SPEEDTEST = "auto_speedtest" 24 | DEFAULT_SPEEDTEST = True 25 | CONF_SPEEDTEST_INTERVAL = "speedtest_interval" 26 | DEFAULT_SPEEDTEST_INTERVAL = 24 27 | CONF_SPEED_UNITS = "speed_units" 28 | SIGNAL_ADD_DEVICE = "googlewifi_add_device" 29 | SIGNAL_DELETE_DEVICE = "googlewifi_delete_device" 30 | 31 | 32 | def unit_convert(data_rate: float, unit_of_measurement: str): 33 | """Convert the speed based on unit of measure.""" 34 | 35 | if unit_of_measurement == UnitOfDataRate.BYTES_PER_SECOND: 36 | data_rate *= 0.125 37 | elif unit_of_measurement == UnitOfDataRate.KILOBYTES_PER_SECOND: 38 | data_rate *= 0.000125 39 | elif unit_of_measurement == UnitOfDataRate.MEGABYTES_PER_SECOND: 40 | data_rate *= 1.25e-7 41 | elif unit_of_measurement == UnitOfDataRate.GIGABYTES_PER_SECOND: 42 | data_rate *= 1.25e-10 43 | elif unit_of_measurement == UnitOfDataRate.KILOBITS_PER_SECOND: 44 | data_rate *= 0.001 45 | elif unit_of_measurement == UnitOfDataRate.MEGABITS_PER_SECOND: 46 | data_rate *= 1e-6 47 | elif unit_of_measurement == UnitOfDataRate.GIGABITS_PER_SECOND: 48 | data_rate *= 1e-9 49 | 50 | return round(data_rate, 2) 51 | -------------------------------------------------------------------------------- /custom_components/googlewifi/device_tracker.py: -------------------------------------------------------------------------------- 1 | """Support for Google Wifi Routers as device tracker.""" 2 | 3 | from homeassistant.components.device_tracker.config_entry import ScannerEntity 4 | from homeassistant.components.device_tracker.const import DOMAIN as DEVICE_TRACKER 5 | from homeassistant.components.device_tracker.const import SourceType 6 | from homeassistant.const import ATTR_NAME 7 | from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC 8 | from homeassistant.helpers.dispatcher import async_dispatcher_connect 9 | 10 | from . import GoogleWifiEntity, GoogleWiFiUpdater 11 | from .const import ( 12 | ATTR_CONNECTIONS, 13 | ATTR_IDENTIFIERS, 14 | ATTR_MANUFACTURER, 15 | ATTR_MODEL, 16 | COORDINATOR, 17 | DEFAULT_ICON, 18 | DEV_CLIENT_MODEL, 19 | DEV_MANUFACTURER, 20 | DOMAIN, 21 | SIGNAL_ADD_DEVICE, 22 | ) 23 | 24 | 25 | async def async_setup_entry(hass, entry, async_add_entities): 26 | """Set up the device tracker platforms.""" 27 | 28 | coordinator = hass.data[DOMAIN][entry.entry_id][COORDINATOR] 29 | entities = [] 30 | 31 | for system_id, system in coordinator.data.items(): 32 | for dev_id, device in system["devices"].items(): 33 | device_name = f"{device['friendlyName']}" 34 | 35 | if device.get("friendlyType"): 36 | device_name = device_name + f" ({device['friendlyType']})" 37 | 38 | entity = GoogleWifiDeviceTracker( 39 | coordinator=coordinator, 40 | name=device_name, 41 | icon=DEFAULT_ICON, 42 | system_id=system_id, 43 | item_id=dev_id, 44 | ) 45 | entities.append(entity) 46 | 47 | async_add_entities(entities) 48 | 49 | async def async_new_entities(device_info): 50 | """Add new entities when they connect to Google Wifi.""" 51 | system_id = device_info["system_id"] 52 | device_id = device_info["device_id"] 53 | device = device_info["device"] 54 | 55 | device_name = f"{device['friendlyName']}" 56 | 57 | if device.get("friendlyType"): 58 | device_name = device_name + f" ({device['friendlyType']})" 59 | 60 | entity = GoogleWifiDeviceTracker( 61 | coordinator=coordinator, 62 | name=device_name, 63 | icon=DEFAULT_ICON, 64 | system_id=system_id, 65 | item_id=device_id, 66 | ) 67 | entities = [entity] 68 | async_add_entities(entities) 69 | 70 | async_dispatcher_connect(hass, SIGNAL_ADD_DEVICE, async_new_entities) 71 | 72 | 73 | class GoogleWifiDeviceTracker(GoogleWifiEntity, ScannerEntity): 74 | """Defines a Google WiFi device tracker.""" 75 | 76 | def __init__(self, coordinator, name, icon, system_id, item_id): 77 | """Initialize the device tracker.""" 78 | super().__init__( 79 | coordinator=coordinator, 80 | name=name, 81 | icon=icon, 82 | system_id=system_id, 83 | item_id=item_id, 84 | ) 85 | 86 | self._is_connected = None 87 | self._mac = None 88 | 89 | @property 90 | def is_connected(self): 91 | """Return true if the device is connected.""" 92 | try: 93 | if self.coordinator.data[self._system_id]["devices"][self._item_id].get( 94 | "connected" 95 | ): 96 | connected_ap = self.coordinator.data[self._system_id]["devices"][ 97 | self._item_id 98 | ].get("apId") 99 | if connected_ap: 100 | connected_ap = self.coordinator.data[self._system_id][ 101 | "access_points" 102 | ][connected_ap]["accessPointSettings"]["accessPointOtherSettings"][ 103 | "roomData" 104 | ][ 105 | "name" 106 | ] 107 | self._attrs["connected_ap"] = connected_ap 108 | else: 109 | self._attrs["connected_ap"] = "NA" 110 | 111 | self._attrs["ip_address"] = self.coordinator.data[self._system_id][ 112 | "devices" 113 | ][self._item_id].get("ipAddress", "NA") 114 | 115 | self._mac = self.coordinator.data[self._system_id]["devices"][ 116 | self._item_id 117 | ].get("macAddress") 118 | 119 | self._attrs["mac"] = self._mac if self._mac else "NA" 120 | 121 | self._is_connected = True 122 | else: 123 | self._is_connected = False 124 | except TypeError: 125 | pass 126 | except KeyError: 127 | pass 128 | # self.hass.async_create_task( 129 | # self.hass.config_entries.async_reload(self.coordinator.entry.entry_id) 130 | # ) 131 | 132 | return self._is_connected 133 | 134 | @property 135 | def source_type(self): 136 | """Return the source type of the client.""" 137 | return SourceType.ROUTER 138 | 139 | @property 140 | def device_info(self): 141 | """Define the device as a device tracker system.""" 142 | if self._mac: 143 | mac = {(CONNECTION_NETWORK_MAC, self._mac)} 144 | else: 145 | mac = {} 146 | 147 | device_info = { 148 | ATTR_IDENTIFIERS: {(DOMAIN, self._item_id)}, 149 | ATTR_NAME: self._name, 150 | ATTR_CONNECTIONS: mac, 151 | ATTR_MANUFACTURER: "Google", 152 | ATTR_MODEL: DEV_CLIENT_MODEL, 153 | "via_device": (DOMAIN, self._system_id), 154 | } 155 | 156 | return device_info 157 | -------------------------------------------------------------------------------- /custom_components/googlewifi/light.py: -------------------------------------------------------------------------------- 1 | """Support for Google Wifi Router light control.""" 2 | import time 3 | 4 | from homeassistant.components.light import ( 5 | ATTR_BRIGHTNESS, 6 | ColorMode, 7 | LightEntity, 8 | LightEntityFeature, 9 | ) 10 | from homeassistant.const import ATTR_NAME 11 | 12 | from . import GoogleWifiEntity, GoogleWiFiUpdater 13 | from .const import ( 14 | ATTR_IDENTIFIERS, 15 | ATTR_MANUFACTURER, 16 | ATTR_MODEL, 17 | COORDINATOR, 18 | DEFAULT_ICON, 19 | DEV_CLIENT_MODEL, 20 | DOMAIN, 21 | PAUSE_UPDATE, 22 | ) 23 | 24 | 25 | async def async_setup_entry(hass, entry, async_add_entities): 26 | """Set up the light platform.""" 27 | 28 | coordinator = hass.data[DOMAIN][entry.entry_id][COORDINATOR] 29 | entities = [] 30 | 31 | for system_id, system in coordinator.data.items(): 32 | for ap_id, access_point in system["access_points"].items(): 33 | ap_name = "Google Access Point" 34 | 35 | if access_point["accessPointSettings"].get("accessPointOtherSettings"): 36 | if access_point["accessPointSettings"]["accessPointOtherSettings"].get( 37 | "apName" 38 | ): 39 | ap_name = access_point["accessPointSettings"][ 40 | "accessPointOtherSettings" 41 | ]["apName"] 42 | 43 | if access_point["accessPointSettings"]["accessPointOtherSettings"].get( 44 | "roomData" 45 | ): 46 | if access_point["accessPointSettings"]["accessPointOtherSettings"][ 47 | "roomData" 48 | ].get("name"): 49 | ap_name = f"{access_point['accessPointSettings']['accessPointOtherSettings']['roomData']['name']} Access Point" 50 | 51 | entity = GoogleWifiLight( 52 | coordinator=coordinator, 53 | name=ap_name, 54 | icon="mdi:lightbulb", 55 | system_id=system_id, 56 | item_id=ap_id, 57 | ) 58 | entities.append(entity) 59 | 60 | async_add_entities(entities) 61 | 62 | 63 | class GoogleWifiLight(GoogleWifiEntity, LightEntity): 64 | """Defines a Google WiFi light.""" 65 | 66 | def __init__(self, coordinator, name, icon, system_id, item_id): 67 | """Initialize the entity.""" 68 | super().__init__( 69 | coordinator=coordinator, 70 | name=name, 71 | icon=icon, 72 | system_id=system_id, 73 | item_id=item_id, 74 | ) 75 | 76 | self._last_brightness = 50 77 | self._state = None 78 | self._brightness = None 79 | self._last_change = 0 80 | 81 | @property 82 | def is_on(self): 83 | since_last = int(time.time()) - self._last_change 84 | 85 | if since_last > PAUSE_UPDATE: 86 | """Return the on/off state of the light.""" 87 | try: 88 | if self.coordinator.data[self._system_id]["access_points"][ 89 | self._item_id 90 | ]["accessPointSettings"]["lightingSettings"].get("intensity"): 91 | self._state = True 92 | else: 93 | self._state = False 94 | except TypeError: 95 | pass 96 | except KeyError: 97 | pass 98 | 99 | return self._state 100 | 101 | @property 102 | def brightness(self): 103 | """Return the current brightness of the light.""" 104 | since_last = int(time.time()) - self._last_change 105 | 106 | if since_last > PAUSE_UPDATE: 107 | try: 108 | brightness = self.coordinator.data[self._system_id]["access_points"][ 109 | self._item_id 110 | ]["accessPointSettings"]["lightingSettings"].get("intensity") 111 | 112 | if brightness: 113 | if brightness > 0: 114 | self._last_brightness = brightness 115 | 116 | self._brightness = brightness * 255 / 100 117 | else: 118 | self._brightness = 0 119 | except TypeError: 120 | pass 121 | except KeyError: 122 | pass 123 | 124 | return self._brightness 125 | 126 | @property 127 | def color_mode(self): 128 | """Return the color mode of the light.""" 129 | return ColorMode.BRIGHTNESS 130 | 131 | @property 132 | def supported_color_modes(self): 133 | """Return the list of supported color modes.""" 134 | return {ColorMode.BRIGHTNESS} 135 | 136 | @property 137 | def device_info(self): 138 | """Define the device as a device tracker system.""" 139 | device_info = { 140 | ATTR_IDENTIFIERS: {(DOMAIN, self._item_id)}, 141 | ATTR_NAME: self._name, 142 | ATTR_MANUFACTURER: "Google", 143 | ATTR_MODEL: DEV_CLIENT_MODEL, 144 | "via_device": (DOMAIN, self._system_id), 145 | } 146 | 147 | return device_info 148 | 149 | async def async_turn_on(self, **kwargs): 150 | """Turn on the light.""" 151 | brightness_pct = 50 152 | 153 | if self._last_brightness: 154 | brightness_pct = ( 155 | self._last_brightness if self._last_brightness > 0 else brightness_pct 156 | ) 157 | 158 | if kwargs.get(ATTR_BRIGHTNESS): 159 | brightness_pct = kwargs[ATTR_BRIGHTNESS] 160 | 161 | brightness = int(brightness_pct * 100 / 255) 162 | 163 | self._brightness = brightness_pct 164 | self._state = True 165 | self._last_change = int(time.time()) 166 | 167 | await self.coordinator.api.set_brightness(self._item_id, brightness) 168 | 169 | async def async_turn_off(self, **kwargs): 170 | """Turn off the light.""" 171 | self._state = False 172 | self._last_change = int(time.time()) 173 | 174 | await self.coordinator.api.set_brightness(self._item_id, 0) 175 | -------------------------------------------------------------------------------- /custom_components/googlewifi/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "domain": "googlewifi", 3 | "name": "Google WiFi", 4 | "config_flow": true, 5 | "documentation": "https://github.com/djtimca/hagooglewifi", 6 | "requirements": [ 7 | "googlewifi==0.0.21" 8 | ], 9 | "issue_tracker": "https://github.com/djtimca/hagooglewifi/issues", 10 | "ssdp": [], 11 | "zeroconf": [], 12 | "homekit": {}, 13 | "dependencies": [], 14 | "codeowners": [ 15 | "@djtimca" 16 | ], 17 | "version": "0.1.34" 18 | } 19 | -------------------------------------------------------------------------------- /custom_components/googlewifi/sensor.py: -------------------------------------------------------------------------------- 1 | """Definition and setup of the Google Wifi Speed Sensor for Home Assistant.""" 2 | 3 | from homeassistant.const import ATTR_NAME, UnitOfDataRate 4 | from homeassistant.exceptions import HomeAssistantError 5 | from homeassistant.helpers import entity_platform 6 | from homeassistant.helpers.update_coordinator import UpdateFailed 7 | from homeassistant.util.dt import as_local, parse_datetime 8 | from homeassistant.components.sensor import ( 9 | SensorDeviceClass, 10 | SensorEntity, 11 | SensorStateClass, 12 | ) 13 | 14 | from . import GoogleWifiEntity, GoogleWiFiUpdater 15 | from .const import ( 16 | ATTR_IDENTIFIERS, 17 | ATTR_MANUFACTURER, 18 | ATTR_MODEL, 19 | ATTR_SW_VERSION, 20 | CONF_SPEED_UNITS, 21 | COORDINATOR, 22 | DEFAULT_ICON, 23 | DEV_MANUFACTURER, 24 | DOMAIN, 25 | unit_convert, 26 | ) 27 | 28 | SERVICE_SPEED_TEST = "speed_test" 29 | 30 | 31 | async def async_setup_entry(hass, entry, async_add_entities): 32 | """Set up the sensor platform for a Wifi system.""" 33 | 34 | coordinator = hass.data[DOMAIN][entry.entry_id][COORDINATOR] 35 | entities = [] 36 | 37 | for system_id, system in coordinator.data.items(): 38 | entity = GoogleWifiSpeedSensor( 39 | coordinator=coordinator, 40 | name=f"Google Wifi System {system_id} Upload Speed", 41 | icon=DEFAULT_ICON, 42 | system_id=system_id, 43 | speed_key="transmitWanSpeedBps", 44 | speed_type="speed_test", 45 | unit_of_measure=entry.options.get( 46 | CONF_SPEED_UNITS, UnitOfDataRate.MEGABITS_PER_SECOND 47 | ), 48 | ) 49 | entities.append(entity) 50 | 51 | entity = GoogleWifiSpeedSensor( 52 | coordinator=coordinator, 53 | name=f"Google Wifi System {system_id} Download Speed", 54 | icon=DEFAULT_ICON, 55 | system_id=system_id, 56 | speed_key="receiveWanSpeedBps", 57 | speed_type="speed_test", 58 | unit_of_measure=entry.options.get( 59 | CONF_SPEED_UNITS, UnitOfDataRate.MEGABITS_PER_SECOND 60 | ), 61 | ) 62 | entities.append(entity) 63 | 64 | entity = GoogleWifiSpeedSensor( 65 | coordinator=coordinator, 66 | name=f"Google Wifi System {system_id} Upload Traffic", 67 | icon=DEFAULT_ICON, 68 | system_id=system_id, 69 | speed_key="transmitSpeedBps", 70 | speed_type="realtime", 71 | unit_of_measure=entry.options.get( 72 | CONF_SPEED_UNITS, UnitOfDataRate.MEGABITS_PER_SECOND 73 | ), 74 | ) 75 | entities.append(entity) 76 | 77 | entity = GoogleWifiSpeedSensor( 78 | coordinator=coordinator, 79 | name=f"Google Wifi System {system_id} Download Traffic", 80 | icon=DEFAULT_ICON, 81 | system_id=system_id, 82 | speed_key="receiveSpeedBps", 83 | speed_type="realtime", 84 | unit_of_measure=entry.options.get( 85 | CONF_SPEED_UNITS, UnitOfDataRate.MEGABITS_PER_SECOND 86 | ), 87 | ) 88 | entities.append(entity) 89 | 90 | entity = GoogleWifiConnectedDevices( 91 | coordinator=coordinator, 92 | name=f"Google Wifi System {system_id} Connected Devices", 93 | icon="mdi:devices", 94 | system_id=system_id, 95 | count_type="main", 96 | ) 97 | entities.append(entity) 98 | 99 | entity = GoogleWifiConnectedDevices( 100 | coordinator=coordinator, 101 | name=f"Google Wifi System {system_id} Guest Devices", 102 | icon="mdi:devices", 103 | system_id=system_id, 104 | count_type="guest", 105 | ) 106 | entities.append(entity) 107 | 108 | entity = GoogleWifiConnectedDevices( 109 | coordinator=coordinator, 110 | name=f"Google Wifi System {system_id} Total Devices", 111 | icon="mdi:devices", 112 | system_id=system_id, 113 | count_type="total", 114 | ) 115 | entities.append(entity) 116 | 117 | async_add_entities(entities) 118 | 119 | # register service for reset 120 | platform = entity_platform.current_platform.get() 121 | 122 | platform.async_register_entity_service( 123 | SERVICE_SPEED_TEST, 124 | {}, 125 | "async_speed_test", 126 | ) 127 | 128 | 129 | class GoogleWifiSpeedSensor(GoogleWifiEntity, SensorEntity): 130 | """Defines a Google WiFi Speed sensor.""" 131 | 132 | def __init__( 133 | self, coordinator, name, icon, system_id, speed_key, speed_type, unit_of_measure 134 | ): 135 | """Initialize the sensor.""" 136 | super().__init__( 137 | coordinator=coordinator, 138 | name=name, 139 | icon=icon, 140 | system_id=system_id, 141 | item_id=None, 142 | ) 143 | 144 | self._state = None 145 | self._device_info = None 146 | self._speed_key = speed_key 147 | self._speed_type = speed_type 148 | self.attrs = {} 149 | self._unit_of_measurement = unit_of_measure 150 | 151 | _attr_state_class = SensorStateClass.MEASUREMENT 152 | 153 | @property 154 | def unique_id(self): 155 | """Return the unique id for this sensor.""" 156 | return f"{self._system_id}_{self._speed_key}" 157 | 158 | @property 159 | def state(self): 160 | """Return the state of the sensor.""" 161 | if self.coordinator.data: 162 | if self._speed_type == "speed_test": 163 | if self.coordinator.data[self._system_id].get("speedtest"): 164 | self._state = float( 165 | self.coordinator.data[self._system_id]["speedtest"][ 166 | self._speed_key 167 | ] 168 | ) 169 | 170 | self._state = unit_convert(self._state, self._unit_of_measurement) 171 | 172 | elif self._speed_type == "realtime": 173 | if self.coordinator.data[self._system_id].get("groupTraffic"): 174 | self._state = float( 175 | self.coordinator.data[self._system_id]["groupTraffic"].get( 176 | self._speed_key, 0 177 | ) 178 | ) 179 | 180 | self._state = unit_convert(self._state, self._unit_of_measurement) 181 | 182 | return self._state 183 | 184 | @property 185 | def unit_of_measurement(self): 186 | """Return the unit of measurement of the sensor.""" 187 | return self._unit_of_measurement 188 | 189 | @property 190 | def device_info(self): 191 | """Define the device as an individual Google WiFi system.""" 192 | 193 | try: 194 | device_info = { 195 | ATTR_MANUFACTURER: DEV_MANUFACTURER, 196 | ATTR_NAME: self._name, 197 | } 198 | 199 | device_info[ATTR_IDENTIFIERS] = {(DOMAIN, self._system_id)} 200 | device_info[ATTR_MODEL] = "Google Wifi" 201 | device_info[ATTR_SW_VERSION] = self.coordinator.data[self._system_id][ 202 | "groupProperties" 203 | ]["otherProperties"]["firmwareVersion"] 204 | 205 | self._device_info = device_info 206 | except TypeError: 207 | pass 208 | except KeyError: 209 | pass 210 | 211 | return self._device_info 212 | 213 | async def async_speed_test(self, **kwargs): 214 | """Run a speed test.""" 215 | await self.coordinator.force_speed_test(system_id=self._system_id) 216 | 217 | 218 | class GoogleWifiConnectedDevices(GoogleWifiEntity): 219 | """Define a connected devices count sensor for Google Wifi.""" 220 | 221 | def __init__(self, coordinator, name, icon, system_id, count_type): 222 | """Initialize the count sensor.""" 223 | 224 | super().__init__( 225 | coordinator=coordinator, 226 | name=name, 227 | icon=icon, 228 | system_id=system_id, 229 | item_id=None, 230 | ) 231 | 232 | self._count_type = count_type 233 | self._state = None 234 | 235 | @property 236 | def unique_id(self): 237 | """Return the unique id for this sensor.""" 238 | return f"{self._system_id}_device_count_{self._count_type}" 239 | 240 | @property 241 | def unit_of_measurement(self): 242 | """Return the unit of measurement for this sensor.""" 243 | return "Devices" 244 | 245 | @property 246 | def device_info(self): 247 | """Define the device as an individual Google WiFi system.""" 248 | 249 | try: 250 | device_info = { 251 | ATTR_MANUFACTURER: DEV_MANUFACTURER, 252 | ATTR_NAME: self._name, 253 | } 254 | 255 | device_info[ATTR_IDENTIFIERS] = {(DOMAIN, self._system_id)} 256 | device_info[ATTR_MODEL] = "Google Wifi" 257 | device_info[ATTR_SW_VERSION] = self.coordinator.data[self._system_id][ 258 | "groupProperties" 259 | ]["otherProperties"]["firmwareVersion"] 260 | 261 | self._device_info = device_info 262 | except TypeError: 263 | pass 264 | except KeyError: 265 | pass 266 | 267 | return self._device_info 268 | 269 | @property 270 | def state(self): 271 | """Return the current count of connected devices.""" 272 | 273 | if self.coordinator.data: 274 | if self._count_type == "main": 275 | self._state = self.coordinator.data[self._system_id][ 276 | "connected_devices" 277 | ] 278 | elif self._count_type == "guest": 279 | self._state = self.coordinator.data[self._system_id]["guest_devices"] 280 | elif self._count_type == "total": 281 | self._state = self.coordinator.data[self._system_id]["total_devices"] 282 | 283 | return self._state 284 | -------------------------------------------------------------------------------- /custom_components/googlewifi/services.yaml: -------------------------------------------------------------------------------- 1 | reset: 2 | description: Reset a Google Wifi Access Point or the System 3 | fields: 4 | entity_id: 5 | description: Access point or system to restart 6 | example: binary_sensor.this_access_point 7 | 8 | prioritize: 9 | description: Prioritize a Google Wifi Client Device for x hours 10 | fields: 11 | entity_id: 12 | description: The entity ID of the device you would like to prioritize. 13 | example: switch.iPhone 14 | duration: 15 | description: The duration in hours that you would like the prioritization to last. 16 | example: 4 17 | 18 | prioritize_reset: 19 | description: Clear any device prioritizations on the Google Wifi system. 20 | fields: 21 | entity_id: 22 | description: A switch entity ID from the Google Wifi System you want to clear. 23 | example: switch.iPhone 24 | 25 | speed_test: 26 | description: Run a WLAN speed test on the Google Wifi system. 27 | fields: 28 | entity_id: 29 | description: The entity id of a speed sensor on the system you want to test. 30 | example: sensor.googlewifi_system_upload_speed 31 | -------------------------------------------------------------------------------- /custom_components/googlewifi/strings.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Google WiFi Integration", 3 | "config": { 4 | "step": { 5 | "user": { 6 | "description": "Please get a refresh token from https://www.angelod.com/onhubauthtool to configure the integration.", 7 | "data": { 8 | "refresh_token": "Refresh Token", 9 | "add_disabled": "Add all entities as enabled?" 10 | } 11 | } 12 | }, 13 | "error": { 14 | "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", 15 | "invalid_auth": "[%key:common::config_flow::error::invalid_auth%]", 16 | "unknown": "[%key:common::config_flow::error::unknown%]" 17 | }, 18 | "abort": { 19 | "single_instance_allowed": "[%key:common::config_flow::abort::single_instance_allowed%]" 20 | } 21 | }, 22 | "options": { 23 | "step": { 24 | "init": { 25 | "data": { 26 | "refresh_token": "Enter the refresh token obtained from https://www.angelod.com/onhubauthtool", 27 | "add_disabled": "Add all entities as enabled?", 28 | "scan_interval": "Polling Interval (seconds)", 29 | "auto_speedtest": "Run speed test automatically?", 30 | "speedtest_interval": "Speed test interval (hours).", 31 | "speed_units": "Unit of measurement for internet speed." 32 | } 33 | } 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /custom_components/googlewifi/switch.py: -------------------------------------------------------------------------------- 1 | """Support for Google Wifi Connected Devices as Switch Internet on/off.""" 2 | import time 3 | 4 | import voluptuous as vol 5 | from homeassistant.components.switch import SwitchEntity 6 | from homeassistant.const import ATTR_NAME, UnitOfDataRate 7 | from homeassistant.core import callback 8 | from homeassistant.helpers import config_validation as cv 9 | from homeassistant.helpers import entity_platform 10 | from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC 11 | from homeassistant.helpers.dispatcher import async_dispatcher_connect 12 | from homeassistant.util.dt import as_local, as_timestamp, parse_datetime 13 | 14 | from . import GoogleWifiEntity, GoogleWiFiUpdater 15 | from .const import ( 16 | ATTR_CONNECTIONS, 17 | ATTR_IDENTIFIERS, 18 | ATTR_MANUFACTURER, 19 | ATTR_MODEL, 20 | CONF_SPEED_UNITS, 21 | COORDINATOR, 22 | DEFAULT_ICON, 23 | DEV_CLIENT_MODEL, 24 | DOMAIN, 25 | PAUSE_UPDATE, 26 | SIGNAL_ADD_DEVICE, 27 | SIGNAL_DELETE_DEVICE, 28 | unit_convert, 29 | ) 30 | 31 | SERVICE_PRIORITIZE = "prioritize" 32 | SERVICE_CLEAR_PRIORITIZATION = "prioritize_reset" 33 | 34 | 35 | async def async_setup_entry(hass, entry, async_add_entities): 36 | """Set up the switch platform.""" 37 | 38 | coordinator = hass.data[DOMAIN][entry.entry_id][COORDINATOR] 39 | device = hass.data[DOMAIN][entry.entry_id] 40 | 41 | entities = [] 42 | 43 | data_unit = entry.options.get(CONF_SPEED_UNITS, UnitOfDataRate.MEGABITS_PER_SECOND) 44 | 45 | for system_id, system in coordinator.data.items(): 46 | for dev_id, device in system["devices"].items(): 47 | device_name = f"{device['friendlyName']}" 48 | 49 | if device.get("friendlyType"): 50 | device_name = device_name + f" ({device['friendlyType']})" 51 | 52 | entity = GoogleWifiSwitch( 53 | coordinator=coordinator, 54 | name=device_name, 55 | icon=DEFAULT_ICON, 56 | system_id=system_id, 57 | item_id=dev_id, 58 | data_unit=data_unit, 59 | ) 60 | entities.append(entity) 61 | 62 | async_add_entities(entities) 63 | 64 | async def async_new_entities(device_info): 65 | """Add new entities when they connect to Google Wifi.""" 66 | system_id = device_info["system_id"] 67 | device_id = device_info["device_id"] 68 | device = device_info["device"] 69 | 70 | device_name = f"{device['friendlyName']}" 71 | 72 | if device.get("friendlyType"): 73 | device_name = device_name + f" ({device['friendlyType']})" 74 | 75 | entity = GoogleWifiSwitch( 76 | coordinator=coordinator, 77 | name=device_name, 78 | icon=DEFAULT_ICON, 79 | system_id=system_id, 80 | item_id=device_id, 81 | data_unit=data_unit, 82 | ) 83 | entities = [entity] 84 | async_add_entities(entities) 85 | 86 | async_dispatcher_connect(hass, SIGNAL_ADD_DEVICE, async_new_entities) 87 | 88 | # register service for reset 89 | platform = entity_platform.current_platform.get() 90 | 91 | platform.async_register_entity_service( 92 | SERVICE_PRIORITIZE, 93 | {vol.Required("duration"): cv.positive_int}, 94 | "async_prioritize_device", 95 | ) 96 | 97 | platform.async_register_entity_service( 98 | SERVICE_CLEAR_PRIORITIZATION, 99 | {}, 100 | "async_clear_prioritization", 101 | ) 102 | 103 | return True 104 | 105 | 106 | class GoogleWifiSwitch(GoogleWifiEntity, SwitchEntity): 107 | """Defines a Google WiFi switch.""" 108 | 109 | def __init__(self, coordinator, name, icon, system_id, item_id, data_unit): 110 | """Initialize the switch.""" 111 | super().__init__( 112 | coordinator=coordinator, 113 | name=name, 114 | icon=icon, 115 | system_id=system_id, 116 | item_id=item_id, 117 | ) 118 | 119 | self._state = None 120 | self._available = None 121 | self._last_change = 0 122 | self._mac = None 123 | self._unit_of_measurement = data_unit 124 | 125 | @property 126 | def is_on(self): 127 | """Return the status of the internet for this device.""" 128 | since_last = int(time.time()) - self._last_change 129 | 130 | if since_last > PAUSE_UPDATE: 131 | try: 132 | is_prioritized = False 133 | is_prioritized_end = "NA" 134 | 135 | if ( 136 | self.coordinator.data[self._system_id]["groupSettings"][ 137 | "lanSettings" 138 | ] 139 | .get("prioritizedStation") 140 | .get("stationId") 141 | ): 142 | if ( 143 | self.coordinator.data[self._system_id]["groupSettings"][ 144 | "lanSettings" 145 | ]["prioritizedStation"]["stationId"] 146 | == self._item_id 147 | ): 148 | end_time = self.coordinator.data[self._system_id][ 149 | "groupSettings" 150 | ]["lanSettings"]["prioritizedStation"]["prioritizationEndTime"] 151 | is_prioritized_end = as_local( 152 | parse_datetime(end_time) 153 | ).strftime("%d-%b-%y %I:%M %p") 154 | 155 | if as_timestamp(parse_datetime(end_time)) > time.time(): 156 | is_prioritized = True 157 | 158 | self._attrs["prioritized"] = is_prioritized 159 | self._attrs["prioritized_end"] = is_prioritized_end 160 | 161 | if self.coordinator.data[self._system_id]["devices"][self._item_id][ 162 | "paused" 163 | ]: 164 | self._state = False 165 | else: 166 | self._state = True 167 | except TypeError: 168 | pass 169 | except KeyError: 170 | pass 171 | 172 | if self.coordinator.data: 173 | self._mac = self.coordinator.data[self._system_id]["devices"][ 174 | self._item_id 175 | ].get("macAddress", None) 176 | 177 | self._attrs["mac"] = self._mac if self._mac else "NA" 178 | self._attrs["ip"] = self.coordinator.data[self._system_id]["devices"][ 179 | self._item_id 180 | ].get("ipAddress", "NA") 181 | 182 | transmit_speed = float( 183 | self.coordinator.data[self._system_id]["devices"][self._item_id] 184 | .get("traffic", {}) 185 | .get("transmitSpeedBps", 0) 186 | ) 187 | 188 | receive_speed = float( 189 | self.coordinator.data[self._system_id]["devices"][self._item_id] 190 | .get("traffic", {}) 191 | .get("receiveSpeedBps", 0) 192 | ) 193 | 194 | self._attrs[ 195 | f"transmit_speed_{self._unit_of_measurement.replace('/', 'p').replace(' ', '_').lower()}" 196 | ] = unit_convert(transmit_speed, self._unit_of_measurement) 197 | self._attrs[ 198 | f"receive_speed_{self._unit_of_measurement.replace('/', 'p').replace(' ', '_').lower()}" 199 | ] = unit_convert(receive_speed, self._unit_of_measurement) 200 | 201 | self._attrs["network"] = self.coordinator.data[self._system_id]["devices"][ 202 | self._item_id 203 | ]["network"] 204 | 205 | return self._state 206 | 207 | @property 208 | def available(self): 209 | """Switch is not available if it is not connected.""" 210 | try: 211 | if ( 212 | self.coordinator.data[self._system_id]["devices"][self._item_id].get( 213 | "connected" 214 | ) 215 | == True 216 | ): 217 | self._available = True 218 | else: 219 | self._available = False 220 | except TypeError: 221 | pass 222 | except KeyError: 223 | pass 224 | 225 | return self._available 226 | 227 | @property 228 | def device_info(self): 229 | """Define the device as a device tracker system.""" 230 | if self._mac: 231 | mac = {(CONNECTION_NETWORK_MAC, self._mac)} 232 | else: 233 | mac = {} 234 | 235 | device_info = { 236 | ATTR_IDENTIFIERS: {(DOMAIN, self._item_id)}, 237 | ATTR_CONNECTIONS: mac, 238 | ATTR_NAME: self._name, 239 | ATTR_MANUFACTURER: "Google", 240 | ATTR_MODEL: DEV_CLIENT_MODEL, 241 | "via_device": (DOMAIN, self._system_id), 242 | } 243 | 244 | return device_info 245 | 246 | async def async_turn_on(self, **kwargs): 247 | """Turn on (unpause) internet to the client.""" 248 | self._state = True 249 | self._last_change = time.time() 250 | self.async_schedule_update_ha_state() 251 | await self.coordinator.api.pause_device(self._system_id, self._item_id, False) 252 | 253 | async def async_turn_off(self, **kwargs): 254 | """Turn on (pause) internet to the client.""" 255 | self._state = False 256 | self._last_change = time.time() 257 | self.async_schedule_update_ha_state() 258 | await self.coordinator.api.pause_device(self._system_id, self._item_id, True) 259 | 260 | async def async_prioritize_device(self, duration): 261 | """Prioritize a device for (optional) x hours.""" 262 | 263 | await self.coordinator.api.clear_prioritization(self._system_id) 264 | 265 | await self.coordinator.api.prioritize_device( 266 | self._system_id, 267 | self._item_id, 268 | duration, 269 | ) 270 | 271 | async def async_clear_prioritization(self): 272 | """Clear previous prioritization.""" 273 | 274 | await self.coordinator.api.clear_prioritization(self._system_id) 275 | -------------------------------------------------------------------------------- /custom_components/googlewifi/translations/en.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Google WiFi Integration", 3 | "config": { 4 | "step": { 5 | "user": { 6 | "description": "Please get a refresh token from https://www.angelod.com/onhubauthtool to configure the integration.", 7 | "data": { 8 | "refresh_token": "Refresh Token", 9 | "add_disabled": "Add all entities as enabled?" 10 | } 11 | } 12 | }, 13 | "error": { 14 | "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", 15 | "invalid_auth": "[%key:common::config_flow::error::invalid_auth%]", 16 | "unknown": "[%key:common::config_flow::error::unknown%]" 17 | }, 18 | "abort": { 19 | "single_instance_allowed": "[%key:common::config_flow::abort::single_instance_allowed%]" 20 | } 21 | }, 22 | "options": { 23 | "step": { 24 | "init": { 25 | "data": { 26 | "refresh_token": "Enter the refresh token obtained from https://www.angelod.com/onhubauthtool", 27 | "add_disabled": "Add all entities as enabled?", 28 | "scan_interval": "Polling Interval (seconds)", 29 | "auto_speedtest": "Run speed test automatically?", 30 | "speedtest_interval": "Speed test interval (hours).", 31 | "speed_units": "Unit of measurement for internet speed." 32 | } 33 | } 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /custom_components/googlewifi/translations/pt-BR.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Integração Google WiFi", 3 | "config": { 4 | "step": { 5 | "user": { 6 | "description": "Obtenha um token de atualização em https://www.angelod.com/onhubauthtool para configurar a integração.", 7 | "data": { 8 | "refresh_token": "Atualizar Token", 9 | "add_disabled": "Adicionar todas as entidades como habilitadas?" 10 | } 11 | } 12 | }, 13 | "error": { 14 | "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", 15 | "invalid_auth": "[%key:common::config_flow::error::invalid_auth%]", 16 | "unknown": "[%key:common::config_flow::error::unknown%]" 17 | }, 18 | "abort": { 19 | "single_instance_allowed": "[%key:common::config_flow::abort::single_instance_allowed%]" 20 | } 21 | }, 22 | "options": { 23 | "step": { 24 | "init": { 25 | "data": { 26 | "refresh_token": "Insira o token de atualização obtido de https://www.angelod.com/onhubauthtool", 27 | "add_disabled": "Adicionar todas as entidades como habilitadas?", 28 | "scan_interval": "Intervalo de escaneamento (segundos)", 29 | "auto_speedtest": "Executar teste de velocidade automaticamente?", 30 | "speedtest_interval": "Intervalo de teste de velocidade (horas).", 31 | "speed_units": "Unidade de medida da velocidade da internet." 32 | } 33 | } 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /custom_components/googlewifi/translations/pt-pt.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Integração Google WiFi", 3 | "config": { 4 | "step": { 5 | "user": { 6 | "description": "Obter um token de atualização em https://www.angelod.com/onhubauthtool para configurar a integração.", 7 | "data": { 8 | "refresh_token": "Atualizar Token", 9 | "add_disabled": "Adicionar todas as entidades como activadas?" 10 | } 11 | } 12 | }, 13 | "error": { 14 | "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", 15 | "invalid_auth": "[%key:common::config_flow::error::invalid_auth%]", 16 | "unknown": "[%key:common::config_flow::error::unknown%]" 17 | }, 18 | "abort": { 19 | "single_instance_allowed": "[%key:common::config_flow::abort::single_instance_allowed%]" 20 | } 21 | }, 22 | "options": { 23 | "step": { 24 | "init": { 25 | "data": { 26 | "refresh_token": "Insir o token de atualização obtido de https://www.angelod.com/onhubauthtool", 27 | "add_disabled": "Adicionar todas as entidades como activas?", 28 | "scan_interval": "Intervalo de pesquisa (segundos)", 29 | "auto_speedtest": "Executar teste de velocidade automaticamente?", 30 | "speedtest_interval": "Intervalo de teste de velocidade (horas).", 31 | "speed_units": "Unidade de medida da velocidade da internet." 32 | } 33 | } 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /hacs.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Google WiFi", 3 | "country": "CA", 4 | "domains": ["binary_sensor"], 5 | "homeassistant": "0.115.0", 6 | "iot_class": ["Cloud Polling"] 7 | } -------------------------------------------------------------------------------- /info.md: -------------------------------------------------------------------------------- 1 | # Google WiFi Home Assistant Integration 2 | 3 | This integration provides control and monitoring of the Google WiFi system within Home Assistant. 4 | 5 | ### Platforms: 6 | 7 | #### Binary Sensor: 8 | 9 | The binary_sensor platform will show the access points that are configured in your system and their connection status to the Internet (on = connected). 10 | 11 | Additionally there is a custom service to allow you to reset either a single access point or the whole wifi system: 12 | 13 | ##### Service: googlewifi.reset 14 | 15 | |Parameter|Description|Example| 16 | |-|-|-| 17 | |entity_id|Access point or system to restart.|binary_sensor.this_access_point| 18 | 19 | #### Device Tracker: 20 | 21 | The device_tracker platform will report the connected (home/away) status of all of the devices which are registered in your Google Wifi network. Note: Google Wifi retains device data for a long time so you should expect to see many duplicated devices which are not connected as part of this integration. There is no way to parse out what is current and what is old. 22 | 23 | #### Switch: 24 | 25 | The switch platform will allow you to turn on and off the internet to any connected device in your Google Wifi system. On = Internet On, Off = Internet Off / Paused. Additionally there are two custom services to allow you to set and clear device prioritization. 26 | 27 | ##### Service: googlewifi.prioritize 28 | 29 | |Parameter|Description|Example| 30 | |-|-|-| 31 | |entity_id|The entity_id of the device you want to prioritize.|switch.my_iphone| 32 | |duration|The duration in hours that you want to prioritize for.|4| 33 | 34 | ##### Service: googlewifi.prioritize_reset 35 | 36 | |Parameter|Description|Example| 37 | |-|-|-| 38 | |entity_id|The entity_id of a device on the system you want to clear.|switch.my_iphone| 39 | 40 | Note: Only one device can be prioritized at a time. If you set a second prioritization it will clear the first one first. 41 | 42 | #### Light: 43 | 44 | The light platform allows you to turn on and off and set the brightness of the lights on each of your Google Wifi hubs. (Just for fun). 45 | 46 | ## Install 47 | 48 | To install this integration you will need a Google Refresh Token which you can get by following the instructions at: https://www.angelod.com/onhubauthtool 49 | 50 | Note that using the Chrome Plugin is much easier. 51 | 52 | Once installed, restart Home Assistant and go to Configuration -> Integrations and click the + to add a new integration. 53 | 54 | Search for Google WiFi and you will see the integration available. 55 | 56 | Enter the refresh token in the integration configuration screen and hit submit. 57 | 58 | Enjoy! --------------------------------------------------------------------------------