Compare commits
	
		
			7 Commits
		
	
	
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
| f8dde06510 | |||
| 5ec1a760f6 | |||
| cd5a4c345e | |||
| d707342f8f | |||
| e12edda588 | |||
| 409aa11fcb | |||
| f73ef26e74 | 
							
								
								
									
										19
									
								
								README.md
									
									
									
									
									
								
							
							
						
						
									
										19
									
								
								README.md
									
									
									
									
									
								
							| @ -83,11 +83,26 @@ async with HonConnection(USER, PASSWORD) as hon: | ||||
|             setting.value = setting.min + setting.step | ||||
| ``` | ||||
|  | ||||
| ## Translation | ||||
| To get the translation of some keys like programs, you can use the translation command to see all of hOn's available translations | ||||
| ```commandline | ||||
| $ pyhOn translate es | ||||
| AC: | ||||
|   APPLIANCE_RENAME: | ||||
|     CONTENT_CHOOSE_NAME: Antes de continuar, debes elegir un nombre... | ||||
|     DEFAULT_NAME: Aire acondicionado | ||||
|     TITLE_CHOOSE_NAME: ¡Elije un nombre para tu aire acondicionado! | ||||
|     TITLE_SAVE_NAME: Para cambiar el nombre de tu aparato: | ||||
| ... | ||||
| ``` | ||||
| This generates a huge output. It is recommended to pipe this into a file | ||||
| ```commandline | ||||
| $ pyhOn translate fr > hon_fr.yaml | ||||
| $ pyhOn translate en --json > hon_en.json | ||||
| ``` | ||||
| ## Tested devices | ||||
| - Haier Washing Machine HW90 | ||||
|  | ||||
| _Unfortunately I don't have any more Haier appliances..._ | ||||
|  | ||||
| ## Usage example | ||||
| This library is used for the custom [HomeAssistant Integration "Haier hOn"](https://github.com/Andre0512/hOn). | ||||
|  | ||||
|  | ||||
| @ -1,9 +1,9 @@ | ||||
| #!/usr/bin/env python | ||||
| import argparse | ||||
| import asyncio | ||||
| import json | ||||
| import logging | ||||
| import sys | ||||
| import time | ||||
| from getpass import getpass | ||||
| from pathlib import Path | ||||
| from pprint import pprint | ||||
| @ -25,6 +25,9 @@ def get_arguments(): | ||||
|     keys = subparser.add_parser("keys", help="print as key format") | ||||
|     keys.add_argument("keys", help="print as key format", action="store_true") | ||||
|     keys.add_argument("--all", help="print also full keys", action="store_true") | ||||
|     translate = subparser.add_parser("translate", help="print available translation keys") | ||||
|     translate.add_argument("translate", help="language (de, en, fr...)", metavar="LANGUAGE") | ||||
|     translate.add_argument("--json", help="print as json", action="store_true") | ||||
|     return vars(parser.parse_args()) | ||||
|  | ||||
|  | ||||
| @ -81,8 +84,22 @@ def create_command(commands, concat=False): | ||||
|     return result | ||||
|  | ||||
|  | ||||
| async def translate(language, json_output=False): | ||||
|     async with HonConnection() as hon: | ||||
|         keys = await hon.translation_keys(language) | ||||
|     if json_output: | ||||
|         print(json.dumps(keys, indent=4)) | ||||
|     else: | ||||
|         clean_keys = json.dumps(keys).replace("\\n", "\\\\n").replace("\\\\r", "").replace("\\r", "") | ||||
|         keys = json.loads(clean_keys) | ||||
|         pretty_print(keys) | ||||
|  | ||||
|  | ||||
| async def main(): | ||||
|     args = get_arguments() | ||||
|     if language := args.get("translate"): | ||||
|         await translate(language, json_output=args.get("json")) | ||||
|         return | ||||
|     if not (user := args["user"]): | ||||
|         user = input("User for hOn account: ") | ||||
|     if not (password := args["password"]): | ||||
|  | ||||
							
								
								
									
										45
									
								
								pyhon/api.py
									
									
									
									
									
								
							
							
						
						
									
										45
									
								
								pyhon/api.py
									
									
									
									
									
								
							| @ -15,7 +15,7 @@ _LOGGER = logging.getLogger() | ||||
|  | ||||
|  | ||||
| class HonConnection: | ||||
|     def __init__(self, email, password, session=None) -> None: | ||||
|     def __init__(self, email="", password="", session=None) -> None: | ||||
|         super().__init__() | ||||
|         self._email = email | ||||
|         self._password = password | ||||
| @ -26,6 +26,7 @@ class HonConnection: | ||||
|  | ||||
|     async def __aenter__(self): | ||||
|         self._session = aiohttp.ClientSession() | ||||
|         if self._email and self._password: | ||||
|             await self.setup() | ||||
|         return self | ||||
|  | ||||
| @ -94,6 +95,48 @@ class HonConnection: | ||||
|                 return {} | ||||
|             return result["payload"]["history"] | ||||
|  | ||||
|     async def last_activity(self, device: HonDevice): | ||||
|         url = f"{const.API_URL}/commands/v1/retrieve-last-activity" | ||||
|         params = {"macAddress": device.mac_address} | ||||
|         async with self._session.get(url, params=params, headers=await self._headers) as response: | ||||
|             result = await response.json() | ||||
|             if result and (activity := result.get("attributes")): | ||||
|                 return activity | ||||
|         return {} | ||||
|  | ||||
|     async def appliance_configuration(self): | ||||
|         url = f"{const.API_URL}/config/v1/appliance-configuration" | ||||
|         headers = {"x-api-key": const.API_KEY, "content-type": "application/json"} | ||||
|         async with self._session.get(url, headers=headers) as response: | ||||
|             result = await response.json() | ||||
|             if result and (data := result.get("payload")): | ||||
|                 return data | ||||
|         return {} | ||||
|  | ||||
|     async def app_config(self, language="en", beta=True): | ||||
|         headers = {"x-api-key": const.API_KEY, "content-type": "application/json"} | ||||
|         url = f"{const.API_URL}/app-config" | ||||
|         payload = { | ||||
|               "languageCode": language, | ||||
|               "beta": beta, | ||||
|               "appVersion": const.APP_VERSION, | ||||
|               "os": const.OS | ||||
|             } | ||||
|         payload = json.dumps(payload, separators=(',', ':')) | ||||
|         async with self._session.post(url, headers=headers, data=payload) as response: | ||||
|             if (result := await response.json()) and (data := result.get("payload")): | ||||
|                 return data | ||||
|         return {} | ||||
|  | ||||
|     async def translation_keys(self, language="en"): | ||||
|         headers = {"x-api-key": const.API_KEY, "content-type": "application/json"} | ||||
|         config = await self.app_config(language=language) | ||||
|         if url := config.get("language", {}).get("jsonPath"): | ||||
|             async with self._session.get(url, headers=headers) as response: | ||||
|                 if result := await response.json(): | ||||
|                     return result | ||||
|         return {} | ||||
|  | ||||
|     async def load_attributes(self, device: HonDevice, loop=False): | ||||
|         params = { | ||||
|             "macAddress": device.mac_address, | ||||
|  | ||||
							
								
								
									
										10
									
								
								pyhon/appliances/wd.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										10
									
								
								pyhon/appliances/wd.py
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,10 @@ | ||||
| class Appliance: | ||||
|     def __init__(self, data): | ||||
|         self._data = data | ||||
|  | ||||
|     def get(self): | ||||
|         if self._data["attributes"]["lastConnEvent"]["category"] == "DISCONNECTED": | ||||
|             self._data["attributes"]["parameters"]["machMode"] = "0" | ||||
|         self._data["active"] = bool(self._data.get("activity")) | ||||
|         self._data["pause"] = self._data["attributes"]["parameters"]["machMode"] == "3" | ||||
|         return self._data | ||||
							
								
								
									
										173
									
								
								pyhon/auth.py
									
									
									
									
									
								
							
							
						
						
									
										173
									
								
								pyhon/auth.py
									
									
									
									
									
								
							| @ -6,6 +6,7 @@ import urllib | ||||
| from urllib import parse | ||||
|  | ||||
| import aiohttp as aiohttp | ||||
| from yarl import URL | ||||
|  | ||||
| from pyhon import const | ||||
|  | ||||
| @ -14,7 +15,8 @@ _LOGGER = logging.getLogger() | ||||
|  | ||||
| class HonAuth: | ||||
|     def __init__(self) -> None: | ||||
|         self._framework = "" | ||||
|         self._access_token = "" | ||||
|         self._refresh_token = "" | ||||
|         self._cognito_token = "" | ||||
|         self._id_token = "" | ||||
|  | ||||
| @ -26,71 +28,15 @@ class HonAuth: | ||||
|     def id_token(self): | ||||
|         return self._id_token | ||||
|  | ||||
|     async def _get_frontdoor_url(self, session, email, password): | ||||
|         data = { | ||||
|             "message": { | ||||
|                 "actions": [ | ||||
|                     { | ||||
|                         "id": "79;a", | ||||
|                         "descriptor": "apex://LightningLoginCustomController/ACTION$login", | ||||
|                         "callingDescriptor": "markup://c:loginForm", | ||||
|                         "params": { | ||||
|                             "username": email, | ||||
|                             "password": password, | ||||
|                             "startUrl": "" | ||||
|                         } | ||||
|                     } | ||||
|                 ] | ||||
|             }, | ||||
|             "aura.context": { | ||||
|                 "mode": "PROD", | ||||
|                 "fwuid": self._framework, | ||||
|                 "app": "siteforce:loginApp2", | ||||
|                 "loaded": {"APPLICATION@markup://siteforce:loginApp2": "YtNc5oyHTOvavSB9Q4rtag"}, | ||||
|                 "dn": [], | ||||
|                 "globals": {}, | ||||
|                 "uad": False}, | ||||
|             "aura.pageURI": f"SmartHome/s/login/?language={const.LANGUAGE}", | ||||
|             "aura.token": None} | ||||
|     @property | ||||
|     def access_token(self): | ||||
|         return self._access_token | ||||
|  | ||||
|         params = {"r": 3, "other.LightningLoginCustom.login": 1} | ||||
|         async with session.post( | ||||
|                 const.AUTH_API + "/s/sfsites/aura", | ||||
|                 headers={"Content-Type": "application/x-www-form-urlencoded"}, | ||||
|                 data="&".join(f"{k}={json.dumps(v)}" for k, v in data.items()), | ||||
|                 params=params | ||||
|         ) as response: | ||||
|             if response.status != 200: | ||||
|                 _LOGGER.error("Unable to connect to the login service: %s\n%s", response.status, await response.text()) | ||||
|                 return "" | ||||
|             try: | ||||
|                 text = await response.text() | ||||
|                 return (await response.json())["events"][0]["attributes"]["values"]["url"] | ||||
|             except json.JSONDecodeError: | ||||
|                 if framework := re.findall('clientOutOfSync.*?Expected: ([\\w-]+?) Actual: (.*?)"', text): | ||||
|                     self._framework, actual = framework[0] | ||||
|                     _LOGGER.debug('Framework update from "%s" to "%s"', self._framework, actual) | ||||
|                     return await self._get_frontdoor_url(session, email, password) | ||||
|                 _LOGGER.error("Unable to retrieve the frontdoor URL. Message: " + text) | ||||
|                 return "" | ||||
|     @property | ||||
|     def refresh_token(self): | ||||
|         return self._refresh_token | ||||
|  | ||||
|     async def _prepare_login(self, session, email, password): | ||||
|         if not (frontdoor_url := await self._get_frontdoor_url(session, email, password)): | ||||
|             return False | ||||
|  | ||||
|         async with session.get(frontdoor_url) as resp: | ||||
|             if resp.status != 200: | ||||
|                 _LOGGER.error("Unable to connect to the login service: %s", resp.status) | ||||
|                 return False | ||||
|  | ||||
|         params = {"retURL": "/SmartHome/apex/CustomCommunitiesLanding"} | ||||
|         async with session.get(f"{const.AUTH_API}/apex/ProgressiveLogin", params=params) as resp: | ||||
|             if resp.status != 200: | ||||
|                 _LOGGER.error("Unable to connect to the login service: %s", resp.status) | ||||
|                 return False | ||||
|         return True | ||||
|  | ||||
|     async def _login(self, session): | ||||
|     async def _load_login(self, session): | ||||
|         nonce = secrets.token_hex(16) | ||||
|         nonce = f"{nonce[:8]}-{nonce[8:12]}-{nonce[12:16]}-{nonce[16:20]}-{nonce[20:]}" | ||||
|         params = { | ||||
| @ -102,17 +48,100 @@ class HonAuth: | ||||
|             "nonce": nonce | ||||
|         } | ||||
|         params = "&".join([f"{k}={v}" for k, v in params.items()]) | ||||
|         async with session.get(f"{const.AUTH_API}/services/oauth2/authorize?{params}") as resp: | ||||
|             if id_token := re.findall("id_token=(.*?)&", await resp.text()): | ||||
|                 self._id_token = id_token[0] | ||||
|                 return True | ||||
|         async with session.get(f"{const.AUTH_API}/services/oauth2/authorize/expid_Login?{params}") as resp: | ||||
|             if not (login_url := re.findall("url = '(.+?)'", await resp.text())): | ||||
|                 return False | ||||
|         async with session.get(login_url[0], allow_redirects=False) as redirect1: | ||||
|             if not (url := redirect1.headers.get("Location")): | ||||
|                 return False | ||||
|         async with session.get(url, allow_redirects=False) as redirect2: | ||||
|             if not (url := redirect2.headers.get("Location") + "&System=IoT_Mobile_App&RegistrationSubChannel=hOn"): | ||||
|                 return False | ||||
|         async with session.get(URL(url, encoded=True)) as login_screen: | ||||
|             if context := re.findall('"fwuid":"(.*?)","loaded":(\\{.*?})', await login_screen.text()): | ||||
|                 fw_uid, loaded_str = context[0] | ||||
|                 loaded = json.loads(loaded_str) | ||||
|                 login_url = login_url[0].replace("/".join(const.AUTH_API.split("/")[:-1]), "") | ||||
|                 return fw_uid, loaded, login_url | ||||
|         return False | ||||
|  | ||||
|     async def authorize(self, email, password, mobile_id): | ||||
|         async with aiohttp.ClientSession() as session: | ||||
|             if not await self._prepare_login(session, email, password): | ||||
|     async def _login(self, session, email, password, fw_uid, loaded, login_url): | ||||
|         data = { | ||||
|             "message": { | ||||
|                 "actions": [ | ||||
|                     { | ||||
|                         "id": "79;a", | ||||
|                         "descriptor": "apex://LightningLoginCustomController/ACTION$login", | ||||
|                         "callingDescriptor": "markup://c:loginForm", | ||||
|                         "params": { | ||||
|                             "username": email, | ||||
|                             "password": password, | ||||
|                             "startUrl": parse.unquote(login_url.split("startURL=")[-1]).split("%3D")[0] | ||||
|                         } | ||||
|                     } | ||||
|                 ] | ||||
|             }, | ||||
|             "aura.context": { | ||||
|                 "mode": "PROD", | ||||
|                 "fwuid": fw_uid, | ||||
|                 "app": "siteforce:loginApp2", | ||||
|                 "loaded": loaded, | ||||
|                 "dn": [], | ||||
|                 "globals": {}, | ||||
|                 "uad": False}, | ||||
|             "aura.pageURI": login_url, | ||||
|             "aura.token": None} | ||||
|  | ||||
|         params = {"r": 3, "other.LightningLoginCustom.login": 1} | ||||
|         async with session.post( | ||||
|                 const.AUTH_API + "/s/sfsites/aura", | ||||
|                 headers={"Content-Type": "application/x-www-form-urlencoded"}, | ||||
|                 data="&".join(f"{k}={json.dumps(v)}" for k, v in data.items()), | ||||
|                 params=params | ||||
|         ) as response: | ||||
|             if response.status == 200: | ||||
|                 try: | ||||
|                     return (await response.json())["events"][0]["attributes"]["values"]["url"] | ||||
|                 except json.JSONDecodeError: | ||||
|                     pass | ||||
|             _LOGGER.error("Unable to login: %s\n%s", response.status, await response.text()) | ||||
|             return "" | ||||
|  | ||||
|     async def _get_token(self, session, url): | ||||
|         async with session.get(url) as resp: | ||||
|             if resp.status != 200: | ||||
|                 _LOGGER.error("Unable to get token: %s", resp.status) | ||||
|                 return False | ||||
|             if not await self._login(session): | ||||
|             url = re.findall("href\\s*=\\s*[\"'](.*?)[\"']", await resp.text()) | ||||
|         async with session.get(url[0]) as resp: | ||||
|             if resp.status != 200: | ||||
|                 _LOGGER.error("Unable to get token: %s", resp.status) | ||||
|                 return False | ||||
|             url = re.findall("href\\s*=\\s*[\"'](.*?)[\"']", await resp.text()) | ||||
|             url = "/".join(const.AUTH_API.split("/")[:-1]) + url[0] | ||||
|         async with session.get(url) as resp: | ||||
|             if resp.status != 200: | ||||
|                 _LOGGER.error("Unable to connect to the login service: %s", resp.status) | ||||
|                 return False | ||||
|             text = await resp.text() | ||||
|         if access_token := re.findall("access_token=(.*?)&", text): | ||||
|             self._access_token = access_token[0] | ||||
|         if refresh_token := re.findall("refresh_token=(.*?)&", text): | ||||
|             self._refresh_token = refresh_token[0] | ||||
|         if id_token := re.findall("id_token=(.*?)&", text): | ||||
|             self._id_token = id_token[0] | ||||
|         return True | ||||
|  | ||||
|     async def authorize(self, email, password, mobile_id): | ||||
|         headers = {"user-agent": const.USER_AGENT} | ||||
|         async with aiohttp.ClientSession(headers=headers) as session: | ||||
|             if login_site := await self._load_login(session): | ||||
|                 fw_uid, loaded, login_url = login_site | ||||
|             else: | ||||
|                 return False | ||||
|             if not (url := await self._login(session, email, password, fw_uid, loaded, login_url)): | ||||
|                 return False | ||||
|             if not await self._get_token(session, url): | ||||
|                 return False | ||||
|  | ||||
|             post_headers = {"Content-Type": "application/json", "id-token": self._id_token} | ||||
|  | ||||
| @ -1,5 +1,6 @@ | ||||
| AUTH_API = "https://he-accounts.force.com/SmartHome" | ||||
| API_URL = "https://api-iot.he.services" | ||||
| API_KEY = "GRCqFhC6Gk@ikWXm1RmnSmX1cm,MxY-configuration" | ||||
| APP = "hon" | ||||
| # All seen id's (different accounts, different devices) are the same, so I guess this hash is static | ||||
| CLIENT_ID = "3MVG9QDx8IX8nP5T2Ha8ofvlmjLZl5L_gvfbT9.HJvpHGKoAS_dcMN8LYpTSYeVFCraUnV.2Ag1Ki7m4znVO6" | ||||
| @ -7,4 +8,4 @@ APP_VERSION = "1.53.7" | ||||
| OS_VERSION = 31 | ||||
| OS = "android" | ||||
| DEVICE_MODEL = "exynos9820" | ||||
| LANGUAGE = "en" | ||||
| USER_AGENT = "Chrome/110.0.5481.153" | ||||
|  | ||||
| @ -1,4 +1,5 @@ | ||||
| import importlib | ||||
| from contextlib import suppress | ||||
|  | ||||
| from pyhon.commands import HonCommand | ||||
| from pyhon.parameter import HonParameterFixed | ||||
| @ -95,6 +96,7 @@ class HonDevice: | ||||
|                 command = self.commands[name] | ||||
|             for key, data in command.settings.items(): | ||||
|                 if not isinstance(data, HonParameterFixed) and parameters.get(key) is not None: | ||||
|                     with suppress(ValueError): | ||||
|                         data.value = parameters.get(key) | ||||
|  | ||||
|     async def load_commands(self): | ||||
|  | ||||
		Reference in New Issue
	
	Block a user
	