Compare commits
10 Commits
Author | SHA1 | Date | |
---|---|---|---|
fe4f6e766e | |||
6b346f766f | |||
f52f84711f | |||
c4d21be388 | |||
5acc81acc3 | |||
43d61ab853 | |||
79a121263f | |||
00ac6912e2 | |||
0f630e854e | |||
1ef5f7a64d |
2
.gitignore
vendored
2
.gitignore
vendored
@ -3,4 +3,4 @@ venv/
|
||||
__pycache__/
|
||||
dist/
|
||||
**/*.egg-info/
|
||||
test.py
|
||||
test*
|
||||
|
55
README.md
55
README.md
@ -1,26 +1,47 @@
|
||||
**This python package is unofficial and is not related in any way to Haier. It was developed by reversed engineered requests and can stop working at anytime!**
|
||||
|
||||
# pyhOn
|
||||
[](https://pypi.org/project/pyhOn)
|
||||
[](https://pypi.org/project/pyhOn)
|
||||
[](https://www.python.org/)
|
||||
[](https://github.com/Andre0512/pyhOn/blob/main/LICENSE)
|
||||
[](https://pypistats.org/packages/pyhon)
|
||||
Control your Haier appliances with python!
|
||||
The idea behind this library is, to make the use of all available commands as simple as possible.
|
||||
|
||||
## Installation
|
||||
```bash
|
||||
pip install pyhOn
|
||||
```
|
||||
|
||||
### Quick overview
|
||||
To get an idea of what is possible, use the commandline-tool `pyhOn`. This lists all available options of the appliances from your Haier Account.
|
||||
To get an idea of what is possible, use the commandline-tool `pyhOn`. This command requests all available options of connected appliances from the hOn api of your Haier Account.
|
||||
```commandline
|
||||
$ pyhOn --user example@mail.com --password pass123
|
||||
========== Waschmaschine ==========
|
||||
commands:
|
||||
pauseProgram: pauseProgram command
|
||||
resumeProgram: resumeProgram command
|
||||
startProgram: startProgram command
|
||||
stopProgram: stopProgram command
|
||||
========== WM - Waschmaschine ==========
|
||||
data:
|
||||
actualWeight: 0
|
||||
airWashTempLevel: 0
|
||||
airWashTime: 0
|
||||
antiAllergyStatus: 0
|
||||
...
|
||||
attributes:
|
||||
parameters:
|
||||
...
|
||||
texture: 1
|
||||
totalElectricityUsed: 28.71
|
||||
totalWashCycle: 35
|
||||
totalWaterUsed: 2494
|
||||
transMode: 0
|
||||
...
|
||||
settings:
|
||||
startProgram:
|
||||
rinseIterations:
|
||||
max: 5
|
||||
min: 3
|
||||
step: 1
|
||||
spinSpeed:
|
||||
- 0
|
||||
- 400
|
||||
- 600
|
||||
- 800
|
||||
...
|
||||
```
|
||||
The claim is, to see everything what you can see in your hOn app and to execute everything you can execute there.
|
||||
|
||||
## Python-API
|
||||
### List devices
|
||||
@ -45,8 +66,6 @@ async with HonConnection(USER, PASSWORD) as hon:
|
||||
```
|
||||
|
||||
### Set command parameter
|
||||
Use `device.settings` to get all variable parameters.
|
||||
Use `device.parmeters` to get also fixed parameters.
|
||||
```python
|
||||
async with HonConnection(USER, PASSWORD) as hon:
|
||||
washing_machine = hon.devices[0]
|
||||
@ -67,7 +86,11 @@ async with HonConnection(USER, PASSWORD) as hon:
|
||||
## Tested devices
|
||||
- Haier Washing Machine HW90
|
||||
|
||||
_Unfortunately I don't have any more haier appliances_
|
||||
_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).
|
||||
|
||||
## Contribution
|
||||
Any kind of contribution is welcome!
|
||||
|
||||
|
@ -21,10 +21,14 @@ def get_arguments():
|
||||
parser = argparse.ArgumentParser(description="pyhOn: Command Line Utility")
|
||||
parser.add_argument("-u", "--user", help="user for haier hOn account")
|
||||
parser.add_argument("-p", "--password", help="password for haier hOn account")
|
||||
subparser = parser.add_subparsers(title="commands", metavar="COMMAND")
|
||||
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")
|
||||
return vars(parser.parse_args())
|
||||
|
||||
|
||||
# yaml.dump() would be done the same, but needs an additional import...
|
||||
# yaml.dump() would be done the same, but needs an additional dependency...
|
||||
def pretty_print(data, key="", intend=0, is_list=False):
|
||||
if type(data) is list:
|
||||
if key:
|
||||
@ -47,6 +51,36 @@ def pretty_print(data, key="", intend=0, is_list=False):
|
||||
print(f"{' ' * intend}{'- ' if is_list else ''}{key}{': ' if key else ''}{data}")
|
||||
|
||||
|
||||
def key_print(data, key="", start=True):
|
||||
if type(data) is list:
|
||||
for i, value in enumerate(data):
|
||||
key_print(value, key=f"{key}.{i}", start=False)
|
||||
elif type(data) is dict:
|
||||
for k, value in sorted(data.items()):
|
||||
key_print(value, key=k if start else f"{key}.{k}", start=False)
|
||||
else:
|
||||
print(f"{key}: {data}")
|
||||
|
||||
|
||||
def create_command(commands, concat=False):
|
||||
result = {}
|
||||
for name, command in commands.items():
|
||||
if not concat:
|
||||
result[name] = {}
|
||||
for parameter, data in command.parameters.items():
|
||||
if data.typology == "enum":
|
||||
value = data.values
|
||||
elif data.typology == "range":
|
||||
value = {"min": data.min, "max": data.max, "step": data.step}
|
||||
else:
|
||||
continue
|
||||
if not concat:
|
||||
result[name][parameter] = value
|
||||
else:
|
||||
result[f"{name}.{parameter}"] = value
|
||||
return result
|
||||
|
||||
|
||||
async def main():
|
||||
args = get_arguments()
|
||||
if not (user := args["user"]):
|
||||
@ -55,9 +89,18 @@ async def main():
|
||||
password = getpass("Password for hOn account: ")
|
||||
async with HonConnection(user, password) as hon:
|
||||
for device in hon.devices:
|
||||
print("=" * 10, device.nick_name, "=" * 10)
|
||||
pretty_print({"commands": device.commands})
|
||||
print("=" * 10, device.appliance_type, "-", device.nick_name, "=" * 10)
|
||||
if args.get("keys"):
|
||||
data = device.data.copy()
|
||||
attr = "get" if args.get("all") else "pop"
|
||||
key_print(data["attributes"].__getattribute__(attr)("parameters"))
|
||||
key_print(data.__getattribute__(attr)("appliance"))
|
||||
key_print(data.__getattribute__(attr)("commands"))
|
||||
key_print(data)
|
||||
pretty_print(create_command(device.commands, concat=True))
|
||||
else:
|
||||
pretty_print({"data": device.data})
|
||||
pretty_print({"settings": create_command(device.commands)})
|
||||
|
||||
|
||||
def start():
|
||||
|
21
pyhon/api.py
21
pyhon/api.py
@ -67,15 +67,15 @@ class HonConnection:
|
||||
|
||||
async def load_commands(self, device: HonDevice):
|
||||
params = {
|
||||
"applianceType": device.appliance_type_name,
|
||||
"code": device.code,
|
||||
"applianceType": device.appliance_type,
|
||||
"code": device.appliance["code"],
|
||||
"applianceModelId": device.appliance_model_id,
|
||||
"firmwareId": "41",
|
||||
"macAddress": device.mac_address,
|
||||
"fwVersion": device.fw_version,
|
||||
"fwVersion": device.appliance["fwVersion"],
|
||||
"os": const.OS,
|
||||
"appVersion": const.APP_VERSION,
|
||||
"series": device.series,
|
||||
"series": device.appliance["series"],
|
||||
}
|
||||
url = f"{const.API_URL}/commands/v1/retrieve"
|
||||
async with self._session.get(url, params=params, headers=await self._headers) as response:
|
||||
@ -84,20 +84,25 @@ class HonConnection:
|
||||
return {}
|
||||
return result
|
||||
|
||||
async def load_attributes(self, device: HonDevice):
|
||||
async def load_attributes(self, device: HonDevice, loop=False):
|
||||
params = {
|
||||
"macAddress": device.mac_address,
|
||||
"applianceType": device.appliance_type_name,
|
||||
"applianceType": device.appliance_type,
|
||||
"category": "CYCLE"
|
||||
}
|
||||
url = f"{const.API_URL}/commands/v1/context"
|
||||
async with self._session.get(url, params=params, headers=await self._headers) as response:
|
||||
if response.status == 403 and not loop:
|
||||
_LOGGER.error("%s - Error %s - %s", url, response.status, await response.text())
|
||||
self._request_headers.pop("cognito-token", None)
|
||||
self._request_headers.pop("id-token", None)
|
||||
return await self.load_attributes(device, loop=True)
|
||||
return (await response.json()).get("payload", {})
|
||||
|
||||
async def load_statistics(self, device: HonDevice):
|
||||
params = {
|
||||
"macAddress": device.mac_address,
|
||||
"applianceType": device.appliance_type_name
|
||||
"applianceType": device.appliance_type
|
||||
}
|
||||
url = f"{const.API_URL}/commands/v1/statistics"
|
||||
async with self._session.get(url, params=params, headers=await self._headers) as response:
|
||||
@ -125,7 +130,7 @@ class HonConnection:
|
||||
},
|
||||
"ancillaryParameters": ancillary_parameters,
|
||||
"parameters": parameters,
|
||||
"applianceType": device.appliance_type_name
|
||||
"applianceType": device.appliance_type
|
||||
}
|
||||
url = f"{const.API_URL}/commands/v1/send"
|
||||
async with self._session.post(url, headers=await self._headers, json=data) as resp:
|
||||
|
0
pyhon/appliances/__init__.py
Normal file
0
pyhon/appliances/__init__.py
Normal file
10
pyhon/appliances/wm.py
Normal file
10
pyhon/appliances/wm.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
|
@ -31,18 +31,15 @@ class HonCommand:
|
||||
|
||||
@property
|
||||
def parameters(self):
|
||||
result = {key: parameter.value for key, parameter in self._parameters.items()}
|
||||
if self._multi:
|
||||
result |= {"program": self._category}
|
||||
return result
|
||||
return self._parameters
|
||||
|
||||
@property
|
||||
def ancillary_parameters(self):
|
||||
return {key: parameter.value for key, parameter in self._ancillary_parameters.items()}
|
||||
|
||||
async def send(self):
|
||||
return await self._connector.send_command(self._device, self._name, self.parameters,
|
||||
self.ancillary_parameters)
|
||||
parameters = {name: parameter.value for name, parameter in self._parameters.items()}
|
||||
return await self._connector.send_command(self._device, self._name, parameters, self.ancillary_parameters)
|
||||
|
||||
def get_programs(self):
|
||||
return self._multi
|
||||
|
124
pyhon/device.py
124
pyhon/device.py
@ -1,8 +1,11 @@
|
||||
import importlib
|
||||
|
||||
from pyhon.commands import HonCommand
|
||||
|
||||
|
||||
class HonDevice:
|
||||
def __init__(self, connector, appliance):
|
||||
appliance["attributes"] = {v["parName"]: v["parValue"] for v in appliance["attributes"]}
|
||||
self._appliance = appliance
|
||||
self._connector = connector
|
||||
self._appliance_model = {}
|
||||
@ -11,74 +14,41 @@ class HonDevice:
|
||||
self._statistics = {}
|
||||
self._attributes = {}
|
||||
|
||||
@property
|
||||
def appliance_id(self):
|
||||
return self._appliance.get("applianceId")
|
||||
try:
|
||||
self._extra = importlib.import_module(f'pyhon.appliances.{self.appliance_type.lower()}')
|
||||
except ModuleNotFoundError:
|
||||
self._extra = None
|
||||
|
||||
def __getitem__(self, item):
|
||||
if "." in item:
|
||||
result = self.data
|
||||
for key in item.split("."):
|
||||
if all([k in "0123456789" for k in key]) and type(result) is list:
|
||||
result = result[int(key)]
|
||||
else:
|
||||
result = result[key]
|
||||
return result
|
||||
else:
|
||||
if item in self.data:
|
||||
return self.data[item]
|
||||
if item in self.attributes["parameters"]:
|
||||
return self.attributes["parameters"].get(item)
|
||||
return self.appliance[item]
|
||||
|
||||
def get(self, item, default=None):
|
||||
try:
|
||||
return self[item]
|
||||
except (KeyError, IndexError):
|
||||
return default
|
||||
|
||||
@property
|
||||
def appliance_model_id(self):
|
||||
return self._appliance.get("applianceModelId")
|
||||
|
||||
@property
|
||||
def appliance_status(self):
|
||||
return self._appliance.get("applianceStatus")
|
||||
|
||||
@property
|
||||
def appliance_type_id(self):
|
||||
return self._appliance.get("applianceTypeId")
|
||||
|
||||
@property
|
||||
def appliance_type_name(self):
|
||||
def appliance_type(self):
|
||||
return self._appliance.get("applianceTypeName")
|
||||
|
||||
@property
|
||||
def brand(self):
|
||||
return self._appliance.get("brand")
|
||||
|
||||
@property
|
||||
def code(self):
|
||||
return self._appliance.get("code")
|
||||
|
||||
@property
|
||||
def connectivity(self):
|
||||
return self._appliance.get("connectivity")
|
||||
|
||||
@property
|
||||
def coords(self):
|
||||
return self._appliance.get("coords")
|
||||
|
||||
@property
|
||||
def eeprom_id(self):
|
||||
return self._appliance.get("eepromId")
|
||||
|
||||
@property
|
||||
def eeprom_name(self):
|
||||
return self._appliance.get("eepromName")
|
||||
|
||||
@property
|
||||
def enrollment_date(self):
|
||||
return self._appliance.get("enrollmentDate")
|
||||
|
||||
@property
|
||||
def first_enrollment(self):
|
||||
return self._appliance.get("firstEnrollment")
|
||||
|
||||
@property
|
||||
def first_enrollment_tbc(self):
|
||||
return self._appliance.get("firstEnrollmentTBC")
|
||||
|
||||
@property
|
||||
def fw_version(self):
|
||||
return self._appliance.get("fwVersion")
|
||||
|
||||
@property
|
||||
def id(self):
|
||||
return self._appliance.get("id")
|
||||
|
||||
@property
|
||||
def last_update(self):
|
||||
return self._appliance.get("lastUpdate")
|
||||
|
||||
@property
|
||||
def mac_address(self):
|
||||
return self._appliance.get("macAddress")
|
||||
@ -91,22 +61,6 @@ class HonDevice:
|
||||
def nick_name(self):
|
||||
return self._appliance.get("nickName")
|
||||
|
||||
@property
|
||||
def purchase_date(self):
|
||||
return self._appliance.get("purchaseDate")
|
||||
|
||||
@property
|
||||
def serial_number(self):
|
||||
return self._appliance.get("serialNumber")
|
||||
|
||||
@property
|
||||
def series(self):
|
||||
return self._appliance.get("series")
|
||||
|
||||
@property
|
||||
def water_hard(self):
|
||||
return self._appliance.get("waterHard")
|
||||
|
||||
@property
|
||||
def commands_options(self):
|
||||
return self._appliance_model.get("options")
|
||||
@ -123,6 +77,10 @@ class HonDevice:
|
||||
def statistics(self):
|
||||
return self._statistics
|
||||
|
||||
@property
|
||||
def appliance(self):
|
||||
return self._appliance
|
||||
|
||||
async def load_commands(self):
|
||||
raw = await self._connector.load_commands(self)
|
||||
self._appliance_model = raw.pop("applianceModel")
|
||||
@ -153,13 +111,13 @@ class HonDevice:
|
||||
result = {}
|
||||
for name, command in self._commands.items():
|
||||
for key, parameter in command.parameters.items():
|
||||
result[f"{name}.{key}"] = parameter
|
||||
result.setdefault(name, {})[key] = parameter.value
|
||||
return result
|
||||
|
||||
async def load_attributes(self):
|
||||
data = await self._connector.load_attributes(self)
|
||||
for name, values in data.get("shadow").get("parameters").items():
|
||||
self._attributes[name] = values["parNewVal"]
|
||||
self._attributes = await self._connector.load_attributes(self)
|
||||
for name, values in self._attributes.pop("shadow").get("parameters").items():
|
||||
self._attributes.setdefault("parameters", {})[name] = values["parNewVal"]
|
||||
|
||||
async def load_statistics(self):
|
||||
self._statistics = await self._connector.load_statistics(self)
|
||||
@ -169,4 +127,8 @@ class HonDevice:
|
||||
|
||||
@property
|
||||
def data(self):
|
||||
return self.attributes | self.parameters | self._appliance | self._statistics
|
||||
result = {"attributes": self.attributes, "appliance": self.appliance, "statistics": self.statistics,
|
||||
**self.parameters}
|
||||
if self._extra:
|
||||
return result | self._extra.Appliance(result).get()
|
||||
return result
|
||||
|
@ -76,7 +76,7 @@ class HonParameterRange(HonParameter):
|
||||
@value.setter
|
||||
def value(self, value):
|
||||
if self._min <= value <= self._max and not value % self._step:
|
||||
self._value = self._value
|
||||
self._value = value
|
||||
else:
|
||||
raise ValueError(f"Allowed: min {self._min} max {self._max} step {self._step}")
|
||||
|
||||
@ -102,7 +102,7 @@ class HonParameterEnum(HonParameter):
|
||||
@value.setter
|
||||
def value(self, value):
|
||||
if value in self.values:
|
||||
self._value = self._value
|
||||
self._value = value
|
||||
else:
|
||||
raise ValueError(f"Allowed values {self._value}")
|
||||
|
||||
@ -113,6 +113,7 @@ class HonParameterProgram(HonParameterEnum):
|
||||
self._command = command
|
||||
self._value = command._category
|
||||
self._values = command._multi
|
||||
self._typology = "enum"
|
||||
|
||||
@property
|
||||
def value(self):
|
||||
@ -123,4 +124,4 @@ class HonParameterProgram(HonParameterEnum):
|
||||
if value in self.values:
|
||||
self._command.set_program(value)
|
||||
else:
|
||||
raise ValueError(f"Allowed values {self._value}")
|
||||
raise ValueError(f"Allowed values {self._values}")
|
||||
|
17
setup.py
17
setup.py
@ -7,18 +7,31 @@ with open("README.md", "r") as f:
|
||||
|
||||
setup(
|
||||
name="pyhOn",
|
||||
version="0.2.1",
|
||||
version="0.3.4",
|
||||
author="Andre Basche",
|
||||
description="Control hOn devices with python",
|
||||
long_description=long_description,
|
||||
long_description_content_type='text/markdown',
|
||||
url="https://github.com/Andre0512/pyh0n",
|
||||
project_urls={
|
||||
"GitHub": "https://github.com/Andre0512/pyhOn",
|
||||
"PyPI": "https://pypi.org/project/pyhOn",
|
||||
},
|
||||
license="MIT",
|
||||
platforms="any",
|
||||
packages=find_packages(),
|
||||
include_package_data=True,
|
||||
python_requires=">=3.10",
|
||||
install_requires=["aiohttp"],
|
||||
classifiers=[
|
||||
"Development Status :: 4 - Beta",
|
||||
"Environment :: Console",
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"Natural Language :: English",
|
||||
"Operating System :: OS Independent",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Topic :: Software Development :: Libraries :: Python Modules",
|
||||
],
|
||||
entry_points={
|
||||
'console_scripts': [
|
||||
'pyhOn = pyhon.__main__:start',
|
||||
|
Reference in New Issue
Block a user