├── requirements.txt ├── example.png ├── logo.jpeg ├── hacs.json ├── requirements-dev.txt ├── requirements-test.txt ├── custom_components └── jq300 │ ├── manifest.json │ ├── translations │ ├── en.json │ └── ru.json │ ├── util.py │ ├── entity.py │ ├── binary_sensor.py │ ├── const.py │ ├── sensor.py │ ├── config_flow.py │ ├── __init__.py │ └── api.py ├── CONTRIBUTING.md ├── info.md ├── pyproject.toml └── LICENSE.md /requirements.txt: -------------------------------------------------------------------------------- 1 | homeassistant>=2022.10.0 2 | paho-mqtt==1.6.1 3 | -------------------------------------------------------------------------------- /example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Limych/ha-jq300/HEAD/example.png -------------------------------------------------------------------------------- /logo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Limych/ha-jq300/HEAD/logo.jpeg -------------------------------------------------------------------------------- /hacs.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "JQ-300/200/100 Indoor Air Quality Meter", 3 | "hacs": "1.6.0", 4 | "homeassistant": "2022.10.0" 5 | } 6 | -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | -r requirements-test.txt 2 | black==23.1.0 3 | packaging==23.0 4 | pre-commit~=3.0 5 | PyGithub~=1.57 6 | pyupgrade~=3.3 7 | yamllint~=1.28 8 | -------------------------------------------------------------------------------- /requirements-test.txt: -------------------------------------------------------------------------------- 1 | -r requirements.txt 2 | asynctest~=0.13 3 | flake8~=5.0 4 | flake8-docstrings~=1.6 5 | mypy==1.0.0 6 | pylint~=2.15 7 | pylint-strict-informational==0.1 8 | pytest~=7.1 9 | pytest-cov~=3.0 10 | pytest-homeassistant-custom-component>=0.12 11 | -------------------------------------------------------------------------------- /custom_components/jq300/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "domain": "jq300", 3 | "name": "JQ-300/200/100 Indoor Air Quality Meter", 4 | "version": "0.10.6", 5 | "documentation": "https://github.com/Limych/ha-jq300", 6 | "issue_tracker": "https://github.com/Limych/ha-jq300/issues", 7 | "dependencies": [], 8 | "config_flow": false, 9 | "codeowners": [ 10 | "@Limych" 11 | ], 12 | "requirements": [ 13 | "paho-mqtt==1.6.1" 14 | ], 15 | "iot_class": "cloud_push" 16 | } -------------------------------------------------------------------------------- /custom_components/jq300/translations/en.json: -------------------------------------------------------------------------------- 1 | { 2 | "config": { 3 | "step": { 4 | "user": { 5 | "title": "Jq300", 6 | "description": "If you need help with the configuration have a look here: https://github.com/Limych/ha-jq300", 7 | "data": { 8 | "username": "Username", 9 | "password": "Password" 10 | } 11 | } 12 | }, 13 | "error": { 14 | "auth": "Username/Password is wrong." 15 | }, 16 | "abort": { 17 | "single_instance_allowed": "Only a single instance is allowed." 18 | } 19 | }, 20 | "options": { 21 | "step": { 22 | "user": { 23 | "data": { 24 | "binary_sensor": "Binary sensor enabled", 25 | "sensor": "Sensor enabled", 26 | "switch": "Switch enabled" 27 | } 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /custom_components/jq300/translations/ru.json: -------------------------------------------------------------------------------- 1 | { 2 | "config": { 3 | "step": { 4 | "user": { 5 | "title": "Jq300", 6 | "description": "Если вам нужна помощь с настройкой, посмотрите здесь: https://github.com/Limych/ha-jq300", 7 | "data": { 8 | "username": "Имя пользователя", 9 | "password": "Пароль" 10 | } 11 | } 12 | }, 13 | "error": { 14 | "auth": "Имя пользователя или пароль — неверны." 15 | }, 16 | "abort": { 17 | "single_instance_allowed": "Допускается только один экземпляр." 18 | } 19 | }, 20 | "options": { 21 | "step": { 22 | "user": { 23 | "data": { 24 | "binary_sensor": "Двоичный датчик активен", 25 | "sensor": "Датчик активен", 26 | "switch": "Выключатель активен" 27 | } 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /custom_components/jq300/util.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2020-2021, Andrey "Limych" Khrolenok 2 | # Creative Commons BY-NC-SA 4.0 International Public License 3 | # (see LICENSE.md or https://creativecommons.org/licenses/by-nc-sa/4.0/) 4 | 5 | """Integration of the JQ-300/200/100 indoor air quality meter. 6 | 7 | For more details about this component, please refer to 8 | https://github.com/Limych/ha-jq300 9 | """ 10 | 11 | import logging 12 | 13 | _LOGGER = logging.getLogger(__name__) 14 | 15 | 16 | def mask(text: str, first: int = 2, last: int = 1): 17 | """Mask text by asterisks.""" 18 | tlen = len(text) 19 | to_show = first + last 20 | return ( 21 | ("" if tlen <= to_show else text[:first]) 22 | + "*" * (tlen - (0 if tlen <= to_show else to_show)) 23 | + ("" if tlen <= to_show else text[-last:]) 24 | ) 25 | 26 | 27 | def mask_email(email: str): 28 | """Mask email by asterisks.""" 29 | local, _, domain = email.partition("@") 30 | parts = domain.split(".") 31 | dname = ".".join(parts[:-1]) 32 | dtype = parts[-1] 33 | return f"{mask(local)}@{mask(dname)}.{dtype}" 34 | -------------------------------------------------------------------------------- /custom_components/jq300/entity.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2020-2021, Andrey "Limych" Khrolenok 2 | # Creative Commons BY-NC-SA 4.0 International Public License 3 | # (see LICENSE.md or https://creativecommons.org/licenses/by-nc-sa/4.0/) 4 | 5 | """Integration of the JQ-300/200/100 indoor air quality meter. 6 | 7 | For more details about this component, please refer to 8 | https://github.com/Limych/ha-jq300 9 | """ 10 | 11 | import logging 12 | 13 | from homeassistant.const import ATTR_ATTRIBUTION 14 | from homeassistant.exceptions import PlatformNotReady 15 | from homeassistant.helpers.entity import Entity 16 | 17 | from .api import Jq300Account 18 | from .const import ATTRIBUTION, DOMAIN 19 | 20 | _LOGGER = logging.getLogger(__name__) 21 | 22 | 23 | class Jq300Entity(Entity): 24 | """Jq300 entity.""" 25 | 26 | def __init__( 27 | self, entity_id: str, account: Jq300Account, device_id, sensor_id, sensor_state 28 | ): 29 | """Initialize a JQ entity.""" 30 | super().__init__() 31 | 32 | self.entity_id = entity_id 33 | 34 | if account.devices == {}: 35 | raise PlatformNotReady 36 | 37 | self._account = account 38 | self._device = account.devices.get(device_id, {}) 39 | self._device_id = device_id 40 | self._sensor_id = sensor_id 41 | 42 | self._attr_unique_id = f"{self._account.unique_id}-{device_id}-{sensor_id}" 43 | self._attr_name = None 44 | self._attr_icon = None 45 | self._attr_device_class = None 46 | self._attr_device_info = { 47 | "identifiers": {(DOMAIN, self._account.unique_id, self._device_id)}, 48 | "name": self._device.get("pt_name"), 49 | "manufacturer": self._device.get("brandname"), 50 | "model": self._device.get("pt_model"), 51 | } 52 | self._attr_extra_state_attributes = { 53 | ATTR_ATTRIBUTION: ATTRIBUTION, 54 | } 55 | 56 | @property 57 | def available(self) -> bool: 58 | """Return True if entity is available.""" 59 | return self._account.device_available(self._device_id) 60 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution guidelines 2 | 3 | Contributing to this project should be as easy and transparent as possible, whether it's: 4 | 5 | - Reporting a bug 6 | - Discussing the current state of the code 7 | - Submitting a fix 8 | - Proposing new features 9 | 10 | ## IMPORTANT! Install development environment first 11 | 12 | When making changes in code, please use the existing development environment — this will save you from many errors and help create more convenient code to support. To install the environment, run the `./bin/setup` script. 13 | 14 | ## Github is used for everything 15 | 16 | Github is used to host code, to track issues and feature requests, as well as accept pull requests. 17 | 18 | Pull requests are the best way to propose changes to the codebase. 19 | 20 | 1. Fork the repo and create your branch from `master`. 21 | 2. If you've changed something, update the documentation. 22 | 3. Make sure your code lints (using black). 23 | 4. Issue that pull request! 24 | 25 | ## Any contributions you make will be under the MIT Software License 26 | 27 | In short, when you submit code changes, your submissions are understood to be under the same [MIT License](http://choosealicense.com/licenses/mit/) that covers the project. Feel free to contact the maintainers if that's a concern. 28 | 29 | ## Report bugs using Github's [issues](../../issues) 30 | 31 | GitHub issues are used to track public bugs. 32 | Report a bug by [opening a new issue](../../issues/new/choose); it's that easy! 33 | 34 | ## Write bug reports with detail, background, and sample code 35 | 36 | **Great Bug Reports** tend to have: 37 | 38 | - A quick summary and/or background 39 | - Steps to reproduce 40 | - Be specific! 41 | - Give sample code if you can. 42 | - What you expected would happen 43 | - What actually happens 44 | - Notes (possibly including why you think this might be happening, or stuff you tried that didn't work) 45 | 46 | People *love* thorough bug reports. I'm not even kidding. 47 | 48 | ## Use a Consistent Coding Style 49 | 50 | Use [black](https://github.com/ambv/black) to make sure the code follows the style. 51 | 52 | ## Test your code modification 53 | 54 | This custom component is based on [integration blueprint template](https://github.com/Limych/ha-blueprint). 55 | 56 | It comes with development environment in a container, easy to launch 57 | if you use Visual Studio Code. With this container you will have a stand alone 58 | Home Assistant instance running and already configured with the included 59 | [`.devcontainer/configuration.yaml`](./.devcontainer/configuration.yaml) 60 | file. 61 | 62 | ## License 63 | 64 | By contributing, you agree that your contributions will be licensed under its MIT License. 65 | -------------------------------------------------------------------------------- /info.md: -------------------------------------------------------------------------------- 1 | {% if prerelease %} 2 | ### NB!: This is a Beta version! 3 | {% endif %} 4 | 5 | [![GitHub Release][releases-shield]][releases] 6 | [![GitHub Activity][commits-shield]][commits] 7 | [![License][license-shield]][license] 8 | 9 | [![hacs][hacs-shield]][hacs] 10 | [![Project Maintenance][maintenance-shield]][user_profile] 11 | [![Support me on Patreon][patreon-shield]][patreon] 12 | 13 | [![Community Forum][forum-shield]][forum] 14 | 15 | _Integration JQ-300 Indoor Air Quality Meter into Home Assistant. From this device you can receive values of TVOC (volatile organic compounds), eCO2 (carbon dioxide), HCHO (formaldehyde), humidity and PM 2.5 (ultrafine particles)._ 16 | 17 | ![logo][logoimg] 18 | 19 | ![example][exampleimg] 20 | 21 | {% if not installed %} 22 | ## Installation 23 | 24 | 1. Click install. 25 | 1. In the HA UI go to "Configuration" -> "Integrations" click "+" and search for "JQ-300". 26 | 27 | {% endif %} 28 | ## Useful Links 29 | 30 | - [Documentation][component] 31 | - [Report a Bug][report_bug] 32 | - [Suggest an idea][suggest_idea] 33 | 34 |

* * *

35 | I put a lot of work into making this repo and component available and updated to inspire and help others! I will be glad to receive thanks from you — it will give me new strength and add enthusiasm: 36 |


37 | Patreon 38 |
or support via Bitcoin or Etherium:
39 | Bitcoin
40 | 16yfCfz9dZ8y8yuSwBFVfiAa3CNYdMh7Ts
41 |

42 | 43 | *** 44 | 45 | [component]: https://github.com/Limych/ha-jq300 46 | [commits-shield]: https://img.shields.io/github/commit-activity/y/Limych/ha-jq300.svg?style=popout 47 | [commits]: https://github.com/Limych/ha-jq300/commits/dev 48 | [hacs-shield]: https://img.shields.io/badge/HACS-Custom-orange.svg?style=popout 49 | [hacs]: https://hacs.xyz 50 | [logoimg]: https://github.com/Limych/ha-jq300/raw/dev/logo.jpeg 51 | [exampleimg]: https://github.com/Limych/ha-jq300/raw/dev/example.png 52 | [forum-shield]: https://img.shields.io/badge/community-forum-brightgreen.svg?style=popout 53 | [forum]: https://community.home-assistant.io/t/jq-300-200-100-indoor-air-quality-meter/189098 54 | [license]: https://github.com/Limych/ha-jq300/blob/main/LICENSE.md 55 | [license-shield]: https://img.shields.io/badge/license-Creative_Commons_BY--NC--SA_License-lightgray.svg?style=popout 56 | [maintenance-shield]: https://img.shields.io/badge/maintainer-Andrey%20Khrolenok%20%40Limych-blue.svg?style=popout 57 | [releases-shield]: https://img.shields.io/github/release/Limych/ha-jq300.svg?style=popout 58 | [releases]: https://github.com/Limych/ha-jq300/releases 59 | [releases-latest]: https://github.com/Limych/ha-jq300/releases/latest 60 | [user_profile]: https://github.com/Limych 61 | [report_bug]: https://github.com/Limych/ha-jq300/issues/new?template=bug_report.md 62 | [suggest_idea]: https://github.com/Limych/ha-jq300/issues/new?template=feature_request.md 63 | [contributors]: https://github.com/Limych/ha-jq300/graphs/contributors 64 | [patreon-shield]: https://img.shields.io/endpoint.svg?url=https%3A%2F%2Fshieldsio-patreon.vercel.app%2Fapi%3Fusername%3DLimych%26type%3Dpatrons&style=popout 65 | [patreon]: https://www.patreon.com/join/limych 66 | -------------------------------------------------------------------------------- /custom_components/jq300/binary_sensor.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2020-2021, Andrey "Limych" Khrolenok 2 | # Creative Commons BY-NC-SA 4.0 International Public License 3 | # (see LICENSE.md or https://creativecommons.org/licenses/by-nc-sa/4.0/) 4 | 5 | """Integration of the JQ-300/200/100 indoor air quality meter. 6 | 7 | For more details about this component, please refer to 8 | https://github.com/Limych/ha-jq300 9 | """ 10 | 11 | import asyncio 12 | import logging 13 | from typing import Optional 14 | 15 | from homeassistant.components.binary_sensor import ENTITY_ID_FORMAT, BinarySensorEntity 16 | from homeassistant.config_entries import ConfigEntry 17 | from homeassistant.const import CONF_DEVICE_CLASS, CONF_DEVICES, CONF_ICON, CONF_NAME 18 | from homeassistant.core import HomeAssistant 19 | from homeassistant.helpers.entity import async_generate_entity_id 20 | 21 | from .api import Jq300Account 22 | from .const import BINARY_SENSORS, CONF_ACCOUNT_CONTROLLER, DOMAIN 23 | from .entity import Jq300Entity 24 | 25 | _LOGGER = logging.getLogger(__name__) 26 | 27 | 28 | async def async_setup_entry( 29 | hass: HomeAssistant, entry: ConfigEntry, async_add_entities 30 | ) -> bool: 31 | """Set up binary_sensor platform.""" 32 | data = hass.data[DOMAIN][entry.entry_id] 33 | account = data[CONF_ACCOUNT_CONTROLLER] # type: Jq300Account 34 | devices = data[CONF_DEVICES] # type: dict 35 | 36 | _LOGGER.debug("Setup binary sensors for account %s", account.name_secure) 37 | 38 | try: 39 | await account.async_update_sensors_or_timeout() 40 | except TimeoutError: 41 | return False 42 | 43 | entities = [] 44 | for dev_name, dev_id in devices.items(): 45 | sensors = account.get_sensors(dev_id) 46 | while not sensors: 47 | _LOGGER.debug("Sensors list is not ready. Wait for 3 sec...") 48 | await asyncio.sleep(3) 49 | sensors = account.get_sensors(dev_id) 50 | 51 | sensor_id = 1 52 | ent_name = BINARY_SENSORS[sensor_id][CONF_NAME] 53 | entity_id = async_generate_entity_id( 54 | ENTITY_ID_FORMAT, "_".join((dev_name, ent_name)), hass=hass 55 | ) 56 | 57 | _LOGGER.debug("Initialize %s", entity_id) 58 | entities.append( 59 | Jq300BinarySensor(entity_id, account, dev_id, sensor_id, sensors[sensor_id]) 60 | ) 61 | 62 | async_add_entities(entities) 63 | return True 64 | 65 | 66 | # pylint: disable=too-many-instance-attributes 67 | class Jq300BinarySensor(Jq300Entity, BinarySensorEntity): 68 | """A binary sensor implementation for JQ device.""" 69 | 70 | def __init__( 71 | self, 72 | entity_id: str, 73 | account: Jq300Account, 74 | device_id, 75 | sensor_id, 76 | sensor_state: Optional[bool], 77 | ): 78 | """Initialize a binary sensor.""" 79 | super().__init__(entity_id, account, device_id, sensor_id, sensor_state) 80 | 81 | self._attr_name = ( 82 | f'{self._device.get("pt_name")} {BINARY_SENSORS[sensor_id][CONF_NAME]}' 83 | ) 84 | self._attr_icon = BINARY_SENSORS[sensor_id][CONF_ICON] 85 | self._attr_device_class = BINARY_SENSORS[sensor_id].get(CONF_DEVICE_CLASS) 86 | self._attr_is_on = sensor_state 87 | 88 | def update(self): 89 | """Update the sensor state if it needed.""" 90 | ret = self._account.get_sensors_raw(self._device_id) 91 | if not ret: 92 | return 93 | 94 | if self._attr_is_on == ret[self._sensor_id]: 95 | return 96 | 97 | self._attr_is_on = ret[self._sensor_id] 98 | _LOGGER.debug("Update state: %s = %s", self.entity_id, self._attr_is_on) 99 | -------------------------------------------------------------------------------- /custom_components/jq300/const.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2020-2021, Andrey "Limych" Khrolenok 2 | # Creative Commons BY-NC-SA 4.0 International Public License 3 | # (see LICENSE.md or https://creativecommons.org/licenses/by-nc-sa/4.0/) 4 | 5 | """Integration of the JQ-300/200/100 indoor air quality meter. 6 | 7 | For more details about this component, please refer to 8 | https://github.com/Limych/ha-jq300 9 | """ 10 | 11 | from datetime import timedelta 12 | from typing import Final 13 | 14 | from homeassistant.components.binary_sensor import ( 15 | DEVICE_CLASS_PROBLEM, 16 | DOMAIN as BINARY_SENSOR, 17 | ) 18 | from homeassistant.components.sensor import DOMAIN as SENSOR 19 | from homeassistant.const import ( 20 | CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, 21 | CONCENTRATION_MILLIGRAMS_PER_CUBIC_METER, 22 | CONCENTRATION_PARTS_PER_MILLION, 23 | CONF_DEVICE_CLASS, 24 | CONF_ENTITY_ID, 25 | CONF_ICON, 26 | CONF_NAME, 27 | CONF_UNIT_OF_MEASUREMENT, 28 | DEVICE_CLASS_HUMIDITY, 29 | DEVICE_CLASS_TEMPERATURE, 30 | PERCENTAGE, 31 | TEMP_CELSIUS, 32 | ) 33 | 34 | # Base component constants 35 | NAME: Final = "JQ-300/200/100 Indoor Air Quality Meter" 36 | DOMAIN: Final = "jq300" 37 | VERSION: Final = "0.10.6" 38 | ATTRIBUTION: Final = "Data provided by JQ-300 Cloud" 39 | ISSUE_URL: Final = "https://github.com/Limych/ha-jq300/issues" 40 | 41 | STARTUP_MESSAGE: Final = f""" 42 | ------------------------------------------------------------------- 43 | {NAME} 44 | Version: {VERSION} 45 | This is a custom integration! 46 | If you have ANY issues with this you need to open an issue here: 47 | {ISSUE_URL} 48 | ------------------------------------------------------------------- 49 | """ 50 | 51 | # Icons 52 | 53 | # Device classes 54 | 55 | # Platforms 56 | PLATFORMS: Final = [BINARY_SENSOR, SENSOR] 57 | 58 | # Configuration and options 59 | CONF_RECEIVE_TVOC_IN_PPB: Final = "receive_tvoc_in_ppb" 60 | CONF_RECEIVE_HCHO_IN_PPB: Final = "receive_hcho_in_ppb" 61 | CONF_ACCOUNT_CONTROLLER: Final = "account_controller" 62 | CONF_YAML: Final = "_yaml" 63 | CONF_PRECISION: Final = "precision" 64 | 65 | # Defaults 66 | 67 | # Attributes 68 | ATTR_DEVICE_ID: Final = "device_id" 69 | ATTR_DEVICE_BRAND: Final = "device_brand" 70 | ATTR_DEVICE_MODEL: Final = "device_model" 71 | ATTR_RAW_STATE: Final = "raw_state" 72 | 73 | SENSORS_FILTER_FRAME: Final = timedelta(minutes=5) 74 | 75 | QUERY_TIMEOUT: Final = 7 # seconds 76 | UPDATE_TIMEOUT: Final = 12 # seconds 77 | AVAILABLE_TIMEOUT: Final = 1800 # seconds 78 | 79 | MWEIGTH_TVOC: Final = 100 # g/mol 80 | MWEIGTH_HCHO: Final = 30.0260 # g/mol 81 | 82 | BINARY_SENSORS: Final = { 83 | 1: { 84 | CONF_NAME: "Air Quality Alert", 85 | CONF_ICON: "mdi:alert", 86 | CONF_DEVICE_CLASS: DEVICE_CLASS_PROBLEM, 87 | }, 88 | } 89 | 90 | SENSORS: Final = { 91 | 4: { 92 | CONF_NAME: "Internal Temperature", 93 | CONF_UNIT_OF_MEASUREMENT: TEMP_CELSIUS, 94 | CONF_ICON: "mdi:thermometer", 95 | CONF_DEVICE_CLASS: DEVICE_CLASS_TEMPERATURE, 96 | CONF_PRECISION: 1, 97 | }, 98 | 5: { 99 | CONF_NAME: "Humidity", 100 | CONF_UNIT_OF_MEASUREMENT: PERCENTAGE, 101 | CONF_ICON: "mdi:water-percent", 102 | CONF_DEVICE_CLASS: DEVICE_CLASS_HUMIDITY, 103 | CONF_PRECISION: 1, 104 | }, 105 | 6: { 106 | CONF_NAME: "PM 2.5", 107 | CONF_UNIT_OF_MEASUREMENT: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, 108 | CONF_ICON: "mdi:air-filter", 109 | CONF_ENTITY_ID: "pm25", 110 | }, 111 | 7: { 112 | CONF_NAME: "HCHO", 113 | CONF_UNIT_OF_MEASUREMENT: CONCENTRATION_MILLIGRAMS_PER_CUBIC_METER, 114 | CONF_ICON: "mdi:cloud", 115 | CONF_PRECISION: 3, 116 | }, 117 | 8: { 118 | CONF_NAME: "TVOC", 119 | CONF_UNIT_OF_MEASUREMENT: CONCENTRATION_MILLIGRAMS_PER_CUBIC_METER, 120 | CONF_ICON: "mdi:radiator", 121 | CONF_PRECISION: 3, 122 | }, 123 | 9: { 124 | CONF_NAME: "eCO2", 125 | CONF_UNIT_OF_MEASUREMENT: CONCENTRATION_PARTS_PER_MILLION, 126 | CONF_ICON: "mdi:molecule-co2", 127 | }, 128 | } 129 | -------------------------------------------------------------------------------- /custom_components/jq300/sensor.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2020-2021, Andrey "Limych" Khrolenok 2 | # Creative Commons BY-NC-SA 4.0 International Public License 3 | # (see LICENSE.md or https://creativecommons.org/licenses/by-nc-sa/4.0/) 4 | 5 | """Integration of the JQ-300/200/100 indoor air quality meter. 6 | 7 | For more details about this component, please refer to 8 | https://github.com/Limych/ha-jq300 9 | """ 10 | import asyncio 11 | import logging 12 | 13 | from homeassistant.components.sensor import ( 14 | ENTITY_ID_FORMAT, 15 | STATE_CLASS_MEASUREMENT, 16 | SensorEntity, 17 | ) 18 | from homeassistant.const import ( 19 | CONF_DEVICE_CLASS, 20 | CONF_DEVICES, 21 | CONF_ENTITY_ID, 22 | CONF_ICON, 23 | CONF_NAME, 24 | ) 25 | from homeassistant.helpers.entity import async_generate_entity_id 26 | 27 | from .api import Jq300Account 28 | from .const import ATTR_RAW_STATE, CONF_ACCOUNT_CONTROLLER, DOMAIN, SENSORS 29 | from .entity import Jq300Entity 30 | 31 | _LOGGER = logging.getLogger(__name__) 32 | 33 | 34 | async def async_setup_entry(hass, entry, async_add_entities): 35 | """Set up sensor platform.""" 36 | data = hass.data[DOMAIN][entry.entry_id] 37 | account = data[CONF_ACCOUNT_CONTROLLER] # type: Jq300Account 38 | devices = data[CONF_DEVICES] # type: dict 39 | 40 | _LOGGER.debug("Setup sensors for account %s", account.name_secure) 41 | 42 | try: 43 | await account.async_update_sensors_or_timeout() 44 | except TimeoutError: 45 | return False 46 | 47 | entities = [] 48 | for dev_name, dev_id in devices.items(): 49 | sensors = account.get_sensors(dev_id) 50 | while not sensors: 51 | _LOGGER.debug("Sensors list is not ready. Wait for 3 sec...") 52 | await asyncio.sleep(3) 53 | sensors = account.get_sensors(dev_id) 54 | 55 | dev_model = account.devices.get(dev_id, {}).get("pt_model") 56 | is_jq300 = dev_model == "JQ_300" 57 | is_jq200 = is_jq300 or (dev_model == "JQ300") 58 | 59 | for sensor_id, sensor_state in sensors.items(): 60 | if ( 61 | sensor_id not in SENSORS 62 | or (sensor_id in (4, 5) and not is_jq200) 63 | or (sensor_id == 6 and not is_jq300) 64 | ): 65 | continue 66 | 67 | ent_name = SENSORS[sensor_id].get( 68 | CONF_ENTITY_ID, SENSORS[sensor_id][CONF_NAME] 69 | ) 70 | entity_id = async_generate_entity_id( 71 | ENTITY_ID_FORMAT, "_".join((dev_name, ent_name)), hass=hass 72 | ) 73 | 74 | _LOGGER.debug("Initialize %s", entity_id) 75 | entities.append( 76 | Jq300Sensor(entity_id, account, dev_id, sensor_id, sensor_state) 77 | ) 78 | 79 | async_add_entities(entities) 80 | return True 81 | 82 | 83 | # pylint: disable=too-many-instance-attributes 84 | class Jq300Sensor(Jq300Entity, SensorEntity): 85 | """A sensor implementation for JQ device.""" 86 | 87 | def __init__( 88 | self, entity_id, account: Jq300Account, device_id, sensor_id, sensor_state 89 | ): 90 | """Initialize a sensor.""" 91 | super().__init__(entity_id, account, device_id, sensor_id, sensor_state) 92 | 93 | self._raw_value = sensor_state 94 | 95 | self._attr_icon = SENSORS[sensor_id][CONF_ICON] 96 | self._attr_name = ( 97 | f"{self._device.get('pt_name')} {SENSORS[sensor_id][CONF_NAME]}" 98 | ) 99 | self._attr_device_class = SENSORS[sensor_id].get(CONF_DEVICE_CLASS) 100 | self._attr_native_unit_of_measurement = self._account.units[sensor_id] 101 | self._attr_native_value = sensor_state 102 | self._attr_state_class = STATE_CLASS_MEASUREMENT 103 | self._attr_extra_state_attributes[ATTR_RAW_STATE] = self._raw_value 104 | 105 | def update(self): 106 | """Update the sensor state if it needed.""" 107 | ret = self._account.get_sensors(self._device_id) 108 | if not ret: 109 | return 110 | 111 | value = ret[self._sensor_id] 112 | raw_value = self._account.get_sensors_raw(self._device_id)[self._sensor_id] 113 | if self._attr_native_value == value and self._raw_value == raw_value: 114 | return 115 | 116 | self._raw_value = raw_value 117 | 118 | self._attr_native_value = value 119 | self._attr_extra_state_attributes[ATTR_RAW_STATE] = raw_value 120 | 121 | _LOGGER.debug("Update state: %s = %s (%s)", self.entity_id, value, raw_value) 122 | -------------------------------------------------------------------------------- /custom_components/jq300/config_flow.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2020-2021, Andrey "Limych" Khrolenok 2 | # Creative Commons BY-NC-SA 4.0 International Public License 3 | # (see LICENSE.md or https://creativecommons.org/licenses/by-nc-sa/4.0/) 4 | 5 | """Integration of the JQ-300/200/100 indoor air quality meter. 6 | 7 | For more details about this component, please refer to 8 | https://github.com/Limych/ha-jq300 9 | """ 10 | 11 | from homeassistant import config_entries 12 | 13 | # pylint: disable=unused-import 14 | from .const import DOMAIN 15 | 16 | 17 | class Jq300FlowHandler(config_entries.ConfigFlow, domain=DOMAIN): 18 | """Config flow for Jq300.""" 19 | 20 | VERSION = 1 21 | CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL 22 | 23 | def __init__(self): 24 | """Initialize.""" 25 | self._errors = {} 26 | 27 | async def async_step_import(self, platform_config): 28 | """Import a config entry. 29 | 30 | Special type of import, we're not actually going to store any data. 31 | Instead, we're going to rely on the values that are in config file. 32 | """ 33 | if self._async_current_entries(): 34 | return self.async_abort(reason="single_instance_allowed") 35 | 36 | return self.async_create_entry(title="configuration.yaml", data=platform_config) 37 | 38 | 39 | # 40 | # async def async_step_user(self, user_input=None): 41 | # """Handle a flow initialized by the user.""" 42 | # self._errors = {} 43 | # 44 | # # Uncomment the next 2 lines if only a single instance of the integration is allowed: 45 | # # if self._async_current_entries(): 46 | # # return self.async_abort(reason="single_instance_allowed") # noqa: E800 47 | # 48 | # if user_input is not None: 49 | # valid = await self._test_credentials( 50 | # user_input[CONF_USERNAME], user_input[CONF_PASSWORD] 51 | # ) 52 | # if valid: 53 | # return self.async_create_entry( 54 | # title=user_input[CONF_USERNAME], data=user_input 55 | # ) 56 | # 57 | # self._errors["base"] = "auth" 58 | # 59 | # return await self._show_config_form(user_input) 60 | # 61 | # @staticmethod 62 | # @callback 63 | # def async_get_options_flow(config_entry): 64 | # """Get component options flow.""" 65 | # return Jq300OptionsFlowHandler(config_entry) 66 | # 67 | # async def _show_config_form(self, user_input): # pylint: disable=unused-argument 68 | # """Show the configuration form to edit location data.""" 69 | # return self.async_show_form( 70 | # step_id="user", 71 | # data_schema=vol.Schema( 72 | # {vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str} 73 | # ), 74 | # errors=self._errors, 75 | # ) 76 | # 77 | # async def _test_credentials(self, username, password): 78 | # """Return true if credentials is valid.""" 79 | # try: 80 | # session = async_create_clientsession(self.hass) 81 | # client = JqApiClient(username, password, session) 82 | # await client.async_get_data() 83 | # return True 84 | # except Exception: # pylint: disable=broad-except 85 | # pass 86 | # return False 87 | # 88 | # 89 | # class Jq300OptionsFlowHandler(config_entries.OptionsFlow): 90 | # """Jq300 config flow options handler.""" 91 | # 92 | # def __init__(self, config_entry): 93 | # """Initialize HACS options flow.""" 94 | # self.config_entry = config_entry 95 | # self.options = dict(config_entry.options) 96 | # 97 | # async def async_step_init(self, user_input=None): # pylint: disable=unused-argument 98 | # """Manage the options.""" 99 | # return await self.async_step_user() 100 | # 101 | # async def async_step_user(self, user_input=None): 102 | # """Handle a flow initialized by the user.""" 103 | # if user_input is not None: 104 | # self.options.update(user_input) 105 | # return await self._update_options() 106 | # 107 | # return self.async_show_form( 108 | # step_id="user", 109 | # data_schema=vol.Schema( 110 | # { 111 | # vol.Required(x, default=self.options.get(x, True)): bool 112 | # for x in sorted(PLATFORMS) 113 | # } 114 | # ), 115 | # ) 116 | # 117 | # async def _update_options(self): 118 | # """Update config entry options.""" 119 | # return self.async_create_entry( 120 | # title=self.config_entry.data.get(CONF_USERNAME), data=self.options 121 | # ) 122 | -------------------------------------------------------------------------------- /custom_components/jq300/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2020-2021, Andrey "Limych" Khrolenok 2 | # Creative Commons BY-NC-SA 4.0 International Public License 3 | # (see LICENSE.md or https://creativecommons.org/licenses/by-nc-sa/4.0/) 4 | 5 | """Integration of the JQ-300/200/100 indoor air quality meter. 6 | 7 | For more details about this component, please refer to 8 | https://github.com/Limych/ha-jq300 9 | """ 10 | 11 | import asyncio 12 | from datetime import timedelta 13 | import logging 14 | 15 | import async_timeout 16 | import voluptuous as vol 17 | 18 | from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry 19 | from homeassistant.const import CONF_DEVICES, CONF_PASSWORD, CONF_USERNAME 20 | from homeassistant.core import HomeAssistant 21 | from homeassistant.exceptions import ConfigEntryNotReady 22 | from homeassistant.helpers.aiohttp_client import async_get_clientsession 23 | import homeassistant.helpers.config_validation as cv 24 | from homeassistant.helpers.typing import ConfigType 25 | 26 | from .api import Jq300Account 27 | from .const import ( 28 | CONF_ACCOUNT_CONTROLLER, 29 | CONF_RECEIVE_HCHO_IN_PPB, 30 | CONF_RECEIVE_TVOC_IN_PPB, 31 | CONF_YAML, 32 | DOMAIN, 33 | PLATFORMS, 34 | STARTUP_MESSAGE, 35 | UPDATE_TIMEOUT, 36 | ) 37 | from .util import mask_email 38 | 39 | _LOGGER = logging.getLogger(__name__) 40 | 41 | 42 | SCAN_INTERVAL = timedelta(seconds=30) 43 | 44 | 45 | ACCOUNT_SCHEMA = vol.Schema( 46 | { 47 | vol.Required(CONF_USERNAME): cv.string, 48 | vol.Required(CONF_PASSWORD): cv.string, 49 | vol.Optional(CONF_DEVICES): vol.All(cv.ensure_list, [cv.string]), 50 | vol.Optional(CONF_RECEIVE_TVOC_IN_PPB, default=False): cv.boolean, 51 | vol.Optional(CONF_RECEIVE_HCHO_IN_PPB, default=False): cv.boolean, 52 | } 53 | ) 54 | 55 | CONFIG_SCHEMA = vol.Schema({DOMAIN: ACCOUNT_SCHEMA}, extra=vol.ALLOW_EXTRA) 56 | 57 | 58 | async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: 59 | """Set up this integration using YAML.""" 60 | # Print startup message 61 | if DOMAIN not in hass.data: 62 | _LOGGER.info(STARTUP_MESSAGE) 63 | hass.data[DOMAIN] = {} 64 | 65 | if DOMAIN not in config: 66 | return True 67 | 68 | hass.data[DOMAIN][CONF_YAML] = config[DOMAIN] 69 | hass.async_create_task( 70 | hass.config_entries.flow.async_init( 71 | DOMAIN, context={"source": SOURCE_IMPORT}, data={} 72 | ) 73 | ) 74 | 75 | return True 76 | 77 | 78 | async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: 79 | """Set up this integration using UI.""" 80 | if entry.source == SOURCE_IMPORT: 81 | config = hass.data[DOMAIN][CONF_YAML] 82 | else: 83 | config = entry.data.copy() 84 | config.update(entry.options) 85 | 86 | username = config.get(CONF_USERNAME) 87 | password = config.get(CONF_PASSWORD) 88 | active_devices = config.get(CONF_DEVICES, []) 89 | receive_tvoc_in_ppb = config.get(CONF_RECEIVE_TVOC_IN_PPB) 90 | receive_hcho_in_ppb = config.get(CONF_RECEIVE_HCHO_IN_PPB) 91 | 92 | _LOGGER.debug("Connecting to account %s", mask_email(username)) 93 | 94 | session = async_get_clientsession(hass) 95 | account = Jq300Account( 96 | hass, session, username, password, receive_tvoc_in_ppb, receive_hcho_in_ppb 97 | ) 98 | 99 | try: 100 | async with async_timeout.timeout(UPDATE_TIMEOUT): 101 | devices = await account.async_update_devices() 102 | except asyncio.TimeoutError as exc: 103 | raise ConfigEntryNotReady from exc 104 | 105 | devs = {} 106 | adevs = [] 107 | for device_id in devices: 108 | name = devices[device_id]["pt_name"] 109 | if active_devices and name not in active_devices: 110 | continue 111 | 112 | adevs.append(device_id) 113 | devs[name] = device_id 114 | 115 | account.active_devices = adevs 116 | 117 | hass.data[DOMAIN][entry.entry_id] = { 118 | CONF_ACCOUNT_CONTROLLER: account, 119 | CONF_DEVICES: devs, 120 | } 121 | 122 | # Load platforms 123 | for platform in PLATFORMS: 124 | hass.async_add_job( 125 | hass.config_entries.async_forward_entry_setup(entry, platform) 126 | ) 127 | 128 | entry.add_update_listener(async_reload_entry) 129 | return True 130 | 131 | 132 | # class Jq300DataUpdateCoordinator(DataUpdateCoordinator): 133 | # """Class to manage fetching data from the API.""" 134 | # 135 | # def __init__( 136 | # self, hass: HomeAssistant, client: JqApiClient 137 | # ) -> None: 138 | # """Initialize.""" 139 | # self.api = client 140 | # self.platforms = [] 141 | # 142 | # super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=SCAN_INTERVAL) 143 | # 144 | # async def _async_update_data(self): 145 | # """Update data via library.""" 146 | # try: 147 | # return await self.api.async_get_data() 148 | # except Exception as exception: 149 | # raise UpdateFailed() from exception 150 | 151 | 152 | async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: 153 | """Handle removal of an entry.""" 154 | # coordinator = hass.data[DOMAIN][entry.entry_id] 155 | unloaded = all( 156 | await asyncio.gather( 157 | *[ 158 | hass.config_entries.async_forward_entry_unload(entry, platform) 159 | for platform in PLATFORMS 160 | # if platform in coordinator.platforms 161 | ] 162 | ) 163 | ) 164 | if unloaded: 165 | hass.data[DOMAIN].pop(entry.entry_id) 166 | 167 | return unloaded 168 | 169 | 170 | async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: 171 | """Reload config entry.""" 172 | await async_unload_entry(hass, entry) 173 | await async_setup_entry(hass, entry) 174 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.black] 2 | target-version = ["py310"] 3 | extend-exclude = "/generated/" 4 | 5 | [tool.isort] 6 | # https://github.com/PyCQA/isort/wiki/isort-Settings 7 | profile = "black" 8 | # will group `import x` and `from x import` of the same module. 9 | force_sort_within_sections = true 10 | known_first_party = [ 11 | "homeassistant", 12 | "tests", 13 | ] 14 | forced_separate = [ 15 | "tests", 16 | ] 17 | combine_as_imports = true 18 | 19 | [tool.pylint.MAIN] 20 | py-version = "3.10" 21 | ignore = [ 22 | "tests", 23 | ] 24 | # Use a conservative default here; 2 should speed up most setups and not hurt 25 | # any too bad. Override on command line as appropriate. 26 | jobs = 2 27 | init-hook = """\ 28 | from pathlib import Path; \ 29 | import sys; \ 30 | 31 | from pylint.config import find_default_config_files; \ 32 | 33 | sys.path.append( \ 34 | str(Path(next(find_default_config_files())).parent.joinpath('pylint/plugins')) 35 | ) \ 36 | """ 37 | load-plugins = [ 38 | "pylint.extensions.code_style", 39 | "pylint.extensions.typing", 40 | "hass_enforce_type_hints", 41 | "hass_imports", 42 | "hass_logger", 43 | "pylint_per_file_ignores", 44 | ] 45 | persistent = false 46 | extension-pkg-allow-list = [ 47 | "av.audio.stream", 48 | "av.stream", 49 | "ciso8601", 50 | "orjson", 51 | "cv2", 52 | ] 53 | fail-on = [ 54 | "I", 55 | ] 56 | 57 | [tool.pylint.BASIC] 58 | class-const-naming-style = "any" 59 | good-names = [ 60 | "_", 61 | "ev", 62 | "ex", 63 | "fp", 64 | "i", 65 | "id", 66 | "j", 67 | "k", 68 | "Run", 69 | "ip", 70 | ] 71 | 72 | [tool.pylint."MESSAGES CONTROL"] 73 | # Reasons disabled: 74 | # format - handled by black 75 | # locally-disabled - it spams too much 76 | # duplicate-code - unavoidable 77 | # cyclic-import - doesn't test if both import on load 78 | # abstract-class-little-used - prevents from setting right foundation 79 | # unused-argument - generic callbacks and setup methods create a lot of warnings 80 | # too-many-* - are not enforced for the sake of readability 81 | # too-few-* - same as too-many-* 82 | # abstract-method - with intro of async there are always methods missing 83 | # inconsistent-return-statements - doesn't handle raise 84 | # too-many-ancestors - it's too strict. 85 | # wrong-import-order - isort guards this 86 | # consider-using-f-string - str.format sometimes more readable 87 | # --- 88 | # Pylint CodeStyle plugin 89 | # consider-using-namedtuple-or-dataclass - too opinionated 90 | # consider-using-assignment-expr - decision to use := better left to devs 91 | disable = [ 92 | "format", 93 | "abstract-method", 94 | "cyclic-import", 95 | "duplicate-code", 96 | "inconsistent-return-statements", 97 | "locally-disabled", 98 | "not-context-manager", 99 | "too-few-public-methods", 100 | "too-many-ancestors", 101 | "too-many-arguments", 102 | "too-many-branches", 103 | "too-many-instance-attributes", 104 | "too-many-lines", 105 | "too-many-locals", 106 | "too-many-public-methods", 107 | "too-many-return-statements", 108 | "too-many-statements", 109 | "too-many-boolean-expressions", 110 | "unused-argument", 111 | "wrong-import-order", 112 | "consider-using-f-string", 113 | "consider-using-namedtuple-or-dataclass", 114 | "consider-using-assignment-expr", 115 | ] 116 | enable = [ 117 | #"useless-suppression", # temporarily every now and then to clean them up 118 | "use-symbolic-message-instead", 119 | ] 120 | 121 | [tool.pylint.REPORTS] 122 | score = false 123 | 124 | [tool.pylint.TYPECHECK] 125 | ignored-classes = [ 126 | "_CountingAttr", # for attrs 127 | ] 128 | mixin-class-rgx = ".*[Mm]ix[Ii]n" 129 | 130 | [tool.pylint.FORMAT] 131 | expected-line-ending-format = "LF" 132 | 133 | [tool.pylint.EXCEPTIONS] 134 | overgeneral-exceptions = [ 135 | "builtins.BaseException", 136 | "builtins.Exception", 137 | # "homeassistant.exceptions.HomeAssistantError", # too many issues 138 | ] 139 | 140 | [tool.pylint.TYPING] 141 | runtime-typing = false 142 | 143 | [tool.pylint.CODE_STYLE] 144 | max-line-length-suggestions = 72 145 | 146 | [tool.pylint-per-file-ignores] 147 | # hass-component-root-import: Tests test non-public APIs 148 | # protected-access: Tests do often test internals a lot 149 | # redefined-outer-name: Tests reference fixtures in the test function 150 | "/tests/"="hass-component-root-import,protected-access,redefined-outer-name" 151 | 152 | [tool.pytest.ini_options] 153 | testpaths = [ 154 | "tests", 155 | ] 156 | norecursedirs = [ 157 | ".git", 158 | "testing_config", 159 | ] 160 | log_format = "%(asctime)s.%(msecs)03d %(levelname)-8s %(threadName)s %(name)s:%(filename)s:%(lineno)s %(message)s" 161 | log_date_format = "%Y-%m-%d %H:%M:%S" 162 | asyncio_mode = "auto" 163 | 164 | [tool.ruff] 165 | target-version = "py310" 166 | 167 | select = [ 168 | "C", # complexity 169 | "D", # docstrings 170 | "E", # pycodestyle 171 | "F", # pyflakes/autoflake 172 | "PGH004", # Use specific rule codes when using noqa 173 | "PLC0414", # Useless import alias. Import alias does not rename original package. 174 | "SIM105", # Use contextlib.suppress({exception}) instead of try-except-pass 175 | "SIM117", # Merge with-statements that use the same scope 176 | "SIM300", # Yoda conditions. Use 'age == 42' instead of '42 == age'. 177 | "SIM401", # Use get from dict with default instead of an if block 178 | "T20", # flake8-print 179 | "TRY004", # Prefer TypeError exception for invalid type 180 | "UP", # pyupgrade 181 | "W", # pycodestyle 182 | ] 183 | 184 | ignore = [ 185 | "D202", # No blank lines allowed after function docstring 186 | "D203", # 1 blank line required before class docstring 187 | "D213", # Multi-line docstring summary should start at the second line 188 | "D404", # First word of the docstring should not be This 189 | "D406", # Section name should end with a newline 190 | "D407", # Section name underlining 191 | "D411", # Missing blank line before section 192 | "E501", # line too long 193 | "E731", # do not assign a lambda expression, use a def 194 | ] 195 | 196 | [tool.ruff.flake8-pytest-style] 197 | fixture-parentheses = false 198 | 199 | [tool.ruff.pyupgrade] 200 | keep-runtime-typing = true 201 | 202 | [tool.ruff.per-file-ignores] 203 | 204 | # TODO: these files have functions that are too complex, but flake8's and ruff's 205 | # complexity (and/or nested-function) handling differs; trying to add a noqa doesn't work 206 | # because the flake8-noqa plugin then disagrees on whether there should be a C901 noqa 207 | # on that line. So, for now, we just ignore C901s on these files as far as ruff is concerned. 208 | 209 | "homeassistant/components/light/__init__.py" = ["C901"] 210 | "homeassistant/components/mqtt/discovery.py" = ["C901"] 211 | "homeassistant/components/websocket_api/http.py" = ["C901"] 212 | 213 | # Allow for main entry & scripts to write to stdout 214 | "homeassistant/__main__.py" = ["T201"] 215 | "homeassistant/scripts/*" = ["T201"] 216 | "script/*" = ["T20"] 217 | 218 | [tool.ruff.mccabe] 219 | max-complexity = 25 220 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | ## creative commons 2 | 3 | # Attribution-NonCommercial-ShareAlike 4.0 International License 4 | 5 | Copyright (c) 2019-2022 Andrey "Limych" Khrolenok 6 | 7 | Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. 8 | 9 | ### Using Creative Commons Public Licenses 10 | 11 | Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. 12 | 13 | * __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors). 14 | 15 | * __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees). 16 | 17 | ## Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License 18 | 19 | By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. 20 | 21 | ### Section 1 – Definitions. 22 | 23 | a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. 24 | 25 | b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. 26 | 27 | c. __BY-NC-SA Compatible License__ means a license listed at [creativecommons.org/compatiblelicenses](http://creativecommons.org/compatiblelicenses), approved by Creative Commons as essentially the equivalent of this Public License. 28 | 29 | d. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. 30 | 31 | e. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. 32 | 33 | f. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. 34 | 35 | g. __License Elements__ means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike. 36 | 37 | h. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License. 38 | 39 | i. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. 40 | 41 | j. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License. 42 | 43 | k. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange. 44 | 45 | l. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. 46 | 47 | m. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. 48 | 49 | n. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. 50 | 51 | ### Section 2 – Scope. 52 | 53 | a. ___License grant.___ 54 | 55 | 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: 56 | 57 | A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and 58 | 59 | B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only. 60 | 61 | 2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 62 | 63 | 3. __Term.__ The term of this Public License is specified in Section 6(a). 64 | 65 | 4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. 66 | 67 | 5. __Downstream recipients.__ 68 | 69 | A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. 70 | 71 | B. __Additional offer from the Licensor – Adapted Material.__ Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply. 72 | 73 | C. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 74 | 75 | 6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). 76 | 77 | b. ___Other rights.___ 78 | 79 | 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 80 | 81 | 2. Patent and trademark rights are not licensed under this Public License. 82 | 83 | 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes. 84 | 85 | ### Section 3 – License Conditions. 86 | 87 | Your exercise of the Licensed Rights is expressly made subject to the following conditions. 88 | 89 | a. ___Attribution.___ 90 | 91 | 1. If You Share the Licensed Material (including in modified form), You must: 92 | 93 | A. retain the following if it is supplied by the Licensor with the Licensed Material: 94 | 95 | i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); 96 | 97 | ii. a copyright notice; 98 | 99 | iii. a notice that refers to this Public License; 100 | 101 | iv. a notice that refers to the disclaimer of warranties; 102 | 103 | v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; 104 | 105 | B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and 106 | 107 | C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 108 | 109 | 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 110 | 111 | 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. 112 | 113 | b. ___ShareAlike.___ 114 | 115 | In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply. 116 | 117 | 1. The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License. 118 | 119 | 2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material. 120 | 121 | 3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply. 122 | 123 | ### Section 4 – Sui Generis Database Rights. 124 | 125 | Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: 126 | 127 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; 128 | 129 | b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and 130 | 131 | c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. 132 | 133 | For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. 134 | 135 | ### Section 5 – Disclaimer of Warranties and Limitation of Liability. 136 | 137 | a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__ 138 | 139 | b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__ 140 | 141 | c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. 142 | 143 | ### Section 6 – Term and Termination. 144 | 145 | a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. 146 | 147 | b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 148 | 149 | 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 150 | 151 | 2. upon express reinstatement by the Licensor. 152 | 153 | For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. 154 | 155 | c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. 156 | 157 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. 158 | 159 | ### Section 7 – Other Terms and Conditions. 160 | 161 | a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. 162 | 163 | b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. 164 | 165 | ### Section 8 – Interpretation. 166 | 167 | a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. 168 | 169 | b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. 170 | 171 | c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. 172 | 173 | d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. 174 | 175 | > Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. 176 | > 177 | > Creative Commons may be contacted at creativecommons.org 178 | -------------------------------------------------------------------------------- /custom_components/jq300/api.py: -------------------------------------------------------------------------------- 1 | """Integration of the JQ-300/200/100 indoor air quality meter. 2 | 3 | For more details about this component, please refer to 4 | https://github.com/Limych/ha-jq300 5 | """ 6 | 7 | # Copyright (c) 2020-2021, Andrey "Limych" Khrolenok 8 | # Creative Commons BY-NC-SA 4.0 International Public License 9 | # (see LICENSE.md or https://creativecommons.org/licenses/by-nc-sa/4.0/) 10 | 11 | import asyncio 12 | from datetime import timedelta 13 | from http import HTTPStatus 14 | import json 15 | import logging 16 | from time import monotonic 17 | from typing import Any, Dict, List, Optional, Union 18 | from urllib.parse import urlparse 19 | 20 | from aiohttp import ClientSession 21 | import async_timeout 22 | import paho.mqtt.client as mqtt 23 | from requests import PreparedRequest 24 | 25 | from homeassistant.const import ( 26 | CONCENTRATION_MILLIGRAMS_PER_CUBIC_METER, 27 | CONCENTRATION_PARTS_PER_BILLION, 28 | CONCENTRATION_PARTS_PER_MILLION, 29 | CONF_UNIT_OF_MEASUREMENT, 30 | ) 31 | from homeassistant.core import HomeAssistant 32 | from homeassistant.util import Throttle 33 | import homeassistant.util.dt as dt_util 34 | 35 | from .const import ( 36 | AVAILABLE_TIMEOUT, 37 | BINARY_SENSORS, 38 | CONF_PRECISION, 39 | MWEIGTH_HCHO, 40 | MWEIGTH_TVOC, 41 | QUERY_TIMEOUT, 42 | SENSORS, 43 | SENSORS_FILTER_FRAME, 44 | UPDATE_TIMEOUT, 45 | ) 46 | from .util import mask_email 47 | 48 | _LOGGER = logging.getLogger(__name__) 49 | 50 | 51 | DevicesDictType = Dict[int, Dict[str, Any]] 52 | SensorsDictType = Dict[str, Union[int, float, bool]] 53 | 54 | 55 | # Error strings 56 | MSG_GENERIC_FAIL = "Sorry.. Something went wrong..." 57 | MSG_LOGIN_FAIL = "Account name or password is wrong, please try again" 58 | MSG_BUSY = "The system is busy" 59 | 60 | QUERY_TYPE_API = "API" 61 | QUERY_TYPE_DEVICE = "DEVICE" 62 | 63 | BASE_URL_API = "http://www.youpinyuntai.com:32086/ypyt-api/api/app/" 64 | BASE_URL_DEVICE = "https://www.youpinyuntai.com:31447/device/" 65 | MQTT_URL = "mqtt://ye5h8c3n:T%4ran8c@www.youpinyuntai.com:55450" 66 | 67 | _USERAGENT_SYSTEM = "Android 6.0.1; RedMi Note 5 Build/RB3N5C" 68 | USERAGENT_API = f"Dalvik/2.1.0 (Linux; U; {_USERAGENT_SYSTEM})" 69 | USERAGENT_DEVICE = ( 70 | f"Mozilla/5.0 (Linux; {_USERAGENT_SYSTEM}; wv) " 71 | "AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 " 72 | "Chrome/68.0.3440.91 Mobile Safari/537.36" 73 | ) 74 | 75 | 76 | class ApiError(Exception): 77 | """Raised when API request ended in error.""" 78 | 79 | 80 | # pylint: disable=too-many-instance-attributes 81 | class Jq300Account: 82 | """JQ-300 cloud account controller.""" 83 | 84 | # pylint: disable=too-many-arguments 85 | def __init__( 86 | self, 87 | hass: HomeAssistant, 88 | session: ClientSession, 89 | username, 90 | password, 91 | receive_tvoc_in_ppb=False, 92 | receive_hcho_in_ppb=False, 93 | ): 94 | """Initialize configured controller.""" 95 | self.params = { 96 | "uid": -1000, 97 | "safeToken": "anonymous", 98 | } 99 | 100 | self.hass = hass 101 | self._session = session 102 | self._username = username 103 | self._password = password 104 | self._receive_tvoc_in_ppb = receive_tvoc_in_ppb 105 | self._receive_hcho_in_ppb = receive_hcho_in_ppb 106 | 107 | self._mqtt = None 108 | self._active_devices = [] 109 | self._devices = {} 110 | self._sensors = {} 111 | self._sensors_raw = {} 112 | self._units = {} 113 | 114 | for sensor_id, data in BINARY_SENSORS.items(): 115 | self._units[sensor_id] = None 116 | 117 | for sensor_id, data in SENSORS.items(): 118 | if (receive_tvoc_in_ppb and sensor_id == 8) or ( 119 | receive_hcho_in_ppb and sensor_id == 7 120 | ): 121 | self._units[sensor_id] = CONCENTRATION_PARTS_PER_BILLION 122 | else: 123 | self._units[sensor_id] = data.get(CONF_UNIT_OF_MEASUREMENT) 124 | 125 | @property 126 | def unique_id(self) -> str: 127 | """Return a controller unique ID.""" 128 | return self._username 129 | 130 | @property 131 | def name(self) -> str: 132 | """Get account name.""" 133 | return self._username 134 | 135 | @property 136 | def name_secure(self) -> str: 137 | """Get account name (secure version).""" 138 | return mask_email(self._username) 139 | 140 | @property 141 | def available(self) -> bool: 142 | """Return True if account is available.""" 143 | return self.is_connected 144 | 145 | @property 146 | def units(self) -> dict: 147 | """Get list of units for sensors.""" 148 | return self._units 149 | 150 | @staticmethod 151 | def _get_useragent(query_type) -> str: 152 | """Generate User-Agent for requests.""" 153 | if query_type == QUERY_TYPE_API: 154 | return USERAGENT_API 155 | 156 | if query_type == QUERY_TYPE_DEVICE: 157 | return USERAGENT_DEVICE 158 | 159 | raise ValueError(f'Unknown query type "{query_type}"') 160 | 161 | def _add_url_params(self, url: str, extra_params: dict): 162 | """Add params to URL.""" 163 | params = self.params.copy() 164 | params.update(extra_params) 165 | 166 | req = PreparedRequest() 167 | req.prepare_url(url, params) 168 | 169 | return req.url 170 | 171 | def _get_url(self, query_type, function: str, extra_params=None) -> str: 172 | """Generate request URL.""" 173 | if query_type == QUERY_TYPE_API: 174 | url = BASE_URL_API + function 175 | elif query_type == QUERY_TYPE_DEVICE: 176 | url = BASE_URL_DEVICE + function 177 | else: 178 | raise ValueError(f'Unknown query type "{query_type}"') 179 | 180 | if extra_params: 181 | url = self._add_url_params(url, extra_params) 182 | return url 183 | 184 | # pylint: disable=too-many-return-statements,too-many-branches 185 | async def _async_query( 186 | self, query_type, function: str, extra_params=None 187 | ) -> Optional[dict]: 188 | """Query data from cloud.""" 189 | url = self._get_url(query_type, function) 190 | _LOGGER.debug("Requesting URL %s", url) 191 | 192 | # allow to override params when necessary 193 | # and update self.params globally for the next connection 194 | params = self.params.copy() 195 | if query_type == QUERY_TYPE_DEVICE: 196 | params["saveToken"] = params["safeToken"] 197 | del params["safeToken"] 198 | if extra_params: 199 | params.update(extra_params) 200 | 201 | try: 202 | response = await self._session.get( 203 | url, 204 | params=params, 205 | headers={"User-Agent": self._get_useragent(query_type)}, 206 | timeout=QUERY_TIMEOUT, 207 | ) 208 | _LOGGER.debug("_query ret %s", response.status) 209 | 210 | # pylint: disable=broad-except 211 | except Exception as err_msg: # pragma: no cover 212 | _LOGGER.error("Error! %s", err_msg) 213 | return None 214 | 215 | if response.status not in ( 216 | HTTPStatus.OK, 217 | HTTPStatus.NO_CONTENT, 218 | ): # pragma: no cover 219 | _LOGGER.debug(MSG_GENERIC_FAIL) 220 | return None 221 | 222 | content = await response.read() 223 | response = json.loads( 224 | content[13:-1] if content.startswith(b"jsoncallback(") else content 225 | ) 226 | 227 | if query_type == QUERY_TYPE_API: 228 | if response["code"] == 102: 229 | _LOGGER.error(MSG_LOGIN_FAIL) 230 | return None 231 | if response["code"] == 9999: 232 | _LOGGER.error(MSG_BUSY) 233 | return None 234 | if response["code"] != 2000: 235 | _LOGGER.error(MSG_GENERIC_FAIL) 236 | return None 237 | else: 238 | if int(response["returnCode"]) != 0: 239 | _LOGGER.error(MSG_GENERIC_FAIL) 240 | self.params["uid"] = -1000 241 | return None 242 | 243 | return response 244 | 245 | @property 246 | def is_connected(self) -> bool: 247 | """Return True if connected to account.""" 248 | return self.params["uid"] > 0 249 | 250 | async def async_connect(self, force: bool = False) -> bool: 251 | """(Re)Connect to account and return connection status.""" 252 | if not force and self.params["uid"] > 0: 253 | return True 254 | 255 | _LOGGER.debug("Connecting to cloud server%s", " (FORCE mode)" if force else "") 256 | 257 | self.params["uid"] = -1000 258 | self.params["safeToken"] = "anonymous" 259 | ret = await self._async_query( 260 | QUERY_TYPE_API, 261 | "loginByEmail", 262 | extra_params={ 263 | "chr": "clt", 264 | "email": self._username, 265 | "password": self._password, 266 | "os": 2, 267 | }, 268 | ) 269 | if not ret: 270 | return await self.async_connect(True) if not force else False 271 | 272 | self.params["uid"] = ret["uid"] 273 | self.params["safeToken"] = ret["safeToken"] 274 | self._devices = {} 275 | 276 | self._mqtt_connect() 277 | 278 | return True 279 | 280 | def _mqtt_connect(self): 281 | _LOGGER.debug("Start connecting to cloud MQTT-server") 282 | if self._mqtt is not None or not self.is_connected: 283 | return 284 | 285 | # pylint: disable=unused-argument 286 | def on_connect_callback(client, userdata, flags, res): 287 | _LOGGER.debug("Connected to MQTT") 288 | try: 289 | self._mqtt_subscribe( 290 | self._get_devices_mqtt_topics(self._active_devices) 291 | ) 292 | except Exception as exc: # pylint: disable=broad-except 293 | logging.exception(exc) 294 | 295 | # pylint: disable=unused-argument 296 | def on_message_callback(client, userdata, message): 297 | try: 298 | msg = json.loads(message.payload) 299 | _LOGGER.debug("Received MQTT message: %s", msg) 300 | self._mqtt_process_message(msg) 301 | except Exception as exc: # pylint: disable=broad-except 302 | logging.exception(exc) 303 | 304 | self._mqtt = mqtt.Client( 305 | client_id="_".join( 306 | (str(self.params["uid"]), str(int(dt_util.now().timestamp() * 1000))) 307 | ), 308 | clean_session=True, 309 | ) 310 | self._mqtt.enable_logger(_LOGGER) 311 | self._mqtt.on_connect = on_connect_callback 312 | self._mqtt.on_message = on_message_callback 313 | parsed = urlparse(MQTT_URL) 314 | if parsed.username is not None: 315 | if parsed.password is not None: 316 | self._mqtt.username_pw_set(parsed.username, parsed.password) 317 | else: 318 | _LOGGER.error( 319 | "The MQTT password was not found, this is required for auth" 320 | ) 321 | self._mqtt.connect_async(host=parsed.hostname, port=parsed.port) 322 | self._mqtt.loop_start() 323 | 324 | def _mqtt_subscribe(self, topics: list): 325 | if self._mqtt.is_connected(): 326 | self._mqtt.subscribe([(x, 0) for x in topics]) 327 | 328 | def _mqtt_unsubscribe(self, topics: list): 329 | if self._mqtt.is_connected(): 330 | self._mqtt.unsubscribe(topics) 331 | 332 | def _mqtt_process_message(self, message: dict): 333 | device_id = None 334 | for dev_id, dev in self.devices.items(): 335 | if message["deviceToken"] == dev["deviceToken"]: 336 | device_id = dev_id 337 | if device_id is None: 338 | return 339 | 340 | if message["type"] == "V": 341 | _LOGGER.debug("Update sensors for device %d", device_id) 342 | self._extract_sensors_data( 343 | device_id, 344 | int(dt_util.now().timestamp()), 345 | json.loads(message["content"]), 346 | ) 347 | self.devices[device_id]["onlinets"] = monotonic() 348 | 349 | elif message["type"] == "C": 350 | if self.devices.get(device_id) is None: 351 | return 352 | online = int(message["content"]) 353 | _LOGGER.debug("Update online status for device %d: %d", device_id, online) 354 | if online != self.devices[device_id].get("onlinestat"): 355 | self.devices[device_id]["onlinets"] = monotonic() 356 | self.devices[device_id]["onlinestat"] = online 357 | 358 | else: 359 | _LOGGER.warning("Unknown message type: %s", message) 360 | 361 | def _get_devices_mqtt_topics(self, device_ids: list) -> list: 362 | if not self.devices: 363 | return [] 364 | 365 | return [ 366 | self.devices[dev_id]["deviceToken"] 367 | for dev_id in device_ids 368 | if dev_id in self.devices 369 | ] 370 | 371 | @property 372 | def active_devices(self) -> List[int]: 373 | """Get list of devices we want to fetch sensors data.""" 374 | return self._active_devices.copy() 375 | 376 | @active_devices.setter 377 | def active_devices(self, devices: List[int]): 378 | """Set list of devices we want to fetch sensors data.""" 379 | unsub = self._get_devices_mqtt_topics( 380 | list(set(self._active_devices) - set(devices)) 381 | ) 382 | sub = self._get_devices_mqtt_topics( 383 | list(set(devices) - set(self._active_devices)) 384 | ) 385 | 386 | self._active_devices = devices 387 | 388 | for device_id in devices: 389 | self._sensors.setdefault(device_id, {}) 390 | 391 | if unsub: 392 | _LOGGER.debug("Unsubscribe from MQTT topics: %s", ", ".join(unsub)) 393 | self._mqtt_unsubscribe(unsub) 394 | if sub: 395 | _LOGGER.debug("Subscribe for new MQTT topics: %s", ", ".join(sub)) 396 | self._mqtt_subscribe(sub) 397 | 398 | @property 399 | def devices(self) -> DevicesDictType: 400 | """Get available devices.""" 401 | return self._devices 402 | 403 | async def async_update_devices(self, force=False) -> Optional[DevicesDictType]: 404 | """Update available devices from cloud.""" 405 | if not await self.async_connect(): 406 | _LOGGER.error("Can't connect to cloud.") 407 | return None 408 | 409 | if not force and self._devices: 410 | return self._devices 411 | 412 | _LOGGER.debug("Updating devices list for account %s", self.name_secure) 413 | 414 | ret = await self._async_query( 415 | QUERY_TYPE_API, 416 | "deviceManager", 417 | extra_params={ 418 | "platform": "android", 419 | "clientType": 2, 420 | "action": "deviceManager", 421 | }, 422 | ) 423 | if not ret: 424 | return await self.async_update_devices(True) if not force else None 425 | 426 | tstamp = int(dt_util.now().timestamp() * 1000) 427 | for dev in ret["deviceInfoBodyList"]: 428 | dev[""] = tstamp 429 | dev["onlinets"] = monotonic() 430 | self._devices[dev["deviceid"]] = dev 431 | 432 | for device_id in self._devices: 433 | self._sensors.setdefault(device_id, {}) 434 | 435 | return self._devices 436 | 437 | def device_available(self, device_id) -> bool: 438 | """Return True if device is available.""" 439 | dev = self.devices.get(device_id, {}) 440 | device_available = dev.get("onlinestat") == 1 441 | device_timeout = (monotonic() - dev.get("onlinets", 0)) <= AVAILABLE_TIMEOUT 442 | online = self.available and device_available and device_timeout 443 | 444 | # pylint: disable=logging-too-many-args 445 | _LOGGER.debug( 446 | "Availability: %s (account) AND %s (device %s) AND %s (timeout) = %s", 447 | self.available, 448 | device_available, 449 | device_id, 450 | device_timeout, 451 | online, 452 | ) 453 | 454 | return online 455 | 456 | def _extract_sensors_data(self, device_id, ts_now: int, sensors: dict): 457 | res = {} 458 | for sensor in sensors: 459 | sensor_id = sensor["seq"] 460 | if ( 461 | sensor["content"] is None 462 | or sensor["content"] == "" 463 | or (sensor_id not in SENSORS and sensor_id not in BINARY_SENSORS) 464 | ): 465 | continue 466 | 467 | res[sensor_id] = float(sensor["content"]) 468 | if sensor_id == 8 and self._receive_tvoc_in_ppb: 469 | res[sensor_id] *= 1000 * 24.45 / MWEIGTH_TVOC 470 | elif sensor_id == 7 and self._receive_hcho_in_ppb: 471 | res[sensor_id] *= 1000 * 24.45 / MWEIGTH_HCHO 472 | if self._units[sensor_id] != CONCENTRATION_MILLIGRAMS_PER_CUBIC_METER: 473 | res[sensor_id] = int(res[sensor_id]) 474 | 475 | self._sensors[device_id][ts_now] = res 476 | self._sensors_raw[device_id] = res 477 | 478 | def get_sensors_raw(self, device_id) -> Optional[SensorsDictType]: 479 | """Get raw values of states of available sensors for device.""" 480 | return self._sensors_raw.get(device_id) 481 | 482 | def get_sensors(self, device_id) -> Optional[SensorsDictType]: 483 | """Get states of available sensors for device.""" 484 | ts_now = int(dt_util.now().timestamp()) 485 | ts_overdue = ts_now - SENSORS_FILTER_FRAME.total_seconds() 486 | 487 | self._sensors.setdefault(device_id, {}) 488 | 489 | # Filter historic states 490 | res = {} 491 | ts_min = max( 492 | list(filter(lambda x: x <= ts_overdue, self._sensors[device_id].keys())) 493 | or {ts_overdue} 494 | ) 495 | for m_ts, val in self._sensors[device_id].items(): 496 | if m_ts >= ts_min: 497 | res[m_ts] = val 498 | self._sensors[device_id] = res 499 | 500 | if not self._sensors[device_id]: 501 | return None 502 | 503 | # Calculate average state values 504 | res = {} 505 | last_ts = ts_overdue 506 | last_data: Dict[int, float] = {} 507 | for sensor_id in self._sensors_raw[device_id]: 508 | res.setdefault(sensor_id, 0) 509 | last_data.setdefault(sensor_id, 0) 510 | 511 | # Sum values 512 | values = list(self._sensors[device_id].items()).copy() 513 | for m_ts, data in values: 514 | val_t = m_ts - last_ts 515 | if val_t > 0: 516 | for sensor_id, val in last_data.items(): 517 | res[sensor_id] += val * val_t 518 | last_ts = max(m_ts, ts_overdue) 519 | last_data = data 520 | 521 | # Add last values 522 | val_t = ts_now - last_ts + 1 523 | for sensor_id, val in last_data.items(): 524 | res[sensor_id] += val * val_t 525 | 526 | # Average and round 527 | length = max( 528 | 1, ts_now - max(min(self._sensors[device_id].keys()), ts_overdue) + 1 529 | ) 530 | for sensor_id in res: 531 | rnd = SENSORS.get(sensor_id, {}).get(CONF_PRECISION, 0) 532 | res[sensor_id] = ( 533 | self._sensors_raw[device_id][1] 534 | if sensor_id == 1 535 | else int(res[sensor_id] / length) 536 | if rnd == 0 537 | or self._units[sensor_id] 538 | in (CONCENTRATION_PARTS_PER_MILLION, CONCENTRATION_PARTS_PER_BILLION) 539 | else round(res[sensor_id] / length, rnd) 540 | ) 541 | 542 | return res 543 | 544 | @Throttle(timedelta(minutes=10)) 545 | async def async_update_sensors(self): 546 | """Update current states of all active devices for account.""" 547 | _LOGGER.debug("Updating sensors state for account %s", self.name_secure) 548 | 549 | ts_now = int(dt_util.now().timestamp()) 550 | 551 | for device_id in self._active_devices: 552 | if self.get_sensors_raw(device_id) is not None: 553 | continue 554 | 555 | ret = await self._async_query( 556 | QUERY_TYPE_DEVICE, 557 | "list", 558 | extra_params={ 559 | "deviceToken": self.devices[device_id]["deviceToken"], 560 | "timestamp": ts_now, 561 | "callback": "jsoncallback", 562 | "_": ts_now, 563 | }, 564 | ) 565 | if not ret: 566 | return 567 | 568 | self._extract_sensors_data(device_id, ts_now, ret["deviceValueVos"]) 569 | 570 | async def async_update_sensors_or_timeout(self, timeout=UPDATE_TIMEOUT): 571 | """Update current states of all active devices for account.""" 572 | start = monotonic() 573 | try: 574 | async with async_timeout.timeout(timeout): 575 | await self.async_update_sensors() 576 | 577 | except asyncio.TimeoutError as err: 578 | _LOGGER.error("Timeout fetching %s device's sensors", self.name_secure) 579 | raise err 580 | 581 | finally: 582 | _LOGGER.debug( 583 | "Finished fetching %s device's sensors in %.3f seconds", 584 | self.name_secure, 585 | monotonic() - start, 586 | ) 587 | --------------------------------------------------------------------------------