├── custom_components
└── airbnk_mqtt
│ ├── services.yaml
│ ├── manifest.json
│ ├── diagnostics.py
│ ├── airbnk_logger.py
│ ├── translations
│ └── en.json
│ ├── strings.json
│ ├── const.py
│ ├── binary_sensor.py
│ ├── cover.py
│ ├── sensor.py
│ ├── __init__.py
│ ├── codes_generator.py
│ ├── airbnk_api.py
│ ├── config_flow.py
│ ├── custom_device.py
│ └── tasmota_device.py
├── .github
└── FUNDING.yml
├── requirements_test.txt
├── tox.ini
├── setup.cfg
├── pyproject.toml
├── tools
├── README.txt
└── generate_payloads.py
├── .gitignore
├── info.md
├── README.md
└── LICENSE
/custom_components/airbnk_mqtt/services.yaml:
--------------------------------------------------------------------------------
1 | reload:
2 | description: Reload airbnk_mqtt and reset its state.
3 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 | custom: ['https://www.buymeacoffee.com/rospogrigio', 'https://paypal.me/rospogrigio']
3 |
--------------------------------------------------------------------------------
/requirements_test.txt:
--------------------------------------------------------------------------------
1 | black==20.8b1
2 | codespell==2.0.0
3 | flake8==3.8.4
4 | mypy==0.800
5 | pydocstyle==5.1.1
6 | pylint==2.6.0
7 | pylint-strict-informational==0.1
8 | homeassistant==2021.1.4
9 |
--------------------------------------------------------------------------------
/custom_components/airbnk_mqtt/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "domain": "airbnk_mqtt",
3 | "name": "Airbnk lock (MQTT-based)",
4 | "version": "1.7.2",
5 | "documentation": "https://github.com/rospogrigio/airbnk_mqtt/",
6 | "dependencies": ["mqtt"],
7 | "codeowners": [
8 | "@rospogrigio"
9 | ],
10 | "issue_tracker": "https://github.com/rospogrigio/airbnk_mqtt/issues",
11 | "requirements": [
12 | ],
13 | "iot_class": "local_polling",
14 | "config_flow": true
15 | }
16 |
--------------------------------------------------------------------------------
/tox.ini:
--------------------------------------------------------------------------------
1 | [tox]
2 | skipsdist = true
3 | envlist = py{38,39}, lint, typing
4 | skip_missing_interpreters = True
5 | cs_exclude_words = hass,unvalid
6 |
7 | [gh-actions]
8 | python =
9 | 3.8: clean, py38, lint, typing
10 | 3.9: clean, py39, lint, typing
11 |
12 | [testenv]
13 | passenv = TOXENV CI
14 | whitelist_externals =
15 | true
16 | setenv =
17 | LANG=en_US.UTF-8
18 | PYTHONPATH = {toxinidir}/airbnk_mqtt
19 | deps =
20 | -r{toxinidir}/requirements_test.txt
21 | commands =
22 | true # TODO: Run tests later
23 | #pytest -n auto --log-level=debug -v --timeout=30 --durations=10 {posargs}
24 |
25 | [testenv:lint]
26 | ignore_errors = True
27 | deps =
28 | {[testenv]deps}
29 | commands =
30 | codespell -q 4 -L {[tox]cs_exclude_words} --skip="*.pyc,*.pyi,*~" custom_components
31 | flake8 custom_components
32 | black --fast --check .
33 | pydocstyle -v custom_components
34 | pylint custom_components/airbnk_mqtt
35 |
36 | [testenv:typing]
37 | commands =
38 | mypy --ignore-missing-imports --follow-imports=skip custom_components
39 |
--------------------------------------------------------------------------------
/custom_components/airbnk_mqtt/diagnostics.py:
--------------------------------------------------------------------------------
1 | """Diagnostics support for Airbnk MQTT."""
2 | from __future__ import annotations
3 | from typing import Any
4 |
5 | from homeassistant.config_entries import ConfigEntry
6 | from homeassistant.core import HomeAssistant
7 | from homeassistant.helpers.device_registry import DeviceEntry
8 |
9 | from .const import DOMAIN, AIRBNK_DEVICES
10 |
11 |
12 | async def async_get_config_entry_diagnostics(
13 | hass: HomeAssistant, entry: ConfigEntry
14 | ) -> dict[str, Any]:
15 | """Return diagnostics for a config entry."""
16 | data = {}
17 | data = {**entry.data}
18 |
19 | # censoring private information
20 | # data["token"] = re.sub(r"[^\-]", "*", data["token"])
21 | # data["userId"] = re.sub(r"[^\-]", "*", data["userId"])
22 | return data
23 |
24 |
25 | async def async_get_device_diagnostics(
26 | hass: HomeAssistant, entry: ConfigEntry, device: DeviceEntry
27 | ) -> dict[str, Any]:
28 | """Return diagnostics for a device entry."""
29 | dev_id = next(iter(device.identifiers))[1]
30 |
31 | data = {}
32 | data["device"] = device
33 | data["log"] = hass.data[DOMAIN][AIRBNK_DEVICES][dev_id].logger.retrieve_log()
34 | return data
35 |
--------------------------------------------------------------------------------
/custom_components/airbnk_mqtt/airbnk_logger.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 | import logging
3 |
4 | from datetime import datetime
5 |
6 | _LOGGER = logging.getLogger(__name__)
7 |
8 | LOG_PERSISTENCE_SECS = 300
9 |
10 |
11 | class AirbnkLogger:
12 | def __init__(self, log_name):
13 | self.logger = logging.getLogger(log_name)
14 | self.log = []
15 |
16 | def append_to_log(self, log_level, msg):
17 | systemTime = datetime.now().timestamp()
18 | self.log.append({"time": systemTime, "level": log_level, "msg": msg})
19 | while self.log[0]["time"] < systemTime - LOG_PERSISTENCE_SECS:
20 | self.log = self.log[1:]
21 |
22 | def retrieve_log(self):
23 | output = []
24 | for record in self.log:
25 | t_stamp = datetime.fromtimestamp(record["time"])
26 | t_stamp_str = t_stamp.strftime("%Y-%m-%d %H:%M:%S ")
27 | output.append(t_stamp_str + record["level"] + ": " + record["msg"])
28 | return output
29 |
30 | def info(self, msg):
31 | self.append_to_log("INFO", msg)
32 | self.logger.info(msg)
33 |
34 | def debug(self, msg):
35 | self.append_to_log("DEBUG", msg)
36 | self.logger.debug(msg)
37 |
38 | def warning(self, msg):
39 | self.append_to_log("WARNING", msg)
40 | self.logger.warning(msg)
41 |
42 | def error(self, msg):
43 | self.append_to_log("ERROR", msg)
44 | self.logger.error(msg)
45 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [flake8]
2 | exclude = .git,.tox
3 | max-line-length = 88
4 | ignore = E203, W503
5 |
6 | [mypy]
7 | python_version = 3.7
8 | ignore_errors = true
9 | follow_imports = silent
10 | ignore_missing_imports = true
11 | warn_incomplete_stub = true
12 | warn_redundant_casts = true
13 | warn_unused_configs = true
14 |
15 | [mypy-homeassistant.block_async_io,homeassistant.bootstrap,homeassistant.components,homeassistant.config_entries,homeassistant.config,homeassistant.const,homeassistant.core,homeassistant.data_entry_flow,homeassistant.exceptions,homeassistant.__init__,homeassistant.loader,homeassistant.__main__,homeassistant.requirements,homeassistant.runner,homeassistant.setup,homeassistant.util,homeassistant.auth.*,homeassistant.components.automation.*,homeassistant.components.binary_sensor.*,homeassistant.components.calendar.*,homeassistant.components.cover.*,homeassistant.components.device_automation.*,homeassistant.components.frontend.*,homeassistant.components.geo_location.*,homeassistant.components.group.*,homeassistant.components.history.*,homeassistant.components.http.*,homeassistant.components.image_processing.*,homeassistant.components.integration.*,homeassistant.components.light.*,homeassistant.components.lock.*,homeassistant.components.mailbox.*,homeassistant.components.media_player.*,homeassistant.components.notify.*,homeassistant.components.persistent_notification.*,homeassistant.components.proximity.*,homeassistant.components.remote.*,homeassistant.components.scene.*,homeassistant.components.sensor.*,homeassistant.components.sun.*,homeassistant.components.switch.*,homeassistant.components.systemmonitor.*,homeassistant.components.tts.*,homeassistant.components.vacuum.*,homeassistant.components.water_heater.*,homeassistant.components.weather.*,homeassistant.components.websocket_api.*,homeassistant.components.zone.*,homeassistant.helpers.*,homeassistant.scripts.*,homeassistant.util.*]
16 | strict = true
17 | ignore_errors = false
18 | warn_unreachable = true
19 | # TODO: turn these off, address issues
20 | allow_any_generics = true
21 | implicit_reexport = true
22 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [tool.black]
2 | target-version = ["py38", "py39"]
3 | include = 'custom_components/airbnk_mqtt/.*\.py'
4 |
5 | # pylint config stolen from Home Assistant
6 | # Use a conservative default here; 2 should speed up most setups and not hurt
7 | # any too bad. Override on command line as appropriate.
8 | # Disabled for now: https://github.com/PyCQA/pylint/issues/3584
9 | #jobs = 2
10 | load-plugins = [
11 | "pylint_strict_informational",
12 | ]
13 | persistent = false
14 | extension-pkg-whitelist = [
15 | "ciso8601",
16 | "cv2",
17 | ]
18 |
19 | [tool.pylint.BASIC]
20 | good-names = [
21 | "_",
22 | "ev",
23 | "ex",
24 | "fp",
25 | "i",
26 | "id",
27 | "j",
28 | "k",
29 | "Run",
30 | "T",
31 | "hs",
32 | ]
33 |
34 | [tool.pylint."MESSAGES CONTROL"]
35 | # Reasons disabled:
36 | # format - handled by black
37 | # locally-disabled - it spams too much
38 | # duplicate-code - unavoidable
39 | # cyclic-import - doesn't test if both import on load
40 | # abstract-class-little-used - prevents from setting right foundation
41 | # unused-argument - generic callbacks and setup methods create a lot of warnings
42 | # too-many-* - are not enforced for the sake of readability
43 | # too-few-* - same as too-many-*
44 | # abstract-method - with intro of async there are always methods missing
45 | # inconsistent-return-statements - doesn't handle raise
46 | # too-many-ancestors - it's too strict.
47 | # wrong-import-order - isort guards this
48 | disable = [
49 | "format",
50 | "abstract-class-little-used",
51 | "abstract-method",
52 | "cyclic-import",
53 | "duplicate-code",
54 | "inconsistent-return-statements",
55 | "locally-disabled",
56 | "not-context-manager",
57 | "too-few-public-methods",
58 | "too-many-ancestors",
59 | "too-many-arguments",
60 | "too-many-branches",
61 | "too-many-instance-attributes",
62 | "too-many-lines",
63 | "too-many-locals",
64 | "too-many-public-methods",
65 | "too-many-return-statements",
66 | "too-many-statements",
67 | "too-many-boolean-expressions",
68 | "unused-argument",
69 | "wrong-import-order",
70 | ]
71 | enable = [
72 | "use-symbolic-message-instead",
73 | ]
74 |
75 | [tool.pylint.REPORTS]
76 | score = false
77 |
78 | [tool.pylint.FORMAT]
79 | expected-line-ending-format = "LF"
80 |
81 | [tool.pylint.MISCELLANEOUS]
82 | notes = "XXX"
83 |
--------------------------------------------------------------------------------
/tools/README.txt:
--------------------------------------------------------------------------------
1 | Instructions to operate Airbnk locks using the nRF Connect App:
2 | 1) download and install nRF Connect App
3 |
4 | 2) open the app, scan for devices and select the lock. Press the RAW button, and export the "Raw data" values. Edit generate_payloads.py and copy the value in the lockAdv parameter (line 35)
5 |
6 | 3) enable debug for airbnk, by adding the following line to configuration.yaml, in the "logs:" part
7 | custom_components.airbnk: debug
8 |
9 | 4) relaunch homeassistant and search the logs for the following output:
10 | 2021-11-16 23:37:47 DEBUG (MainThread) [custom_components.airbnk.airbnk_api] GetCloudDevices succeeded (200): {
11 | "code":200,
12 | "data":[
13 | {
14 | "sn":"...",
15 | "deviceName":"...",
16 | [...],
17 | "appKey":"...",
18 | "newSninfo":"HTWsm...aTj2w==",
19 | [...]
20 | }
21 | ],
22 | "info":"OK",
23 | "totalNum":0,
24 | "totalPage":0
25 | }
26 |
27 | 5) copy the values of "appKey" and "newSninfo" in the related fields into generate_payloads.py script (lines 31, 32)
28 |
29 | 6) now launch the script with "./generate_payloads.py [1,2]" (1 is for opening, 2 is for closing)
30 | The output should be something like
31 | DECRYPTED KEYS: {'lockSn': '1234567', 'lockType': 'M510', 'manufacturerKey': b'69...20', 'bindingKey': b'bc...35'}
32 | TIME IS 1637101770
33 | LOCKEVENTS b'0201061BFFBABA...' 138
34 | OPCODE FOR CLOSING IS b'AA101A035A3EA4A5CA7FA4DDD007BBE4E7A9A2A6FE84BCE5EAFED9553500000000000000'
35 | PACKET 1 IS FF00AA101A035A3EA4A5CA7FA4DDD007BBE4E7A9
36 | PACKET 2 IS FF01A2A6FE84BCE5EAFED9553500000000000000
37 |
38 | 7) transfer the values for PACKET 1 and 2 to your phone
39 |
40 | 8) go back to nRF Connect app, select the lock and press "Connect", click on the 3 dots on the top right and "Read characteristics". Then, click on the "Unknown Service (UUID 0xFFF0) and you'll see the current values of the characteristics 0xFFF1, 0xFFF2 and 0xFFF3. Press the first "Up-arrow" next to the title "Unknown Characteristic" for UUID 0xFFF2, and paste the value of PACKET 1 in the field New Value (leave BYTEARRAY as value type), and press "SEND". Then press again the "Up-arrow" and paste the VALUE of PACKET 2. Finally, click "SEND"... and the lock should open/close!
41 |
42 | 9) to operate it again, you need to repeat step 2), because a part of the value has changed (in detail, the bytes 26 and 27)
43 |
--------------------------------------------------------------------------------
/custom_components/airbnk_mqtt/translations/en.json:
--------------------------------------------------------------------------------
1 | {
2 | "config": {
3 | "abort": {
4 | "already_configured": "The integration is already configured.",
5 | "cannot_connect": "Failed to connect to Airbnk Cloud.",
6 | "init_failed": "Failed to initialize Airbnk API.",
7 | "code_request_failed": "Failed to request verification code.",
8 | "token_retrieval_failed": "Failed to retrieve access token."
9 | },
10 | "error": {
11 | "cannot_connect": "Failed to connect",
12 | "device_fail": "Unexpected error",
13 | "device_timeout": "Failed to connect",
14 | "forbidden": "Invalid authentication",
15 | "invalid_auth": "Invalid authentication",
16 | "unknown": "Unexpected error"
17 | },
18 | "step": {
19 | "user": {
20 | "data": {
21 | "email": "Email address"
22 | },
23 | "description": "Enter the email address you use to login to Airbnk Cloud, then press Submit to request a verification code.",
24 | "title": "Configure Airbnk Lock"
25 | },
26 | "verify": {
27 | "title": "Enter verification code",
28 | "description": "Enter the code you received via email, then press Submit to complete the procedure.",
29 | "data": {
30 | "email": "Email address",
31 | "code": "Verification code"
32 | }
33 | },
34 | "configure_device": {
35 | "title": "Enter device parameters",
36 | "description": "Enter the device type, MAC address and topic\nfor MQTT connection with {model} lock, s/n {sn}.",
37 | "data": {
38 | "device_mqtt_type": "Device MQTT type",
39 | "mac_address": "MAC address",
40 | "mqtt_topic": "MQTT topic",
41 | "skip_device": "Skip this device"
42 | }
43 | },
44 | "messagebox": {
45 | "title": "Done",
46 | "description": "{action} configuration for {model} lock, s/n {sn}."
47 | }
48 |
49 | }
50 | },
51 | "options": {
52 | "step": {
53 | "init": {
54 | "title": "Configure options for MQTT-based Airbnk integration",
55 | "data": {
56 | "retries_num": "Number of retries in case of failure"
57 | }
58 | }
59 | }
60 | }
61 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # pipenv
88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
91 | # install all needed dependencies.
92 | #Pipfile.lock
93 |
94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95 | __pypackages__/
96 |
97 | # Celery stuff
98 | celerybeat-schedule
99 | celerybeat.pid
100 |
101 | # SageMath parsed files
102 | *.sage.py
103 |
104 | # Environments
105 | .env
106 | .venv
107 | env/
108 | venv/
109 | ENV/
110 | env.bak/
111 | venv.bak/
112 |
113 | # Spyder project settings
114 | .spyderproject
115 | .spyproject
116 |
117 | # Rope project settings
118 | .ropeproject
119 |
120 | # mkdocs documentation
121 | /site
122 |
123 | # mypy
124 | .mypy_cache/
125 | .dmypy.json
126 | dmypy.json
127 |
128 | # Pyre type checker
129 | .pyre/
130 |
--------------------------------------------------------------------------------
/custom_components/airbnk_mqtt/strings.json:
--------------------------------------------------------------------------------
1 | {
2 | "config": {
3 | "step": {
4 | "user": {
5 | "title": "Configure Airbnk Lock",
6 | "description": "Enter the [%key:common::config_flow::data::email] you use to login to Airbnk Cloud, then press Submit to request a verification code.",
7 | "data": {
8 | "email": "[%key:common::config_flow::data::email]"
9 | }
10 | },
11 | "verify": {
12 | "title": "Enter verification code",
13 | "description": "Enter the [%key:common::config_flow::data::code] you received via email, then press Submit to complete the procedure.",
14 | "data": {
15 | "email": "[%key:common::config_flow::data::email]",
16 | "code": "[%key:common::config_flow::data::code]"
17 | }
18 | },
19 | "configure_device": {
20 | "title": "Enter device parameters",
21 | "description": "Enter the device type, MAC address and topic\nfor MQTT connection with {model} lock, s/n {sn}.",
22 | "data": {
23 | "device_mqtt_type": "[%key:common::config_flow::data::device_mqtt_type]",
24 | "mac_address": "[%key:common::config_flow::data::mac_address]",
25 | "mqtt_topic": "[%key:common::config_flow::data::mqtt_topic]",
26 | "skip_device": "[%key:common::config_flow::data::skip_device]"
27 | }
28 | },
29 | "messagebox": {
30 | "title": "Done",
31 | "description": "{action} configuration for {model} lock, s/n {sn}."
32 | }
33 | },
34 | "abort": {
35 | "already_configured": "[%key:common::config_flow::abort::already_configured]",
36 | "init_failed": "[%key:common::config_flow::abort::init_failed]",
37 | "code_request_failed": "[%key:common::config_flow::abort::code_request_failed]",
38 | "token_retrieval_failed": "[%key:common::config_flow::abort::token_retrieval_failed]",
39 | "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]"
40 | },
41 | "error": {
42 | "unknown": "[%key:common::config_flow::error::unknown%]",
43 | "invalid_auth": "[%key:common::config_flow::error::invalid_auth%]",
44 | "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]"
45 | }
46 | },
47 | "options": {
48 | "step": {
49 | "init": {
50 | "title": "Configure options for MQTT-based Airbnk integration",
51 | "data": {
52 | "retries_num": "Number of retries in case of failure"
53 | }
54 | }
55 | }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/custom_components/airbnk_mqtt/const.py:
--------------------------------------------------------------------------------
1 | """Constants for Airbnk MQTT integration."""
2 |
3 | from homeassistant.components.sensor import SensorDeviceClass
4 | from homeassistant.const import (
5 | CONF_DEVICE_CLASS,
6 | CONF_TOKEN,
7 | CONF_NAME,
8 | CONF_TYPE,
9 | CONF_UNIT_OF_MEASUREMENT,
10 | PERCENTAGE,
11 | UnitOfElectricPotential,
12 | UnitOfTime,
13 | SIGNAL_STRENGTH_DECIBELS,
14 | )
15 |
16 | DOMAIN = "airbnk_mqtt"
17 |
18 | CONF_USERID = "userId"
19 | CONF_TOKENSET = CONF_TOKEN + "set"
20 | CONF_UUID = "uuid"
21 | CONF_DEVICE_CONFIGS = "device_configs"
22 | CONF_LOCKSTATUS = "lockStatus"
23 | CONF_MQTT_TOPIC = "mqtt_topic"
24 | CONF_MAC_ADDRESS = "mac_address"
25 | CONF_VOLTAGE_THRESHOLDS = "voltage_thresholds"
26 | CONF_RETRIES_NUM = "retries_num"
27 |
28 | CONF_DEVICE_MQTT_TYPE = "device_mqtt_type"
29 | CONF_CUSTOM_MQTT = "Custom MQTT"
30 | CONF_TASMOTA_MQTT = "Tasmota MQTT"
31 | CONF_MQTT_TYPES = [CONF_CUSTOM_MQTT, CONF_TASMOTA_MQTT]
32 |
33 | AIRBNK_DATA = "airbnk_data"
34 | AIRBNK_API = "airbnk_api"
35 | AIRBNK_DEVICES = "airbnk_devices"
36 | AIRBNK_DISCOVERY_NEW = "airbnk_discovery_new_{}"
37 | DEFAULT_RETRIES_NUM = 10
38 |
39 | TIMEOUT = 60
40 |
41 | LOCK_STATE_LOCKED = 0
42 | LOCK_STATE_UNLOCKED = 1
43 | LOCK_STATE_JAMMED = 2
44 | LOCK_STATE_OPERATING = 3
45 | LOCK_STATE_FAILED = 4
46 |
47 | LOCK_STATE_STRINGS = {
48 | LOCK_STATE_LOCKED: "Locked",
49 | LOCK_STATE_UNLOCKED: "Unlocked",
50 | LOCK_STATE_JAMMED: "Jammed",
51 | LOCK_STATE_OPERATING: "Operating",
52 | LOCK_STATE_FAILED: "Failed",
53 | }
54 |
55 | SENSOR_TYPE_STATE = "state"
56 | SENSOR_TYPE_BATTERY = "battery"
57 | SENSOR_TYPE_VOLTAGE = "voltage"
58 | SENSOR_TYPE_LAST_ADVERT = "last_advert"
59 | SENSOR_TYPE_LOCK_EVENTS = "lock_events"
60 | SENSOR_TYPE_SIGNAL_STRENGTH = "signal_strength"
61 |
62 | SENSOR_TYPE_BATTERY_LOW = "battery_low"
63 |
64 | SENSOR_TYPES = {
65 | SENSOR_TYPE_STATE: {
66 | CONF_NAME: "Status",
67 | CONF_TYPE: SENSOR_TYPE_STATE,
68 | },
69 | SENSOR_TYPE_BATTERY: {
70 | CONF_NAME: "Battery",
71 | CONF_TYPE: SENSOR_TYPE_BATTERY,
72 | CONF_DEVICE_CLASS: SensorDeviceClass.BATTERY,
73 | CONF_UNIT_OF_MEASUREMENT: PERCENTAGE,
74 | },
75 | SENSOR_TYPE_VOLTAGE: {
76 | CONF_NAME: "Battery voltage",
77 | CONF_TYPE: SENSOR_TYPE_VOLTAGE,
78 | CONF_DEVICE_CLASS: SensorDeviceClass.VOLTAGE,
79 | CONF_UNIT_OF_MEASUREMENT: UnitOfElectricPotential.VOLT,
80 | },
81 | SENSOR_TYPE_LAST_ADVERT: {
82 | CONF_NAME: "Time from last advert",
83 | CONF_TYPE: SENSOR_TYPE_LAST_ADVERT,
84 | CONF_UNIT_OF_MEASUREMENT: UnitOfTime.SECONDS,
85 | },
86 | SENSOR_TYPE_SIGNAL_STRENGTH: {
87 | CONF_NAME: "Signal strength",
88 | CONF_TYPE: SENSOR_TYPE_SIGNAL_STRENGTH,
89 | CONF_DEVICE_CLASS: SensorDeviceClass.SIGNAL_STRENGTH,
90 | CONF_UNIT_OF_MEASUREMENT: SIGNAL_STRENGTH_DECIBELS,
91 | },
92 | SENSOR_TYPE_LOCK_EVENTS: {
93 | CONF_NAME: "Lock events counter",
94 | CONF_TYPE: SENSOR_TYPE_LOCK_EVENTS,
95 | },
96 | }
--------------------------------------------------------------------------------
/custom_components/airbnk_mqtt/binary_sensor.py:
--------------------------------------------------------------------------------
1 | """Support for Airbnk binary sensors."""
2 | from __future__ import annotations
3 | import logging
4 |
5 | from homeassistant.components.binary_sensor import (
6 | BinarySensorEntity,
7 | )
8 | from homeassistant.components.sensor import SensorDeviceClass
9 |
10 | from .const import (
11 | DOMAIN as AIRBNK_DOMAIN,
12 | AIRBNK_DEVICES,
13 | SENSOR_TYPE_BATTERY_LOW,
14 | )
15 |
16 | _LOGGER = logging.getLogger(__name__)
17 |
18 | SENSOR_ICON = "hass:post-outline"
19 |
20 |
21 | async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
22 | """Old way of setting up the platform.
23 |
24 | Can only be called when a user accidentally mentions the platform in their
25 | config. But even in that case it would have been ignored.
26 | """
27 |
28 |
29 | async def async_setup_entry(hass, entry, async_add_entities):
30 | """Set up Airbnk sensors based on config_entry."""
31 | sensors = []
32 | for dev_id, device in hass.data[AIRBNK_DOMAIN][AIRBNK_DEVICES].items():
33 | sensor = AirbnkBinarySensor(hass, device, SENSOR_TYPE_BATTERY_LOW)
34 | sensors.append(sensor)
35 | async_add_entities(sensors)
36 |
37 |
38 | class AirbnkBinarySensor(BinarySensorEntity):
39 | """Representation of a Binary Sensor."""
40 |
41 | def __init__(self, hass, device, monitored_attr: str):
42 | """Initialize the sensor."""
43 | self.hass = hass
44 | self._device = device
45 | self._monitored_attribute = monitored_attr
46 | deviceName = self._device._lockConfig["deviceName"]
47 | self._name = f"{deviceName} Battery Low"
48 |
49 | async def async_added_to_hass(self):
50 | """Run when this Entity has been added to HA."""
51 | # Sensors should also register callbacks to HA when their state changes
52 | self._device.register_callback(self.async_write_ha_state)
53 |
54 | @property
55 | def available(self):
56 | """Return if entity is available or not."""
57 | return self._device.is_available
58 |
59 | @property
60 | def unique_id(self):
61 | """Return a unique ID."""
62 | devID = self._device._lockConfig["sn"]
63 | return f"{devID}_{self._monitored_attribute}"
64 |
65 | @property
66 | def name(self):
67 | """Return the name of the sensor."""
68 | return self._name
69 |
70 | @property
71 | def device_info(self):
72 | """Return a device description for device registry."""
73 | return self._device.device_info
74 |
75 | @property
76 | def state(self):
77 | """Return the state of the sensor."""
78 | if self._monitored_attribute in self._device._lockData:
79 | return self._device._lockData[self._monitored_attribute]
80 | return None
81 |
82 | @property
83 | def device_class(self):
84 | """Return the class of this device."""
85 | return SensorDeviceClass.BATTERY
86 |
87 | @property
88 | def icon(self):
89 | """Return the icon of this device."""
90 | return None
91 |
92 | async def async_update(self):
93 | """Retrieve latest state."""
94 | # _LOGGER.debug("async_update")
95 |
--------------------------------------------------------------------------------
/custom_components/airbnk_mqtt/cover.py:
--------------------------------------------------------------------------------
1 | """Support for Airbnk locks, treated as covers."""
2 | import logging
3 |
4 | from homeassistant.components.cover import CoverEntity, CoverEntityFeature
5 |
6 | from .const import (
7 | DOMAIN as AIRBNK_DOMAIN,
8 | AIRBNK_DEVICES,
9 | LOCK_STATE_LOCKED,
10 | LOCK_STATE_UNLOCKED,
11 | LOCK_STATE_JAMMED,
12 | LOCK_STATE_OPERATING,
13 | LOCK_STATE_FAILED,
14 | )
15 |
16 | _LOGGER = logging.getLogger(__name__)
17 |
18 | LOCK_STATE_ICONS = {
19 | LOCK_STATE_LOCKED: "hass:door-closed-lock",
20 | LOCK_STATE_UNLOCKED: "hass:door-closed",
21 | LOCK_STATE_JAMMED: "hass:lock-question",
22 | LOCK_STATE_OPERATING: "hass:lock-reset",
23 | LOCK_STATE_FAILED: "hass:lock-alert",
24 | }
25 |
26 |
27 | async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
28 | """Old way of setting up the platform.
29 |
30 | Can only be called when a user accidentally mentions the platform in their
31 | config. But even in that case it would have been ignored.
32 | """
33 |
34 |
35 | async def async_setup_entry(hass, entry, async_add_entities):
36 | """Set up Airbnk covers based on config_entry."""
37 | locks = []
38 | for dev_id, device in hass.data[AIRBNK_DOMAIN][AIRBNK_DEVICES].items():
39 | lock = AirbnkLock(device, dev_id)
40 | locks.append(lock)
41 | async_add_entities(locks)
42 |
43 |
44 | class AirbnkLock(CoverEntity):
45 | """Representation of a lock."""
46 |
47 | def __init__(self, device, lock_id: str):
48 | """Initialize the zone."""
49 | self._device = device
50 | self._lock_id = lock_id
51 | deviceName = self._device._lockConfig["deviceName"]
52 | self._name = f"{deviceName}"
53 |
54 | async def async_added_to_hass(self):
55 | """Run when this Entity has been added to HA."""
56 | # Sensors should also register callbacks to HA when their state changes
57 | self._device.register_callback(self.async_write_ha_state)
58 |
59 | @property
60 | def available(self):
61 | """Return if entity is available or not."""
62 | return self._device.is_available
63 |
64 | @property
65 | def supported_features(self):
66 | """Flag supported features."""
67 | return CoverEntityFeature.OPEN | CoverEntityFeature.CLOSE
68 |
69 | @property
70 | def unique_id(self):
71 | """Return a unique ID."""
72 | devID = self._device._lockConfig["sn"]
73 | return f"{devID}"
74 |
75 | @property
76 | def icon(self):
77 | """Icon to use in the frontend, if any."""
78 | return LOCK_STATE_ICONS[self._device.curr_state]
79 |
80 | @property
81 | def name(self):
82 | """Return the name of the lock."""
83 | return self._name
84 |
85 | @property
86 | def device_info(self):
87 | """Return a device description for device registry."""
88 | return self._device.device_info
89 |
90 | @property
91 | def is_opening(self):
92 | """Return if cover is opening."""
93 | return False
94 |
95 | @property
96 | def is_closing(self):
97 | """Return if cover is closing."""
98 | return False
99 |
100 | @property
101 | def is_open(self):
102 | """Return if the cover is open or not."""
103 | return None
104 |
105 | @property
106 | def is_closed(self):
107 | """Return if the cover is closed or not."""
108 | return None
109 |
110 | async def async_open_cover(self, **kwargs):
111 | """Open the cover."""
112 | if self._device.curr_state == LOCK_STATE_OPERATING:
113 | _LOGGER.warning("Operation already in progress: please wait")
114 | raise Exception("Operation already in progress: please wait")
115 | return
116 |
117 | _LOGGER.debug("Launching command to open")
118 | await self._device.operateLock(1)
119 |
120 | async def async_close_cover(self, **kwargs):
121 | """Close cover."""
122 | if self._device.curr_state == LOCK_STATE_OPERATING:
123 | _LOGGER.warning("Operation already in progress: please wait")
124 | raise Exception("Operation already in progress: please wait")
125 | return
126 |
127 | _LOGGER.debug("Launching command to close")
128 | await self._device.operateLock(2)
129 |
130 | async def async_stop_cover(self, **kwargs):
131 | """Stop the cover."""
132 | _LOGGER.debug("Stop command is undefined")
133 | raise NotImplementedError
134 |
135 | async def async_update(self):
136 | """Retrieve latest state."""
137 | # _LOGGER.debug("async_update")
138 |
--------------------------------------------------------------------------------
/custom_components/airbnk_mqtt/sensor.py:
--------------------------------------------------------------------------------
1 | """Support for Airbnk sensors."""
2 | from __future__ import annotations
3 | import logging
4 |
5 | from homeassistant.helpers.entity import Entity
6 | from homeassistant.components.sensor import SensorDeviceClass
7 |
8 | from homeassistant.const import (
9 | CONF_ICON,
10 | CONF_NAME,
11 | CONF_TYPE,
12 | CONF_UNIT_OF_MEASUREMENT,
13 | )
14 |
15 | from .const import (
16 | DOMAIN as AIRBNK_DOMAIN,
17 | AIRBNK_DEVICES,
18 | SENSOR_TYPE_STATE,
19 | SENSOR_TYPE_BATTERY,
20 | SENSOR_TYPE_VOLTAGE,
21 | SENSOR_TYPE_LAST_ADVERT,
22 | SENSOR_TYPE_LOCK_EVENTS,
23 | SENSOR_TYPE_SIGNAL_STRENGTH,
24 | SENSOR_TYPES,
25 | )
26 |
27 | _LOGGER = logging.getLogger(__name__)
28 |
29 | SENSOR_ICON = "hass:post-outline"
30 |
31 |
32 | async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
33 | """Old way of setting up the platform.
34 |
35 | Can only be called when a user accidentally mentions the platform in their
36 | config. But even in that case it would have been ignored.
37 | """
38 |
39 |
40 | async def async_setup_entry(hass, entry, async_add_entities):
41 | """Set up Airbnk sensors based on config_entry."""
42 | sensors = []
43 | for dev_id, device in hass.data[AIRBNK_DOMAIN][AIRBNK_DEVICES].items():
44 | for sensor_type in SENSOR_TYPES:
45 | sensor = AirbnkSensor.factory(hass, device, sensor_type)
46 | sensors.append(sensor)
47 | async_add_entities(sensors)
48 |
49 |
50 | class AirbnkSensor(Entity):
51 | """Representation of a Sensor."""
52 |
53 | @staticmethod
54 | def factory(hass, device, monitored_attr):
55 | """Initialize any AirbnkSensor."""
56 | cls = {
57 | SENSOR_TYPE_STATE: AirbnkTextSensor,
58 | SENSOR_TYPE_BATTERY: AirbnkBatterySensor,
59 | SENSOR_TYPE_VOLTAGE: AirbnkTextSensor,
60 | SENSOR_TYPE_SIGNAL_STRENGTH: AirbnkTextSensor,
61 | SENSOR_TYPE_LAST_ADVERT: AirbnkTextSensor,
62 | SENSOR_TYPE_LOCK_EVENTS: AirbnkTextSensor,
63 | }[SENSOR_TYPES[monitored_attr][CONF_TYPE]]
64 | return cls(hass, device, monitored_attr)
65 |
66 | def __init__(self, hass, device, monitored_attr: str):
67 | """Initialize the sensor."""
68 | self.hass = hass
69 | self._device = device
70 | self._monitored_attribute = monitored_attr
71 | self._sensor = SENSOR_TYPES[monitored_attr]
72 | deviceName = self._device._lockConfig["deviceName"]
73 | self._name = f"{deviceName} {self._sensor[CONF_NAME]}"
74 |
75 | async def async_added_to_hass(self):
76 | """Run when this Entity has been added to HA."""
77 | # Sensors should also register callbacks to HA when their state changes
78 | self._device.register_callback(self.async_write_ha_state)
79 |
80 | @property
81 | def available(self):
82 | """Return if entity is available or not."""
83 | return self._device.is_available
84 |
85 | @property
86 | def unique_id(self):
87 | """Return a unique ID."""
88 | devID = self._device._lockConfig["sn"]
89 | return f"{devID}_{self._monitored_attribute}"
90 |
91 | @property
92 | def name(self):
93 | """Return the name of the sensor."""
94 | return self._name
95 |
96 | @property
97 | def device_info(self):
98 | """Return a device description for device registry."""
99 | return self._device.device_info
100 |
101 | @property
102 | def state(self):
103 | """Return the state of the sensor."""
104 | raise NotImplementedError
105 |
106 | @property
107 | def device_class(self):
108 | """Return the class of this device."""
109 | return self._sensor.get("SensorDeviceClass.DEVICE_CLASS")
110 |
111 | @property
112 | def icon(self):
113 | """Return the icon of this device."""
114 | return self._sensor.get(CONF_ICON)
115 |
116 | @property
117 | def unit_of_measurement(self):
118 | """Return the unit of measurement."""
119 | return self._sensor.get(CONF_UNIT_OF_MEASUREMENT)
120 |
121 | async def async_update(self):
122 | """Retrieve latest state."""
123 | # _LOGGER.debug("async_update")
124 |
125 |
126 | class AirbnkBatterySensor(AirbnkSensor):
127 | """Representation of a Battery Sensor."""
128 |
129 | @property
130 | def state(self):
131 | """Return the state of the sensor."""
132 | self._device.check_availability()
133 | if self._monitored_attribute in self._device._lockData:
134 | return self._device._lockData[self._monitored_attribute]
135 | return None
136 |
137 |
138 | class AirbnkTextSensor(AirbnkSensor):
139 | """Representation of a generic text sensor."""
140 |
141 | @property
142 | def state(self):
143 | """Return the state of the sensor."""
144 | if self._monitored_attribute in self._device._lockData:
145 | return self._device._lockData[self._monitored_attribute]
146 | return None
147 |
--------------------------------------------------------------------------------
/info.md:
--------------------------------------------------------------------------------
1 | [](https://github.com/rospogrigio/airbnk/releases)
2 | [](https://github.com/custom-components/hacs)
3 | [](https://github.com/rospogrigio)
4 |
5 | # Airbnk lock MQTT-based HomeAssistant integration
6 |
7 | MQTT-based control of Airbnk smart locks that are supported by Airbnk (now WeHere) app.
8 |
9 | Supported devices (using an ESP32 device as a Wifi-to-Bluetooth bridge):
10 | - M300 (tested)
11 | - M500
12 | - M510 (tested)
13 | - M530 (tested)
14 | - M531 (tested)
15 |
16 | # Prerequisites:
17 |
18 | 1. a) Have an ESP32 device with Tasmota Bluetooth firmware installed (see tasmota32-bluetooth.bin here: http://ota.tasmota.com/tasmota32/release/ for release version or here http://ota.tasmota.com/tasmota32/ for development version), **OR**
19 |
20 | b) Have an ESP32 device with @formatBCE's custom firmware (see https://github.com/formatBCE/Airbnk-MQTTOpenGateway)
21 | 2. Set up a MQTT broker (mosquitto or HA add-on: see https://www.home-assistant.io/docs/mqtt/broker/).
22 | 3. Configure the ESP32 to connect to it. In the MQTT Configuration page, take note of the MQTT topic of the ESP32, or set it at your desire.
23 | 4. Determine the MAC address of your lock.
24 |
25 | # Installation:
26 |
27 | Copy the airbnk folder and all of its contents into your Home Assistant's custom_components folder. This is often located inside of your /config folder. If you are running Hass.io, use SAMBA to copy the folder over. If you are running Home Assistant Supervised, the custom_components folder might be located at /usr/share/hassio/homeassistant. It is possible that your custom_components folder does not exist. If that is the case, create the folder in the proper location, and then copy the airbnk folder and all of its contents inside the newly created custom_components folder.
28 |
29 | Alternatively, you can install airbnk through HACS by adding this as a custom repository: press the three dots on the top right -> custom repositories -> type this URL in the Repository field and select Integration in the Category field.
30 |
31 | # Usage:
32 |
33 | The integration can be configured in the following way (YAML config files are NOT supported):
34 |
35 | # Installation using config flow
36 |
37 | Start by going to Configuration - Integration and pressing the "+ ADD INTEGRATION" button to create a new Integration, then select "Airbnk lock (MQTT-based)" in the drop-down menu.
38 |
39 | Follow the instructions: in the first dialog, you just have to type the email used in the Airbnk/WeHere App.
40 |
41 | **_Note: Airbnk cloud allows to have each user logged in only one device. So, if you use the same email used in the Airbnk app, the user on the app will be logged out. As a consequence, it is suggested to create a new user with full permissions with a different email to be used in the HomeAssistant integration._**
42 |
43 | After pressing the "Submit" button, you will receive a verification code via email that has to be typed into the second dialog. After pressing Submit, the integration will download the info of your device(s) from the cloud, including the necessary keys for encrypting the commands for the lock. Then, for each registered lock device you'll be prompted to input its MQTT topic (see Prerequisites, #3) and MAC address (see Prerequisites, #4). It is also possible to skip the device in order to avoid adding it to HA:
44 |
45 | 
46 |
47 | Once you press submit and confirm, the Integration will be added, and the Airbnk locks successfully configured will be created. For each lock, 2 entities are created:
48 | - a Cover entity, that allows to operate the lock
49 | - several Sensor entities, that provides the status of the lock, the battery percentage and other utility info. If the command times out, the status sensor will present the "Failed" status.
50 |
51 | # Note:
52 |
53 | **The locks are added using Cover entities instead of Lock entities**. This choice is due to the fact that Lock entities only provide one available command (Unlock or Lock), depending on the status of the entity. But, since it can be operated also manually, it is impossible to have an actual knowledge of the real status of the lock. Moreover, most users could desire to give double Lock or Unlock commands.
54 |
55 | As a consequence, the Cover entity is used being deemed more suitable, because it allows to have both commands always available.
56 |
57 | # To-do list:
58 |
59 | * Improve Tasmota stability (maybe recompiling the firmware?).
60 | * Introduce the usage of ESPHome instead of Tasmota, and perform benchmarking of the two approaches in order to select the most fast/stable.
61 |
62 | # Thanks to:
63 |
64 | This code is based on @nourmehdi 's great work, in finding a way to sniff the traffic and retrieve the token and decompile the app in order to find out the lock codes generation algorithm. This integration would probably not exist without his pioneering and support.
65 |
66 | Huge contribution also came from @formatBCE, who created the custom firmware for ESP32 devices, and provided great support.
67 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://github.com/rospogrigio/airbnk/releases)
2 | [](https://github.com/custom-components/hacs)
3 | [](https://github.com/rospogrigio)
4 |
5 | # Airbnk lock MQTT-based HomeAssistant integration
6 |
7 | MQTT-based control of Airbnk smart locks that are supported by Airbnk (now WeHere) app.
8 |
9 | Supported devices (using an ESP32 device as a Wifi-to-Bluetooth bridge):
10 | - M300 (tested)
11 | - M500
12 | - M510 (tested)
13 | - M530 (tested)
14 | - M531 (tested)
15 |
16 | # Prerequisites:
17 |
18 | 1. a) Have an ESP32 device with Tasmota Bluetooth firmware installed (see tasmota32-bluetooth.bin here: http://ota.tasmota.com/tasmota32/release/ for release version or here http://ota.tasmota.com/tasmota32/ for development version), **OR**
19 |
20 | b) Have an ESP32 device with @formatBCE's custom firmware (see https://github.com/formatBCE/Airbnk-MQTTOpenGateway)
21 | 2. Set up a MQTT broker (mosquitto or HA add-on: see https://www.home-assistant.io/docs/mqtt/broker/).
22 | 3. Configure the ESP32 to connect to it. In the MQTT Configuration page, take note of the MQTT topic of the ESP32, or set it at your desire.
23 | 4. Determine the MAC address of your lock.
24 |
25 | # Installation:
26 |
27 | Copy the airbnk folder and all of its contents into your Home Assistant's custom_components folder. This is often located inside of your /config folder. If you are running Hass.io, use SAMBA to copy the folder over. If you are running Home Assistant Supervised, the custom_components folder might be located at /usr/share/hassio/homeassistant. It is possible that your custom_components folder does not exist. If that is the case, create the folder in the proper location, and then copy the airbnk folder and all of its contents inside the newly created custom_components folder.
28 |
29 | Alternatively, you can install airbnk through HACS by adding this as a custom repository: press the three dots on the top right -> custom repositories -> type this URL in the Repository field and select Integration in the Category field.
30 |
31 | # Usage:
32 |
33 | The integration can be configured in the following way (YAML config files are NOT supported):
34 |
35 | # Installation using config flow
36 |
37 | Start by going to Configuration - Integration and pressing the "+ ADD INTEGRATION" button to create a new Integration, then select "Airbnk lock (MQTT-based)" in the drop-down menu.
38 |
39 | Follow the instructions: in the first dialog, you just have to type the email used in the Airbnk/WeHere App.
40 |
41 | **_Note: Airbnk cloud allows to have each user logged in only one device. So, if you use the same email used in the Airbnk app, the user on the app will be logged out. As a consequence, it is suggested to create a new user with full permissions with a different email to be used in the HomeAssistant integration._**
42 |
43 | After pressing the "Submit" button, you will receive a verification code via email that has to be typed into the second dialog. After pressing Submit, the integration will download the info of your device(s) from the cloud, including the necessary keys for encrypting the commands for the lock. Then, for each registered lock device you'll be prompted to input its MQTT topic (see Prerequisites, #3) and MAC address (see Prerequisites, #4). It is also possible to skip the device in order to avoid adding it to HA:
44 |
45 | 
46 |
47 | Once you press submit and confirm, the Integration will be added, and the Airbnk locks successfully configured will be created. For each lock, 2 entities are created:
48 | - a Cover entity, that allows to operate the lock
49 | - several Sensor entities, that provides the status of the lock, the battery percentage and other utility info. If the command times out, the status sensor will present the "Failed" status.
50 |
51 | # Note:
52 |
53 | **The locks are added using Cover entities instead of Lock entities**. This choice is due to the fact that Lock entities only provide one available command (Unlock or Lock), depending on the status of the entity. But, since it can be operated also manually, it is impossible to have an actual knowledge of the real status of the lock. Moreover, most users could desire to give double Lock or Unlock commands.
54 |
55 | As a consequence, the Cover entity is used being deemed more suitable, because it allows to have both commands always available.
56 |
57 | # To-do list:
58 |
59 | * Improve Tasmota stability (maybe recompiling the firmware?).
60 | * Introduce the usage of ESPHome instead of Tasmota, and perform benchmarking of the two approaches in order to select the most fast/stable.
61 |
62 | # Thanks to:
63 |
64 | This code is based on @nourmehdi 's great work, in finding a way to sniff the traffic and retrieve the token and decompile the app in order to find out the lock codes generation algorithm. This integration would probably not exist without his pioneering and support.
65 |
66 | Huge contribution also came from @formatBCE, who created the custom firmware for ESP32 devices, and provided great support.
67 |
68 |
69 |
70 |
--------------------------------------------------------------------------------
/custom_components/airbnk_mqtt/__init__.py:
--------------------------------------------------------------------------------
1 | """Platform for the Airbnk MQTT-based integration."""
2 | import asyncio
3 | import datetime
4 | import logging
5 | import voluptuous as vol
6 |
7 | from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
8 | from homeassistant.helpers.service import async_register_admin_service
9 | from homeassistant.core import HomeAssistant
10 | from homeassistant.const import CONF_TOKEN, SERVICE_RELOAD
11 |
12 | from .airbnk_api import AirbnkApi
13 | from .const import (
14 | DOMAIN,
15 | AIRBNK_DEVICES,
16 | CONF_DEVICE_CONFIGS,
17 | CONF_VOLTAGE_THRESHOLDS,
18 | CONF_USERID,
19 | CONF_DEVICE_MQTT_TYPE,
20 | CONF_CUSTOM_MQTT,
21 | )
22 | from .tasmota_device import TasmotaMqttLockDevice
23 | from .custom_device import CustomMqttLockDevice
24 |
25 | _LOGGER = logging.getLogger(__name__)
26 |
27 | ENTRY_IS_SETUP = "airbnk_entry_is_setup"
28 |
29 | PARALLEL_UPDATES = 0
30 |
31 | SERVICE_FORCE_UPDATE = "force_update"
32 | SERVICE_PULL_DEVICES = "pull_devices"
33 |
34 | SIGNAL_DELETE_ENTITY = "airbnk_delete"
35 | SIGNAL_UPDATE_ENTITY = "airbnk_update"
36 |
37 | MIN_TIME_BETWEEN_UPDATES = datetime.timedelta(seconds=15)
38 |
39 | COMPONENT_TYPES = ["binary_sensor", "cover", "sensor"]
40 |
41 | CONFIG_SCHEMA = vol.Schema(vol.All({DOMAIN: vol.Schema({})}), extra=vol.ALLOW_EXTRA)
42 |
43 |
44 | async def async_setup(hass, config):
45 | """Setup the Airbnk component."""
46 |
47 | async def _handle_reload(service):
48 | """Handle reload service call."""
49 | _LOGGER.debug("Service %s.reload called: reloading integration", DOMAIN)
50 |
51 | current_entries = hass.config_entries.async_entries(DOMAIN)
52 |
53 | reload_tasks = [
54 | hass.config_entries.async_reload(entry.entry_id)
55 | for entry in current_entries
56 | ]
57 |
58 | await asyncio.gather(*reload_tasks)
59 | _LOGGER.debug("RELOAD DONE")
60 |
61 | async_register_admin_service(
62 | hass,
63 | DOMAIN,
64 | SERVICE_RELOAD,
65 | _handle_reload,
66 | )
67 |
68 | if DOMAIN not in config:
69 | return True
70 |
71 | conf = config.get(DOMAIN)
72 | if conf is not None:
73 | hass.async_create_task(
74 | hass.config_entries.flow.async_init(
75 | DOMAIN, context={"source": SOURCE_IMPORT}, data=conf
76 | )
77 | )
78 |
79 | return True
80 |
81 |
82 | async def async_migrate_entry(hass, config_entry: ConfigEntry):
83 | """Migrate old entry."""
84 | _LOGGER.debug("Migrating from version %s", config_entry.version)
85 |
86 | if config_entry.version == 1:
87 |
88 | new_data = {**config_entry.data}
89 | device_configs = new_data[CONF_DEVICE_CONFIGS]
90 | for dev_id, dev_config in device_configs.items():
91 | res_json = await AirbnkApi.getVoltageCfg(
92 | hass,
93 | new_data[CONF_USERID],
94 | new_data[CONF_TOKEN],
95 | dev_config["deviceType"],
96 | dev_config["hardwareVersion"],
97 | )
98 | if res_json is None:
99 | _LOGGER.error("Migration from version %s FAILED", config_entry.version)
100 | return False
101 | _LOGGER.debug("Retrieved voltage config: %s", res_json)
102 |
103 | dev_config[CONF_VOLTAGE_THRESHOLDS] = []
104 | for i in range(1, 5):
105 | dev_config[CONF_VOLTAGE_THRESHOLDS].append(
106 | float(res_json["fvoltage" + str(i)])
107 | )
108 |
109 | config_entry.version = 2
110 | hass.config_entries.async_update_entry(config_entry, data=new_data)
111 |
112 | _LOGGER.info("Migration to version %s successful", config_entry.version)
113 |
114 | return True
115 |
116 |
117 | async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
118 | """Establish connection with Airbnk."""
119 |
120 | device_configs = entry.data[CONF_DEVICE_CONFIGS]
121 | entry.add_update_listener(async_options_updated)
122 | _LOGGER.debug("DEVICES ARE %s", device_configs)
123 | lock_devices = {}
124 | for dev_id, dev_config in device_configs.items():
125 | if dev_config[CONF_DEVICE_MQTT_TYPE] == CONF_CUSTOM_MQTT:
126 | lock_devices[dev_id] = CustomMqttLockDevice(hass, dev_config, entry.options)
127 | else:
128 | lock_devices[dev_id] = TasmotaMqttLockDevice(
129 | hass, dev_config, entry.options
130 | )
131 | await lock_devices[dev_id].mqtt_subscribe()
132 |
133 | hass.data[DOMAIN] = {AIRBNK_DEVICES: lock_devices}
134 |
135 | for component in COMPONENT_TYPES:
136 | await hass.config_entries.async_forward_entry_setups(entry, [component])
137 | return True
138 |
139 |
140 | async def async_options_updated(hass, entry):
141 | """Triggered by config entry options updates."""
142 | for dev_id, device in hass.data[DOMAIN][AIRBNK_DEVICES].items():
143 | device.set_options(entry.options)
144 |
145 |
146 | async def async_unload_entry(hass, config_entry):
147 | """Unload a config entry."""
148 | _LOGGER.debug("Unloading %s %s", config_entry.entry_id, config_entry.data)
149 |
150 | # Create a list of coroutines to be awaited
151 | tasks = [
152 | hass.config_entries.async_forward_entry_unload(config_entry, component)
153 | for component in COMPONENT_TYPES
154 | ]
155 |
156 | # Await each coroutine individually
157 | await asyncio.gather(*tasks)
158 |
159 | for dev_id, device in hass.data[DOMAIN][AIRBNK_DEVICES].items():
160 | _LOGGER.debug("Unsubscribing %s", dev_id)
161 | await device.mqtt_unsubscribe()
162 |
163 | hass.data[DOMAIN].pop(AIRBNK_DEVICES)
164 | _LOGGER.debug("...done")
165 | return True
166 |
167 |
168 | async def airbnk_api_setup(hass, host, key, uuid, password):
169 | """Create a Airbnk instance only once."""
170 | return
171 |
--------------------------------------------------------------------------------
/custom_components/airbnk_mqtt/codes_generator.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 | import base64
3 | import binascii
4 | import hashlib
5 | import logging
6 | import time
7 |
8 | from cryptography.hazmat.backends import default_backend
9 | from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
10 |
11 | _LOGGER = logging.getLogger(__name__)
12 |
13 | MAX_NORECEIVE_TIME = 30
14 |
15 |
16 | class AESCipher:
17 | """Cipher module for AES decryption."""
18 |
19 | def __init__(self, key):
20 | """Initialize a new AESCipher."""
21 | self.block_size = 16
22 | self.cipher = Cipher(algorithms.AES(key), modes.ECB(), default_backend())
23 |
24 | def encrypt(self, raw, use_base64=True):
25 | """Encrypt data to be sent to device."""
26 | encryptor = self.cipher.encryptor()
27 | crypted_text = encryptor.update(self._pad(raw)) + encryptor.finalize()
28 | return base64.b64encode(crypted_text) if use_base64 else crypted_text
29 |
30 | def decrypt(self, enc, use_base64=True):
31 | """Decrypt data from device."""
32 | if use_base64:
33 | enc = base64.b64decode(enc)
34 |
35 | decryptor = self.cipher.decryptor()
36 | return self._unpad(decryptor.update(enc) + decryptor.finalize())
37 |
38 | def _pad(self, data):
39 | padnum = self.block_size - len(data) % self.block_size
40 | return data + padnum * chr(padnum).encode()
41 |
42 | @staticmethod
43 | def _unpad(data):
44 | return data[: -ord(data[len(data) - 1 :])]
45 |
46 |
47 | def XOR64Buffer(arr, value):
48 | for i in range(0, 64):
49 | arr[i] ^= value
50 | return arr
51 |
52 |
53 | def generateWorkingKey(arr, i):
54 | arr2 = bytearray(72)
55 | arr2[0 : len(arr)] = arr
56 | arr2 = XOR64Buffer(arr2, 0x36)
57 | arr2[71] = i & 0xFF
58 | i = i >> 8
59 | arr2[70] = i & 0xFF
60 | i = i >> 8
61 | arr2[69] = i & 0xFF
62 | i = i >> 8
63 | arr2[68] = i & 0xFF
64 | arr2sha1 = hashlib.sha1(arr2).digest()
65 | arr3 = bytearray(84)
66 | arr3[0 : len(arr)] = arr
67 | arr3 = XOR64Buffer(arr3, 0x5C)
68 | arr3[64:84] = arr2sha1
69 | arr3sha1 = hashlib.sha1(arr3).digest()
70 | return arr3sha1
71 |
72 |
73 | def generatePswV2(arr):
74 | arr2 = bytearray(8)
75 | for i in range(0, 4):
76 | b = arr[i + 16]
77 | i2 = i * 2
78 | arr2[i2] = arr[(b >> 4) & 15]
79 | arr2[i2 + 1] = arr[b & 15]
80 | return arr2
81 |
82 |
83 | def generateSignatureV2(key, i, arr):
84 | lenArr = len(arr)
85 | arr2 = bytearray(lenArr + 68)
86 | arr2[0:20] = key[0:20]
87 | arr2 = XOR64Buffer(arr2, 0x36)
88 | arr2[64 : 64 + lenArr] = arr
89 | arr2[lenArr + 67] = i & 0xFF
90 | i = i >> 8
91 | arr2[lenArr + 66] = i & 0xFF
92 | i = i >> 8
93 | arr2[lenArr + 65] = i & 0xFF
94 | i = i >> 8
95 | arr2[lenArr + 64] = i & 0xFF
96 | arr2sha1 = hashlib.sha1(arr2).digest()
97 | arr3 = bytearray(84)
98 | arr3[0:20] = key[0:20]
99 | arr3 = XOR64Buffer(arr3, 0x5C)
100 | arr3[64 : 64 + len(arr2sha1)] = arr2sha1
101 | arr3sha1 = hashlib.sha1(arr3).digest()
102 | return generatePswV2(arr3sha1)
103 |
104 |
105 | def getCheckSum(arr, i1, i2):
106 | c = 0
107 | for i in range(i1, i2):
108 | c = c + arr[i]
109 | return c & 0xFF
110 |
111 |
112 | class AirbnkCodesGenerator:
113 | manufactureKey = ""
114 | bindingkey = ""
115 | systemTime = 0
116 |
117 | def __init__(self):
118 | return
119 |
120 | def generateOperationCode(self, lock_dir, curr_lockEvents):
121 | if lock_dir != 1 and lock_dir != 2:
122 | return None
123 |
124 | self.systemTime = int(round(time.time()))
125 | # self.systemTime = 1637590376
126 | opCode = self.makePackageV3(lock_dir, self.systemTime, curr_lockEvents)
127 | _LOGGER.debug("OperationCode for dir %s is %s", lock_dir, opCode)
128 |
129 | return opCode
130 |
131 | def makePackageV3(self, lockOp, tStamp, curr_lockEvents):
132 | code = bytearray(36)
133 | code[0] = 0xAA
134 | code[1] = 0x10
135 | code[2] = 0x1A
136 | code[3] = code[4] = 3
137 | code[5] = 16 + lockOp
138 | code[8] = 1
139 | code[12] = tStamp & 0xFF
140 | tStamp = tStamp >> 8
141 | code[11] = tStamp & 0xFF
142 | tStamp = tStamp >> 8
143 | code[10] = tStamp & 0xFF
144 | tStamp = tStamp >> 8
145 | code[9] = tStamp & 0xFF
146 | toEncrypt = code[4:18]
147 | manKey = self.manufacturerKey[0:16]
148 | encrypted = AESCipher(manKey).encrypt(toEncrypt, False)
149 | code[4:20] = encrypted
150 | workingKey = generateWorkingKey(self.bindingKey, 0)
151 | signature = generateSignatureV2(workingKey, curr_lockEvents, code[3:20])
152 | # print("Working Key is {} {} {}".format(workingKey, lockEvents, code[3:20]))
153 | # print("Signature is {}".format(signature))
154 | code[20 : 20 + len(signature)] = signature
155 | code[20 + len(signature)] = getCheckSum(code, 3, 28)
156 | return binascii.hexlify(code).upper()
157 | # return code
158 |
159 | def decryptKeys(self, newSnInfo, appKey):
160 | decr_json = {}
161 | dec = base64.b64decode(newSnInfo)
162 | sstr2 = dec[: len(dec) - 10]
163 | key = appKey[: len(appKey) - 4]
164 | dec = AESCipher(bytes(key, "utf-8")).decrypt(sstr2, False)
165 | lockSn = dec[0:16].decode("utf-8").rstrip("\x00")
166 | decr_json["lockSn"] = lockSn
167 | decr_json["lockModel"] = dec[80:88].decode("utf-8").rstrip("\x00")
168 | manKeyEncrypted = dec[16:48]
169 | bindKeyEncrypted = dec[48:80]
170 | toHash = bytes(lockSn + appKey, "utf-8")
171 | hash_object = hashlib.sha1()
172 | hash_object.update(toHash)
173 | jdkSHA1 = hash_object.hexdigest()
174 | key2 = bytes.fromhex(jdkSHA1[0:32])
175 | self.manufacturerKey = AESCipher(key2).decrypt(manKeyEncrypted, False)
176 | self.bindingKey = AESCipher(key2).decrypt(bindKeyEncrypted, False)
177 | return decr_json
178 |
--------------------------------------------------------------------------------
/custom_components/airbnk_mqtt/airbnk_api.py:
--------------------------------------------------------------------------------
1 | """Platform for the Airbnk cloud-based integration."""
2 | import datetime
3 | import functools
4 | import logging
5 | import requests
6 |
7 | from homeassistant.util import Throttle
8 | from homeassistant.const import CONF_TOKEN
9 |
10 | from .const import CONF_MQTT_TOPIC, CONF_MAC_ADDRESS
11 |
12 | _LOGGER = logging.getLogger(__name__)
13 |
14 | AIRBNK_CLOUD_URL = "https://wehereapi.seamooncloud.com"
15 | AIRBNK_LANGUAGE = "2"
16 | AIRBNK_VERSION = "A_FD_1.8.0"
17 | MIN_TIME_BETWEEN_UPDATES = datetime.timedelta(seconds=15)
18 |
19 | AIRBNK_HEADERS = {"user-agent": "okhttp/3.12.0", "Accept-Encoding": "gzip, deflate"}
20 |
21 |
22 | class AirbnkApi:
23 | """Airbnk API."""
24 |
25 | def __init__(self, hass, entry_data):
26 | """Initialize a new Airbnk API."""
27 | _LOGGER.info("Initialing Airbnk API...")
28 | self.hass = hass
29 | self._config_data = entry_data
30 | self.token = None
31 | self.devices = {}
32 |
33 | _LOGGER.debug("Initialing Airbnk API (%s)", entry_data[CONF_TOKEN])
34 |
35 | # if entry is not None:
36 | # self.token = entry_data[CONF_TOKEN].copy()
37 |
38 | _LOGGER.info("Airbnk API initialized.")
39 |
40 | @staticmethod
41 | async def requestVerificationCode(hass, email):
42 | """Attempt to refresh the Access Token."""
43 | url = AIRBNK_CLOUD_URL + "/api/lock/sms?loginAcct=" + email
44 | url += "&language=" + AIRBNK_LANGUAGE + "&version=" + AIRBNK_VERSION
45 | url += "&mark=10&userId="
46 |
47 | try:
48 | func = functools.partial(requests.post, url, headers=AIRBNK_HEADERS)
49 | res = await hass.async_add_executor_job(func)
50 | except Exception as e:
51 | _LOGGER.error("CALL FAILED: %s", e)
52 |
53 | if res.status_code != 200:
54 | _LOGGER.error(
55 | "Verification code request failed (%s): %s", res.status_code, res.text
56 | )
57 | return False
58 |
59 | _LOGGER.info("Verification code request succeeded.")
60 | return True
61 |
62 | @staticmethod
63 | async def retrieveAccessToken(hass, email, code):
64 | _LOGGER.info("Retrieving new Token...")
65 | url = AIRBNK_CLOUD_URL + "/api/lock/loginByAuthcode?loginAcct=" + email
66 | url += "&authCode=" + code + "&systemCode=Android"
67 | url += "&language=" + AIRBNK_LANGUAGE + "&version=" + AIRBNK_VERSION
68 | url += "&deviceID=123456789012345&mark=1"
69 | _LOGGER.info("Retrieving: %s", url)
70 |
71 | try:
72 | func = functools.partial(requests.get, url, headers=AIRBNK_HEADERS)
73 | res = await hass.async_add_executor_job(func)
74 | except Exception as e:
75 | _LOGGER.error("CALL FAILED: %s", e)
76 |
77 | if res.status_code != 200:
78 | _LOGGER.error("Token retrieval failed (%s): %s", res.status_code, res.text)
79 | return None
80 |
81 | res_json = res.json()
82 |
83 | if res_json["code"] != 200:
84 | _LOGGER.error(
85 | "Token retrieval failed2 (%s): %s", res_json["code"], res.text
86 | )
87 | return None
88 |
89 | _LOGGER.info("Token retrieval succeeded.")
90 | return res_json
91 |
92 | @staticmethod
93 | async def getCloudDevices(hass, userId, token):
94 | """Get array of AirbnkDevice objects and get their data."""
95 | _LOGGER.debug("calling getCloudDevices()")
96 |
97 | url = AIRBNK_CLOUD_URL + "/api/v2/lock/getAllDevicesNew"
98 | url += "?language=" + AIRBNK_LANGUAGE + "&userId=" + userId
99 | url += "&version=" + AIRBNK_VERSION + "&token=" + token
100 | _LOGGER.info("Retrieving: %s", url)
101 |
102 | try:
103 | func = functools.partial(requests.get, url, headers=AIRBNK_HEADERS)
104 | res = await hass.async_add_executor_job(func)
105 | except Exception as e:
106 | _LOGGER.error("GCD CALL FAILED: %s", e)
107 |
108 | if res.status_code != 200:
109 | _LOGGER.error("GCD failed (%s): %s", res.status_code, res.text)
110 | return None
111 |
112 | json_data = res.json()
113 | if json_data["code"] != 200:
114 | _LOGGER.error("GCD failed2 (%s): %s", json_data["code"], res.text)
115 | return None
116 |
117 | _LOGGER.debug("GetCloudDevices succeeded (%s): %s", res.status_code, res.text)
118 |
119 | res = {}
120 | deviceConfigs = {}
121 | for dev_data in json_data["data"] or []:
122 | if dev_data["deviceType"][0] in ["W", "F"]:
123 | _LOGGER.info("Device '%s' is filtered out", dev_data["deviceName"])
124 | else:
125 | res[dev_data["sn"]] = dev_data["deviceName"]
126 | dev_data[CONF_MQTT_TOPIC] = "tasmota_doorlock"
127 | dev_data[CONF_MAC_ADDRESS] = "5893D8424E3A"
128 | deviceConfigs[dev_data["sn"]] = dev_data
129 | return deviceConfigs
130 |
131 | @staticmethod
132 | async def getVoltageCfg(hass, userId, token, lock_model, hw_version):
133 | """Get array of AirbnkDevice objects and get their data."""
134 | _LOGGER.debug("calling getVoltageCfg()")
135 |
136 | url = AIRBNK_CLOUD_URL + "/api/lock/getAllInfo1"
137 | url += "?language=" + AIRBNK_LANGUAGE + "&userId=" + userId
138 | url += "&version=" + AIRBNK_VERSION + "&token=" + token
139 | _LOGGER.info("Retrieving: %s", url)
140 |
141 | try:
142 | func = functools.partial(requests.get, url, headers=AIRBNK_HEADERS)
143 | res = await hass.async_add_executor_job(func)
144 | except Exception as e:
145 | _LOGGER.error("GVC CALL FAILED: %s", e)
146 | return None
147 |
148 | if res.status_code != 200:
149 | _LOGGER.error("GVC failed (%s): %s", res.status_code, res.text)
150 | return None
151 |
152 | json_data = res.json()
153 | if json_data["code"] != 200:
154 | _LOGGER.error("GVC failed2 (%s): %s", json_data["code"], res.text)
155 | return None
156 |
157 | _LOGGER.debug("getVoltageCfg succeeded (%s)", res.status_code)
158 |
159 | if "voltageCfg" not in json_data["data"]:
160 | return None
161 | for volt_cfg in json_data["data"]["voltageCfg"]:
162 | if (
163 | volt_cfg["fdeviceType"] == lock_model
164 | and volt_cfg["fhardwareVersion"] == hw_version
165 | ):
166 | return volt_cfg
167 |
168 | return None
169 |
170 | @Throttle(MIN_TIME_BETWEEN_UPDATES)
171 | async def async_update(self, **kwargs):
172 | """Pull the latest data from Airbnk."""
173 | _LOGGER.debug("API UPDATE")
174 |
--------------------------------------------------------------------------------
/custom_components/airbnk_mqtt/config_flow.py:
--------------------------------------------------------------------------------
1 | """Config flow for the Airbnk platform."""
2 | import logging
3 | import voluptuous as vol
4 |
5 | from homeassistant import config_entries
6 | from homeassistant.const import CONF_EMAIL, CONF_CODE, CONF_TOKEN
7 | from homeassistant.core import callback
8 |
9 | from .airbnk_api import AirbnkApi
10 | from .const import (
11 | DOMAIN,
12 | CONF_USERID,
13 | CONF_MQTT_TOPIC,
14 | CONF_MAC_ADDRESS,
15 | CONF_DEVICE_CONFIGS,
16 | CONF_VOLTAGE_THRESHOLDS,
17 | CONF_DEVICE_MQTT_TYPE,
18 | CONF_MQTT_TYPES,
19 | CONF_RETRIES_NUM,
20 | DEFAULT_RETRIES_NUM,
21 | )
22 |
23 | _LOGGER = logging.getLogger(__name__)
24 |
25 | SKIP_DEVICE = "skip_device"
26 |
27 | STEP1_SCHEMA = vol.Schema({vol.Required(CONF_EMAIL): str})
28 |
29 | STEP2_SCHEMA = vol.Schema({vol.Required(CONF_EMAIL): str, vol.Required(CONF_CODE): str})
30 |
31 | STEP3_SCHEMA = vol.Schema(
32 | {
33 | vol.Required(CONF_DEVICE_MQTT_TYPE, default=CONF_MQTT_TYPES[0]): vol.In(
34 | CONF_MQTT_TYPES
35 | ),
36 | vol.Required(CONF_MAC_ADDRESS): str,
37 | vol.Required(CONF_MQTT_TOPIC): str,
38 | vol.Required(SKIP_DEVICE, default=False): bool,
39 | }
40 | )
41 |
42 |
43 | def schema_defaults(schema, dps_list=None, **defaults):
44 | """Create a new schema with default values filled in."""
45 | copy = schema.extend({})
46 | for field, field_type in copy.schema.items():
47 | if field.schema in defaults:
48 | field.default = vol.default_factory(defaults[field])
49 | return copy
50 |
51 |
52 | @config_entries.HANDLERS.register(DOMAIN)
53 | class FlowHandler(config_entries.ConfigFlow):
54 | """Handle a config flow."""
55 |
56 | VERSION = 2
57 | CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL
58 |
59 | def __init__(self):
60 | """Initialize the Airbnk config flow."""
61 | self.host = None
62 | self.entry_data = {}
63 | self.entry_data[CONF_DEVICE_CONFIGS] = {}
64 | self.device_configs = {}
65 | self.device_index = 0
66 |
67 | @staticmethod
68 | @callback
69 | def async_get_options_flow(config_entry):
70 | """Get the options flow for this handler."""
71 | return AirbnkMqttOptionsFlowHandler(config_entry)
72 |
73 | async def _create_entry(self):
74 | """Register new entry."""
75 | # if not self.unique_id:
76 | # await self.async_set_unique_id(password)
77 | # self._abort_if_unique_id_configured()
78 | if self._async_current_entries():
79 | return self.async_abort(reason="already_configured")
80 |
81 | await self.async_set_unique_id("Airbnk_" + self.entry_data[CONF_USERID])
82 |
83 | return self.async_create_entry(
84 | title="Airbnk",
85 | data={
86 | CONF_EMAIL: self.entry_data[CONF_EMAIL],
87 | CONF_TOKEN: self.entry_data[CONF_TOKEN],
88 | CONF_USERID: self.entry_data[CONF_USERID],
89 | CONF_DEVICE_CONFIGS: self.entry_data[CONF_DEVICE_CONFIGS],
90 | },
91 | )
92 |
93 | async def async_step_init(self, user_input=None):
94 | """User initiated config flow."""
95 | if user_input is None:
96 | return self.async_show_form(step_id="user", data_schema=STEP1_SCHEMA)
97 | return await self.async_step_verify(user_input)
98 |
99 | async def async_step_user(self, user_input=None):
100 | """User initiated config flow."""
101 | if user_input is None:
102 | return self.async_show_form(step_id="user", data_schema=STEP1_SCHEMA)
103 | return await self.async_step_verify(user_input)
104 |
105 | async def async_step_verify(self, user_input=None):
106 | """Config flow: second step."""
107 | if user_input.get(CONF_CODE) is None:
108 | email = user_input.get(CONF_EMAIL)
109 | res = await AirbnkApi.requestVerificationCode(self.hass, email)
110 | if res is False:
111 | return self.async_abort(reason="code_request_failed")
112 |
113 | defaults = {}
114 | defaults.update(user_input or {})
115 | return self.async_show_form(
116 | step_id="verify", data_schema=schema_defaults(STEP2_SCHEMA, **defaults)
117 | )
118 | return await self.async_get_device_configs(
119 | user_input.get(CONF_EMAIL), user_input.get(CONF_CODE)
120 | )
121 |
122 | async def async_get_device_configs(self, email, code):
123 | """Create device."""
124 | res_json = await AirbnkApi.retrieveAccessToken(self.hass, email, code)
125 |
126 | if res_json is None:
127 | return self.async_abort(reason="token_retrieval_failed")
128 | _LOGGER.info("Token retrieval data: %s", res_json)
129 |
130 | self.entry_data[CONF_EMAIL] = res_json["data"][CONF_EMAIL]
131 | self.entry_data[CONF_USERID] = res_json["data"][CONF_USERID]
132 | self.entry_data[CONF_TOKEN] = res_json["data"][CONF_TOKEN]
133 | _LOGGER.debug(
134 | "Done!: %s %s %s",
135 | self.entry_data[CONF_USERID],
136 | email,
137 | self.entry_data[CONF_TOKEN],
138 | )
139 |
140 | self.device_configs = await AirbnkApi.getCloudDevices(
141 | self.hass, self.entry_data[CONF_USERID], self.entry_data[CONF_TOKEN]
142 | )
143 | if len(self.device_configs) == 0:
144 | return await self._create_entry()
145 | return await self.async_step_configure_device()
146 |
147 | async def async_step_configure_device(self, user_input=None):
148 | # Config flow: third step.
149 | config_key = list(self.device_configs.keys())[self.device_index]
150 | _LOGGER.debug("Configuring %s", config_key)
151 |
152 | if user_input is not None:
153 | return await self.async_step_messagebox(user_input)
154 |
155 | dev_config = self.device_configs[config_key]
156 | defaults = {}
157 | defaults.update(user_input or {})
158 | return self.async_show_form(
159 | step_id="configure_device",
160 | data_schema=schema_defaults(STEP3_SCHEMA, **defaults),
161 | errors={},
162 | description_placeholders={
163 | "model": dev_config["deviceType"],
164 | "sn": dev_config["sn"],
165 | },
166 | )
167 |
168 | async def async_step_messagebox(self, user_input=None):
169 | # Config flow: third step.
170 | config_key = list(self.device_configs.keys())[self.device_index]
171 | _LOGGER.debug("messagebox for device %s", config_key)
172 |
173 | if CONF_MAC_ADDRESS in user_input:
174 | dev_config = self.device_configs[config_key]
175 | action = "Skipped"
176 | if user_input.get(SKIP_DEVICE) is False:
177 | dev_config[CONF_DEVICE_MQTT_TYPE] = user_input.get(
178 | CONF_DEVICE_MQTT_TYPE
179 | )
180 | dev_config[CONF_MAC_ADDRESS] = (
181 | user_input.get(CONF_MAC_ADDRESS).replace(":", "").upper()
182 | )
183 | dev_config[CONF_MQTT_TOPIC] = user_input.get(CONF_MQTT_TOPIC)
184 |
185 | res_json = await AirbnkApi.getVoltageCfg(
186 | self.hass,
187 | self.entry_data[CONF_USERID],
188 | self.entry_data[CONF_TOKEN],
189 | dev_config["deviceType"],
190 | dev_config["hardwareVersion"],
191 | )
192 | voltage_cfg = []
193 | if res_json is None:
194 | _LOGGER.error(
195 | "Failed to retrieve voltage config for device %s", config_key
196 | )
197 | voltage_cfg = [0, 0, 0, 0]
198 | else:
199 | _LOGGER.debug("Retrieved voltage config: %s", res_json)
200 | for i in range(1, 5):
201 | voltage_cfg.append(float(res_json["fvoltage" + str(i)]))
202 |
203 | dev_config[CONF_VOLTAGE_THRESHOLDS] = voltage_cfg
204 | self.entry_data[CONF_DEVICE_CONFIGS][config_key] = dev_config
205 | action = "Added"
206 |
207 | return self.async_show_form(
208 | step_id="messagebox",
209 | data_schema=None,
210 | errors={},
211 | description_placeholders={
212 | "model": dev_config["deviceType"],
213 | "sn": dev_config["sn"],
214 | "action": action,
215 | },
216 | )
217 | self.device_index += 1
218 | if self.device_index < len(self.device_configs):
219 | return await self.async_step_configure_device()
220 | return await self._create_entry()
221 |
222 | async def async_step_import(self, user_input):
223 | """Import a config entry from YAML."""
224 | _LOGGER.error("This integration does not support configuration via YAML file.")
225 |
226 |
227 | class AirbnkMqttOptionsFlowHandler(config_entries.OptionsFlow):
228 | """Handle Transmission client options."""
229 |
230 | def __init__(self, config_entry):
231 | """Initialize Transmission options flow."""
232 | self.config_entry = config_entry
233 |
234 | async def async_step_init(self, user_input=None):
235 | """Manage the Transmission options."""
236 | if user_input is not None:
237 | _LOGGER.debug("New options: %s", user_input)
238 | return self.async_create_entry(title="", data=user_input)
239 |
240 | options = {
241 | vol.Optional(
242 | CONF_RETRIES_NUM,
243 | default=self.config_entry.options.get(
244 | CONF_RETRIES_NUM, DEFAULT_RETRIES_NUM
245 | ),
246 | ): vol.All(vol.Coerce(int), vol.Range(min=0, max=10)),
247 | }
248 |
249 | return self.async_show_form(step_id="init", data_schema=vol.Schema(options))
250 |
--------------------------------------------------------------------------------
/tools/generate_payloads.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | #
3 | # TuyaPower (Tuya Power Stats)
4 | # Power Probe - Wattage of smart devices - JSON Output
5 |
6 | import base64
7 | import binascii
8 | import hashlib
9 | import json
10 | import logging
11 | import socket
12 | import time
13 | import binascii
14 | import struct
15 | import sys
16 | from operator import xor
17 | from collections import namedtuple
18 | from contextlib import contextmanager
19 |
20 | from cryptography.hazmat.backends import default_backend
21 | from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
22 |
23 | _LOGGER = logging.getLogger("test")
24 | _LOGGER.setLevel(level=logging.DEBUG) # Debug hack!
25 |
26 | from Crypto.Cipher import AES
27 | import base64
28 | import re
29 |
30 | # Paste here the values you find in the logs after enabling debug ( "custom_components.airbnk: debug" in configuration.yaml ):
31 | newSnInfo = 'HTWsm....yTj2w=='
32 | appKey = "..."
33 |
34 | # Paste here the log advertisement value you can get from nRF Connect:
35 | lockAdv = b'0201...1BFFBABA...'
36 | # 0 1 2 3 4 5 6 7 8 9 101112131415161718192021222324252627
37 |
38 |
39 | class AESCipher:
40 | """Cipher module for Tuya communication."""
41 |
42 | def __init__(self, key):
43 | """Initialize a new AESCipher."""
44 | self.block_size = 16
45 | self.cipher = Cipher(algorithms.AES(key), modes.ECB(), default_backend())
46 |
47 | def encrypt(self, raw, use_base64=True):
48 | """Encrypt data to be sent to device."""
49 | encryptor = self.cipher.encryptor()
50 | crypted_text = encryptor.update(self._pad(raw)) + encryptor.finalize()
51 | return base64.b64encode(crypted_text) if use_base64 else crypted_text
52 |
53 | def decrypt(self, enc, use_base64=True):
54 | """Decrypt data from device."""
55 | if use_base64:
56 | enc = base64.b64decode(enc)
57 |
58 | decryptor = self.cipher.decryptor()
59 | return self._unpad(decryptor.update(enc) + decryptor.finalize())
60 |
61 | def _pad(self, data):
62 | padnum = self.block_size - len(data) % self.block_size
63 | return data + padnum * chr(padnum).encode()
64 |
65 | @staticmethod
66 | def _unpad(data):
67 | return data[: -ord(data[len(data) - 1 :])]
68 |
69 |
70 |
71 | def _decode_payload(payload):
72 | _LOGGER.debug("decode payload=%r", payload)
73 |
74 | version=3.3
75 |
76 | if payload.startswith(PROTOCOL_VERSION_BYTES_31):
77 | payload = payload[len(PROTOCOL_VERSION_BYTES_31) :] # remove version header
78 | # remove (what I'm guessing, but not confirmed is) 16-bytes of MD5
79 | # hexdigest of payload
80 | payload = cipher.decrypt(payload[16:])
81 | elif version == 3.3:
82 | if payload.startswith(
83 | PROTOCOL_VERSION_BYTES_33
84 | ):
85 | payload = payload[len(PROTOCOL_33_HEADER) :]
86 | print("todecrypt payload [{}]".format(payload))
87 | payload = cipher.decrypt(payload, False)
88 | print("decrypted payload [{}]".format(payload))
89 | _LOGGER.debug("decrypted payload=%r", payload)
90 |
91 | # if "data unvalid" in payload:
92 | # self.dev_type = "type_0d"
93 | # _LOGGER.debug(
94 | # "'data unvalid' error detected: switching to dev_type %r",
95 | # self.dev_type,
96 | # )
97 | # return None
98 | elif not payload.startswith(b"{"):
99 | raise Exception(f"Unexpected payload={payload}")
100 |
101 | if not isinstance(payload, str):
102 | payload = payload.decode()
103 | _LOGGER.debug("decrypted result=%r", payload)
104 | return json.loads(payload)
105 |
106 | #def str2HexStr(String str):
107 | # char[] charArray = "0123456789ABCdef".toCharArray();
108 | # StringBuilder sb = new StringBuilder("");
109 | # byte[] bytes = str.getBytes();
110 | # for (int i = 0; i < bytes.length; i++) {
111 | # sb.append(charArray[(bytes[i] & 240) >> 4]);
112 | # sb.append(charArray[bytes[i] & 15]);
113 | # }
114 | # return sb.toString().trim();
115 | # }
116 |
117 | def dispose(str, str2):
118 | dec = base64.b64decode(str)
119 | #print("PRE {} {}".format(dec, len(dec)))
120 | #bf1 = binascii.hexlify(dec) # bytesToHexFun1(dec)
121 | sstr = dec[-10:]
122 | sstr2 = dec[:len(dec)-10]
123 | # print("POST {} {}".format(sstr2, len(sstr2)))
124 | key = str2[:len(str2)-4]
125 | # print("KEY {} {}".format(key, len(key)))
126 | dec = AESCipher(bytes(key,'utf-8')).decrypt(sstr2, False)
127 | # print("DEC {} {}".format(dec, len(dec)))
128 | json = {}
129 | lockSn = dec[0:16].decode('utf-8').rstrip('\x00')
130 | lockType = dec[80:88].decode('utf-8').rstrip('\x00')
131 | manKeyEncrypted = dec[16:48]
132 | bindKeyEncrypted = dec[48:80]
133 | # print("SN {} {}".format(lockSn, lockType))
134 | # print("ENC {} {}".format(manKeyEncrypted, bindKeyEncrypted))
135 | #toHash = bytearray("".join("{:02x}".format(ord(c)) for c in (lockSn+str2)),'utf-8')
136 | toHash = bytes(lockSn+str2, 'utf-8')
137 | hash_object = hashlib.sha1()
138 | hash_object.update(toHash)
139 | jdkSHA1 = hash_object.hexdigest()
140 | key2 = bytes.fromhex(jdkSHA1[0:32])
141 | # print("SHA1 {} -> {}".format(toHash, key2))
142 | manKey = AESCipher(key2).decrypt(manKeyEncrypted, False)
143 | # print("DEC MANKEY {}".format(manKey))
144 | bindKey = AESCipher(key2).decrypt(bindKeyEncrypted, False)
145 | # print("DEC BINDKEY {}".format(bindKey))
146 | #jdkSHA1 = hashlib.sha1(str(toHash).encode('utf-8')).digest()
147 | return { "lockSn": lockSn, "lockType": lockType, "manufacturerKey": manKey, "bindingKey": bindKey, }
148 |
149 | def XOR64Buffer(arr, value):
150 | for i in range(0,64):
151 | arr[i] ^= value
152 | return arr
153 |
154 | def generateWorkingKey(arr, i):
155 | arr2 = bytearray(72)
156 | arr2[0:len(arr)] = arr
157 | # print("ARR IS {}".format(arr))
158 | arr2 = XOR64Buffer(arr2, 0x36)
159 | arr2[71] = (i & 0xFF)
160 | i = i >> 8
161 | arr2[70] = (i & 0xFF)
162 | i = i >> 8
163 | arr2[69] = (i & 0xFF)
164 | i = i >> 8
165 | arr2[68] = (i & 0xFF)
166 | # print("ARR2 IS {} {}".format(arr2,len(arr2)))
167 | arr2sha1 = hashlib.sha1(arr2).digest()
168 | # print("ARR2SHA IS {} {}".format(arr2sha1,len(arr2sha1)))
169 | arr3 = bytearray(84)
170 | arr3[0:len(arr)] = arr
171 | arr3 = XOR64Buffer(arr3, 0x5c)
172 | arr3[64:84] = arr2sha1
173 | # print("ARR3 IS {} {}".format(arr3,len(arr3)))
174 | arr3sha1 = hashlib.sha1(arr3).digest()
175 | # print("ARR3SHA IS {} {}".format(arr3sha1,len(arr3sha1)))
176 | return arr3sha1
177 |
178 | def generatePswV2(arr):
179 | arr2 = bytearray(8)
180 | for i in range(0, 4):
181 | b = arr[i+16]
182 | i2 = i * 2
183 | arr2[i2] = arr[(b >> 4) & 15]
184 | arr2[i2 + 1] = arr[b & 15]
185 | return arr2
186 |
187 |
188 | def generateSignatureV2(key, i, arr):
189 | #print("ARR IS {} {}".format(arr,len(arr)))
190 | lenArr = len(arr)
191 | arr2 = bytearray(lenArr+68)
192 | arr2[0:20] = key[0:20]
193 | arr2 = XOR64Buffer(arr2, 0x36)
194 | arr2[64:64+lenArr] = arr
195 | arr2[lenArr+67] = (i & 0xFF)
196 | i = i >> 8
197 | arr2[lenArr+66] = (i & 0xFF)
198 | i = i >> 8
199 | arr2[lenArr+65] = (i & 0xFF)
200 | i = i >> 8
201 | arr2[lenArr+64] = (i & 0xFF)
202 | # print("ARR2 IS {} {}".format(arr2,len(arr2)))
203 | arr2sha1 = hashlib.sha1(arr2).digest()
204 | # print("ARR2SHA IS {} {}".format(arr2sha1,len(arr2sha1)))
205 | arr3 = bytearray(84)
206 | arr3[0:20] = key[0:20]
207 | arr3 = XOR64Buffer(arr3, 0x5c)
208 | arr3[64:64+len(arr2sha1)] = arr2sha1
209 | # print("ARR3 IS {} {}".format(arr3,len(arr3)))
210 | arr3sha1 = hashlib.sha1(arr3).digest()
211 | # print("ARR3SHA IS {} {}".format(arr3sha1,len(arr3sha1)))
212 | return generatePswV2(arr3sha1)
213 |
214 | def getCheckSum(arr, i1, i2):
215 | c = 0
216 | for i in range(i1, i2):
217 | c = c + arr[i]
218 | return (c & 0xFF)
219 |
220 | def makePackageV3(advInfo, lockInfo, lockOp, tStamp):
221 | code = bytearray(36)
222 | code[0] = 0xAA
223 | code[1] = 16
224 | code[2] = 26
225 | code[3] = code[4] = 3
226 | code[5] = 16 + lockOp
227 | code[8] = 1
228 | code[12] = (tStamp & 0xFF)
229 | tStamp = tStamp >> 8
230 | code[11] = (tStamp & 0xFF)
231 | tStamp = tStamp >> 8
232 | code[10] = (tStamp & 0xFF)
233 | tStamp = tStamp >> 8
234 | code[9] = (tStamp & 0xFF)
235 | toEncrypt = code[4:18]
236 | manKey = lockInfo["manufacturerKey"][0:16]
237 | encrypted = AESCipher(manKey).encrypt(toEncrypt, False)
238 | # print("CODE IS {} {} {}".format(code, len(code), encrypted))
239 | code[4:20] = encrypted
240 | # print("CODE IS {} {}".format(code, len(code)))
241 | lockEventsStr = advInfo[46:54]
242 | lockEvents = int(lockEventsStr, 16)
243 | # print("LOCK EVENTS {} {}".format(advInfo, lockEvents))
244 | workingKey = generateWorkingKey(lockInfo["bindingKey"], 0)
245 | signature = generateSignatureV2(workingKey, lockEvents, code[3:20])
246 | # print("SIGN: {}".format(signature))
247 | code[20:20+len(signature)] = signature
248 | code[20+len(signature)] = getCheckSum(code, 3, 28)
249 | # print("CODE IS {} {}".format(code, len(code)))
250 | return binascii.hexlify(code).upper()
251 |
252 |
253 | lockDir = 1
254 |
255 | if len(sys.argv) > 1:
256 | lockDir = int(sys.argv[1])
257 |
258 | if lockDir not in [1,2]:
259 | print("BAD PARAMETER ({}): exiting.".format(lockDir))
260 | exit(-1)
261 |
262 | dirs=["OPENING", "CLOSING"]
263 |
264 | lockInfo = dispose(newSnInfo, appKey)
265 | print("DECRYPTED KEYS: {}".format(lockInfo))
266 |
267 | currTime = 1636707960
268 | currTime = int(time.time())
269 | print("TIME IS {}".format(currTime))
270 |
271 |
272 | opCode = makePackageV3(lockAdv, lockInfo, lockDir, currTime)
273 |
274 | print("OPCODE FOR {} IS {}".format(dirs[lockDir-1], opCode))
275 | opCode1 = "FF00" + opCode[0:36].decode('utf-8')
276 | opCode2 = "FF01" + opCode[36:].decode('utf-8')
277 | print("PACKET 1 IS {}".format(opCode1))
278 | print("PACKET 2 IS {}".format(opCode2))
279 |
280 |
--------------------------------------------------------------------------------
/custom_components/airbnk_mqtt/custom_device.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 | import json
3 | import time
4 | from typing import Callable
5 |
6 | from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC
7 | from homeassistant.components import mqtt
8 | from homeassistant.core import HomeAssistant, callback
9 |
10 | from .const import (
11 | DOMAIN as AIRBNK_DOMAIN,
12 | SENSOR_TYPE_STATE,
13 | SENSOR_TYPE_BATTERY,
14 | SENSOR_TYPE_BATTERY_LOW,
15 | SENSOR_TYPE_VOLTAGE,
16 | SENSOR_TYPE_LAST_ADVERT,
17 | SENSOR_TYPE_LOCK_EVENTS,
18 | SENSOR_TYPE_SIGNAL_STRENGTH,
19 | LOCK_STATE_LOCKED,
20 | LOCK_STATE_UNLOCKED,
21 | LOCK_STATE_JAMMED,
22 | LOCK_STATE_OPERATING,
23 | LOCK_STATE_FAILED,
24 | LOCK_STATE_STRINGS,
25 | CONF_MAC_ADDRESS,
26 | CONF_MQTT_TOPIC,
27 | CONF_VOLTAGE_THRESHOLDS,
28 | CONF_RETRIES_NUM,
29 | DEFAULT_RETRIES_NUM,
30 | )
31 |
32 | from .codes_generator import AirbnkCodesGenerator
33 | from .airbnk_logger import AirbnkLogger
34 |
35 |
36 | MAX_NORECEIVE_TIME = 30
37 |
38 | BLETelemetryTopic = "%s/tele"
39 | BLEOpTopic = "%s/command"
40 | BLEStateTopic = "%s/adv"
41 | BLEOperationReportTopic = "%s/command_result"
42 |
43 |
44 | class CustomMqttLockDevice:
45 |
46 | utcMinutes = None
47 | voltage = None
48 | isBackLock = None
49 | isInit = None
50 | isImageA = None
51 | isHadNewRecord = None
52 | curr_state = LOCK_STATE_UNLOCKED
53 | softVersion = None
54 | isEnableAuto = None
55 | opensClockwise = None
56 | isLowBattery = None
57 | magnetcurr_state = None
58 | isMagnetEnable = None
59 | isBABA = None
60 | lversionOfSoft = None
61 | versionOfSoft = None
62 | versionCode = None
63 | serialnumber = None
64 | lockEvents = 0
65 | _lockConfig = {}
66 | _lockData = {}
67 | _codes_generator = None
68 | cmd = {}
69 | last_advert_time = 0
70 | last_telemetry_time = 0
71 | is_available = False
72 | retries_num = DEFAULT_RETRIES_NUM
73 | curr_try = 0
74 |
75 | def __init__(self, hass: HomeAssistant, device_config, entry_options):
76 | self.logger = AirbnkLogger(__name__)
77 | self.logger.debug(
78 | "Setting up CustomMqttLockDevice for sn %s" % device_config["sn"]
79 | )
80 | self.hass = hass
81 | self._callbacks = set()
82 | self._unsubscribe_callbacks = set()
83 | self._lockConfig = device_config
84 | self._codes_generator = AirbnkCodesGenerator()
85 | self._lockData = self._codes_generator.decryptKeys(
86 | device_config["newSninfo"], device_config["appKey"]
87 | )
88 | self.set_options(entry_options)
89 | self.logger.debug("...done")
90 |
91 | @property
92 | def device_info(self):
93 | """Return a device description for device registry."""
94 | devID = self._lockData["lockSn"]
95 | return {
96 | "identifiers": {
97 | # Serial numbers are unique identifiers within a specific domain
98 | (AIRBNK_DOMAIN, devID)
99 | },
100 | "manufacturer": "Airbnk",
101 | "model": self._lockConfig["deviceType"],
102 | "name": self._lockConfig["deviceName"],
103 | "sw_version": self._lockConfig["firmwareVersion"],
104 | "connections": {
105 | (CONNECTION_NETWORK_MAC, self._lockConfig[CONF_MAC_ADDRESS])
106 | },
107 | }
108 |
109 | def check_availability(self):
110 | curr_time = int(round(time.time()))
111 | deltatime1 = curr_time - self.last_advert_time
112 | deltatime2 = curr_time - self.last_telemetry_time
113 | # self.logger.debug(
114 | # "Last reply was %s - %s secs ago" %
115 | # (deltatime1, deltatime2)
116 | # )
117 | if min(deltatime1, deltatime2) >= MAX_NORECEIVE_TIME:
118 | self.is_available = False
119 |
120 | @property
121 | def islocked(self) -> bool | None:
122 | if self.curr_state == LOCK_STATE_LOCKED:
123 | return True
124 | else:
125 | return False
126 |
127 | @property
128 | def isunlocked(self) -> bool | None:
129 | if self.curr_state == LOCK_STATE_UNLOCKED:
130 | return True
131 | else:
132 | return False
133 |
134 | @property
135 | def isjammed(self) -> bool | None:
136 | if self.curr_state == LOCK_STATE_JAMMED:
137 | return True
138 | else:
139 | return False
140 |
141 | @property
142 | def state(self):
143 | return LOCK_STATE_STRINGS[self.curr_state]
144 |
145 | def set_options(self, entry_options):
146 | """Register callback, called when lock changes state."""
147 | self.logger.debug("Options set: %s" % entry_options)
148 | self.retries_num = entry_options.get(CONF_RETRIES_NUM, DEFAULT_RETRIES_NUM)
149 |
150 | async def mqtt_subscribe(self):
151 | if "mqtt" not in self.hass.data:
152 | self.logger.error(
153 | "MQTT is not connected: cannot subscribe. "
154 | "Have you configured an MQTT Broker?"
155 | )
156 | return
157 |
158 | @callback
159 | async def adv_received(_p0) -> None:
160 | self.parse_adv_message(_p0.payload)
161 |
162 | @callback
163 | async def operation_msg_received(_p0) -> None:
164 | self.parse_operation_message(_p0.payload)
165 |
166 | @callback
167 | async def telemetry_msg_received(_p0) -> None:
168 | self.parse_telemetry_message(_p0.payload)
169 |
170 | callback_func = await mqtt.async_subscribe(
171 | self.hass,
172 | BLEStateTopic % self._lockConfig[CONF_MQTT_TOPIC],
173 | msg_callback=adv_received,
174 | )
175 | self._unsubscribe_callbacks.add(callback_func)
176 |
177 | callback_func = await mqtt.async_subscribe(
178 | self.hass,
179 | BLETelemetryTopic % self._lockConfig[CONF_MQTT_TOPIC],
180 | msg_callback=telemetry_msg_received,
181 | )
182 | self._unsubscribe_callbacks.add(callback_func)
183 |
184 | callback_func = await mqtt.async_subscribe(
185 | self.hass,
186 | BLEOperationReportTopic % self._lockConfig[CONF_MQTT_TOPIC],
187 | msg_callback=operation_msg_received,
188 | )
189 | self._unsubscribe_callbacks.add(callback_func)
190 |
191 | async def mqtt_unsubscribe(self):
192 | for callback_func in self._unsubscribe_callbacks:
193 | callback_func()
194 |
195 | def register_callback(self, callback: Callable[[], None]) -> None:
196 | """Register callback, called when lock changes state."""
197 | self._callbacks.add(callback)
198 |
199 | def parse_telemetry_message(self, msg):
200 | # TODO
201 | self.logger.debug("Received telemetry %s" % msg)
202 | self.last_telemetry_time = int(round(time.time()))
203 | self.is_available = True
204 |
205 | def parse_adv_message(self, msg):
206 | self.logger.debug("Received adv %s" % msg)
207 | payload = json.loads(msg)
208 | mac_address = self._lockConfig[CONF_MAC_ADDRESS]
209 | mqtt_advert = payload["data"]
210 | mqtt_mac = payload["mac"].replace(":", "").upper()
211 | self.logger.debug("Config mac %s, received %s" % (mac_address, mqtt_mac))
212 | if mqtt_mac != mac_address.upper():
213 | return
214 |
215 | self.parse_MQTT_advert(mqtt_advert.upper())
216 | time2 = self.last_advert_time
217 | self.last_advert_time = int(round(time.time()))
218 | if "rssi" in payload:
219 | rssi = payload["rssi"]
220 | self._lockData[SENSOR_TYPE_SIGNAL_STRENGTH] = rssi
221 |
222 | deltatime = self.last_advert_time - time2
223 | self._lockData[SENSOR_TYPE_LAST_ADVERT] = deltatime
224 | self.is_available = True
225 | self.logger.debug("Time from last message: %s secs" % str(deltatime))
226 |
227 | for callback_func in self._callbacks:
228 | callback_func()
229 |
230 | def parse_operation_message(self, msg):
231 | self.logger.debug("Received operation result %s" % msg)
232 | payload = json.loads(msg)
233 | mac_address = self._lockConfig[CONF_MAC_ADDRESS]
234 | mqtt_mac = payload["mac"].replace(":", "").upper()
235 |
236 | if mqtt_mac != mac_address.upper():
237 | return
238 |
239 | msg_sign = payload["sign"]
240 | self.logger.debug("Received sign: %s" % msg_sign)
241 | self.logger.debug("Command sign: %s" % self.cmd["sign"])
242 | if msg_sign != self.cmd["sign"]:
243 | self.logger.error("Returning.")
244 | return
245 |
246 | msg_state = payload["success"]
247 | if msg_state is False:
248 | if self.curr_try < self.retries_num:
249 | self.curr_try += 1
250 | time.sleep(0.5)
251 | self.logger.debug("Retrying: attempt %i" % self.curr_try)
252 | self.curr_state = LOCK_STATE_OPERATING
253 | for callback_func in self._callbacks:
254 | callback_func()
255 | self.send_mqtt_command()
256 | else:
257 | self.logger.error("No more retries: command FAILED")
258 | self.curr_state = LOCK_STATE_FAILED
259 | for callback_func in self._callbacks:
260 | callback_func()
261 | raise Exception("Failed sending command: returned %s", msg_state)
262 | return
263 | else:
264 | self.parse_new_lockStatus(payload["lockStatus"])
265 | for callback_func in self._callbacks:
266 | callback_func()
267 |
268 | async def operateLock(self, lock_dir):
269 | self.logger.debug("operateLock called (%s)" % lock_dir)
270 | self.curr_state = LOCK_STATE_OPERATING
271 | self.curr_try = 0
272 | for callback_func in self._callbacks:
273 | callback_func()
274 |
275 | opCode = self._codes_generator.generateOperationCode(lock_dir, self.lockEvents)
276 | self.cmd = {}
277 | self.cmd["command1"] = "FF00" + opCode[0:36].decode("utf-8")
278 | self.cmd["command2"] = "FF01" + opCode[36:].decode("utf-8")
279 | self.cmd["sign"] = self._codes_generator.systemTime
280 | self.send_mqtt_command()
281 |
282 | def send_mqtt_command(self):
283 | mqtt.publish(
284 | self.hass,
285 | BLEOpTopic % self._lockConfig[CONF_MQTT_TOPIC],
286 | json.dumps(self.cmd),
287 | )
288 |
289 | def parse_new_lockStatus(self, lockStatus):
290 | self.logger.debug("Parsing new lockStatus: %s" % lockStatus)
291 | bArr = bytearray.fromhex(lockStatus)
292 | if bArr[0] != 0xAA or bArr[3] != 0x02 or bArr[4] != 0x04:
293 | self.logger.error("Wrong lockStatus msg: %s" % lockStatus)
294 | return
295 |
296 | lockEvents = (bArr[10] << 24) | (bArr[11] << 16) | (bArr[12] << 8) | bArr[13]
297 | self.lockEvents = max(self.lockEvents, lockEvents)
298 | self.voltage = ((float)((bArr[14] << 8) | bArr[15])) * 0.01
299 | self.curr_state = (bArr[16] >> 4) & 3
300 |
301 | def parse_MQTT_advert(self, mqtt_advert):
302 | self.logger.debug("Parsing advert msg: %s" % mqtt_advert)
303 | bArr = bytearray.fromhex(mqtt_advert)
304 | if bArr[0] != 0xBA or bArr[1] != 0xBA:
305 | self.logger.error("Wrong advert msg: %s" % mqtt_advert)
306 | return
307 |
308 | self.voltage = ((float)((bArr[16] << 8) | bArr[17])) * 0.01
309 | self.boardModel = bArr[2]
310 | self.lversionOfSoft = bArr[3]
311 | self.sversionOfSoft = (bArr[4] << 16) | (bArr[5] << 8) | bArr[6]
312 | serialnumber = bArr[7:16].decode("utf-8").strip("\0")
313 | if serialnumber != self._lockConfig["sn"]:
314 | self.logger.error(
315 | "ERROR: s/n in advert (%s) is different from cloud data (%s)"
316 | % (serialnumber, self._lockConfig["sn"])
317 | )
318 |
319 | lockEvents = (bArr[18] << 24) | (bArr[19] << 16) | (bArr[20] << 8) | bArr[21]
320 | new_state = (bArr[22] >> 4) & 3
321 | self.opensClockwise = (bArr[22] & 0x80) != 0
322 | self.lockEvents = max(self.lockEvents, lockEvents)
323 | if self.curr_state != LOCK_STATE_FAILED:
324 | self.curr_state = new_state
325 | if self.opensClockwise and self.curr_state != LOCK_STATE_JAMMED:
326 | self.curr_state = 1 - self.curr_state
327 |
328 | z = False
329 | self.isBackLock = (bArr[22] & 1) != 0
330 | self.isInit = (2 & bArr[22]) != 0
331 | self.isImageA = (bArr[22] & 4) != 0
332 | self.isHadNewRecord = (bArr[22] & 8) != 0
333 | self.isEnableAuto = (bArr[22] & 0x40) != 0
334 | self.isLowBattery = (bArr[23] & 0x10) != 0
335 | self.magnetcurr_state = (bArr[23] >> 5) & 3
336 | if (bArr[23] & 0x80) != 0:
337 | z = True
338 |
339 | self.isMagnetEnable = z
340 | self.isBABA = True
341 |
342 | self.battery_perc = self.calculate_battery_percentage(self.voltage)
343 | self._lockData[SENSOR_TYPE_STATE] = self.state
344 | self._lockData[SENSOR_TYPE_BATTERY] = self.battery_perc
345 | self._lockData[SENSOR_TYPE_VOLTAGE] = self.voltage
346 | self._lockData[SENSOR_TYPE_BATTERY_LOW] = self.isLowBattery
347 | self._lockData[SENSOR_TYPE_LOCK_EVENTS] = self.lockEvents
348 |
349 | return
350 |
351 | def calculate_battery_percentage(self, voltage):
352 | voltages = self._lockConfig[CONF_VOLTAGE_THRESHOLDS]
353 | perc = 0
354 | if voltage >= voltages[2]:
355 | perc = 100
356 | elif voltage >= voltages[1]:
357 | perc = 66.6 + 33.3 * (voltage - voltages[1]) / (voltages[2] - voltages[1])
358 | else:
359 | perc = 33.3 + 33.3 * (voltage - voltages[0]) / (voltages[1] - voltages[0])
360 | perc = max(perc, 0)
361 | return round(perc, 1)
362 |
--------------------------------------------------------------------------------
/custom_components/airbnk_mqtt/tasmota_device.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 | import base64
3 | import json
4 | import time
5 | import asyncio
6 | from typing import Callable
7 |
8 | from cryptography.hazmat.backends import default_backend
9 | from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
10 |
11 | from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC
12 | from homeassistant.components import mqtt
13 | from homeassistant.core import HomeAssistant, callback
14 |
15 | from .const import (
16 | DOMAIN as AIRBNK_DOMAIN,
17 | SENSOR_TYPE_STATE,
18 | SENSOR_TYPE_BATTERY,
19 | SENSOR_TYPE_BATTERY_LOW,
20 | SENSOR_TYPE_VOLTAGE,
21 | SENSOR_TYPE_LAST_ADVERT,
22 | SENSOR_TYPE_SIGNAL_STRENGTH,
23 | LOCK_STATE_LOCKED,
24 | LOCK_STATE_UNLOCKED,
25 | LOCK_STATE_JAMMED,
26 | LOCK_STATE_OPERATING,
27 | LOCK_STATE_FAILED,
28 | LOCK_STATE_STRINGS,
29 | CONF_MAC_ADDRESS,
30 | CONF_MQTT_TOPIC,
31 | CONF_VOLTAGE_THRESHOLDS,
32 | CONF_RETRIES_NUM,
33 | DEFAULT_RETRIES_NUM,
34 | )
35 |
36 | from .codes_generator import AirbnkCodesGenerator
37 | from .airbnk_logger import AirbnkLogger
38 |
39 | MAX_NORECEIVE_TIME = 30
40 |
41 | BLEOpTopic = "cmnd/%s/BLEOp"
42 | BLERule1Topic = "cmnd/%s/Rule1"
43 | BLEDetailsTopic = "cmnd/%s/BLEDetails2"
44 | BLEDetailsAllTopic = "cmnd/%s/BLEDetails3"
45 | BLEStateTopic = "tele/%s/BLE"
46 | write_characteristic_UUID = "FFF2"
47 | read_characteristic_UUID = "FFF3"
48 | service_UUID = "FFF0"
49 |
50 |
51 | class AESCipher:
52 | """Cipher module for AES decryption."""
53 |
54 | def __init__(self, key):
55 | """Initialize a new AESCipher."""
56 | self.block_size = 16
57 | self.cipher = Cipher(algorithms.AES(key), modes.ECB(), default_backend())
58 |
59 | def encrypt(self, raw, use_base64=True):
60 | """Encrypt data to be sent to device."""
61 | encryptor = self.cipher.encryptor()
62 | crypted_text = encryptor.update(self._pad(raw)) + encryptor.finalize()
63 | return base64.b64encode(crypted_text) if use_base64 else crypted_text
64 |
65 | def decrypt(self, enc, use_base64=True):
66 | """Decrypt data from device."""
67 | if use_base64:
68 | enc = base64.b64decode(enc)
69 |
70 | decryptor = self.cipher.decryptor()
71 | return self._unpad(decryptor.update(enc) + decryptor.finalize())
72 |
73 | def _pad(self, data):
74 | padnum = self.block_size - len(data) % self.block_size
75 | return data + padnum * chr(padnum).encode()
76 |
77 | @staticmethod
78 | def _unpad(data):
79 | return data[: -ord(data[len(data) - 1 :])]
80 |
81 |
82 | class TasmotaMqttLockDevice:
83 |
84 | utcMinutes = None
85 | voltage = None
86 | battery_perc = None
87 | isBackLock = None
88 | isInit = None
89 | isImageA = None
90 | isHadNewRecord = None
91 | curr_state = LOCK_STATE_UNLOCKED
92 | softVersion = None
93 | isEnableAuto = None
94 | opensClockwise = None
95 | isLowBattery = None
96 | magnetcurr_state = None
97 | isMagnetEnable = None
98 | isBABA = None
99 | lversionOfSoft = None
100 | sversionOfSoft = None
101 | serialnumber = None
102 | lockEvents = 0
103 | _lockConfig = {}
104 | _lockData = {}
105 | _codes_generator = None
106 | frame1hex = ""
107 | frame2hex = ""
108 | frame1sent = False
109 | frame2sent = False
110 | last_advert_time = 0
111 | is_available = False
112 | retries_num = DEFAULT_RETRIES_NUM
113 | curr_try = 0
114 |
115 | def __init__(self, hass: HomeAssistant, device_config, entry_options):
116 | self.logger = AirbnkLogger(__name__)
117 | self.logger.debug(
118 | "Setting up TasmotaMqttLockDevice for sn %s" % device_config["sn"]
119 | )
120 | self.hass = hass
121 | self._callbacks = set()
122 | self._unsubscribe_callbacks = set()
123 | self._lockConfig = device_config
124 | self._codes_generator = AirbnkCodesGenerator()
125 | self._lockData = self._codes_generator.decryptKeys(
126 | device_config["newSninfo"], device_config["appKey"]
127 | )
128 | self.set_options(entry_options)
129 | mac_address = self._lockConfig[CONF_MAC_ADDRESS]
130 | if mac_address is not None and mac_address != "":
131 | self.requestDetails(mac_address)
132 | else:
133 | self.scanAllAdverts()
134 |
135 | @property
136 | def device_info(self):
137 | """Return a device description for device registry."""
138 | devID = self._lockData["lockSn"]
139 | return {
140 | "identifiers": {
141 | # Serial numbers are unique identifiers within a specific domain
142 | (AIRBNK_DOMAIN, devID)
143 | },
144 | "manufacturer": "Airbnk",
145 | "model": self._lockConfig["deviceType"],
146 | "name": self._lockConfig["deviceName"],
147 | "sw_version": self._lockConfig["firmwareVersion"],
148 | "connections": {
149 | (CONNECTION_NETWORK_MAC, self._lockConfig[CONF_MAC_ADDRESS])
150 | },
151 | }
152 |
153 | def check_availability(self):
154 | curr_time = int(round(time.time()))
155 | deltatime = curr_time - self.last_advert_time
156 | # self.logger.debug("Last reply was %s secs ago" % deltatime)
157 | if deltatime >= MAX_NORECEIVE_TIME:
158 | self.is_available = False
159 |
160 | @property
161 | def islocked(self) -> bool | None:
162 | if self.curr_state == LOCK_STATE_LOCKED:
163 | return True
164 | else:
165 | return False
166 |
167 | @property
168 | def isunlocked(self) -> bool | None:
169 | if self.curr_state == LOCK_STATE_UNLOCKED:
170 | return True
171 | else:
172 | return False
173 |
174 | @property
175 | def isjammed(self) -> bool | None:
176 | if self.curr_state == LOCK_STATE_JAMMED:
177 | return True
178 | else:
179 | return False
180 |
181 | @property
182 | def state(self):
183 | return LOCK_STATE_STRINGS[self.curr_state]
184 |
185 | def set_options(self, entry_options):
186 | """Register callback, called when lock changes state."""
187 | self.logger.debug("Options set: %s" % entry_options)
188 | self.retries_num = entry_options.get(CONF_RETRIES_NUM, DEFAULT_RETRIES_NUM)
189 |
190 | async def mqtt_subscribe(self):
191 | if "mqtt" not in self.hass.data:
192 | self.logger.error(
193 | "MQTT is not connected: cannot subscribe. "
194 | "Have you configured an MQTT Broker?"
195 | )
196 | return
197 |
198 | @callback
199 | async def message_received(_p0) -> None:
200 | await self.async_parse_MQTT_message(_p0.payload)
201 |
202 | callback_func = await mqtt.async_subscribe(
203 | self.hass,
204 | BLEStateTopic % self._lockConfig[CONF_MQTT_TOPIC],
205 | msg_callback=message_received,
206 | )
207 | self._unsubscribe_callbacks.add(callback_func)
208 |
209 | async def mqtt_unsubscribe(self):
210 | for callback_func in self._unsubscribe_callbacks:
211 | callback_func()
212 |
213 | def register_callback(self, callback: Callable[[], None]) -> None:
214 | """Register callback, called when lock changes state."""
215 | self._callbacks.add(callback)
216 |
217 | def parse_from_fff3_read_prop(self, sn, barr=[0]):
218 | # Initialising empty Lockeradvertising variables
219 | # The init initialiser is used to init object from
220 | # BLE read properties returned when reading
221 | # 0Xfff3 characteristic
222 |
223 | # According to type of the lock, checks the byte array
224 | # and parse using type1 or type2 func
225 | if barr != [0] and barr is not None:
226 | if barr[6] == 240:
227 | self.type1(barr, sn)
228 | else:
229 | self.type2(barr, sn)
230 |
231 | async def async_parse_MQTT_message(self, msg):
232 | self.logger.debug("Received msg %s" % msg)
233 | payload = json.loads(msg)
234 | msg_type = list(payload.keys())[0]
235 | mac_address = self._lockConfig[CONF_MAC_ADDRESS]
236 | if "details" in msg_type.lower() and ("p" and "mac" in payload[msg_type]):
237 | mqtt_advert = payload[msg_type]["p"]
238 | mqtt_mac = payload[msg_type]["mac"]
239 | if mac_address is None or mac_address == "":
240 | sn_hex = "".join(
241 | "{:02x}".format(ord(c)) for c in self._lockData["lockSn"]
242 | )
243 | if mqtt_advert[24 : 24 + len(sn_hex)] != sn_hex:
244 | return
245 | self._lockConfig[CONF_MAC_ADDRESS] = mqtt_mac
246 | mac_address = mqtt_mac
247 | self.requestDetails(mqtt_mac)
248 |
249 | if mqtt_mac == mac_address and len(mqtt_advert) == 62:
250 | self.parse_MQTT_advert(mqtt_advert[10:])
251 | time2 = self.last_advert_time
252 | self.last_advert_time = int(round(time.time()))
253 | if "RSSI" in payload[msg_type]:
254 | rssi = payload[msg_type]["RSSI"]
255 | self._lockData[SENSOR_TYPE_SIGNAL_STRENGTH] = rssi
256 |
257 | deltatime = self.last_advert_time - time2
258 | self._lockData[SENSOR_TYPE_LAST_ADVERT] = deltatime
259 | if deltatime < MAX_NORECEIVE_TIME:
260 | self.is_available = True
261 | self.logger.debug(
262 | "Time from last message: %s secs" % str(deltatime)
263 | )
264 | elif time2 != 0:
265 | self.logger.error(
266 | "Time from last message: %s secs: device unavailable"
267 | % str(deltatime)
268 | )
269 | self.is_available = False
270 |
271 | for callback_func in self._callbacks:
272 | callback_func()
273 |
274 | if "operation" in msg_type.lower() and ("state" and "MAC" in payload[msg_type]):
275 | if payload[msg_type]["MAC"] != mac_address:
276 | return
277 | msg_state = payload[msg_type]["state"]
278 | if "FAIL" in msg_state:
279 | self.logger.error("Failed sending frame: returned %s" % msg_state)
280 |
281 | if self.curr_try < self.retries_num:
282 | self.curr_try += 1
283 | await asyncio.sleep(0.5)
284 | self.logger.debug("Retrying: attempt %i" % self.curr_try)
285 | self.curr_state = LOCK_STATE_OPERATING
286 | for callback_func in self._callbacks:
287 | callback_func()
288 | if self.frame1sent:
289 | await self.async_sendFrame2()
290 | else:
291 | await self.async_sendFrame1()
292 | else:
293 | self.logger.error("No more retries: command FAILED")
294 | self.curr_state = LOCK_STATE_FAILED
295 | for callback_func in self._callbacks:
296 | callback_func()
297 | raise Exception("Failed sending frame: returned %s", msg_state)
298 |
299 | return
300 |
301 | msg_written_payload = payload[msg_type]["write"]
302 | if msg_written_payload == self.frame1hex.upper():
303 | self.frame1sent = True
304 | await self.async_sendFrame2()
305 |
306 | if msg_written_payload == self.frame2hex.upper():
307 | self.frame2sent = True
308 | for callback_func in self._callbacks:
309 | callback_func()
310 |
311 | async def operateLock(self, lock_dir):
312 | self.logger.debug(
313 | "operateLock called (%s): attempt %i" % (lock_dir, self.curr_try)
314 | )
315 | self.curr_state = LOCK_STATE_OPERATING
316 | self.curr_try = 0
317 | self.frame1sent = False
318 | self.frame2sent = False
319 | for callback_func in self._callbacks:
320 | callback_func()
321 |
322 | opCode = self._codes_generator.generateOperationCode(lock_dir, self.lockEvents)
323 | self.frame1hex = "FF00" + opCode[0:36].decode("utf-8")
324 | self.frame2hex = "FF01" + opCode[36:].decode("utf-8")
325 |
326 | await self.async_sendFrame1()
327 |
328 | def requestDetails(self, mac_addr):
329 | mqtt.publish(
330 | self.hass,
331 | BLERule1Topic % self._lockConfig[CONF_MQTT_TOPIC],
332 | "ON Mqtt#Connected DO BLEDetails2 %s ENDON" % mac_addr,
333 | )
334 | mqtt.publish(self.hass, BLERule1Topic % self._lockConfig[CONF_MQTT_TOPIC], "1")
335 | mqtt.publish(
336 | self.hass, BLEDetailsTopic % self._lockConfig[CONF_MQTT_TOPIC], mac_addr
337 | )
338 |
339 | def scanAllAdverts(self):
340 | mqtt.publish(
341 | self.hass, BLEDetailsAllTopic % self._lockConfig[CONF_MQTT_TOPIC], ""
342 | )
343 |
344 | async def async_sendFrame1(self):
345 | mqtt.publish(
346 | self.hass,
347 | BLEOpTopic % self._lockConfig[CONF_MQTT_TOPIC],
348 | self.BLEOPWritePAYLOADGen(self.frame1hex),
349 | )
350 |
351 | async def async_sendFrame2(self):
352 | mqtt.publish(
353 | self.hass,
354 | BLEOpTopic % self._lockConfig[CONF_MQTT_TOPIC],
355 | self.BLEOPWritePAYLOADGen(self.frame2hex),
356 | )
357 |
358 | def BLEOPWritePAYLOADGen(self, frame):
359 | mac_address = self._lockConfig[CONF_MAC_ADDRESS]
360 | write_UUID = write_characteristic_UUID
361 | payload = f"M:{mac_address} s:{service_UUID} c:{write_UUID} w:{frame} go"
362 | self.logger.debug("Sending payload [ %s ]" % payload)
363 | return payload
364 |
365 | def BLEOPreadPAYLOADGen(self):
366 | mac_address = self._lockData["mac_address"]
367 | return f"M:{mac_address} s:{service_UUID} c:{read_characteristic_UUID} r go"
368 |
369 | def type1(self, barr, sn):
370 | self.serialnumber = sn
371 | self.lockEvents = (
372 | (barr[10] << 24) | (barr[11] << 16) | (barr[12] << 8) | barr[13]
373 | )
374 | self.voltage = ((((barr[14] & 255) << 8) | (barr[15] & 255))) * 0.01
375 | magnetenableindex = False
376 | self.isBackLock = (barr[16] & 1) != 0
377 | self.isInit = (barr[16] & 2) != 0
378 | self.isImageA = (barr[16] & 4) != 0
379 | self.isHadNewRecord = (barr[16] & 8) != 0
380 | i = ((barr[16] & 255) >> 4) & 7
381 |
382 | if i == 0 or i == 5:
383 | self.curr_state = LOCK_STATE_UNLOCKED
384 | elif i == 1 or i == 4:
385 | self.curr_state = LOCK_STATE_LOCKED
386 | else:
387 | self.curr_state = LOCK_STATE_JAMMED
388 |
389 | self.softVersion = (
390 | (str(int(barr[7]))) + "." + (str(int(barr[8]))) + "." + (str(int(barr[9])))
391 | )
392 | self.isEnableAuto = (barr[16] & 128) != 0
393 | self.opensClockwise = (barr[16] & 64) == 0
394 | self.isLowBattery = (16 & barr[17]) != 0
395 | self.magnetcurr_state = (barr[17] >> 5) & 3
396 | if (barr[17] & 128) != 0:
397 | magnetenableindex = True
398 |
399 | self.isMagnetEnable = magnetenableindex
400 | self.isBABA = True
401 | self.parse1(barr, sn)
402 |
403 | # Function used to set properties type2 lock
404 | def type2(self, barr, sn):
405 | self.serialnumber = sn
406 | self.lockEvents = (
407 | ((barr[8] & 255) << 24)
408 | | ((barr[9] & 255) << 16)
409 | | ((barr[10] & 255) << 8)
410 | | (barr[11] & 255)
411 | )
412 | self.utcMinutes = (
413 | ((barr[12] & 255) << 24)
414 | | ((barr[13] & 255) << 16)
415 | | ((barr[14] & 255) << 8)
416 | | (barr[15] & 255)
417 | )
418 | self.voltage = ((barr[16] & 255)) * 0.1
419 | index = True
420 | self.isBackLock = (barr[17] & 1) != 0
421 | self.isInit = (barr[17] & 2) != 0
422 | self.isImageA = (barr[17] & 4) != 0
423 | self.isHadNewRecord = (8 & barr[17]) != 0
424 | self.curr_state = ((barr[17] & 255) >> 4) & 3
425 | self.isEnableAuto = (barr[17] & 64) != 0
426 | if (barr[17] & 128) == 0:
427 | index = False
428 |
429 | self.opensClockwise = index
430 | self.isBABA = False
431 | self.parse2(barr, sn)
432 |
433 | def parse2(self, barr, sn):
434 | if barr is None:
435 | return None
436 |
437 | barr2 = bytearray(23)
438 | barr2[0] = 173
439 | barr2[1] = barr[6]
440 | barr2[2] = barr[7]
441 | if sn is not None and len(sn) > 0:
442 | length = len(sn)
443 | bytes1 = bytes(sn, "utf-8")
444 | for i in range(length):
445 |
446 | barr2[i + 3] = bytes1[i]
447 |
448 | barr2[12] = barr[8]
449 | barr2[13] = barr[9]
450 | barr2[14] = barr[10]
451 | barr2[15] = barr[11]
452 | barr2[16] = barr[12]
453 | barr2[17] = barr[13]
454 | barr2[18] = barr[14]
455 | barr2[19] = barr[15]
456 | barr2[20] = barr[16]
457 | barr2[21] = barr[17]
458 | barr2[22] = barr[18]
459 |
460 | return bytearray.hex(barr2)
461 |
462 | def parse1(self, barr, sn):
463 | if barr is None:
464 | return None
465 |
466 | barr2 = bytearray(24)
467 | barr2[0] = 186
468 | barr2[1] = 186
469 | barr2[4] = barr[7]
470 | barr2[5] = barr[8]
471 | barr2[6] = barr[9]
472 | if sn is not None and len(sn) > 0:
473 | length = len(sn)
474 | bytes1 = bytes(sn, "utf-8")
475 | for i in range(length):
476 | barr2[i + 7] = bytes1[i]
477 |
478 | barr2[16] = barr[14]
479 | barr2[17] = barr[15]
480 | barr2[18] = barr[10]
481 | barr2[19] = barr[11]
482 | barr2[20] = barr[12]
483 | barr2[21] = barr[13]
484 | barr2[22] = barr[16]
485 | barr2[23] = barr[17]
486 |
487 | return bytearray.hex(barr2)
488 |
489 | def parse_MQTT_advert(self, mqtt_advert):
490 |
491 | bArr = bytearray.fromhex(mqtt_advert)
492 | if bArr[0] != 0xBA or bArr[1] != 0xBA:
493 | self.logger.error("Wrong advert msg: %s" % mqtt_advert)
494 | return
495 |
496 | self.voltage = ((float)((bArr[16] << 8) | bArr[17])) * 0.01
497 | self.boardModel = bArr[2]
498 | self.lversionOfSoft = bArr[3]
499 | self.sversionOfSoft = (bArr[4] << 16) | (bArr[5] << 8) | bArr[6]
500 | serialnumber = bArr[7:16].decode("utf-8").strip("\0")
501 | if serialnumber != self._lockConfig["sn"]:
502 | self.logger.error(
503 | "ERROR: s/n in advert (%s) is different from cloud data (%s)"
504 | % (serialnumber, self._lockConfig["sn"])
505 | )
506 |
507 | lockEvents = (bArr[18] << 24) | (bArr[19] << 16) | (bArr[20] << 8) | bArr[21]
508 | new_state = (bArr[22] >> 4) & 3
509 | self.opensClockwise = (bArr[22] & 0x80) != 0
510 | if self.curr_state < LOCK_STATE_OPERATING or self.lockEvents != lockEvents:
511 | self.lockEvents = lockEvents
512 | self.curr_state = new_state
513 | if self.opensClockwise and self.curr_state is not LOCK_STATE_JAMMED:
514 | self.curr_state = 1 - self.curr_state
515 |
516 | z = False
517 | self.isBackLock = (bArr[22] & 1) != 0
518 | self.isInit = (2 & bArr[22]) != 0
519 | self.isImageA = (bArr[22] & 4) != 0
520 | self.isHadNewRecord = (bArr[22] & 8) != 0
521 | self.isEnableAuto = (bArr[22] & 0x40) != 0
522 | self.isLowBattery = (bArr[23] & 0x10) != 0
523 | self.magnetcurr_state = (bArr[23] >> 5) & 3
524 | if (bArr[23] & 0x80) != 0:
525 | z = True
526 |
527 | self.isMagnetEnable = z
528 | self.isBABA = True
529 |
530 | self.battery_perc = self.calculate_battery_percentage(self.voltage)
531 | self._lockData[SENSOR_TYPE_STATE] = self.state
532 | self._lockData[SENSOR_TYPE_BATTERY] = self.battery_perc
533 | self._lockData[SENSOR_TYPE_VOLTAGE] = self.voltage
534 | self._lockData[SENSOR_TYPE_BATTERY_LOW] = self.isLowBattery
535 | # print("LOCK: {}".format(self._lockData))
536 |
537 | return
538 |
539 | def calculate_battery_percentage(self, voltage):
540 | voltages = self._lockConfig[CONF_VOLTAGE_THRESHOLDS]
541 | perc = 0
542 | if voltage >= voltages[2]:
543 | perc = 100
544 | elif voltage >= voltages[1]:
545 | perc = 66.6 + 33.3 * (voltage - voltages[1]) / (voltages[2] - voltages[1])
546 | else:
547 | perc = 33.3 + 33.3 * (voltage - voltages[0]) / (voltages[1] - voltages[0])
548 | perc = max(perc, 0)
549 | return round(perc, 1)
550 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------