pax_global_header00006660000000000000000000000064146512443130014515gustar00rootroot0000000000000052 comment=ef3f98e49b043d3823666ab7f1b18ecb1624b7d3 jafar-atili-pySwitchbee-ef3f98e/000077500000000000000000000000001465124431300166775ustar00rootroot00000000000000jafar-atili-pySwitchbee-ef3f98e/.gitignore000066400000000000000000000034711465124431300206740ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ pip-wheel-metadata/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover *.py,cover .hypothesis/ .pytest_cache/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # PEP 582; used by e.g. github.com/David-OConnor/pyflow __pypackages__/ # Celery stuff celerybeat-schedule celerybeat.pid # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ # OSX .DS_Store .travis workspace.code-workspacejafar-atili-pySwitchbee-ef3f98e/LICENSE000066400000000000000000000261351465124431300177130ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. jafar-atili-pySwitchbee-ef3f98e/MANIFEST.in000066400000000000000000000000361465124431300204340ustar00rootroot00000000000000include src/switchbee/py.typedjafar-atili-pySwitchbee-ef3f98e/README.md000066400000000000000000000066151465124431300201660ustar00rootroot00000000000000# pySwitchbee A Python module library to control [SwitchBee](https://www.switchbee.com) smart home devices. ![PyPI](https://img.shields.io/pypi/v/pyswitchbee?label=pypi%20package) ![PyPI - Downloads](https://img.shields.io/pypi/dm/pyswitchbee) ![alt text](https://brands.home-assistant.io/switchbee/logo@2x.png) ## Example code usage: ```python from asyncio import get_event_loop from aiohttp import ClientSession, ClientTimeout, TCPConnector from switchbee.api import CentralUnitAPI from switchbee.device import ApiStateCommand, DeviceType async def main(): session = ClientSession( connector=TCPConnector(ssl=False), timeout=ClientTimeout(total=3), ) cu = CentralUnitAPI("192.168.50.2", "user", "pass", session) await cu.connect() print(f"Central Unit Name: {cu.name}") print(f"Central Unit MAC: {cu.mac}") print(f"Central Unit Version: {cu.version}") devices = await cu.devices for device in devices: # set the dimmer lights to 50% brightness if device.type == DeviceType.Dimmer: print( "Discovered Dimmer device called {device.name}" " current brightness is {device.brigt}" ) await cu.set_state(device.id, 50) # set the shutters position to 30% opened if device.type == DeviceType.Shutter: print( "Discovered Shutter device called {device.name}" " current position is {device.position}" ) await cu.set_state(device.id, 30) # turn off switches if device.type == DeviceType.Switch: print( "Discovered Switch device called {device.name}" " current state is {device.state}" ) await cu.set_state(device.id, ApiStateCommand.OFF) # set timer switch on for 10 minutes if device.type == DeviceType.TimedPower: print( "Discovered Timed Power device called {device.name}" " current state is {device.state} with {device.minutes_left} " "minutes left until shutdown" ) await cu.set_state(device.id, 10) session.close() if __name__ == "__main__": get_event_loop().run_until_complete(main()) exit() ``` ## Using the CLI tool: Alternatively, it is possible to control [SwitchBee](https://www.switchbee.com) devices using the cli tool `switchbee_cli.py` as following: To list devices that currently on: `python switchbee_cli.py -i 192.168.50.2 -u USERNAME -p PASSWORD get_states --only-on` ``` '_state': 'ON', 'hardware': , 'id': 311, 'name': 'Ceiling', 'type': , 'zone': 'Outdoo Storage'} { '_state': 'ON', 'hardware': , 'id': 142, 'name': 'Spotlights', 'type': , 'zone': 'Porch'} ``` To set shutter with device id 392 position 50%: `python switchbee_cli.py -i 192.168.50.2 -u USERNAME -p PASSWORD set_state --device-id 392 --state 50` To turn on Power Timed Switch with device id 450 for 30 minutes: `python switchbee_cli.py -i 192.168.50.2 -u USERNAME -p PASSWORD set_state --device-id 450 --state 30` To turn off light with device id 122: `python switchbee_cli.py -i 192.168.50.2 -u USERNAME -p PASSWORD set_state --device-id 122 --state OFF` jafar-atili-pySwitchbee-ef3f98e/mypy.ini000066400000000000000000000007621465124431300204030ustar00rootroot00000000000000[mypy] python_version = 3.9 show_error_codes = true follow_imports = silent ignore_missing_imports = true strict_equality = true warn_incomplete_stub = true warn_redundant_casts = true warn_unused_configs = true warn_unused_ignores = true check_untyped_defs = true disallow_incomplete_defs = true disallow_subclassing_any = true disallow_untyped_calls = true disallow_untyped_decorators = true disallow_untyped_defs = true no_implicit_optional = true warn_return_any = true warn_unreachable = true jafar-atili-pySwitchbee-ef3f98e/pyproject.toml000066400000000000000000000014561465124431300216210ustar00rootroot00000000000000 [build-system] requires = ["setuptools>=61.0.0", "wheel"] build-backend = "setuptools.build_meta" [project] name = "pyswitchbee" version = "1.8.3" description = "SwitchBee Python Integration." readme = "README.md" authors = [{ name = "Jafar Atili", email = "at.jafar@outlook.com" }] keywords = [ "home", "automation", "switchbee", "smart" ] classifiers = [ "Intended Audience :: Developers", "Operating System :: OS Independent", "Topic :: Home Automation", "Topic :: Software Development :: Libraries :: Python Modules", "Typing :: Typed", "License :: OSI Approved :: Apache Software License", ] dependencies = [ "aiohttp", "awesomeversion"] requires-python = ">=3.9" [project.urls] homepage = "https://pypi.org/project/pyswitchbee/" repository = "https://github.com/jafar-atili/pySwitchbee/" jafar-atili-pySwitchbee-ef3f98e/scripts/000077500000000000000000000000001465124431300203665ustar00rootroot00000000000000jafar-atili-pySwitchbee-ef3f98e/scripts/discover.py000066400000000000000000000023021465124431300225530ustar00rootroot00000000000000#! python3 """Python script for discovering SwitchBee Central Units.""" from argparse import ArgumentParser, RawDescriptionHelpFormatter from asyncio import get_event_loop, sleep from dataclasses import asdict from pprint import PrettyPrinter from switchbee.central_unit import CentralUnitFinder, CentralUnit printer = PrettyPrinter(indent=4) parser = ArgumentParser( description="Discover and print info of SwitchBee Central Unit devices", formatter_class=RawDescriptionHelpFormatter, ) parser.add_argument( "delay", help="number of seconds to run, defaults to 3", type=int, nargs="?", default=3, ) async def print_devices( delay: int, ) -> None: """Run the SwitchBee finder and register callback for discovered devices.""" def on_device_found_callback(device: CentralUnit) -> None: """Use as a callback printing found devices.""" printer.pprint(asdict(device)) print() async with CentralUnitFinder(on_device_found_callback): await sleep(delay) if __name__ == "__main__": args = parser.parse_args() try: get_event_loop().run_until_complete(print_devices(args.delay)) except KeyboardInterrupt: exit() jafar-atili-pySwitchbee-ef3f98e/scripts/switchbee_cli.py000066400000000000000000000106721465124431300235520ustar00rootroot00000000000000import asyncio import time from argparse import ArgumentParser from dataclasses import asdict from pprint import PrettyPrinter from aiohttp import ClientSession, ClientTimeout, TCPConnector from switchbee.api.polling import CentralUnitPolling from switchbee.device import ApiStateCommand, DeviceType printer = PrettyPrinter(indent=4) import logging import sys root = logging.getLogger() root.setLevel(logging.DEBUG) handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") handler.setFormatter(formatter) root.addHandler(handler) def initialize_parser() -> ArgumentParser: parser = ArgumentParser(description="Discover and print info of SwitchBee devices") parser.add_argument( "-i", "--central-unit-ip", help="SwitchBee Central Unit IP address", type=str, required=True, ) parser.add_argument( "-u", "--username", help="SwitchBee Central Unit IP username", type=str, required=True, ) parser.add_argument( "-p", "--password", help="SwitchBee Central Unit password", type=str, required=True, ) subparsers = parser.add_subparsers(dest="action", description="supported actions") subparsers.add_parser("get_devices", help="print devices") get_states_sp = subparsers.add_parser( "get_states", help="get SwitchBee devices states" ) subparsers.add_parser("get_stats", help="get SwitchBee devices stats") subparsers.add_parser("get_configuration", help="get SwitchBee configuration") get_states_sp.add_argument( "--only-on", dest="only_on", help="show devices with state ON only", required=False, action="store_true", ) get_states_sp.add_argument( "--delay", help="Delay in seconds", type=int, default=1, ) set_state_sp = subparsers.add_parser("set_state", help="set state") set_state_sp.add_argument( "-i", "--device-id", help="device id", required=True, type=int, ) set_state_sp.add_argument( "-s", "--state", help="new state of the device", required=True, type=str, ) return parser async def main(args): session = ClientSession( connector=TCPConnector(ssl=False), timeout=ClientTimeout(total=5), ) cu = CentralUnitPolling(args.central_unit_ip, args.username, args.password, session) await cu.connect() print(f"Central Unit: {cu.name}") print(f"Central MAC: {cu.mac}") print(f"Central Version: {cu.version}") if args.action == "get_devices": for device in cu.devices.values(): printer.pprint(asdict(device)) if args.action == "get_states": sec_delay = args.delay while sec_delay: await cu.fetch_configuration() await cu.fetch_states() for device in cu.devices.values(): if args.only_on: if ( device.type == DeviceType.Shutter and device.position > 0 or device.type == DeviceType.Dimmer and device.brightness > 0 or device.type in [DeviceType.Switch, DeviceType.TimedPowerSwitch] and device.state == ApiStateCommand.ON ): printer.pprint(asdict(device)) print() else: printer.pprint(asdict(device)) print() time.sleep(1) sec_delay -= 1 if args.action == "set_state": if args.state.isdigit(): printer.pprint(await cu.set_state(args.device_id, int(args.state))) elif args.state in [ApiStateCommand.ON, ApiStateCommand.OFF]: printer.pprint(await cu.set_state(args.device_id, args.state)) else: print(f"Invalid state {args.state}, only ON|OFF|Number are allowed") if args.action == "get_stats": printer.pprint(await cu.get_stats()) if args.action == "get_configuration": printer.pprint(await cu.get_configuration()) await session.close() if __name__ == "__main__": parser = initialize_parser() args = parser.parse_args() asyncio.run(main(args)) exit() jafar-atili-pySwitchbee-ef3f98e/scripts/switchbee_rpc_cli.py000066400000000000000000000115321465124431300244120ustar00rootroot00000000000000import asyncio import time from argparse import ArgumentParser from dataclasses import asdict from pprint import PrettyPrinter import logging import sys from typing import Any from aiohttp import ClientSession, ClientTimeout, TCPConnector from switchbee.api.wsrpc import CentralUnitWsRPC from switchbee.device import ApiStateCommand printer = PrettyPrinter(indent=4) root = logging.getLogger() root.setLevel(logging.DEBUG) handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") handler.setFormatter(formatter) root.addHandler(handler) def initialize_parser() -> ArgumentParser: parser = ArgumentParser(description="Discover and print info of SwitchBee devices") parser.add_argument( "-i", "--central-unit-ip", help="SwitchBee Central Unit IP address", type=str, required=True, ) parser.add_argument( "-u", "--username", help="SwitchBee Central Unit IP username", type=str, required=True, ) parser.add_argument( "-p", "--password", help="SwitchBee Central Unit password", type=str, required=True, ) subparsers = parser.add_subparsers(dest="action", description="supported actions") subparsers.add_parser("get_devices", help="print devices") get_states_sp = subparsers.add_parser( "get_states", help="get SwitchBee devices states" ) subparsers.add_parser("get_stats", help="get SwitchBee devices stats") subparsers.add_parser("get_configuration", help="get SwitchBee configuration") get_states_sp.add_argument( "--only-on", dest="only_on", help="show devices with state ON only", required=False, action="store_true", ) get_states_sp.add_argument( "--delay", help="Delay in seconds", type=int, default=1, ) set_state_sp = subparsers.add_parser("set_state", help="set state") set_state_sp.add_argument( "-i", "--device-id", help="device id", required=True, type=int, ) set_state_sp.add_argument( "-s", "--state", help="new state of the device", required=True, type=str, ) return parser def on_notification(data: dict[str, Any]): print(f'Device {data["name"]} ({data["id"]}) state changed to {data["newValue"]}') async def main(args): async with ClientSession( connector=TCPConnector(ssl=False), timeout=ClientTimeout(total=10), ) as session: cu = CentralUnitWsRPC(args.central_unit_ip, args.username, args.password, session, on_notification) await cu.connect() await cu.fetch_configuration() await cu.fetch_states() print(f"Central Unit: {cu.name}") print(f"Central MAC: {cu.mac}") print(f"Central Version: {cu.version}") await asyncio.sleep(10000) if args.action == "get_devices": for device in cu.devices.values(): printer.pprint(asdict(device)) if args.action == "get_states": sec_delay = args.delay while sec_delay: await cu.fetch_configuration() await cu.fetch_states() for device in cu.devices.values(): if args.only_on: if ( device.type == DeviceType.Shutter and device.position > 0 or device.type == DeviceType.Dimmer and device.brightness > 0 or device.type in [DeviceType.Switch, DeviceType.TimedPowerSwitch] and device.state == ApiStateCommand.ON ): printer.pprint(asdict(device)) print() else: printer.pprint(asdict(device)) print() time.sleep(1) sec_delay -= 1 if args.action == "set_state": if args.state.isdigit(): printer.pprint(await cu.set_state(args.device_id, int(args.state))) elif args.state in [ApiStateCommand.ON, ApiStateCommand.OFF]: printer.pprint(await cu.set_state(args.device_id, args.state)) else: print(f"Invalid state {args.state}, only ON|OFF|Number are allowed") if args.action == "get_stats": printer.pprint(await cu.get_stats()) if args.action == "get_configuration": printer.pprint(await cu.get_configuration()) if __name__ == "__main__": parser = initialize_parser() args = parser.parse_args() asyncio.run(main(args)) exit() jafar-atili-pySwitchbee-ef3f98e/src/000077500000000000000000000000001465124431300174665ustar00rootroot00000000000000jafar-atili-pySwitchbee-ef3f98e/src/switchbee/000077500000000000000000000000001465124431300214435ustar00rootroot00000000000000jafar-atili-pySwitchbee-ef3f98e/src/switchbee/__init__.py000066400000000000000000000001441465124431300235530ustar00rootroot00000000000000from .const import SWITCHBEE_BRAND name = "switchbee" __all__ = ["api", "device", "central_unit"] jafar-atili-pySwitchbee-ef3f98e/src/switchbee/api/000077500000000000000000000000001465124431300222145ustar00rootroot00000000000000jafar-atili-pySwitchbee-ef3f98e/src/switchbee/api/__init__.py000066400000000000000000000011651465124431300243300ustar00rootroot00000000000000from __future__ import annotations from awesomeversion import AwesomeVersion __all__ = ["polling", "wsrpc", "central_unit"] from .polling import CentralUnitPolling from .wsrpc import ( CentralUnitWsRPC, DeviceConnectionError, InvalidMessage, ConnectionClosed, ) from .central_unit import ( SwitchBeeError, SwitchBeeTokenError, SwitchBeeDeviceOfflineError, CUVersion, ) def is_wsrpc_api(api: CentralUnitPolling | CentralUnitWsRPC) -> bool: assert isinstance(api.version, CUVersion) if AwesomeVersion(str(api.version)) >= AwesomeVersion("1.4.6.1"): return True return False jafar-atili-pySwitchbee-ef3f98e/src/switchbee/api/central_unit.py000066400000000000000000000436011465124431300252610ustar00rootroot00000000000000from __future__ import annotations import re from datetime import timedelta from logging import getLogger from typing import Any, List from abc import ABC, abstractmethod from aiohttp import ClientSession from switchbee.const import ApiAttribute, ApiCommand, ApiStatus from switchbee.device import ( DeviceType, HardwareType, SwitchBeeBaseDevice, SwitchBeeDimmer, SwitchBeeGroupSwitch, SwitchBeeRollingScenario, SwitchBeeScenario, SwitchBeeShutter, SwitchBeeSomfy, SwitchBeeSwitch, SwitchBeeThermostat, SwitchBeeTimedSwitch, SwitchBeeTimerSwitch, SwitchBeeTwoWay, ) from ..utils import timestamp_now logger = getLogger(__name__) class SwitchBeeError(Exception): pass class SwitchBeeTokenError(Exception): pass class SwitchBeeDeviceOfflineError(Exception): pass TOKEN_EXPIRATION = int(timedelta(minutes=55).total_seconds()) * 1000 STATE_MAP = [ DeviceType.Switch, DeviceType.GroupSwitch, DeviceType.Dimmer, DeviceType.Shutter, DeviceType.TimedPowerSwitch, DeviceType.Thermostat, DeviceType.TimedSwitch, ] class CUVersion: def __init__(self, version: str) -> None: self.major: int | str = 0 self.minor: int = 0 self.revision: int = 0 self.build: int = 0 self._initialize(version) def _initialize(self, version: str) -> None: if match := re.match(r"(\d+|\S)\.(\d+)\.(\d+)\((\d+)\)$", version): self.major = match.group(1) self.minor = int(match.group(2)) self.revision = int(match.group(3)) self.build = int(match.group(4)) def __repr__(self) -> str: return f"{self.major}.{self.minor}.{self.revision}.{self.build}" class CentralUnitAPI(ABC): _login_count: int = -1 # we don't count the first login _token: str | None = None _token_expiration: int = 0 def __init__( self, ip_address: str, user: str, password: str, aiohttp_session: ClientSession ) -> None: self._ip_address: str = ip_address self._username: str = user self._password: str = password self._aiohttp_session: ClientSession = aiohttp_session self._mac: str | None = None self._unique_id: str | None = None self._version: CUVersion | None = None self._name: str | None = None self._last_conf_change: int = 0 self._devices_map: dict[ int, SwitchBeeSwitch | SwitchBeeGroupSwitch | SwitchBeeTimedSwitch | SwitchBeeShutter | SwitchBeeSomfy | SwitchBeeDimmer | SwitchBeeThermostat | SwitchBeeScenario | SwitchBeeRollingScenario | SwitchBeeTimerSwitch | SwitchBeeTwoWay, ] = {} self._modules_map: dict[int, set] = {} @property def name(self) -> str | None: return self._name @property def version(self) -> CUVersion | None: return self._version @property def mac(self) -> str | None: return self._mac @property def unique_id(self) -> str | None: return self._unique_id @property def devices( self, ) -> dict[ int, SwitchBeeSwitch | SwitchBeeGroupSwitch | SwitchBeeTimedSwitch | SwitchBeeShutter | SwitchBeeSomfy | SwitchBeeDimmer | SwitchBeeThermostat | SwitchBeeScenario | SwitchBeeRollingScenario | SwitchBeeTimerSwitch | SwitchBeeTwoWay, ]: return self._devices_map @property def last_conf_change(self) -> int: return self._last_conf_change @property def devices_list( self, ) -> List[SwitchBeeBaseDevice]: return list(self._devices_map.values()) @property def reconnect_count(self) -> int: return self._login_count def module_display(self, unit_id: int) -> str: return " and ".join(list(self._modules_map[unit_id])) async def login_if_needed(self) -> None: if not self._token or (timestamp_now() >= self._token_expiration): logger.info( "Logging into the Central Unit due to %s", "invalid token" if not self._token else " expiry", ) await self._login() @abstractmethod async def connect(self) -> None: raise NotImplementedError @abstractmethod async def call( self, command: str | None = None, params: dict[str, Any] | int | list | None = None, timeout: int = 10, ) -> dict[str, Any]: raise NotImplementedError @abstractmethod async def _send_request(self, command: str, params: Any = {}) -> dict: raise NotImplementedError @abstractmethod async def _login(self) -> None: raise NotImplementedError def _update_login(self, resp: dict[str, Any]) -> None: self._login_count += 1 self._token = resp[ApiAttribute.DATA][ApiAttribute.TOKEN] # instead of dealing with time synchronization issue, we # calculate one hour from now and set it to be the expiration time of the token # self._token_expiration = resp[ApiAttribute.DATA][ApiAttribute.EXPIRATION] self._token_expiration = timestamp_now() + TOKEN_EXPIRATION async def get_configuration(self) -> dict: await self.login_if_needed() return await self._send_request(ApiCommand.GET_CONF) async def get_multiple_states(self, ids: list) -> dict: """returns JSON {'status': 'OK', 'data': [{'id': 212, 'state': 'OFF'}, {'id': 343, 'state': 'OFF'}]}""" await self.login_if_needed() if not len(ids): return {} return await self._send_request(ApiCommand.GET_MULTI_STATES, ids) async def get_state(self, id: int) -> dict: """returns JSON {'status': 'OK', 'data': 'OFF'}""" await self.login_if_needed() return await self._send_request(ApiCommand.GET_STATE, id) async def set_state(self, id: int, state: str | int | dict[str, int | str]) -> dict: """returns JSON {'status': 'OK', 'data': 'OFF/ON'}""" await self.login_if_needed() return await self._send_request( ApiCommand.OPERATE, {"directive": "SET", "itemId": id, "value": state} ) async def get_stats(self) -> dict: """returns {'status': 'OK', 'data': {}} on my unit""" await self.login_if_needed() return await self._send_request(ApiCommand.STATS) async def get_users(self) -> dict: """returns users.""" await self.login_if_needed() return await self._send_request(ApiCommand.GET_USERS) async def fetch_configuration( self, include: list[DeviceType] | None = [], ) -> None: await self.login_if_needed() data = await self.get_configuration() if data[ApiAttribute.STATUS] != ApiStatus.OK: raise SwitchBeeError # clear the old fetched devices self._devices_map.clear() self._modules_map.clear() self._name = data[ApiAttribute.DATA][ApiAttribute.NAME] self._version = CUVersion(data[ApiAttribute.DATA][ApiAttribute.VERSION]) self._mac = data[ApiAttribute.DATA][ApiAttribute.MAC] self._unique_id = ( None if ApiAttribute.CU_CODE not in data[ApiAttribute.DATA] else data[ApiAttribute.DATA][ApiAttribute.CU_CODE] ) if include is None: return for zone in data[ApiAttribute.DATA][ApiAttribute.ZONES]: for item in zone[ApiAttribute.ITEMS]: try: device_type = DeviceType(item[ApiAttribute.TYPE]) except ValueError: logger.warning( "Unknown device type %s (%s), Skipping", item[ApiAttribute.TYPE], item[ApiAttribute.NAME], ) continue except KeyError: logger.error( "device %s missing type attribute, Skipping", item[ApiAttribute.NAME], ) continue if include and device_type not in include: logger.info( "Skipping %s (%s)", device_type.value, item[ApiAttribute.NAME] ) continue try: device_hw = HardwareType(item[ApiAttribute.HARDWARE]) except ValueError: logger.warning( "Unknown hardware type %s (%s), Skipping", item[ApiAttribute.HARDWARE], item[ApiAttribute.NAME], ) continue except KeyError: logger.error( "device %s missing hardware attribute, Skipping", item[ApiAttribute.NAME], ) continue try: device_id = item[ApiAttribute.ID] except KeyError: logger.error( "device %s missing id attribute, Skipping", item, ) continue try: device_name = item[ApiAttribute.NAME] except KeyError: logger.error( "device %s missing name attribute, Skipping", item, ) device_name = "Unknown" # add switch type device if device_type == DeviceType.Switch: self._devices_map[item[ApiAttribute.ID]] = SwitchBeeSwitch( id=device_id, name=device_name, zone=zone[ApiAttribute.NAME], hardware=device_hw, type=device_type, ) # add dimmer (light) device elif device_type == DeviceType.Dimmer: self._devices_map[item[ApiAttribute.ID]] = SwitchBeeDimmer( id=device_id, name=device_name, zone=zone[ApiAttribute.NAME], hardware=device_hw, type=device_type, ) # add shutter device elif device_type == DeviceType.Shutter: self._devices_map[item[ApiAttribute.ID]] = SwitchBeeShutter( id=device_id, name=device_name, zone=zone[ApiAttribute.NAME], hardware=device_hw, type=device_type, ) # add timed power switch device elif device_type == DeviceType.TimedPowerSwitch: self._devices_map[item[ApiAttribute.ID]] = SwitchBeeTimerSwitch( id=device_id, name=device_name, zone=zone[ApiAttribute.NAME], hardware=device_hw, type=device_type, ) # add scenario elif device_type == DeviceType.Scenario: self._devices_map[item[ApiAttribute.ID]] = SwitchBeeScenario( id=device_id, name=device_name, zone=zone[ApiAttribute.NAME], hardware=device_hw, type=device_type, ) # add group switch only of hardware type != VIRTUAL as we can't read their statuses elif ( device_type == DeviceType.GroupSwitch and device_hw != HardwareType.Virtual ): self._devices_map[item[ApiAttribute.ID]] = SwitchBeeGroupSwitch( id=device_id, name=device_name, zone=zone[ApiAttribute.NAME], hardware=device_hw, type=device_type, ) elif device_type in [DeviceType.Thermostat, DeviceType.VRFAC]: self._devices_map[item[ApiAttribute.ID]] = SwitchBeeThermostat( id=device_id, name=device_name, zone=zone[ApiAttribute.NAME], hardware=device_hw, type=device_type, modes=item[ApiAttribute.MODES], temperature_unit=item[ApiAttribute.TEMPERATURE_UNITS], ) # add rolling scenario elif device_type == DeviceType.RollingScenario: self._devices_map[item[ApiAttribute.ID]] = SwitchBeeRollingScenario( id=device_id, name=device_name, zone=zone[ApiAttribute.NAME], hardware=device_hw, type=device_type, ) # add timed switch elif device_type == DeviceType.TimedSwitch: self._devices_map[item[ApiAttribute.ID]] = SwitchBeeTimedSwitch( id=device_id, name=device_name, zone=zone[ApiAttribute.NAME], hardware=device_hw, type=device_type, ) # add two way elif device_type == DeviceType.TwoWay: self._devices_map[item[ApiAttribute.ID]] = SwitchBeeTwoWay( id=device_id, name=device_name, zone=zone[ApiAttribute.NAME], hardware=device_hw, type=device_type, ) # add somfy elif device_type == DeviceType.Somfy: self._devices_map[item[ApiAttribute.ID]] = SwitchBeeSomfy( id=device_id, name=device_name, zone=zone[ApiAttribute.NAME], hardware=device_hw, type=device_type, ) # add gro else: logger.warning( f"Unsupported Type {item[ApiAttribute.TYPE]} {item[ApiAttribute.HARDWARE]}" ) continue unit_id = self._devices_map[item[ApiAttribute.ID]].unit_id if unit_id not in self._modules_map: self._modules_map[unit_id] = set() self._modules_map[unit_id].add( self._devices_map[item[ApiAttribute.ID]].hardware.display ) async def fetch_states( self, ) -> None: states = await self.get_multiple_states( [ dev for dev in self._devices_map.keys() if (self._devices_map[dev].hardware != HardwareType.Virtual or self._devices_map[dev].type == DeviceType.VRFAC) and self._devices_map[dev].type in [ DeviceType.Switch, DeviceType.GroupSwitch, DeviceType.Dimmer, DeviceType.Shutter, DeviceType.TimedPowerSwitch, DeviceType.Thermostat, DeviceType.TimedSwitch, DeviceType.VRFAC, ] ] ) if not states: logger.debug('get_multiple_states returned empty dict') return for device_state in states[ApiAttribute.DATA]: device_id = device_state[ApiAttribute.ID] self.update_device_state(device_id, device_state[ApiAttribute.STATE]) def update_device_state(self, device_id: int, new_state: str | int | dict) -> bool: """Update device state.""" if device_id not in self._devices_map: logger.debug("Device id %d is not tracked", device_id) return False device = self._devices_map[device_id] if isinstance(device, SwitchBeeDimmer): assert isinstance(new_state, (str, int)) device.brightness = new_state # type: ignore elif isinstance(device, SwitchBeeShutter): assert isinstance(new_state, (str, int)) device.position = new_state # type: ignore elif isinstance( device, ( SwitchBeeSwitch, SwitchBeeGroupSwitch, SwitchBeeTimedSwitch, SwitchBeeTimerSwitch, ), ): assert isinstance(new_state, (int, str)) device.state = new_state elif isinstance(device, SwitchBeeThermostat): if not isinstance(new_state, dict): logger.warning( "%s: Received invalid state from CU, keeping the old one: %s", device.name, new_state, ) return False try: device.state = new_state[ApiAttribute.POWER] except TypeError: logger.warning( "%s: Received invalid state from CU, keeping the old one: %s", device.name, new_state, ) return False device.mode = new_state[ApiAttribute.MODE] device.fan = new_state[ApiAttribute.FAN] device.target_temperature = new_state[ApiAttribute.CONFIGURED_TEMPERATURE] device.temperature = new_state[ApiAttribute.ROOM_TEMPERATURE] else: return False return True jafar-atili-pySwitchbee-ef3f98e/src/switchbee/api/polling.py000066400000000000000000000076331465124431300242430ustar00rootroot00000000000000from __future__ import annotations from asyncio import TimeoutError from datetime import timedelta from json import JSONDecodeError from logging import getLogger from typing import Any from .central_unit import ( CentralUnitAPI, SwitchBeeError, SwitchBeeTokenError, SwitchBeeDeviceOfflineError, ) from aiohttp import ClientSession from aiohttp.client_exceptions import ClientConnectorError from switchbee.const import ApiAttribute, ApiCommand, ApiStatus logger = getLogger(__name__) class CentralUnitPolling(CentralUnitAPI): def __init__( self, ip_address: str, username: str, password: str, aiohttp_session: ClientSession, ) -> None: super().__init__(ip_address, username, password, aiohttp_session) async def connect(self) -> None: await self.fetch_configuration(None) await self.fetch_states() async def call( self, command: str | None = None, params: dict[str, Any] | int | list | None = None, timeout: int = 10, ) -> dict[str, Any]: """Websocket RPC call.""" body = { ApiAttribute.COMMAND: command, ApiAttribute.PARAMS: params, ApiAttribute.TOKEN: self._token, } try: async with self._aiohttp_session.post( url=f"https://{self._ip_address}/commands", json=body ) as response: if response.status == 200: try: json_result: dict = await response.json( content_type=None, encoding="utf8" ) if json_result[ApiAttribute.STATUS] != ApiStatus.OK: # check if invalid token or token expired if json_result[ApiAttribute.STATUS] in [ ApiStatus.INVALID_TOKEN, ApiStatus.TOKEN_EXPIRED, ]: self._token = None raise SwitchBeeTokenError( json_result[ApiAttribute.STATUS] ) if json_result[ApiAttribute.STATUS] == ApiStatus.OFFLINE: raise SwitchBeeDeviceOfflineError( f"Central Unit replied with bad status ({json_result[ApiAttribute.STATUS]}): {json_result}" ) raise SwitchBeeError( f"Central Unit replied with bad status ({json_result[ApiAttribute.STATUS]}): {json_result}" ) else: return json_result except JSONDecodeError: raise SwitchBeeError(f"Unexpected response: {response.read()}") else: raise SwitchBeeError( f"Request to the Central Unit failed with status={response.status}" ) except TimeoutError as exp: raise SwitchBeeError( "Timed out while waiting for the Central Unit to reply" ) from exp except ClientConnectorError as exp: raise SwitchBeeError("Failed to communicate with the Central Unit") from exp async def _login(self) -> None: try: resp = await self.call( ApiCommand.LOGIN, { ApiAttribute.USER: self._username, ApiAttribute.PASS: self._password, }, ) except SwitchBeeError: self._token = None self._token_expiration = 0 raise super()._update_login(resp) async def _send_request(self, command: str, params: Any = {}) -> dict: return await self.call(command, params) jafar-atili-pySwitchbee-ef3f98e/src/switchbee/api/wsrpc.py000066400000000000000000000177211465124431300237340ustar00rootroot00000000000000from __future__ import annotations from asyncio import Future, TimeoutError, create_task, tasks from dataclasses import dataclass from logging import getLogger from typing import Any, Callable from .central_unit import CentralUnitAPI, SwitchBeeError import async_timeout from aiohttp import ClientSession, ClientWebSocketResponse, WSMessage, WSMsgType from aiohttp.client_exceptions import ClientError, WSServerHandshakeError from switchbee.const import ApiAttribute, ApiCommand logger = getLogger(__name__) class DeviceConnectionError(Exception): pass class InvalidMessage(Exception): pass class ConnectionClosed(Exception): pass async def receive_json_or_raise(msg: WSMessage) -> dict[str, Any]: """Receive json or raise.""" if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSED, WSMsgType.CLOSING): raise ConnectionClosed("Connection was closed.") if msg.type == WSMsgType.ERROR: raise InvalidMessage("Received message error") if msg.type != WSMsgType.TEXT: raise InvalidMessage(f"Received non-Text message: {msg.type}") try: data: dict[str, Any] = msg.json() except ValueError as err: raise InvalidMessage(f"Received invalid JSON: {msg.data}") from err if status := data.get("status") == "ERROR": raise SwitchBeeError("Response Error: %s", data) return data @dataclass class SessionData: """SessionData (src/dst/auth) class.""" src: str | None dst: str | None auth: dict[str, Any] | None class RPCCall: """RPCCall class.""" def __init__( self, call_id: int, command: str | None, params: dict[str, Any] | int | list | None, token: str | None, session: SessionData, ): """Initialize RPC class.""" self.auth = session.auth self.call_id = call_id self.command = command self.params = params self.token = token self.src = session.src self.dst = session.dst self.resolve: Future = Future() @property def request_frame(self) -> dict[str, Any]: """Request frame.""" msg: dict[str, Any] = {"commandId": self.call_id, "command": self.command} if self.params: msg["params"] = self.params if self.token: msg["token"] = self.token return msg class CentralUnitWsRPC(CentralUnitAPI): def __init__( self, ip_address: str, user_name: str, password: str, aiohttp_session: ClientSession, on_notification: Callable | None = None, ) -> None: super().__init__(ip_address, user_name, password, aiohttp_session) self._client: ClientWebSocketResponse | None = None self._receive_task: tasks.Task[None] | None = None self._calls: dict[int, RPCCall] = {} self._on_notification = on_notification self._call_id = 0 self._session = SessionData(f"swb-{id(self)}", None, None) @property def connected(self) -> bool: """Return if we're currently connected.""" return self._client is not None and not self._client.closed @property def _next_id(self) -> int: self._call_id += 1 return self._call_id def subscribe_updates(self, callback: Callable) -> None: self._on_notification = callback async def connect(self) -> None: if self.connected: raise RuntimeError("Already connected") logger.debug("Trying to connect to device at %s", self._ip_address) try: self._client = await self._aiohttp_session.ws_connect( f"http://{self._ip_address}:7891" ) except ( WSServerHandshakeError, ClientError, ) as err: raise DeviceConnectionError(err) from err except TimeoutError as err: raise DeviceConnectionError(err) from err self._receive_task = create_task(self._rx_msgs()) await self._login() await self.fetch_configuration() await self.fetch_states() logger.info("Connected to %s", self._ip_address) async def _send_json(self, data: dict[str, Any]) -> None: """Send json frame to device.""" logger.debug("send(%s): %s", self._ip_address, data) assert self._client await self._client.send_json(data) async def _rx_msgs(self) -> None: assert self._client while not self._client.closed: try: msg = await self._client.receive() frame = await receive_json_or_raise(msg) logger.debug("recv(%s): %s", self._ip_address, frame) except InvalidMessage as err: logger.error( "Invalid Message from central unit %s: %s", self._ip_address, err ) except ConnectionClosed: break except SwitchBeeError as err: logger.error( "Response error from central unit %s: %s", self._ip_address, err ) if not self._client.closed: self.handle_frame(frame) logger.debug("Websocket client connection from %s closed", self._ip_address) for call_item in self._calls.values(): call_item.resolve.cancel() self._calls.clear() if not self._client.closed: await self._client.close() self._client = None def handle_frame(self, frame: dict[str, Any]) -> None: """Handle RPC frame.""" if command_id := frame.get("commandId"): # looks like a response if command_id not in self._calls: logger.warning("Response for an unknown request id: %s", command_id) return call = self._calls.pop(command_id) if not call.resolve.cancelled(): call.resolve.set_result(frame) else: if notification_type := frame.get("notificationType"): # this is a notification logger.debug("Notification %s %s", notification_type, frame) # update the devices states based on the event self.update_device_state_from_event(frame) if self._on_notification: self._on_notification(frame) else: logger.warning("Invalid frame: %s", frame) async def call( self, command: str | None = None, params: dict[str, Any] | int | list | None = None, timeout: int = 10, ) -> dict[str, Any]: """Websocket RPC call.""" if self._client is None: raise RuntimeError("Not connected") call = RPCCall(self._next_id, command, params, self._token, self._session) self._calls[call.call_id] = call try: async with async_timeout.timeout(timeout): await self._send_json(call.request_frame) resp: dict[str, Any] = await call.resolve except TimeoutError as exc: raise DeviceConnectionError(call) from exc logger.debug("%s -> %s", call.params, resp) return resp async def _send_request( self, command: str, params: dict[str, Any] | int | list | None = None ) -> dict: if not self.connected: await self.connect() return await self.call(command, params) async def _login(self) -> None: resp = await self.call( ApiCommand.LOGIN, { ApiAttribute.USER: self._username, ApiAttribute.PASS: self._password, }, ) super()._update_login(resp) def update_device_state_from_event(self, push_data: dict) -> None: """Update device state from notification data.""" if ApiAttribute.ID not in push_data: logger.error("Received update with no device id: %s", push_data) return self.update_device_state( push_data[ApiAttribute.ID], push_data[ApiAttribute.NEW_VALUE] ) jafar-atili-pySwitchbee-ef3f98e/src/switchbee/central_unit/000077500000000000000000000000001465124431300241325ustar00rootroot00000000000000jafar-atili-pySwitchbee-ef3f98e/src/switchbee/central_unit/__init__.py000066400000000000000000000100371465124431300262440ustar00rootroot00000000000000from __future__ import annotations import socket from asyncio import BaseTransport, DatagramProtocol, DatagramTransport, get_running_loop from dataclasses import dataclass from json import loads from logging import getLogger from types import TracebackType from typing import Any, Callable, Optional, Type, cast _LOGGER = getLogger(__name__) PORT = 8872 @dataclass class CentralUnit: """Central Unit data class.""" name: str version: str mac_address: str switches: int ip_address: str external_ip_address: str port: int timezone: int timezone_name: str time_str: str no_users: bool class UdpClientProtocol(DatagramProtocol): def __init__(self, on_datagram: Callable[[CentralUnit], Any]): self.message = "FIND" self.transport: DatagramTransport | None = None self._on_datagram = on_datagram def connection_made(self, transport: BaseTransport) -> None: self.transport = cast(DatagramTransport, transport) sock = transport.get_extra_info("socket") sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) self.broadcast() def datagram_received(self, data: bytes, addr: tuple[str, int]) -> None: _LOGGER.debug("Received:", data.decode()) if data: json_data = loads(data.decode()) json_data["internalIp"] = addr[0] self._on_datagram( CentralUnit( json_data["name"], json_data["CUVersion"], str(json_data["mac"]).replace("-", ":"), json_data["switches"], addr[0], json_data["ip"], json_data["port"], json_data["timeZone"], json_data["timeZoneName"], json_data["timeStr"], json_data["NoUsers"], ) ) def error_received(self, exc: Optional[Exception]) -> None: _LOGGER.error("Error received:", exc) def broadcast(self) -> None: _LOGGER.debug("sending:", self.message) assert self.transport self.transport.sendto(self.message.encode(), ("255.255.255.255", PORT)) def connection_lost(self, exc: Optional[Exception]) -> None: if exc: _LOGGER.critical(f"udp bridge lost its connection {exc}") else: _LOGGER.info("udp connection stopped") class CentralUnitFinder: def __init__( self, on_device: Callable[[CentralUnit], Any], ) -> None: self._on_device = on_device self._central_units: dict[str, Any] = {} self._transport: BaseTransport | None = None self._is_running = False async def __aenter__(self) -> "CentralUnitFinder": """Enter CentralUnitFinder asynchronous context manager.""" await self.start() return self async def __aexit__( self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType], ) -> None: """Exit the CentralUnitFinder asynchronous context manager.""" await self.stop() async def start(self) -> None: """Create an asynchronous listener and start the bridge.""" _LOGGER.info("starting the udp bridge on port %s", PORT) transport, protocol = await get_running_loop().create_datagram_endpoint( lambda: UdpClientProtocol(self._on_device), family=socket.AF_INET, ) self._transport = transport _LOGGER.debug("udp bridge on port %s started", PORT) self._is_running = True async def stop(self) -> None: """Stop the asynchronous bridge.""" if self._transport and not self._transport.is_closing(): _LOGGER.info("stopping the udp bridge on port %s", PORT) self._transport.close() else: _LOGGER.info("udp bridge on port %s not started", PORT) self._is_running = False jafar-atili-pySwitchbee-ef3f98e/src/switchbee/const.py000066400000000000000000000047641465124431300231560ustar00rootroot00000000000000class ApiCommand: # SwitchBee Request commands LOGIN = "LOGIN" GET_CONF = "GET_CONFIGURATION" GET_MULTI_STATES = "GET_MULTIPLE_STATES" GET_STATE = "GET_STATE" STATS = "STATS" OPERATE = "OPERATE" STATE = "STATE" GET_USERS = "GET_USERS" class ApiStatus: FAILED = "FAILED" OK = "OK" INVALID_TOKEN = "INVALID_TOKEN" TOKEN_EXPIRED = "TOKEN_EXPIRED" LOGIN_FAILED = "LOGIN_FAILED" OFFLINE = "OFFLINE" class ApiAttribute: # SwitchBee request attributes COMMAND = "command" PARAMS = "params" USER = "username" PASS = "password" DATA = "data" MAC = "mac" STATUS = "status" EXPIRATION = "expiration" TOKEN = "token" ZONES = "zones" ITEMS = "items" TYPE = "type" ID = "id" STATE = "state" NAME = "name" HARDWARE = "hw" VERSION = "version" LAST_CONF_CHANGE = "lastConfChange" TEMPERATURE_UNITS = "temperatureUnits" MODES = "modes" POWER = "power" MODE = "mode" FAN = "fan" CONFIGURED_TEMPERATURE = "configuredTemperature" ROOM_TEMPERATURE = "roomTemperature" NEW_VALUE = "newValue" CU_CODE = "cuCode" class ApiStateCommand: ON = "ON" OFF = "OFF" OFFLINE = "OFFLINE" # SwitchBee device hardware class ApiDeviceHardware: DIMMABLE_SWITCH = "DIMMABLE_SWITCH" SHUTTER = "SHUTTER" VIRTUAL = "VIRTUAL" TIMED_POWER_SWITCH = "TIMED_POWER_SWITCH" THERMOSTAT = "THERMOSTAT" SOCKET_IR = "SOCKET_IR" SOMFY = "SOMFY" IRRIGATION = "IRRIGATION" REPEATER = "REPEATER" GROUP_SWITCH = "GROUP_SWITCH" STIKER_SWITCH = "STIKER_SWITCH" REGULAR_SWITCH = "REGULAR_SWITCH" class ApiDeviceType: # SwitchBee device types DIMMER = "DIMMER" REPEATER = "REPEATER" SWITCH = "SWITCH" SHUTTER = "SHUTTER" TWO_WAY = "TWO_WAY" GROUP_SWITCH = "GROUP_SWITCH" SCENARIO = "SCENARIO" TIMED_POWER = "TIMED_POWER" IR_DEVICE = "IR_DEVICE" THERMOSTAT = "THERMOSTAT" LOCK_GROUP = "LOCK_GROUP" TIMED_SWITCH = "TIMED_SWITCH" LOUVERED_SHUTTER = "LOUVERED_SHUTTER" SOMFY = "SOMFY" ROLLING_SCENARIO = "ROLLING_SCENARIO" VRF_AC = "VRF_AC" class ThermostatMode: HEAT = "HEAT" COOL = "COOL" FAN = "FAN" class ThermostatFanSpeed: LOW = "LOW" MEDIUM = "MED" HIGH = "HIGH" AUTO = "AUTO" class ThermostatTemperatureUnit: CELSIUS = "CELSIUS" FAHRENHEIT = "FAHRENHEIT" SWITCHBEE_BRAND = "SwitchBee" class SomfyCommand: UP = "UP" DOWN = "DOWN" MY = "MY" jafar-atili-pySwitchbee-ef3f98e/src/switchbee/device/000077500000000000000000000000001465124431300227025ustar00rootroot00000000000000jafar-atili-pySwitchbee-ef3f98e/src/switchbee/device/__init__.py000066400000000000000000000234411465124431300250170ustar00rootroot00000000000000from __future__ import annotations from abc import ABC from dataclasses import dataclass, field from enum import Enum, unique from typing import Any, List, final from ..const import ApiDeviceHardware, ApiDeviceType, ApiStateCommand from ..utils import timestamp_now @unique class DeviceType(Enum): """Enum class representing the device's type.""" Dimmer = ApiDeviceType.DIMMER, "Light" Switch = ApiDeviceType.SWITCH, "Switch" Shutter = ApiDeviceType.SHUTTER, "Shutter" Scenario = ApiDeviceType.SCENARIO, "Scenario" Repeater = ApiDeviceType.REPEATER, "Repeater" GroupSwitch = ApiDeviceType.GROUP_SWITCH, "Group Switch" TwoWay = ApiDeviceType.TWO_WAY, "Two Way" TimedPowerSwitch = ApiDeviceType.TIMED_POWER, "Timed Power Switch" Thermostat = ApiDeviceType.THERMOSTAT, "Thermostat" LockGroup = ApiDeviceType.LOCK_GROUP, "Lock Group" TimedSwitch = ApiDeviceType.TIMED_SWITCH, "Timed Switch" Somfy = ApiDeviceType.SOMFY, "Somfy" IrDevice = ApiDeviceType.IR_DEVICE, "Infra Red Device" RollingScenario = ApiDeviceType.ROLLING_SCENARIO, "Rolling Scenario" VRFAC = ApiDeviceType.VRF_AC, "VRF Unit" def __new__(cls, *args: Any, **kwds: Any): # type: ignore obj = object.__new__(cls) obj._value_ = args[0] return obj # ignore the first param since it's already set by __new__ def __init__(self, _: str, display: str = "") -> None: self._display = display def __str__(self) -> str: return self.display # this makes sure that the description is read-only @property def display(self) -> str: return self._display class HardwareType(Enum): Virtual = ApiDeviceHardware.VIRTUAL, "Virtual" Dimmable = ApiDeviceHardware.DIMMABLE_SWITCH, "Switch" Shutter = ApiDeviceHardware.SHUTTER, "Shutter" TimedPowerSwitch = ApiDeviceHardware.TIMED_POWER_SWITCH, "Timed Power Switch" Thermostat = ApiDeviceHardware.THERMOSTAT, "CoolSwitch" Somfy = ApiDeviceHardware.SOMFY, "Somfy" SocketIR = ApiDeviceHardware.SOCKET_IR, "Socket IR" StickerSwitch = ApiDeviceHardware.STIKER_SWITCH, "Sticker Switch" RegularSwitch = ApiDeviceHardware.REGULAR_SWITCH, "Regular Switch" Repeater = ApiDeviceHardware.REPEATER, "Repeater" def __new__(cls, *args: Any, **kwds: Any): # type: ignore obj = object.__new__(cls) obj._value_ = args[0] return obj # ignore the first param since it's already set by __new__ def __init__(self, _: str, display: str = "") -> None: self._display = display def __str__(self) -> str: return self.display # this makes sure that the description is read-only @property def display(self) -> str: return self._display @dataclass class SwitchBeeBaseDevice(ABC): id: int name: str zone: str type: DeviceType hardware: HardwareType def __post_init__(self) -> None: """Post initialization, set last_data_update to the instantiation datetime.""" self.last_data_update = timestamp_now() self.unit_id = self.id // 10 def __hash__(self) -> int: return self.id @dataclass class SwitchBeeBaseSwitch(ABC): _state: str | int | None = field(init=False, default=None) @property def state(self) -> str | int | None: return self._state @state.setter def state(self, value: str | int) -> None: if value in [ApiStateCommand.OFF, 0]: self._state = ApiStateCommand.OFF elif value in [ApiStateCommand.ON, 100]: self._state = ApiStateCommand.ON else: # OFFLINE self._state = -1 @dataclass class SwitchBeeBaseShutter(ABC): _position: int | None = field(init=False, default=None) @property def position(self) -> int | None: return self._position @position.setter def position(self, value: str | int) -> None: if isinstance(value, int): self._position = int(value) else: if value == ApiStateCommand.ON: self._position = 100 elif value == ApiStateCommand.OFF: self._position = 0 else: # OFFLINE self._position = -1 @dataclass class SwitchBeeBaseDimmer(ABC): _brightness: int = field(init=False, repr=False) @property def brightness(self) -> int: return self._brightness @brightness.setter def brightness(self, value: str | int) -> None: if isinstance(value, int): self._brightness = int(value) else: if value == ApiStateCommand.ON: self._brightness = 100 elif value == ApiStateCommand.OFF: self._brightness = 0 else: # OFFLINE self._brightness = -1 @dataclass class SwitchBeeBaseTimer(ABC): _minutes_left: int = field(init=False, repr=False) _state: str | int = field(init=False, repr=False) @property def state(self) -> str | int: return self._state @state.setter def state(self, value: str | int) -> None: if value: if value == ApiStateCommand.OFF: self._minutes_left = 0 self._state = value elif value == ApiStateCommand.OFFLINE: self._minutes_left = -1 self._state = -1 else: self._minutes_left = int(value) self._state = ApiStateCommand.ON @property def minutes_left(self) -> int: return self._minutes_left @dataclass class SwitchBeeBaseThermostat(ABC): modes: List[str] temperature_unit: str mode: str = field(init=False, repr=False) fan: str = field(init=False, repr=False) target_temperature: int = field(init=False, repr=False) temperature: int = field(init=False, repr=False) max_temperature: int = 31 min_temperature: int = 16 @final @dataclass class SwitchBeeSwitch(SwitchBeeBaseSwitch, SwitchBeeBaseDevice): def __post_init__(self) -> None: """Post initialization validate device type category as Switch.""" if self.type != DeviceType.Switch: raise ValueError("only Switch are allowed") super().__post_init__() @final @dataclass class SwitchBeeShutter(SwitchBeeBaseShutter, SwitchBeeBaseDevice): def __post_init__(self) -> None: """Post initialization validate device type category as Shutter.""" if self.type != DeviceType.Shutter: raise ValueError("only Shutter are allowed") super().__post_init__() @final @dataclass class SwitchBeeDimmer(SwitchBeeBaseDimmer, SwitchBeeBaseDevice): def __post_init__(self) -> None: """Post initialization validate device type category as Dimmer.""" if self.type != DeviceType.Dimmer: raise ValueError("only Dimmer are allowed") super().__post_init__() @final @dataclass class SwitchBeeTimerSwitch(SwitchBeeBaseTimer, SwitchBeeBaseDevice): def __post_init__(self) -> None: """Post initialization validate device type category as TimedPowerSwitch.""" if self.type != DeviceType.TimedPowerSwitch: raise ValueError("only TimedPowerSwitch are allowed") super().__post_init__() @final @dataclass class SwitchBeeScenario(SwitchBeeBaseDevice): def __post_init__(self) -> None: """Post initialization validate device type category as Scenario.""" if self.type != DeviceType.Scenario: raise ValueError("only Scenario are allowed") super().__post_init__() @final @dataclass class SwitchBeeRollingScenario(SwitchBeeBaseDevice): def __post_init__(self) -> None: """Post initialization validate device type category as Rolling Scenario.""" if self.type != DeviceType.RollingScenario: raise ValueError("only Rolling Scenario are allowed") super().__post_init__() @final @dataclass class SwitchBeeGroupSwitch(SwitchBeeBaseSwitch, SwitchBeeBaseDevice): def __post_init__(self) -> None: """Post initialization validate device type category as GroupSwitch.""" if self.type != DeviceType.GroupSwitch: raise ValueError("only GroupSwitch are allowed") super().__post_init__() @final @dataclass class SwitchBeeTimedSwitch(SwitchBeeBaseSwitch, SwitchBeeBaseDevice): def __post_init__(self) -> None: """Post initialization validate device type category as TimedSwitch.""" if self.type != DeviceType.TimedSwitch: raise ValueError("only TimedSwitch are allowed") super().__post_init__() @final @dataclass class SwitchBeeThermostat( SwitchBeeBaseThermostat, SwitchBeeBaseSwitch, SwitchBeeBaseDevice ): def __post_init__(self) -> None: """Post initialization validate device type category as Thermostat.""" if self.type not in [DeviceType.Thermostat, DeviceType.VRFAC]: raise ValueError("only Thermostat are allowed") super().__post_init__() @final @dataclass class SwitchBeeLockGroup(SwitchBeeBaseSwitch, SwitchBeeBaseDevice): def __post_init__(self) -> None: """Post initialization validate device type category as Switch.""" if self.type != DeviceType.LockGroup: raise ValueError("only lock group are allowed") super().__post_init__() @final @dataclass class SwitchBeeTwoWay(SwitchBeeBaseSwitch, SwitchBeeBaseDevice): def __post_init__(self) -> None: """Post initialization validate device type category as TwoWay.""" if self.type != DeviceType.TwoWay: raise ValueError("only Two Way are allowed") super().__post_init__() @final @dataclass class SwitchBeeSomfy(SwitchBeeBaseDevice): def __post_init__(self) -> None: """Post initialization validate device type category as Scenario.""" if self.type != DeviceType.Somfy: raise ValueError("only Scenario are allowed") super().__post_init__() jafar-atili-pySwitchbee-ef3f98e/src/switchbee/py.typed000066400000000000000000000000001465124431300231300ustar00rootroot00000000000000jafar-atili-pySwitchbee-ef3f98e/src/switchbee/utils.py000066400000000000000000000002271465124431300231560ustar00rootroot00000000000000from datetime import datetime def timestamp_now() -> int: """Returns the current timestamp.""" return int(datetime.now().timestamp() * 1000) jafar-atili-pySwitchbee-ef3f98e/tests/000077500000000000000000000000001465124431300200415ustar00rootroot00000000000000jafar-atili-pySwitchbee-ef3f98e/tests/resources/000077500000000000000000000000001465124431300220535ustar00rootroot00000000000000jafar-atili-pySwitchbee-ef3f98e/tests/resources/GET_CONFIGURATION.json000066400000000000000000000470671465124431300254720ustar00rootroot00000000000000{ "status": "OK", "data": { "mac": "D2-CB-2E-78-B0-35", "name": "Home", "version": "1.4.3(0)", "lastConfChange": 1653316439851, "zones": [{ "name": "קומה ראשית", "items": [{ "operations": [{ "itemId": 2, "value": 29 }, { "itemId": 1, "value": 35 }, { "itemId": 22, "value": 29 }, { "itemId": 31, "value": 29 }, { "itemId": 41, "value": 29 }, { "itemId": 21, "value": 29 }], "id": 100040, "name": "שלב אור", "hw": "VIRTUAL", "type": "SCENARIO" }, { "id": 561, "name": "תקרה", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "operations": [{ "itemId": 2, "value": 0 }, { "itemId": 1, "value": 0 }, { "itemId": 22, "value": 0 }, { "itemId": 31, "value": 0 }, { "itemId": 41, "value": 0 }, { "itemId": 21, "value": 0 }], "id": 100030, "name": "סגירת חלונות", "hw": "VIRTUAL", "type": "SCENARIO" }, { "id": 181, "name": "מדרגות קיר עליו", "hw": "DIMMABLE_SWITCH", "type": "DIMMER" }, { "id": 571, "name": "Repeater", "hw": "REPEATER", "type": "REPEATER" }, { "id": 121, "name": "מחסן (תחת מדרגות)", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 182, "name": "מדרגות תחתון", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }] }, { "name": "סלון ראשי", "items": [{ "id": 592, "name": "תאורה צפונית", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 591, "name": "תאורה דרומית", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 71, "name": "קיר", "hw": "DIMMABLE_SWITCH", "type": "DIMMER" }, { "id": 593, "name": "לד מזנון", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "operations": [593, 581, 171], "id": 481, "name": "לדים", "hw": "DIMMABLE_SWITCH", "type": "GROUP_SWITCH" }, { "id": 22, "name": "מזרחי", "hw": "SHUTTER", "type": "SHUTTER" }, { "id": 21, "name": "צפוני", "hw": "SHUTTER", "type": "SHUTTER" }] }, { "name": "סלון", "items": [{ "id": 12, "name": "קיר", "hw": "DIMMABLE_SWITCH", "type": "DIMMER" }, { "id": 1, "name": "צפוני", "hw": "SHUTTER", "type": "SHUTTER" }, { "id": 2, "name": "מערבי", "hw": "SHUTTER", "type": "SHUTTER" }, { "id": 11, "name": "תקרה", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }] }, { "name": "מטבח", "items": [{ "id": 132, "name": "פס צבירה", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 131, "name": "חדר אוכל", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 31, "name": "מטבח", "hw": "SHUTTER", "type": "SHUTTER" }, { "id": 41, "name": "חדר אוכל", "hw": "SHUTTER", "type": "SHUTTER" }, { "id": 91, "name": "ממ״ד", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 581, "name": "לד ", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 171, "name": "לד", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "operations": [581, 171], "id": 612, "name": "לדים", "hw": "DIMMABLE_SWITCH", "type": "GROUP_SWITCH" }] }, { "name": "Two Way Zone", "items": [{ "operations": [221], "id": 281, "name": "תאורת קיר מיטה", "hw": "DIMMABLE_SWITCH", "type": "TWO_WAY" }, { "operations": [182], "id": 292, "name": "מדרגות", "hw": "DIMMABLE_SWITCH", "type": "TWO_WAY" }, { "operations": [301], "id": 321, "name": "מסדרון תקרה", "hw": "DIMMABLE_SWITCH", "type": "TWO_WAY" }, { "operations": [301], "id": 331, "name": "מסדרון תקרה", "hw": "DIMMABLE_SWITCH", "type": "TWO_WAY" }, { "operations": [352], "id": 362, "name": "תאורת תקרה", "hw": "DIMMABLE_SWITCH", "type": "TWO_WAY" }, { "operations": [351], "id": 361, "name": "קיר ימין", "hw": "DIMMABLE_SWITCH", "type": "TWO_WAY" }, { "operations": [353], "id": 363, "name": "קיר שמאל", "hw": "DIMMABLE_SWITCH", "type": "TWO_WAY" }, { "operations": [301], "id": 161, "name": "מסדרון תקרה", "hw": "DIMMABLE_SWITCH", "type": "TWO_WAY" }, { "operations": [511], "id": 532, "name": "מדרגות", "hw": "DIMMABLE_SWITCH", "type": "TWO_WAY" }, { "operations": [212], "id": 242, "name": "לד", "hw": "DIMMABLE_SWITCH", "type": "TWO_WAY" }, { "operations": [212], "id": 271, "name": "לד", "hw": "DIMMABLE_SWITCH", "type": "TWO_WAY" }, { "operations": [192], "id": 342, "name": "תקרה", "hw": "DIMMABLE_SWITCH", "type": "TWO_WAY" }, { "operations": [302], "id": 322, "name": "קיר", "hw": "DIMMABLE_SWITCH", "type": "TWO_WAY" }, { "operations": [302], "id": 332, "name": "קיר", "hw": "DIMMABLE_SWITCH", "type": "TWO_WAY" }, { "operations": [302], "id": 162, "name": "קיר", "hw": "DIMMABLE_SWITCH", "type": "TWO_WAY" }, { "operations": [211], "id": 282, "name": "קיר", "hw": "DIMMABLE_SWITCH", "type": "TWO_WAY" }, { "operations": [211], "id": 232, "name": "קיר", "hw": "DIMMABLE_SWITCH", "type": "TWO_WAY" }, { "operations": [181], "id": 291, "name": "מדרגות עליון", "hw": "DIMMABLE_SWITCH", "type": "TWO_WAY" }, { "operations": [592], "id": 72, "name": "תאורה צפונית", "hw": "DIMMABLE_SWITCH", "type": "TWO_WAY" }, { "operations": [213], "id": 272, "name": "ספוטים חש", "hw": "DIMMABLE_SWITCH", "type": "TWO_WAY" }, { "operations": [213], "id": 241, "name": "ספוטים חש", "hw": "DIMMABLE_SWITCH", "type": "TWO_WAY" }, { "operations": [561], "id": 611, "name": "תקרה קומה ראשית", "hw": "DIMMABLE_SWITCH", "type": "TWO_WAY" }] }, { "name": "שירותי אורחים", "items": [{ "id": 102, "name": "וונטה", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 101, "name": "תאורה", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }] }, { "name": "משרד", "items": [{ "id": 343, "name": "קיר שמאל", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 341, "name": "קיר ימין", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 191, "name": "חלון ", "hw": "SHUTTER", "type": "SHUTTER" }, { "id": 192, "name": "תקרה", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }] }, { "name": "מקלחת ילדים", "items": [{ "id": 201, "name": "חלון", "hw": "SHUTTER", "type": "SHUTTER" }] }, { "name": "מקלחת הורים", "items": [{ "id": 432, "name": "תאורת מראה", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 433, "name": "וונטה", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 421, "name": "חלון צפוני", "hw": "SHUTTER", "type": "SHUTTER" }, { "id": 431, "name": "תאורת תקרה", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 551, "name": "מחמם מגבות", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }] }, { "name": "חדר ארונות", "items": [{ "id": 413, "name": "תאורת תקרה", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 411, "name": "חלון מזרחי", "hw": "SHUTTER", "type": "SHUTTER" }] }, { "name": "חדר שינה", "items": [{ "id": 221, "name": "תאורת קיר מיטה", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 251, "name": "טואלט", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 262, "name": "חלון צפוני", "hw": "SHUTTER", "type": "SHUTTER" }, { "id": 261, "name": "חלון מערבי", "hw": "SHUTTER", "type": "SHUTTER" }, { "id": 212, "name": "לד חדר שינה", "hw": "DIMMABLE_SWITCH", "type": "DIMMER" }, { "id": 231, "name": "תאורת קריאה דרו", "hw": "DIMMABLE_SWITCH", "type": "DIMMER" }, { "id": 211, "name": "קיר", "hw": "DIMMABLE_SWITCH", "type": "DIMMER" }, { "id": 222, "name": "מיטה צד שמאל", "hw": "DIMMABLE_SWITCH", "type": "DIMMER" }, { "id": 213, "name": "ספוטים", "hw": "DIMMABLE_SWITCH", "type": "DIMMER" }] }, { "name": "מסדרון קומה 2", "items": [{ "id": 301, "name": "תאורת תקרה", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 302, "name": "תאורת קיר", "hw": "DIMMABLE_SWITCH", "type": "DIMMER" }, { "id": 601, "name": "בוילר", "hw": "TIMED_POWER_SWITCH", "type": "TIMED_POWER" }] }, { "name": "מחסן חיצוני", "items": [{ "id": 152, "name": "קיר חוץ", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 151, "name": "תקרה חוץ", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 311, "name": "תקרה פנים", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }] }, { "name": "מרפסת כניסה", "items": [{ "id": 112, "name": "ספוטים", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 141, "name": "כניסה", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 142, "name": "שקוע רצפה", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 111, "name": "שרשרת", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 502, "name": "מדרגות", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }] }, { "name": "חדר שינה מערבי", "items": [{ "id": 353, "name": "קיר שמאל", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 351, "name": "קיר ימין", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 352, "name": "תאורת תקרה", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 372, "name": "חלון מערבי", "hw": "SHUTTER", "type": "SHUTTER" }, { "id": 371, "name": "חלון דרומי", "hw": "SHUTTER", "type": "SHUTTER" }] }, { "name": "חוץ", "items": [{ "id": 381, "name": "אפ/דאון דרומי", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 442, "name": "פרוזקטורים צפון", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 441, "name": "פרוז׳קטורים דרום", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 452, "name": "פרוזקטורים מערב", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 451, "name": "פרוזקטורים מזרח", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 382, "name": "אפ/דאון צפוני", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 462, "name": "אפ/דאון מערבי", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 461, "name": "אפ/דאון מזרחי", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "operations": [442, 441, 452, 451], "id": 100400, "name": "פרוז׳קטורים", "hw": "VIRTUAL", "type": "GROUP_SWITCH" }] }, { "name": "גדר", "items": [{ "id": 391, "name": "אפ/דאון גדר פנים מזרח", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 392, "name": "אפ/דאון גדר פנים צפון", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 401, "name": "ספוטים מזרחיים", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 483, "name": "אפ/דאון שער חוץ", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 482, "name": "אפ/דאון כניסה חוץ", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 491, "name": "ספוטים כניסה", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 402, "name": "ספוטים צפון", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 493, "name": "אפ דאון מערב", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }] }, { "name": "סצנות", "items": [{ "operations": [142, 381, 382, 462, 461, 483, 482], "id": 100310, "name": "תאורת חוץ", "hw": "VIRTUAL", "type": "GROUP_SWITCH" }, { "operations": [{ "itemId": 21, "value": 100 }, { "itemId": 22, "value": 100 }, { "itemId": 1, "value": 100 }, { "itemId": 2, "value": 100 }, { "itemId": 31, "value": 100 }, { "itemId": 41, "value": 100 }], "id": 100350, "name": "פתיחת חלונות קומה 1", "hw": "VIRTUAL", "type": "SCENARIO" }, { "operations": [{ "itemId": 21, "value": 0 }, { "itemId": 22, "value": 0 }, { "itemId": 1, "value": 0 }, { "itemId": 2, "value": 0 }, { "itemId": 31, "value": 0 }, { "itemId": 41, "value": 0 }, { "itemId": 201, "value": 0 }, { "itemId": 421, "value": 0 }, { "itemId": 411, "value": 0 }, { "itemId": 261, "value": 0 }, { "itemId": 372, "value": 0 }, { "itemId": 371, "value": 0 }], "id": 62, "name": "סגירת חלונות", "hw": "DIMMABLE_SWITCH", "type": "SCENARIO" }, { "operations": [{ "itemId": 21, "value": 0 }, { "itemId": 22, "value": 0 }, { "itemId": 1, "value": 0 }, { "itemId": 2, "value": 0 }, { "itemId": 31, "value": 0 }, { "itemId": 41, "value": 0 }], "id": 100360, "name": "סגירת חלונות קומה 1", "hw": "VIRTUAL", "type": "SCENARIO" }, { "operations": [{ "itemId": 201, "value": 0 }, { "itemId": 421, "value": 0 }, { "itemId": 411, "value": 0 }, { "itemId": 261, "value": 0 }, { "itemId": 372, "value": 0 }, { "itemId": 371, "value": 0 }], "id": 100370, "name": "סגירת חלונות קומה 2", "hw": "VIRTUAL", "type": "SCENARIO" }, { "operations": [{ "itemId": 201, "value": 100 }, { "itemId": 421, "value": 100 }, { "itemId": 411, "value": 100 }, { "itemId": 261, "value": 100 }, { "itemId": 372, "value": 100 }, { "itemId": 371, "value": 100 }], "id": 100380, "name": "פתיחת חלונות קומה 2", "hw": "VIRTUAL", "type": "SCENARIO" }, { "operations": [511, 531], "id": 100440, "name": "מדרגות", "hw": "VIRTUAL", "type": "GROUP_SWITCH" }, { "operations": [{ "itemId": 21, "value": 33 }, { "itemId": 22, "value": 30 }, { "itemId": 1, "value": 34 }, { "itemId": 2, "value": 32 }, { "itemId": 31, "value": 30 }, { "itemId": 41, "value": 35 }], "id": 61, "name": "שלב אור קומה 1", "hw": "DIMMABLE_SWITCH", "type": "SCENARIO" }, { "operations": [{ "itemId": 121, "value": 0 }, { "itemId": 182, "value": 0 }, { "itemId": 561, "value": 0 }, { "itemId": 181, "value": 0 }, { "itemId": 21, "value": 0 }, { "itemId": 22, "value": 0 }, { "itemId": 71, "value": 0 }, { "itemId": 593, "value": 0 }, { "itemId": 592, "value": 0 }, { "itemId": 591, "value": 0 }, { "itemId": 11, "value": 0 }, { "itemId": 1, "value": 0 }, { "itemId": 2, "value": 0 }, { "itemId": 12, "value": 0 }, { "itemId": 132, "value": 0 }, { "itemId": 131, "value": 0 }, { "itemId": 31, "value": 0 }, { "itemId": 41, "value": 0 }, { "itemId": 91, "value": 0 }, { "itemId": 581, "value": 0 }, { "itemId": 171, "value": 0 }, { "itemId": 102, "value": 0 }, { "itemId": 101, "value": 0 }, { "itemId": 343, "value": 0 }, { "itemId": 341, "value": 0 }, { "itemId": 191, "value": 0 }, { "itemId": 192, "value": 0 }, { "itemId": 201, "value": 0 }, { "itemId": 432, "value": 0 }, { "itemId": 433, "value": 0 }, { "itemId": 421, "value": 0 }, { "itemId": 431, "value": 0 }, { "itemId": 551, "value": 0 }, { "itemId": 413, "value": 0 }, { "itemId": 411, "value": 0 }, { "itemId": 221, "value": 0 }, { "itemId": 251, "value": 0 }, { "itemId": 261, "value": 0 }, { "itemId": 212, "value": 0 }, { "itemId": 231, "value": 0 }, { "itemId": 211, "value": 0 }, { "itemId": 301, "value": 0 }, { "itemId": 302, "value": 0 }, { "itemId": 601, "value": 0 }, { "itemId": 152, "value": 0 }, { "itemId": 151, "value": 0 }, { "itemId": 311, "value": 0 }, { "itemId": 353, "value": 0 }, { "itemId": 351, "value": 0 }, { "itemId": 352, "value": 0 }, { "itemId": 372, "value": 0 }, { "itemId": 371, "value": 0 }, { "itemId": 511, "value": 0 }, { "itemId": 512, "value": 0 }, { "itemId": 513, "value": 0 }, { "itemId": 531, "value": 0 }, { "itemId": 523, "value": 0 }, { "itemId": 522, "value": 0 }, { "itemId": 521, "value": 0 }, { "itemId": 542, "value": 0 }], "id": 100540, "name": "Good Nigh", "hw": "VIRTUAL", "type": "SCENARIO" }] }, { "name": "קומה 3", "items": [{ "id": 511, "name": "קיר מדרגות", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 512, "name": "תקרה (מ.כביסה)", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 513, "name": "תקרה", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 531, "name": "תקרה (מדרגות)", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }] }, { "name": "גג", "items": [{ "id": 523, "name": "פרוז׳קטור צפון", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 522, "name": "פרוז׳קטור מזרח", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }, { "id": 521, "name": "פרוז׳קטור דרום", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }] }, { "name": "חדר שינה מזרחי", "items": [{ "id": 542, "name": "תקרה", "hw": "DIMMABLE_SWITCH", "type": "SWITCH" }] }] } }