├── LICENSE.txt ├── setup.py ├── .gitignore ├── README.md ├── LICENCE └── googlewifi └── __init__.py /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright 2020 Tim Empringham 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | 3 | with open("README.md", "r") as fh: 4 | long_description = fh.read() 5 | 6 | setuptools.setup( 7 | name="googlewifi", 8 | packages=["googlewifi"], 9 | version="0.0.21", 10 | license='apache-2.0', 11 | author="Tim Empringham", 12 | author_email="tim.empringham@live.ca", 13 | description="Google WiFi API wrapper for integration to Google Wifi systems.", 14 | long_description=long_description, 15 | long_description_content_type="text/markdown", 16 | url="https://github.com/djtimca/googlewifi-api", 17 | download_url = 'https://github.com/djtimca/googlewifi-api/archive/v_0.0.21.tar.gz', 18 | keywords = ['Google', 'Wifi'], 19 | classifiers=[ 20 | 'Development Status :: 3 - Alpha', 21 | 'Intended Audience :: Developers', 22 | 'Topic :: Software Development :: Build Tools', 23 | 'License :: OSI Approved :: Apache Software License', 24 | 'Programming Language :: Python :: 3', 25 | 'Programming Language :: Python :: 3.4', 26 | 'Programming Language :: Python :: 3.5', 27 | 'Programming Language :: Python :: 3.6', 28 | ], 29 | python_requires='>=3.8', 30 | install_requires=['ghome-foyer-api>=1.0.0,<2.0.0'], 31 | ) 32 | -------------------------------------------------------------------------------- /.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 | 131 | # Testing files 132 | test.py 133 | test*.json 134 | /test_data -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # googlewifi-api 2 | PyPi Integration for Google WiFi Services for Home Assistant integration. Also provides bluetooth scanning from Google/Nest Home, Mini etc smart speakers to return information about bluetooth devices in the area. 3 | 4 | ## Required - Refresh Token 5 | 6 | In order to use this API you will need to get a Refresh Token by using the tools or Chrome plugin at https://www.angelod.com/onhubauthtool 7 | 8 | ## Available Methods 9 | 10 | When you initiate the GoogleWifi class you will need to pass in your refresh token that you receive using the tools at www.angelod.com. 11 | 12 | Session can be sent as an optional aiohttp session if you are managing your session within an application. 13 | 14 | ### get_systems() 15 | 16 | Returns a structured data set that includes the entire system data including system status, access point information and status, and devices from the network. 17 | 18 | ### pause_device(system_id:str, device_id:str, pause_state:bool) 19 | 20 | Pause or unpause a specific device on the network. Must specify the system_id, device_id and pause_state (True to pause, False to unpause). Returns True/False on success of the call. 21 | 22 | ### prioritize_device(system_id:str, device_id:str, duration_hours:int (default 1)) 23 | 24 | Prioritize a device for a period of hours (to be specified by duration_hours) from 1 hour to 6 hours maximum. Must specify the system_id and device_id. If duration_hours is not passed it will default to 1 hour prioritization. Returns True/False on success of the call. 25 | 26 | ### clear_prioritization(system_id:str) 27 | 28 | Clear any existing device prioritization from the system. Must specify the system_id to clear. Returns True/False on success of the call. 29 | 30 | ### set_brightness(ap_id:str, brightness:int) 31 | 32 | Set the light brightness on the Access Point. Must specify the access point id (ap_id) and the desired brightness. Brightness range is 0-100. Returns True/False on the success of the call. 33 | 34 | ### restart_ap(ap_id:str) 35 | 36 | Restart a specific Access Point. Must specify the access point (ap_id). Returns True/False on the success of the call. 37 | 38 | ### restart_system(system_id:str) 39 | 40 | Restart the entire system. Must specify the system to restart (system_id). Returns True/False on the success of the call. 41 | 42 | ### refresh_tokens() 43 | 44 | Will return a dict of local access tokens for Google Home/Mini etc devices in format {cloud_device_id:local_access_token}. These tokens are required to access a Google Home device for bluetooth updates and scanning. 45 | 46 | ### update_info(host:str) 47 | 48 | Will return the detailed capabilities and information for a Google Home/Mini etc device. You have to provide the host IP (ie. 192.168.0.20) and it will return a detailed JSON payload which includes the capabilities of the device as well as the cloud device ID which can be used to extract the correct local access token from the refresh_tokens() dict. 49 | 50 | ### get_bluetooth_status(host:str, token:str) 51 | 52 | Will return the current bluetooth status for the Google Home/Mini etc device. 53 | 54 | ### get_bluetooth_devices(host:str, token:str) 55 | 56 | Will return a list of all bluetooth devices which are within range of that Google Home/Mini etc including the MAC address, device type, name, and RSSI (signal strength). 57 | 58 | ### run_speed_test(system_id:str) 59 | 60 | Will run a WAN speed test on the system and return the results (upload/download speed). 61 | 62 | Note: This library was built specifically for integration to Home Assistant. 63 | -------------------------------------------------------------------------------- /LICENCE: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /googlewifi/__init__.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import aiohttp 3 | import json 4 | import datetime 5 | import dateutil.parser 6 | import grpc 7 | 8 | from ghome_foyer_api.api_pb2 import GetHomeGraphRequest 9 | from ghome_foyer_api.api_pb2_grpc import StructuresServiceStub 10 | 11 | GH_HEADERS = {"Content-Type": "application/json"} 12 | class GoogleWifi: 13 | 14 | def __init__(self, refresh_token, session:aiohttp.ClientSession = None): 15 | """Get the API Bearer Token.""" 16 | 17 | if session: 18 | self._session = session 19 | else: 20 | self._session = aiohttp.ClientSession() 21 | 22 | self._refresh_token = refresh_token 23 | self._access_token = None 24 | self._api_token = None 25 | self._systems = None 26 | self._access_points = {} 27 | 28 | async def post_api( 29 | self, 30 | url:str, 31 | headers:str=None, 32 | payload:str=None, 33 | params:str=None, 34 | json_payload=None, 35 | ): 36 | """Post to the Google APIs.""" 37 | async with self._session.post( 38 | url, 39 | headers=headers, 40 | data=payload, 41 | params=params, 42 | verify_ssl=False, 43 | json=json_payload, 44 | timeout=30, 45 | ) as resp: 46 | try: 47 | response = await resp.text() 48 | except aiohttp.ClientConnectorError as error: 49 | raise ConnectionError(error) 50 | 51 | 52 | if response: 53 | try: 54 | response = json.loads(response) 55 | except json.JSONDecodeError as error: 56 | raise ValueError(error) 57 | 58 | return response 59 | 60 | async def get_api(self, url:str, headers:str=None, payload:str=None, params:str=None): 61 | """Get call to Google APIs.""" 62 | try: 63 | async with self._session.get( 64 | url, 65 | headers=headers, 66 | data=payload, 67 | params=params, 68 | verify_ssl=False, 69 | timeout=30, 70 | ) as resp: 71 | try: 72 | response = await resp.text() 73 | except aiohttp.ConnectionError as error: 74 | raise ConnectionError(error) 75 | except asyncio.TimeoutError as error: 76 | raise GoogleHomeIgnoreDevice(error) 77 | 78 | if response: 79 | try: 80 | response = json.loads(response) 81 | except json.JSONDecodeError as error: 82 | raise ValueError(error) 83 | 84 | return response 85 | 86 | async def put_api(self, url:str, headers:str=None, payload:str=None, params:str=None): 87 | """Put call to Google APIs.""" 88 | async with self._session.put( 89 | url, 90 | headers=headers, 91 | data=payload, 92 | params=params, 93 | verify_ssl=False, 94 | timeout=30, 95 | ) as resp: 96 | try: 97 | response = await resp.text() 98 | except aiohttp.ConnectionError as error: 99 | raise ConnectionError(error) 100 | 101 | if response: 102 | try: 103 | response = json.loads(response) 104 | except json.JSONDecodeError as error: 105 | raise ValueError(error) 106 | 107 | return response 108 | 109 | async def delete_api(self, url:str, headers:str=None, payload:str=None, params:str=None): 110 | """Delete call to Google APIs.""" 111 | async with self._session.delete( 112 | url, 113 | headers=headers, 114 | data=payload, 115 | params=params, 116 | verify_ssl=False, 117 | timeout=30, 118 | ) as resp: 119 | try: 120 | response = await resp.text() 121 | except aiohttp.ConnectionError as error: 122 | raise ConnectionError(error) 123 | 124 | if response: 125 | try: 126 | response = json.loads(response) 127 | except json.JSONDecodeError as error: 128 | raise ValueError(error) 129 | 130 | return response 131 | 132 | async def get_access_token(self): 133 | """Get Access Token""" 134 | url = "https://www.googleapis.com/oauth2/v4/token" 135 | payload = f"client_id=936475272427.apps.googleusercontent.com&grant_type=refresh_token&refresh_token={self._refresh_token}" 136 | headers = { 137 | 'Content-Type': 'application/x-www-form-urlencoded' 138 | } 139 | 140 | response = await self.post_api(url, headers, payload) 141 | 142 | self._access_token = response.get("access_token", None) 143 | 144 | async def get_api_token(self): 145 | """Get the API Token.""" 146 | 147 | if not self._access_token: 148 | await self.get_access_token() 149 | 150 | if not self._access_token: 151 | raise ConnectionError("Authorization Error") 152 | 153 | oath_url = "https://oauthaccountmanager.googleapis.com/v1/issuetoken" 154 | payload = "app_id=com.google.OnHub&client_id=586698244315-vc96jg3mn4nap78iir799fc2ll3rk18s.apps.googleusercontent.com&hl=en-US&lib_ver=3.3&response_type=token&scope=https%3A//www.googleapis.com/auth/accesspoints%20https%3A//www.googleapis.com/auth/clouddevices" 155 | headers = { 156 | 'Authorization': f"Bearer {self._access_token}", 157 | 'Content-Type': 'application/x-www-form-urlencoded' 158 | } 159 | 160 | response = await self.post_api(oath_url, headers, payload) 161 | 162 | self._api_token = response.get("token", None) 163 | if self._api_token: 164 | return True 165 | 166 | async def connect(self): 167 | """Authenticate to the Google Wifi services.""" 168 | success = True 169 | 170 | if not self._api_token: 171 | success = await self.get_api_token() 172 | 173 | if success: 174 | return True 175 | else: 176 | return False 177 | 178 | async def get_systems(self): 179 | """Get the systems on this account.""" 180 | if await self.connect(): 181 | url = "https://googlehomefoyer-pa.googleapis.com/v2/groups?prettyPrint=false" 182 | headers = { 183 | "Authorization": f"Bearer {self._api_token}", 184 | "Content-Type": "application/json; charset=utf-8" 185 | } 186 | payload = {} 187 | 188 | response = await self.get_api(url, headers, payload) 189 | 190 | if response.get("groups"): 191 | return await self.structure_systems(response) 192 | else: 193 | raise GoogleWifiException("Failed to retreive Google Wifi Data.") 194 | 195 | async def get_devices(self, system_id): 196 | """Retrieve the devices list for a given system.""" 197 | 198 | if await self.connect(): 199 | url = f"https://googlehomefoyer-pa.googleapis.com/v2/groups/{system_id}/stations?prettyPrint=false" 200 | headers = { 201 | "Content-Type": "application/json; charset=utf-8", 202 | "Authorization": f"Bearer {self._api_token}" 203 | } 204 | payload = {} 205 | 206 | response = await self.get_api(url, headers, payload) 207 | 208 | return(response) 209 | 210 | async def get_status(self, system_id): 211 | """Retrieve the status payload for a system.""" 212 | 213 | if await self.connect(): 214 | url=f"https://googlehomefoyer-pa.googleapis.com/v2/groups/{system_id}/status?prettyPrint=false" 215 | headers = { 216 | "Content-Type": "application/json; charset=utf-8", 217 | "Authorization": f"Bearer {self._api_token}" 218 | } 219 | payload = {} 220 | 221 | response = await self.get_api(url, headers, payload) 222 | 223 | return(response) 224 | 225 | async def structure_systems(self, system_data): 226 | """Structure the data with ids in dict.""" 227 | systems = {} 228 | 229 | for this_system in system_data["groups"]: 230 | systems[this_system["id"]] = this_system 231 | 232 | system_status = await self.get_status(this_system["id"]) 233 | system_metrics = await self.get_realtime_metrics(this_system["id"]) 234 | 235 | try: 236 | systems[this_system["id"]]["status"] = system_status["wanConnectionStatus"] 237 | systems[this_system["id"]]["groupTraffic"] = system_metrics.get("groupTraffic",None) 238 | except KeyError as error: 239 | raise GoogleWifiException(error) 240 | 241 | blocking_policies = {} 242 | if this_system["groupSettings"].get("familyHubSettings").get("stationPolicies"): 243 | for blocking_policy in this_system["groupSettings"]["familyHubSettings"]["stationPolicies"]: 244 | blocking_policies[blocking_policy["stationId"]] = blocking_policy 245 | 246 | this_status = {} 247 | for this_ap in system_status["apStatuses"]: 248 | this_status[this_ap["apId"]] = this_ap 249 | 250 | system_status["status"] = this_status 251 | 252 | access_points = {} 253 | 254 | try: 255 | for this_ap in this_system["accessPoints"]: 256 | access_points[this_ap["id"]] = this_ap 257 | access_points[this_ap["id"]]["status"] = system_status["status"][this_ap["id"]]["apState"] 258 | except KeyError as error: 259 | raise GoogleWifiException(error) 260 | 261 | systems[this_system["id"]]["access_points"] = access_points 262 | 263 | devices_list = await self.get_devices(this_system["id"]) 264 | 265 | devices = {} 266 | station_ids = [] 267 | 268 | try: 269 | for this_device in devices_list["stations"]: 270 | devices[this_device["id"]] = this_device 271 | station_ids.append(this_device["id"]) 272 | device_paused = False 273 | 274 | if blocking_policies.get(this_device["id"]): 275 | expire_date = dateutil.parser.parse(blocking_policies[this_device["id"]]["blockingPolicy"]["expiryTimestamp"]) 276 | 277 | if expire_date > datetime.datetime.now(datetime.timezone.utc) or expire_date.timestamp() == 0: 278 | device_paused = True 279 | 280 | devices[this_device["id"]]["paused"] = device_paused 281 | except KeyError as error: 282 | raise GoogleWifiException(error) 283 | 284 | sensitive_info = await self.get_sensitive_info(system_id=this_system["id"], station_ids=station_ids) 285 | for this_station in sensitive_info: 286 | if this_station["stationId"] in devices: 287 | devices[this_station["stationId"]]["macAddress"] = this_station.get("macAddress",{}) 288 | 289 | if system_metrics.get("stationMetrics"): 290 | for this_station in system_metrics.get("stationMetrics"): 291 | if this_station["station"]["id"] in devices: 292 | devices[this_station["station"]["id"]]["traffic"] = this_station.get("traffic",{}) 293 | 294 | systems[this_system["id"]]["devices"] = devices 295 | 296 | return systems 297 | 298 | async def pause_device(self, system_id:str, device_id:str, pause_state:bool): 299 | """Pause or unpause a specific device""" 300 | 301 | if await self.connect(): 302 | url = f"https://googlehomefoyer-pa.googleapis.com/v2/groups/{system_id}/stationBlocking?prettyPrint=false" 303 | headers = { 304 | "Content-Type": "application/json; charset=utf-8", 305 | "Authorization": f"Bearer {self._api_token}" 306 | } 307 | 308 | payload = { 309 | "blocked": str(pause_state).lower(), 310 | "stationId": device_id 311 | } 312 | payload = json.dumps(payload) 313 | 314 | response = await self.put_api(url, headers, payload) 315 | 316 | return response.get("operation").get("operationState") == "CREATED" 317 | 318 | else: 319 | return False 320 | 321 | async def prioritize_device(self, system_id:str, device_id:str, duration_hours:int=1): 322 | """Set priority device for specified time (default 1 hour).""" 323 | 324 | if await self.connect(): 325 | duration_hours = 1 if duration_hours < 1 else duration_hours 326 | duration_hours = 6 if duration_hours > 6 else duration_hours 327 | 328 | url = f"https://googlehomefoyer-pa.googleapis.com/v2/groups/{system_id}/prioritizedStation?prettyPrint=false" 329 | headers = { 330 | "Content-Type": "application/json; charset=utf-8", 331 | "Authorization": f"Bearer {self._api_token}" 332 | } 333 | 334 | end_time = datetime.datetime.now() + datetime.timedelta(hours=duration_hours) 335 | 336 | end_time = end_time.astimezone().replace(microsecond=0).isoformat() 337 | 338 | payload = { 339 | "stationId": device_id, 340 | "prioritizationEndTime": end_time 341 | } 342 | 343 | payload = json.dumps(payload) 344 | 345 | response = await self.put_api(url, headers=headers, payload=payload) 346 | 347 | return response.get("operation").get("operationState") == "CREATED" 348 | 349 | else: 350 | return False 351 | 352 | async def clear_prioritization(self, system_id:str): 353 | """Clear any device prioritization.""" 354 | 355 | if await self.connect(): 356 | url=f"https://googlehomefoyer-pa.googleapis.com/v2/groups/{system_id}/prioritizedStation?prettyPrint=false" 357 | 358 | headers = { 359 | "Content-Type": "application/json; charset=utf-8", 360 | "Authorization": f"Bearer {self._api_token}" 361 | } 362 | 363 | payload = {} 364 | 365 | response = await self.delete_api(url, headers=headers, payload=payload) 366 | 367 | return response.get("operation").get("operationState") == "CREATED" 368 | 369 | else: 370 | return False 371 | 372 | async def set_brightness(self, ap_id:str, brightness:int): 373 | """Set Access Point Light Brightness.""" 374 | 375 | if await self.connect(): 376 | brightness = 0 if brightness < 0 else brightness 377 | brightness = 100 if brightness > 100 else brightness 378 | 379 | url = f"https://googlehomefoyer-pa.googleapis.com/v2/accesspoints/{ap_id}/lighting?prettyPrint=false" 380 | 381 | headers = { 382 | "Content-Type": "application/json; charset=utf-8", 383 | "Authorization": f"Bearer {self._api_token}" 384 | } 385 | 386 | payload = { 387 | "automatic": False, 388 | "intensity": brightness 389 | } 390 | 391 | payload = json.dumps(payload) 392 | 393 | response = await self.put_api(url, headers=headers, payload=payload) 394 | 395 | return response.get("operation").get("operationState") == "CREATED" 396 | 397 | else: 398 | return False 399 | 400 | async def restart_ap(self, ap_id:str): 401 | """Restart a specific Access Point.""" 402 | 403 | if await self.connect(): 404 | url=f"https://googlehomefoyer-pa.googleapis.com/v2/accesspoints/{ap_id}/reboot?prettyPrint=false" 405 | 406 | headers = { 407 | "Content-Type": "application/json; charset=utf-8", 408 | "Authorization": f"Bearer {self._api_token}" 409 | } 410 | 411 | payload = {} 412 | 413 | response = await self.post_api(url, headers=headers, payload=payload) 414 | 415 | return response.get("operation").get("operationState") == "CREATED" 416 | 417 | else: 418 | return False 419 | 420 | async def restart_system(self, system_id:str): 421 | """Restart the whole Google Wifi System.""" 422 | 423 | if await self.connect(): 424 | url = f"https://googlehomefoyer-pa.googleapis.com/v2/groups/{system_id}/reboot?prettyPrint=false" 425 | 426 | headers = { 427 | "Content-Type": "application/json; charset=utf-8", 428 | "Authorization": f"Bearer {self._api_token}" 429 | } 430 | 431 | payload = {} 432 | 433 | response = await self.post_api(url, headers=headers, payload=payload) 434 | 435 | return response.get("operation").get("operationState") == "CREATED" 436 | 437 | else: 438 | return False 439 | 440 | async def refresh_tokens(self): 441 | """Refresh the Google Access tokens for local Google devices.""" 442 | if await self.connect(): 443 | creds = grpc.access_token_call_credentials(self._api_token) 444 | ssl = grpc.ssl_channel_credentials() 445 | composite = grpc.composite_channel_credentials(ssl, creds) 446 | channel = grpc.secure_channel("googlehomefoyer-pa.googleapis.com:443", composite) 447 | service = StructuresServiceStub(channel) 448 | resp = service.GetHomeGraph(GetHomeGraphRequest()) 449 | data = resp.home.devices 450 | 451 | tokens = {} 452 | 453 | for device in data: 454 | # this is the 'cloud device id' 455 | if device.local_auth_token != "": 456 | tokens[ 457 | device.device_info.project_info.string2 458 | ] = device.local_auth_token 459 | 460 | return tokens 461 | 462 | async def update_info(self, host): 463 | """Update data from Google Home.""" 464 | 465 | if await self.connect(): 466 | url = f"https://{host}:8443/setup/eureka_info" 467 | params = { 468 | "params":"version,audio,name,build_info,detail,device_info,net,wifi,setup,settings,opt_in,opencast,multizone,proxy,night_mode_params,user_eq,room_equalizer", 469 | "options":"detail" 470 | } 471 | 472 | response = await self.get_api(url=url,params=params) 473 | 474 | if response: 475 | return response 476 | else: 477 | raise GoogleHomeUpdateFailed() 478 | 479 | async def get_bluetooth_status(self, host, token): 480 | """Retrieve the current bluetooth status.""" 481 | if await self.connect(): 482 | url = f"https://{host}:8443/setup/bluetooth/status" 483 | headers = {"cast-local-authorization-token": token} 484 | 485 | response = await self.get_api(url=url,headers=headers) 486 | 487 | return response 488 | 489 | async def get_bluetooth_devices(self, host, token): 490 | """Retrieve the current bluetooth clients from a Google Home.""" 491 | 492 | if await self.connect(): 493 | url = f"https://{host}:8443/setup/bluetooth/scan" 494 | data = {"enable": True, "clear_results": True, "timeout": 5} 495 | headers = GH_HEADERS 496 | headers["Host"] = host 497 | headers["cast-local-authorization-token"] = token 498 | 499 | await self.post_api(url=url,headers=headers,json_payload=data) 500 | await asyncio.sleep(5) 501 | 502 | url = f"https://{host}:8443/setup/bluetooth/scan_results" 503 | 504 | response = await self.get_api(url=url,headers=headers) 505 | 506 | return response 507 | 508 | async def create_wan_speedtest(self, system_id:str): 509 | """Start a speed test operation on a system.""" 510 | if await self.connect(): 511 | url = f"https://googlehomefoyer-pa.googleapis.com/v2/groups/{system_id}/wanSpeedTest" 512 | headers = { 513 | "Content-Type": "application/json; charset=utf-8", 514 | "Authorization": f"Bearer {self._api_token}" 515 | } 516 | payload = {} 517 | params = ( 518 | ('prettyPrint', 'false'), 519 | ) 520 | 521 | response = await self.post_api(url=url,headers=headers,payload=payload,params=params) 522 | operation_id = response["operation"]["operationId"] 523 | 524 | return operation_id 525 | 526 | async def check_operation(self, operation_id: str): 527 | """Check the status of a speed test operation.""" 528 | if await self.connect(): 529 | url = f"https://googlehomefoyer-pa.googleapis.com/v2/operations/{operation_id}" 530 | headers = { 531 | "Content-Type": "application/json; charset=utf-8", 532 | "Authorization": f"Bearer {self._api_token}" 533 | } 534 | payload = {} 535 | params = ( 536 | ('prettyPrint', 'false'), 537 | ) 538 | 539 | return await self.get_api(url=url,headers=headers,payload=payload,params=params) 540 | 541 | async def speed_test_results(self, system_id:str): 542 | """Retrieve the speed test results.""" 543 | if await self.connect(): 544 | url = f"https://googlehomefoyer-pa.googleapis.com/v2/groups/{system_id}/speedTestResults" 545 | headers = { 546 | "Content-Type": "application/json; charset=utf-8", 547 | "Authorization": f"Bearer {self._api_token}" 548 | } 549 | payload = {} 550 | params = ( 551 | ('prettyPrint', 'false'), 552 | ('maxResultCount', 1) 553 | ) 554 | 555 | response = await self.get_api(url=url,headers=headers,payload=payload,params=params) 556 | 557 | return response["speedTestResults"] 558 | 559 | async def run_speed_test(self, system_id:str): 560 | """Run a speed test and return the results.""" 561 | if await self.connect(): 562 | operation_id = await self.create_wan_speedtest(system_id=system_id) 563 | 564 | status = await self.check_operation(operation_id) 565 | status = status["operationState"] 566 | 567 | while status != "DONE": 568 | status = await self.check_operation(operation_id) 569 | status = status["operationState"] 570 | await asyncio.sleep(5) 571 | 572 | results = await self.speed_test_results(system_id=system_id) 573 | return results[0] 574 | 575 | async def start_retrieve_sensitive_info(self, system_id:str, station_ids:list): 576 | """Start the request to return the device sensitive information.""" 577 | if await self.connect(): 578 | url = f"https://googlehomefoyer-pa.googleapis.com/v2/groups/{system_id}/stations/operations/sensitiveInfo" 579 | 580 | headers = { 581 | "Content-Type": "application/json; charset=utf-8", 582 | "Authorization": f"Bearer {self._api_token}" 583 | } 584 | json_payload = {"stationIds":station_ids} 585 | params = ( 586 | ('prettyPrint', 'false'), 587 | ) 588 | 589 | response = await self.post_api(url=url,headers=headers,json_payload=json_payload,params=params) 590 | operation_id = response.get("operation",[]).get("operationId") 591 | 592 | return operation_id 593 | 594 | async def sensitive_info_results(self, operation_id:str): 595 | """Return the results of the sensitive info request.""" 596 | if await self.connect(): 597 | url = f"https://googlehomefoyer-pa.googleapis.com/v2/operations/{operation_id}/sensitiveInfo" 598 | params = ( 599 | ('prettyPrint', 'false'), 600 | ) 601 | headers = { 602 | "Content-Type": "application/json; charset=utf-8", 603 | "Authorization": f"Bearer {self._api_token}" 604 | } 605 | payload = {} 606 | 607 | return await self.get_api(url=url, headers=headers, payload=payload, params=params) 608 | 609 | async def get_sensitive_info(self, system_id:str, station_ids:list): 610 | """Return a full set of sensitive info on the system.""" 611 | if await self.connect(): 612 | operation_id = await self.start_retrieve_sensitive_info( 613 | system_id=system_id,station_ids=station_ids 614 | ) 615 | 616 | status = await self.check_operation(operation_id) 617 | status = status["operationState"] 618 | 619 | while status != "DONE": 620 | status = await self.check_operation(operation_id) 621 | status = status["operationState"] 622 | await asyncio.sleep(5) 623 | 624 | results = await self.sensitive_info_results(operation_id=operation_id) 625 | return results.get("stationSensitiveInfos",[]) 626 | 627 | async def get_realtime_metrics(self, system_id:str): 628 | """Return real-time metrics from the system.""" 629 | if await self.connect(): 630 | url = f"https://googlehomefoyer-pa.googleapis.com/v2/groups/{system_id}/realtimeMetrics" 631 | params = ( 632 | ('prettyPrint', 'false'), 633 | ) 634 | headers = { 635 | "Content-Type": "application/json; charset=utf-8", 636 | "Authorization": f"Bearer {self._api_token}" 637 | } 638 | payload = {} 639 | 640 | return await self.get_api(url=url, headers=headers, payload=payload, params=params) 641 | 642 | 643 | class GoogleWifiException(Exception): 644 | """Platform not ready exception.""" 645 | pass 646 | 647 | class GoogleHomeUpdateFailed(Exception): 648 | """Google Home Update failed, token refresh required.""" 649 | 650 | class GoogleHomeIgnoreDevice(Exception): 651 | """Google Home can't get data, ignore it.""" 652 | --------------------------------------------------------------------------------