pysmlight 0.0.10__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,23 @@
1
+ Metadata-Version: 2.1
2
+ Name: pysmlight
3
+ Version: 0.0.10
4
+ Summary: A library implemnting API control of the SLZB-06 LAN Coordinators.
5
+ Home-page: https://github.com/smlight-workspace/pysmlight
6
+ License: Apache-2.0
7
+ Keywords: smlight,slzb-06,zigbee
8
+ Author: Tim Lunn
9
+ Author-email: tl@smlight.tech
10
+ Requires-Python: >=3.11,<4.0
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Requires-Dist: aiohttp (>=3.9.3)
16
+ Requires-Dist: aiohttp_sse_client2 (>=0.3.0,<0.4.0)
17
+ Requires-Dist: mashumaro (>=3.10)
18
+ Project-URL: Repository, https://github.com/smlight-workspace/pysmlight
19
+ Description-Content-Type: text/markdown
20
+
21
+ # PySMLIGHT - SLZB-06x
22
+
23
+ A python library for controlling SMLIGHT SLZB-06 network coordinators
@@ -0,0 +1,3 @@
1
+ # PySMLIGHT - SLZB-06x
2
+
3
+ A python library for controlling SMLIGHT SLZB-06 network coordinators
@@ -0,0 +1,69 @@
1
+ [tool.poetry]
2
+ name = "pysmlight"
3
+ version = "0.0.10"
4
+ repository = "https://github.com/smlight-workspace/pysmlight"
5
+ license = "Apache-2.0"
6
+ description = "A library implemnting API control of the SLZB-06 LAN Coordinators."
7
+ authors = ["Tim Lunn <tl@smlight.tech>"]
8
+ readme = "README.md"
9
+ keywords = ["smlight", "slzb-06", "zigbee"]
10
+
11
+ [tool.poetry.dependencies]
12
+ python = "^3.11"
13
+ aiohttp = ">=3.9.3"
14
+ aiohttp_sse_client2 = "^0.3.0"
15
+ # attrs = "^23.2.0"
16
+ mashumaro = ">=3.10"
17
+
18
+ [build-system]
19
+ requires = ["poetry-core"]
20
+ build-backend = "poetry.core.masonry.api"
21
+
22
+ [tool.ruff]
23
+ select = [
24
+ # Pyflakes
25
+ "F",
26
+ # Pycodestyle
27
+ "E",
28
+ "W"
29
+ ]
30
+ src = ["pysmlight", "tests"]
31
+
32
+ [tool.pytest.ini_options]
33
+ addopts = "--showlocals --verbose"
34
+ testpaths = ["tests"]
35
+ timeout = 20
36
+ log_format = "%(asctime)s.%(msecs)03d %(levelname)s %(message)s"
37
+ log_date_format = "%Y-%m-%d %H:%M:%S"
38
+ asyncio_mode = "auto"
39
+
40
+ [tool.mypy]
41
+ check_untyped_defs = true
42
+ show_error_codes = true
43
+ show_error_context = true
44
+ disable_error_code = [
45
+ "attr-defined",
46
+ "arg-type",
47
+ ]
48
+
49
+ [tool.isort]
50
+ profile = "black"
51
+ # will group `import x` and `from x import` of the same module.
52
+ force_sort_within_sections = true
53
+ known_first_party = ["universal_silabs_flasher", "tests"]
54
+ forced_separate = "tests"
55
+ combine_as_imports = true
56
+
57
+ [tool.flake8]
58
+ exclude = [".venv", ".git", ".tox", "docs", "venv", "bin", "lib", "deps", "build"]
59
+ # To work with Black
60
+ max-line-length = 88
61
+ # W503: Line break occurred before a binary operator
62
+ # E203: Whitespace before ':'
63
+ # E501: line too long
64
+ # D202 No blank lines allowed after function docstring
65
+ ignore = ["W503", "E203", "E501", "D202"]
66
+ per-file-ignores = ["tests/*:F811,F401,F403"]
67
+
68
+ [tool.pyupgrade]
69
+ py311plus = true
@@ -0,0 +1,7 @@
1
+ __all__ = [
2
+ "Api2",
3
+ "Info",
4
+ "Sensors",
5
+ ]
6
+
7
+ from pysmlight.web import Api2, Info, Sensors
@@ -0,0 +1,109 @@
1
+ from enum import Enum, auto, unique
2
+
3
+ FW_URL = "https://smlight.tech/flasher/firmware/bin/slzb06x/ota.php"
4
+ FW_DEV_URL = "https://smlight.tech/flasher/firmware/bin/slzb06x/ota_dev.php"
5
+ MODE_LIST: list[str] = ["LAN", "WiFi", "USB"]
6
+
7
+ PARAM_LIST: list[str] = [
8
+ "coordMode",
9
+ "zbRev",
10
+ "espRev",
11
+ "inetState",
12
+ ]
13
+
14
+
15
+ @unique
16
+ class Actions(Enum):
17
+ API_GET_PAGE = 0
18
+ API_GET_PARAM = 1
19
+ API_STARTWIFISCAN = 2
20
+ API_SEND_HEX = 3
21
+ API_CMD = 4
22
+ API_GET_LOG = 5
23
+ API_FLASH_ZB = 6
24
+ API_WIFICONNECTSTAT = 7
25
+ API_FLASH_ESP = 8
26
+
27
+
28
+ @unique
29
+ class Commands(Enum):
30
+ CMD_ZB_ROUTER_RECON = 0
31
+ CMD_ZB_RST = 1
32
+ CMD_ZB_BSL = 2
33
+ CMD_ESP_RES = 3
34
+ CMD_CLEAR_LOG = 4
35
+ CMD_ZB_ENERGY_SCAN = 5
36
+ CMD_ZB_LED_NETWORK = 6
37
+ CMD_ZB_LED_PERMIT = 7
38
+ CMD_ZB_LED_DISABLED = 8
39
+ CMD_HARD_RESET = 9
40
+
41
+
42
+ @unique
43
+ class Pages(Enum):
44
+ API2_PAGE_DASHBOARD = 0
45
+ API2_PAGE_MODE = 1
46
+ API2_PAGE_NETWORK = 2
47
+ API2_PAGE_ZHA_Z2M = 3
48
+ API2_PAGE_SECURITY = 4
49
+ API2_PAGE_VPN = 5
50
+ API2_PAGE_SETTINGS_GENERAL = 6
51
+ API2_PAGE_SETTINGS_OTA = 7
52
+ API2_PAGE_SETTINGS_LED = 8
53
+ API2_PAGE_SETTINGS_TIME = 9
54
+ API2_PAGE_SETTINGS_SYSTEM_LOG = 10
55
+ API2_PAGE_ABOUT = 11
56
+ API2_PAGE_WIFI = 12
57
+
58
+
59
+ Devices: dict[str, int] = {
60
+ "SLZB-06": 0,
61
+ "SLZB-06M": 1,
62
+ "SLZB-06Mg24": 2,
63
+ "SLZB-06p7": 3,
64
+ "SLZB-06p10": 4,
65
+ }
66
+ ZB_TYPES: dict[int, str] = {
67
+ -1: "Unknown",
68
+ 0: "Coordinator",
69
+ 1: "Router",
70
+ 2: "RESERVED",
71
+ }
72
+
73
+
74
+ class Events(Enum):
75
+ API2_WIFISCANSTATUS = 0
76
+ ESP_UPD_done = auto()
77
+ EVENT_INET_STATE = auto()
78
+ FW_UPD_done = auto()
79
+ LOG_STR = auto()
80
+ SAVE_PARAMS = auto()
81
+ ZB_FW_err = auto()
82
+ ZB_FW_info = auto()
83
+ ZB_FW_prgs = auto()
84
+ ZB_ENERGY_SCAN_DONE = auto()
85
+
86
+
87
+ class Settings(Enum):
88
+ DISABLE_LEDS = (Pages.API2_PAGE_SETTINGS_LED, "disableLeds")
89
+ NIGHT_MODE = (Pages.API2_PAGE_SETTINGS_LED, "nightMode")
90
+ ZB_AUTOUPDATE = (Pages.API2_PAGE_SETTINGS_OTA, "enabled")
91
+
92
+
93
+ class WifiStatus(Enum):
94
+ WL_NO_SHIELD = 255 # for compatibility with WiFi Shield library
95
+ WL_IDLE_STATUS = 0
96
+ WL_NO_SSID_AVAIL = 1
97
+ WL_SCAN_COMPLETED = 2
98
+ WL_CONNECTED = 3
99
+ WL_CONNECT_FAILED = 4
100
+ WL_CONNECTION_LOST = 5
101
+ WL_DISCONNECTED = 6
102
+
103
+
104
+ class WifiMode(Enum):
105
+ WIFI_MODE_NULL = 0 # null mode
106
+ WIFI_MODE_STA = 1 # WiFi station mode
107
+ WIFI_MODE_AP = 2 # WiFi soft-AP mode
108
+ WIFI_MODE_APSTA = 3 # WiFi station + soft-AP mode
109
+ WIFI_MODE_MAX = 4
@@ -0,0 +1,13 @@
1
+ """Exceptions for pysmlight"""
2
+
3
+
4
+ class SmlightError(Exception):
5
+ """Generic SMLIGHT exception."""
6
+
7
+
8
+ class SmlightConnectionError(SmlightError):
9
+ """SMLIGHT connection exception."""
10
+
11
+
12
+ class SmlightAuthError(SmlightError):
13
+ """SMLIGHT authentication exception."""
@@ -0,0 +1,78 @@
1
+ from dataclasses import dataclass
2
+
3
+ from mashumaro import DataClassDictMixin
4
+
5
+
6
+ @dataclass
7
+ class Firmware(DataClassDictMixin):
8
+ mode: str | None = None # ESP|ZB
9
+ type: int | None = None
10
+ notes: str | None = None
11
+ rev: str | None = None
12
+ link: str | None = None
13
+ ver: str | None = None
14
+ dev: bool = False
15
+
16
+ def set_mode(self, mode):
17
+ self.mode = mode
18
+
19
+
20
+ @dataclass
21
+ class Info(DataClassDictMixin):
22
+ coord_mode: int | str | None = None # Enum
23
+ device_ip: str | None = None
24
+ fs_total: int | None = None
25
+ fw_channel: str | None = None # dev, beta or stable
26
+ MAC: str | None = None
27
+ model: str | None = None
28
+ ram_total: int | None = None
29
+ sw_version: str | None = None
30
+ wifi_mode: int | None = None # enum (off, client, AP etc)
31
+ zb_flash_size: int | None = None
32
+ zb_hw: str | None = None
33
+ zb_ram_size: int | None = None
34
+ zb_version: int | None = None
35
+ zb_type: int | None = None # enum (coordinator, router, thread)
36
+
37
+ @classmethod
38
+ def load_payload(cls, payload):
39
+ return cls(
40
+ # coord_mode=payload.mode,
41
+ device_ip=payload.device_ip,
42
+ MAC=payload.MAC,
43
+ model=payload.model,
44
+ fw_channel="stable",
45
+ sw_version=payload.sw_version,
46
+ zb_hw=payload.zb_hw,
47
+ zb_version=int(payload.zb_version),
48
+ )
49
+
50
+ def __post_init__(self):
51
+ if self.model is not None:
52
+ self.model = self.model.replace("P", "p")
53
+
54
+
55
+ @dataclass
56
+ class Sensors(DataClassDictMixin):
57
+ esp32_temp: float = 0
58
+ zb_temp: float = 0
59
+ uptime: int = 0 # Should be timestamp
60
+ socket_uptime: int = 0 # Should be timestamp
61
+ ram_usage: int | None = None
62
+ fs_used: int | None = None
63
+ ethernet: bool = False
64
+ wifi_connected: bool = False
65
+ wifi_status: int | str | None = None # enum (off, client, AP etc)
66
+
67
+ # toggle states:
68
+ disable_leds: bool | None = None
69
+ night_mode: bool | None = None
70
+ auto_zigbee: bool | None = None
71
+
72
+ @classmethod
73
+ def load_payload(cls, payload):
74
+ return cls(
75
+ esp32_temp=payload.esp32_temp,
76
+ zb_temp=payload.zb_temp,
77
+ uptime=payload.uptime,
78
+ )
@@ -0,0 +1,38 @@
1
+ """ Handle device info for legacy firmware so can offer upgrade."""
2
+ import re
3
+
4
+
5
+ class Payload:
6
+ def __init__(self, data=None) -> None:
7
+ self.json = data
8
+ self.model = None
9
+ self.MAC = None
10
+ if data:
11
+ self.unpack()
12
+
13
+ def unpack(self):
14
+ self.device_ip = self.json["ethIp"]
15
+ self.model = self.json["DEVICE"].replace("P", "p")
16
+ self.MAC = self.json["wifiMac"]
17
+ self.coord_mode = self.clean(self.json["coordMode"])
18
+ self.sw_version = self.json["BUILD"]
19
+ self.uptime = self.clean(self.json["uptime"])
20
+ self.zb_hw = self.json["zbHw"]
21
+ self.zb_version = self.json["zbRev"]
22
+
23
+ def clean(self, str: str) -> str:
24
+ """
25
+ Strip localisation formatting, temporary for testing.
26
+ End point should be updated
27
+ """
28
+ text = None
29
+ if "U_time" in str:
30
+ text = str.replace("[U_time]^ ", "")
31
+ text = text.replace("^", ":")
32
+ else:
33
+ text = re.sub(r"\[|\]", "", str)
34
+ return text
35
+
36
+ @property
37
+ def dump(self):
38
+ return self.json
@@ -0,0 +1,65 @@
1
+ import logging
2
+ from typing import Callable
3
+
4
+ import aiohttp
5
+ from aiohttp_sse_client2 import client as sse_client
6
+
7
+ from .const import Events
8
+
9
+ _LOGGER = logging.getLogger(__name__)
10
+
11
+ # override logging level aiohttp_sse_client2 library
12
+ aiologger = logging.getLogger("aiohttp_sse_client2")
13
+ aiologger.setLevel(logging.INFO)
14
+
15
+
16
+ class sseClient:
17
+ """Initialise a client to receive Server Sent Events (SSE)"""
18
+
19
+ def __init__(self, host, session):
20
+ self.callbacks = {}
21
+ self.session = session
22
+ self.url = f"http://{host}/events"
23
+ self.timeout = aiohttp.ClientTimeout(
24
+ total=None, connect=None, sock_connect=None, sock_read=30
25
+ )
26
+
27
+ async def client(self):
28
+ while True:
29
+ await self.sse_stream()
30
+
31
+ async def sse_stream(self):
32
+ async with sse_client.EventSource(
33
+ self.url, session=self.session, timeout=self.timeout
34
+ ) as event_source:
35
+ try:
36
+ async for event in event_source:
37
+ _LOGGER.debug(event)
38
+ await self.message_handler(event)
39
+ except aiohttp.ClientConnectionError:
40
+ _LOGGER.debug("Client Connection error")
41
+ else:
42
+ _LOGGER.debug("Connection closed cleanly")
43
+
44
+ async def message_handler(self, event):
45
+ self.callbacks.get(event.type, lambda x: None)(event)
46
+ self.callbacks.get("*", lambda x: None)(event)
47
+
48
+ def register_callback(self, event: Events, cb: Callable):
49
+ """register a callback for a specific event type or all events"""
50
+ if event and event.name in self.callbacks:
51
+ _LOGGER.warning("Callback for %s already exists, overwriting", event)
52
+
53
+ if event is not None:
54
+ self.callbacks[event.name] = cb
55
+ else:
56
+ self.callbacks["*"] = cb
57
+
58
+ def deregister_callback(self, event: Events) -> Callable:
59
+ """Deregister callbacks per event type"""
60
+ cb: Callable
61
+ if event is None:
62
+ cb = self.callbacks.pop("*", None)
63
+ else:
64
+ cb = self.callbacks.pop(event.name, None)
65
+ return cb
@@ -0,0 +1,291 @@
1
+ #!/usr/bin/env python3
2
+ from collections.abc import Callable
3
+ import json
4
+ import logging
5
+ import time
6
+ from typing import Any, Dict
7
+ import urllib.parse
8
+
9
+ from aiohttp import BasicAuth, ClientSession
10
+ from aiohttp.client_exceptions import ClientConnectorError
11
+
12
+ from .const import (
13
+ FW_DEV_URL,
14
+ FW_URL,
15
+ PARAM_LIST,
16
+ Actions,
17
+ Commands,
18
+ Devices,
19
+ Events,
20
+ Pages,
21
+ )
22
+ from .exceptions import SmlightAuthError, SmlightConnectionError
23
+ from .models import Firmware, Info, Sensors
24
+ from .payload import Payload
25
+ from .sse import sseClient
26
+
27
+ try:
28
+ from . import secrets
29
+ except ImportError:
30
+ pass
31
+
32
+ _LOGGER = logging.getLogger(__name__)
33
+
34
+ start = time.time()
35
+
36
+
37
+ class webClient:
38
+ def __init__(self, host: str, session: ClientSession | None = None) -> None:
39
+ self.auth: BasicAuth | None = None
40
+ # we can't modify headers on the passed in session from HA,
41
+ # if needed can be overridden at request level
42
+ self.headers = {"Content-Type": "application/json; charset=utf-8"}
43
+ self.post_headers = {"Content-Type": "application/x-www-form-urlencoded"}
44
+ self.host = host
45
+ self.session: ClientSession | None = session
46
+
47
+ self.set_urls()
48
+
49
+ async def async_init(self) -> None:
50
+ if self.session is None:
51
+ self.session = ClientSession(headers=self.headers, auth=self.auth)
52
+ if self.host != "smlight.tech":
53
+ if await self.check_auth_needed():
54
+ _LOGGER.info("Authentication required")
55
+ # fallback to hardcoded test credentials
56
+ if secrets and self.auth is None:
57
+ self.auth = BasicAuth(secrets.apiuser, secrets.apipass)
58
+
59
+ _LOGGER.debug("Session created")
60
+
61
+ async def authenticate(self, user: str, password: str) -> bool:
62
+ """Pass in credentials and check auth is successful"""
63
+ self.auth = BasicAuth(user, password)
64
+ return not await self.check_auth_needed(True)
65
+
66
+ async def check_auth_needed(self, authenticate: bool = False) -> bool:
67
+ """
68
+ Check if authentication is needed for the device
69
+ Optionally validate authentication credentials
70
+ Raises error on Connection or Auth failure
71
+ """
72
+ if self.session is None:
73
+ self.session = ClientSession(headers=self.headers)
74
+
75
+ auth = None
76
+ res = False
77
+ if authenticate:
78
+ auth = self.auth
79
+
80
+ try:
81
+ params = {"action": Actions.API_GET_PAGE.value, "page": 1}
82
+ async with self.session.get(self.url, auth=auth, params=params) as response:
83
+ if response.status == 401:
84
+ res = True
85
+ if authenticate:
86
+ raise SmlightAuthError("Authentication Error")
87
+ except ClientConnectorError:
88
+ _LOGGER.debug("Connection error")
89
+ raise SmlightConnectionError("Connection failed")
90
+
91
+ return res
92
+
93
+ async def get(self, params: Dict[str, Any], url=None) -> str | None:
94
+ if self.session is None:
95
+ self.session = ClientSession(headers=self.headers)
96
+ if url is None:
97
+ url = self.url
98
+ async with self.session.get(
99
+ url, headers=self.headers, params=params, auth=self.auth
100
+ ) as response:
101
+ if response.status == 404:
102
+ return None
103
+ hdr = response.headers.get("respValuesArr")
104
+ if hdr is not None and (
105
+ params and int(params["action"]) == Actions.API_GET_PAGE.value
106
+ ):
107
+ return hdr
108
+ else:
109
+ return await response.text(encoding="utf-8")
110
+
111
+ async def post(self, params):
112
+ if self.session is None:
113
+ self.session = ClientSession(headers=self.headers)
114
+ data = urllib.parse.urlencode(params)
115
+ async with self.session.post(
116
+ self.setting_url,
117
+ data=data,
118
+ headers=self.post_headers,
119
+ auth=self.auth,
120
+ ) as response:
121
+ await response.text(encoding="utf-8")
122
+ return response.status == 200
123
+
124
+ def set_host(self, host: str) -> None:
125
+ self.host = host
126
+ self.set_urls()
127
+
128
+ def set_urls(self) -> None:
129
+ self.url = f"http://{self.host}/api2"
130
+ self.config_url = f"http://{self.host}/config"
131
+ self.metrics_url = f"http://{self.host}/metrics"
132
+ self.setting_url = f"http://{self.host}/settings/saveParams"
133
+ self.info_url = f"http://{self.host}/ha_info"
134
+ self.sensor_url = f"http://{self.host}/ha_sensors"
135
+
136
+ async def close(self) -> None:
137
+ if self.session is not None:
138
+ await self.session.close()
139
+ self.session = None
140
+
141
+ async def __aenter__(self) -> "webClient":
142
+ await self.async_init()
143
+ return self
144
+
145
+ async def __aexit__(self, exc_type, exc, tb) -> None:
146
+ await self.close()
147
+
148
+
149
+ class Api2(webClient):
150
+ def __init__(
151
+ self,
152
+ host: str,
153
+ *,
154
+ session: ClientSession | None = None,
155
+ sse: sseClient | None = None,
156
+ ) -> None:
157
+ self.settings_cb: Dict[str, Callable] = {}
158
+ self.cmds = CmdWrapper(self.set_cmd)
159
+ super().__init__(host, session=session)
160
+
161
+ if session is not None:
162
+ self.sse = sseClient(host, session)
163
+ elif sse:
164
+ self.sse = sse
165
+ self.sse.register_callback(Events.SAVE_PARAMS, self._handle_settings)
166
+
167
+ def _handle_settings(self, event: Events) -> None:
168
+ data = json.loads(event.data)
169
+ changes = data.pop("changes")
170
+ for setting in changes:
171
+ if setting in self.settings_cb:
172
+ result = data.copy()
173
+ result.update({setting: changes[setting]})
174
+ self.settings_cb[setting](result)
175
+
176
+ def register_settings_cb(self, setting, cb: Callable) -> None:
177
+ # callback = partial(cb, setting)
178
+ self.settings_cb[setting] = cb
179
+
180
+ async def get_device_payload(self) -> Payload:
181
+ data = await self.get_page(Pages.API2_PAGE_DASHBOARD)
182
+ res = Payload(data)
183
+ return res
184
+
185
+ async def get_firmware_version(
186
+ self, device: str | None = None, mode: str = "ESP"
187
+ ) -> list[Firmware] | None:
188
+ """Get firmware version for device and mode (ESP|ZB)"""
189
+ params = {"type": mode}
190
+ url = FW_DEV_URL if mode == "ZB" else FW_URL
191
+ response = await self.get(params=params, url=url)
192
+ data = json.loads(response)
193
+
194
+ if mode == "ZB" and device is not None:
195
+ data = data.get(str(Devices[device]), None)
196
+ if not data:
197
+ return None
198
+ else:
199
+ data = data["fw"]
200
+ fw = []
201
+ for d in data:
202
+ item = Firmware.from_dict(d)
203
+ item.set_mode(mode)
204
+ fw.append(item)
205
+ return fw
206
+
207
+ async def get_page(self, page: Pages) -> dict | None:
208
+ """Extract Respvaluesarr json from page response header"""
209
+ params = {"action": Actions.API_GET_PAGE.value, "page": page.value}
210
+ res = await self.get(params)
211
+ data = json.loads(res)
212
+ if data:
213
+ return data
214
+ return None
215
+
216
+ async def get_param(self, param) -> str | None:
217
+ if param in PARAM_LIST:
218
+ params = {"action": Actions.API_GET_PARAM.value, "param": param}
219
+ return await self.get(params)
220
+ return None
221
+
222
+ async def get_info_old(self) -> Info:
223
+ payload = await self.get_device_payload()
224
+ return Info.load_payload(payload)
225
+
226
+ async def get_info(self) -> Info:
227
+ res = await self.get(params=None, url=self.info_url)
228
+ if res is None:
229
+ res = await self.get_info_old()
230
+ return res
231
+ data = json.loads(res)
232
+ return Info.from_dict(data["Info"])
233
+
234
+ async def get_sensors(self) -> Sensors:
235
+ res = await self.get(params=None, url=self.sensor_url)
236
+ data = json.loads(res)
237
+ return Sensors.from_dict(data["Sensors"])
238
+
239
+ async def set_cmd(self, cmd: Commands) -> bool:
240
+ params = {"action": Actions.API_CMD.value, "cmd": cmd.value}
241
+ res = await self.get(params)
242
+ return res == "ok"
243
+
244
+ async def fw_update(self, mode, fw_url, fw_type=None, fw_version=None) -> None:
245
+ # Register callback 'ESP_UPD_done'? before calling this
246
+ if mode == "ZB":
247
+ params = {
248
+ "action": Actions.API_FLASH_ZB.value,
249
+ "fwUrl": fw_url,
250
+ "fwType": fw_type,
251
+ "fwVer": fw_version,
252
+ }
253
+ else:
254
+ params = {"action": Actions.API_FLASH_ESP.value, "fwUrl": fw_url}
255
+ await self.get(params)
256
+
257
+ async def set_toggle(self, page: Pages, toggle: str, value: bool) -> bool:
258
+ state = "on" if value else "off"
259
+ params = {"pageId": page.value, toggle: state, "ha": True}
260
+ res = await self.post(params)
261
+ return res
262
+
263
+ async def scan_wifi(self):
264
+ _LOGGER.debug("Scanning wifi")
265
+ self.sse.register_callback(Events.API2_WIFISCANSTATUS, self.wifi_callback)
266
+ params = {"action": Actions.API_STARTWIFISCAN.value}
267
+ await self.get(params)
268
+
269
+ def wifi_callback(self, msg):
270
+ _LOGGER.debug("WIFI callback")
271
+ _LOGGER.info(msg)
272
+ self.sse.deregister_callback(Events.API2_WIFISCANSTATUS)
273
+
274
+
275
+ class CmdWrapper:
276
+ """Convenience wrapper for HA when sending commands to the device."""
277
+
278
+ def __init__(self, set_cmd):
279
+ self.set_cmd = set_cmd
280
+
281
+ async def reboot(self):
282
+ await self.set_cmd(Commands.CMD_ESP_RES)
283
+
284
+ async def zb_bootloader(self):
285
+ await self.set_cmd(Commands.CMD_ZB_BSL)
286
+
287
+ async def zb_restart(self):
288
+ await self.set_cmd(Commands.CMD_ZB_RST)
289
+
290
+ async def zb_router(self):
291
+ await self.set_cmd(Commands.CMD_ZB_ROUTER_RECON)