pax_global_header00006660000000000000000000000064150225232310014505gustar00rootroot0000000000000052 comment=47fb2d2847a5fc72573d8fc4b3c61cbb6dea6794 Explicatis-GmbH-pysmarlaapi-01906c0/000077500000000000000000000000001502252323100172115ustar00rootroot00000000000000Explicatis-GmbH-pysmarlaapi-01906c0/.github/000077500000000000000000000000001502252323100205515ustar00rootroot00000000000000Explicatis-GmbH-pysmarlaapi-01906c0/.github/workflows/000077500000000000000000000000001502252323100226065ustar00rootroot00000000000000Explicatis-GmbH-pysmarlaapi-01906c0/.github/workflows/publish.yml000066400000000000000000000064621502252323100250070ustar00rootroot00000000000000name: Publish Python 🐍 distribution 📦 to PyPI and TestPyPI on: push jobs: build: name: Build distribution 📦 runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: persist-credentials: false - name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.x" - name: Install pypa/build run: >- python3 -m pip install build --user - name: Build a binary wheel and a source tarball run: python3 -m build - name: Store the distribution packages uses: actions/upload-artifact@v4 with: name: python-package-distributions path: dist/ publish-to-pypi: name: >- Publish Python 🐍 distribution 📦 to PyPI if: startsWith(github.ref, 'refs/tags/') # only publish to PyPI on tag pushes needs: - build runs-on: ubuntu-latest environment: name: pypi url: https://pypi.org/p/pysmarlaapi permissions: id-token: write # IMPORTANT: mandatory for trusted publishing steps: - name: Download all the dists uses: actions/download-artifact@v4 with: name: python-package-distributions path: dist/ - name: Publish distribution 📦 to PyPI uses: pypa/gh-action-pypi-publish@release/v1 github-release: name: >- Sign the Python 🐍 distribution 📦 with Sigstore and upload them to GitHub Release needs: - publish-to-pypi runs-on: ubuntu-latest permissions: contents: write # IMPORTANT: mandatory for making GitHub Releases id-token: write # IMPORTANT: mandatory for sigstore steps: - name: Download all the dists uses: actions/download-artifact@v4 with: name: python-package-distributions path: dist/ - name: Sign the dists with Sigstore uses: sigstore/gh-action-sigstore-python@v3.0.0 with: inputs: >- ./dist/*.tar.gz ./dist/*.whl - name: Create GitHub Release env: GITHUB_TOKEN: ${{ github.token }} run: >- gh release create "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" --notes "" - name: Upload artifact signatures to GitHub Release env: GITHUB_TOKEN: ${{ github.token }} # Upload to GitHub Release using the `gh` CLI. # `dist/` contains the built packages, and the # sigstore-produced signatures and certificates. run: >- gh release upload "$GITHUB_REF_NAME" dist/** --repo "$GITHUB_REPOSITORY" publish-to-testpypi: name: Publish Python 🐍 distribution 📦 to TestPyPI needs: - build runs-on: ubuntu-latest environment: name: testpypi url: https://test.pypi.org/p/pysmarlaapi permissions: id-token: write # IMPORTANT: mandatory for trusted publishing steps: - name: Download all the dists uses: actions/download-artifact@v4 with: name: python-package-distributions path: dist/ - name: Publish distribution 📦 to TestPyPI uses: pypa/gh-action-pypi-publish@release/v1 with: repository-url: https://test.pypi.org/legacy/ Explicatis-GmbH-pysmarlaapi-01906c0/.gitignore000066400000000000000000000034651502252323100212110ustar00rootroot00000000000000# 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/ # Ignore config file with secrets /config.py Explicatis-GmbH-pysmarlaapi-01906c0/.pre-commit-config.yaml000066400000000000000000000027111502252323100234730ustar00rootroot00000000000000ci: autoupdate_commit_msg: "chore: update pre-commit hooks" autofix_commit_msg: "style: pre-commit fixes" repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.1.0 hooks: - id: check-added-large-files - id: check-case-conflict - id: check-merge-conflict - id: check-symlinks - id: check-yaml - id: debug-statements - id: end-of-file-fixer - id: mixed-line-ending - id: requirements-txt-fixer - id: trailing-whitespace - repo: https://github.com/PyCQA/isort rev: 5.12.0 hooks: - id: isort - repo: https://github.com/asottile/pyupgrade rev: v2.31.0 hooks: - id: pyupgrade args: [--py37-plus] - repo: https://github.com/hadialqattan/pycln rev: v1.2.5 hooks: - id: pycln args: [--config=pyproject.toml] stages: [manual] - repo: https://github.com/codespell-project/codespell rev: v2.1.0 hooks: - id: codespell - repo: https://github.com/pre-commit/pygrep-hooks rev: v1.9.0 hooks: - id: python-check-blanket-noqa - id: python-check-blanket-type-ignore - id: python-no-log-warn - id: python-no-eval - id: python-use-type-annotations - id: rst-backticks - id: rst-directive-colons - id: rst-inline-touching-normal - repo: https://github.com/mgedmin/check-manifest rev: "0.47" hooks: - id: check-manifest stages: [manual] Explicatis-GmbH-pysmarlaapi-01906c0/.pypirc000066400000000000000000000002361502252323100205210ustar00rootroot00000000000000[distutils] index-servers = pypi testpypi [pypi] repository = https://upload.pypi.org/legacy/ [testpypi] repository = https://test.pypi.org/legacy/ Explicatis-GmbH-pysmarlaapi-01906c0/.vscode/000077500000000000000000000000001502252323100205525ustar00rootroot00000000000000Explicatis-GmbH-pysmarlaapi-01906c0/.vscode/settings.json000066400000000000000000000010561502252323100233070ustar00rootroot00000000000000{ "editor.formatOnSave": true, "editor.formatOnPaste": true, "files.trimTrailingWhitespace": true, "files.autoSave": "onFocusChange", "git.autofetch": true, "[jsonc]": { "editor.defaultFormatter": "vscode.json-language-features" }, "[python]": { "editor.defaultFormatter": "ms-python.black-formatter" }, "pylint.args": [ "--rcfile=pyproject.toml" ], "black-formatter.args": [ "--config=pyproject.toml" ], "isort.args": [ "--settings-path=pyproject.toml" ] } Explicatis-GmbH-pysmarlaapi-01906c0/LICENSE000066400000000000000000000261351502252323100202250ustar00rootroot00000000000000 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. Explicatis-GmbH-pysmarlaapi-01906c0/README.md000066400000000000000000000006061502252323100204720ustar00rootroot00000000000000# pysmarlaapi A python library providing an API for Swing2Sleep Smarla. This library will let you control your Swing2Sleep Smarla device. It requires the firmware of the Smarla device to be version 1.6.X or newer. Otherwise you cannot connect/pair to your device. ## Library usage Install pysmarlaapi using pip ### Example usage Please refer to the examples provided in the repository. Explicatis-GmbH-pysmarlaapi-01906c0/pyproject.toml000066400000000000000000000107221502252323100221270ustar00rootroot00000000000000[build-system] requires = ["flit_core >=3.12,<4"] build-backend = "flit_core.buildapi" [project] name = "pysmarlaapi" authors = [ {name = "Robin Lintermann", email = "robin.lintermann@explicatis.com"}, ] classifiers = [ "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", ] dependencies = [ "aiohttp~=3.11", "jsonpickle~=4.0.0", "pysignalr~=1.1.0", ] description = "Swing2Sleep Smarla API" license = "Apache-2.0" readme = "README.md" requires-python = ">=3.11" dynamic = ["version"] [project.urls] Repository = "https://github.com/Explicatis-GmbH/pysmarlaapi" Issues = "https://github.com/Explicatis-GmbH/pysmarlaapi/issues" [tool.flit.module] name = "pysmarlaapi" [tool.black] line-length = 120 fast = true [tool.flake8] max-line-length = 120 select = "F,E,W,B,B901,B902,B903" exclude = [ ".eggs", ".git", ".tox", "nssm", "obj", "out", "packages", "pywin32", "tests", "swagger_client" ] ignore = [ "E722", "B001", "W503", "E203" ] [tool.pylint] extension-pkg-whitelist= [ "numpy", "torch", "cv2", "pyodbc", "pydantic", "ciso8601", "netcdf4", "scipy" ] ignore="CVS" ignore-patterns="test.*?py,conftest.py" init-hook='import sys; sys.setrecursionlimit(8 * sys.getrecursionlimit())' jobs=0 limit-inference-results=100 persistent="yes" suggestion-mode="yes" unsafe-load-any-extension="no" [tool.pylint.'MESSAGES CONTROL'] enable="c-extension-no-member" [tool.pylint.'REPORTS'] evaluation="10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)" output-format="text" reports="no" score="yes" [tool.pylint.'REFACTORING'] max-nested-blocks=5 never-returning-functions="sys.exit" [tool.pylint.'BASIC'] argument-naming-style="snake_case" attr-naming-style="snake_case" bad-names= [ "foo", "bar" ] class-attribute-naming-style="any" class-naming-style="PascalCase" const-naming-style="UPPER_CASE" docstring-min-length=-1 function-naming-style="snake_case" good-names= [ "i", "j", "k", "ex", "Run", "_" ] include-naming-hint="yes" inlinevar-naming-style="any" method-naming-style="snake_case" module-naming-style="any" no-docstring-rgx="^_" property-classes="abc.abstractproperty" variable-naming-style="snake_case" [tool.pylint.'FORMAT'] ignore-long-lines="^\\s*(# )?.*['\"]??" indent-after-paren=4 indent-string=' ' max-line-length=120 max-module-lines=1000 single-line-class-stmt="no" single-line-if-stmt="no" [tool.pylint.'LOGGING'] logging-format-style="old" logging-modules="logging" [tool.pylint.'MISCELLANEOUS'] notes= [ "FIXME", "XXX", "TODO" ] [tool.pylint.'SIMILARITIES'] ignore-comments="yes" ignore-docstrings="yes" ignore-imports="yes" min-similarity-lines=7 [tool.pylint.'SPELLING'] max-spelling-suggestions=4 spelling-store-unknown-words="no" [tool.pylint.'STRING'] check-str-concat-over-line-jumps="no" [tool.pylint.'TYPECHECK'] contextmanager-decorators="contextlib.contextmanager" generated-members="numpy.*,np.*,pyspark.sql.functions,collect_list" ignore-mixin-members="yes" ignore-none="yes" ignore-on-opaque-inference="yes" ignored-classes="optparse.Values,thread._local,_thread._local,numpy,torch,swagger_client" ignored-modules="numpy,torch,swagger_client,netCDF4,scipy" missing-member-hint="yes" missing-member-hint-distance=1 missing-member-max-choices=1 [tool.pylint.'VARIABLES'] additional-builtins="dbutils" allow-global-unused-variables="yes" callbacks= [ "cb_", "_cb" ] dummy-variables-rgx="_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_" ignored-argument-names="_.*|^ignored_|^unused_" init-import="no" redefining-builtins-modules="six.moves,past.builtins,future.builtins,builtins,io" [tool.pylint.'CLASSES'] defining-attr-methods= [ "__init__", "__new__", "setUp", "__post_init__" ] exclude-protected= [ "_asdict", "_fields", "_replace", "_source", "_make" ] valid-classmethod-first-arg="cls" valid-metaclass-classmethod-first-arg="cls" [tool.pylint.'DESIGN'] max-args=5 max-attributes=7 max-bool-expr=5 max-branches=12 max-locals=15 max-parents=7 max-public-methods=20 max-returns=6 max-statements=50 min-public-methods=2 [tool.pylint.'IMPORTS'] allow-wildcard-with-all="no" analyse-fallback-blocks="no" deprecated-modules="optparse,tkinter.tix" [tool.pylint.'EXCEPTIONS'] overgeneral-exceptions= [ "BaseException", "Exception" ] Explicatis-GmbH-pysmarlaapi-01906c0/pysmarlaapi/000077500000000000000000000000001502252323100215335ustar00rootroot00000000000000Explicatis-GmbH-pysmarlaapi-01906c0/pysmarlaapi/__init__.py000066400000000000000000000001321502252323100236400ustar00rootroot00000000000000__version__ = "0.9.0" from .classes import Connection from .federwiege import Federwiege Explicatis-GmbH-pysmarlaapi-01906c0/pysmarlaapi/classes/000077500000000000000000000000001502252323100231705ustar00rootroot00000000000000Explicatis-GmbH-pysmarlaapi-01906c0/pysmarlaapi/classes/__init__.py000066400000000000000000000001051502252323100252750ustar00rootroot00000000000000from .auth_token import AuthToken from .connection import Connection Explicatis-GmbH-pysmarlaapi-01906c0/pysmarlaapi/classes/auth_token.py000066400000000000000000000016561502252323100257130ustar00rootroot00000000000000import base64 import json from dataclasses import dataclass from typing import Self import jsonpickle @dataclass class AuthToken: refreshToken: str token: str dateCreated: str appIdentifier: str serialNumber: str appVersion: str appCulture: str @classmethod def from_json(cls, value: dict) -> Self: value["py/object"] = "pysmarlaapi.classes.auth_token.AuthToken" return jsonpickle.decode(json.dumps(value)) @classmethod def from_string(cls, value: str) -> Self: return AuthToken.from_json(json.loads(value)) @classmethod def from_base64(cls, value: str) -> Self: token = base64.b64decode(value.encode()).decode() return AuthToken.from_string(token) def get_string(self) -> str: return jsonpickle.encode(self, unpicklable=False) def get_base64(self) -> str: return base64.b64encode(self.get_string().encode()).decode() Explicatis-GmbH-pysmarlaapi-01906c0/pysmarlaapi/classes/connection.py000066400000000000000000000030171502252323100257020ustar00rootroot00000000000000import asyncio import aiohttp import jsonpickle from . import AuthToken class Connection: def __init__(self, url: str, token: AuthToken = None, token_str=None, token_json=None, token_b64=None): self.url = url if token is not None: self.token = token elif token_json is not None: self.token = AuthToken.from_json(token_json) elif token_str is not None: self.token = AuthToken.from_string(token_str) elif token_b64 is not None: self.token = AuthToken.from_base64(token_b64) else: self.token = None def get_token(self) -> str: return self.token.token async def refresh_token(self) -> bool: try: async with aiohttp.ClientSession(self.url) as session: content = await self._get_token(session) except (aiohttp.ClientError, asyncio.TimeoutError): return False if not content: return False try: self.token = AuthToken.from_json(content) except ValueError: return False return True async def _get_token(self, session: aiohttp.ClientSession): async with await session.post( "/api/AppParing/getToken", headers={"accept": "*/*", "Content-Type": "application/json"}, data=jsonpickle.encode(self.token, unpicklable=False), ) as response: if response.status != 200: return None return await response.json() Explicatis-GmbH-pysmarlaapi-01906c0/pysmarlaapi/connection_hub/000077500000000000000000000000001502252323100245305ustar00rootroot00000000000000Explicatis-GmbH-pysmarlaapi-01906c0/pysmarlaapi/connection_hub/__init__.py000066400000000000000000000105331502252323100266430ustar00rootroot00000000000000import asyncio import logging import random import uuid from pysignalr.client import SignalRClient from pysignalr.transport.abstract import ConnectionState from ..classes import Connection async def event_wait(event, timeout): try: await asyncio.wait_for(event.wait(), timeout) except asyncio.TimeoutError: return class ConnectionHub: """SignalRCore Hub Provides interface via websocket for the controller using the SignalRCore protocol. """ @property def running(self): return self._running @property def connected(self): return self.client._transport._state == ConnectionState.connected if self.client else False def __init__( self, event_loop: asyncio.AbstractEventLoop, connection: Connection, interval: int = 60, backoff: int = 300, ): self.connection: Connection = connection self._loop = event_loop self._interval = interval self._backoff = backoff self.logger = logging.getLogger(f"{__package__}[{self.connection.token.serialNumber}]") self.listeners = set() self._running = False self._wake = asyncio.Event() self.client = None self.setup() async def notifycontrollerconnection(self, args): value = args[0] if value == "ControllerConnected": await self.notify_listeners(True) else: await self.notify_listeners(False) def setup(self): self.client = SignalRClient(self.connection.url + "/MobileAppHub", retry_count=1) self.client.on_open(self.on_open_function) self.client.on_close(self.on_close_function) self.client.on_error(self.on_error) self.client.on("SetNotifyAppConnectionCallback", self.notifycontrollerconnection) def add_listener(self, listener): if self.running: return self.listeners.add(listener) def remove_listener(self, listener): if self.running: return self.listeners.remove(listener) async def notify_listeners(self, value): for listener in self.listeners: await listener(value) async def on_open_function(self): self.logger.info("Connection to server established") async def on_close_function(self): self.logger.info("Connection to server closed") async def on_error(self, message): self.logger.error("Connection error occurred: %s", str(message)) def start(self): if self.running: return self._running = True asyncio.run_coroutine_threadsafe(self.connection_watcher(), self._loop) def stop(self): if not self.running: return self._running = False self.close_connection() self.wake_up() async def connection_watcher(self): while self.running: await self.refresh_token() try: await self.client.run() except Exception as e: self.logger.warning("Error during connection: %s: %s", type(e).__name__, str(e)) # Random backoff to avoid simultaneous connection attempts backoff = random.randint(0, self._backoff) await event_wait(self._wake, self._interval + backoff) self._wake.clear() def wake_up(self): self._wake.set() def close_connection(self): if not self.connected: return asyncio.run_coroutine_threadsafe(self.client._transport._ws.close(), self._loop) async def refresh_token(self): await self.connection.refresh_token() self.client._transport._headers["Authorization"] = f"Bearer {self.connection.get_token()}" self.logger.info("Auth token refreshed") def send_serialized_data(self, event, value=None): serialized_result = { "callIdentifier": { "requestNonce": str(uuid.uuid4()), }, } if value is not None: serialized_result["value"] = value self.logger.debug("Sending data, Event: %s, Payload: %s", event, str(serialized_result)) asyncio.run_coroutine_threadsafe(self.async_send_data(event, [serialized_result]), self._loop) async def async_send_data(self, event, data): try: await self.client.send(event, data) except Exception: pass Explicatis-GmbH-pysmarlaapi-01906c0/pysmarlaapi/federwiege/000077500000000000000000000000001502252323100236415ustar00rootroot00000000000000Explicatis-GmbH-pysmarlaapi-01906c0/pysmarlaapi/federwiege/__init__.py000066400000000000000000000036151502252323100257570ustar00rootroot00000000000000import asyncio import threading from ..classes import Connection from ..connection_hub import ConnectionHub from .classes import Service from .services import AnalyserService, BabywiegeService, InfoService class Federwiege: @property def running(self): return self.hub.running @property def connected(self): return self.hub.connected async def on_controller_connection_change(self, value): self.available = value if value: self.sync() def __init__(self, event_loop: asyncio.AbstractEventLoop, connection: Connection): self.serial_number = connection.token.serialNumber self.hub = ConnectionHub(event_loop, connection) self.services: dict[str, Service] = { "babywiege": BabywiegeService(self.hub), "analyser": AnalyserService(self.hub), "info": InfoService(self.hub), } self.registered = False self._lock = threading.Lock() self.available = False def get_service(self, key: str): if key not in self.services: return None return self.services[key] def get_property(self, service_key: str, prop_key: str): service = self.get_service(service_key) if not service: return None return service.get_property(prop_key) def connect(self): with self._lock: if not self.registered: return self.hub.start() def disconnect(self): self.hub.stop() def sync(self): for service in self.services.values(): service.sync() def register(self): with self._lock: if self.registered: return self.registered = True self.hub.add_listener(self.on_controller_connection_change) for service in self.services.values(): service.register() Explicatis-GmbH-pysmarlaapi-01906c0/pysmarlaapi/federwiege/classes/000077500000000000000000000000001502252323100252765ustar00rootroot00000000000000Explicatis-GmbH-pysmarlaapi-01906c0/pysmarlaapi/federwiege/classes/__init__.py000066400000000000000000000000741502252323100274100ustar00rootroot00000000000000from .property import Property from .service import Service Explicatis-GmbH-pysmarlaapi-01906c0/pysmarlaapi/federwiege/classes/property.py000066400000000000000000000020101502252323100275250ustar00rootroot00000000000000import asyncio from typing import Generic, TypeVar from ...connection_hub import ConnectionHub _VT = TypeVar("_VT") class Property(Generic[_VT]): value: _VT | None = None def __init__(self, hub: ConnectionHub): self.hub = hub self.listeners = set() self.lock = asyncio.Lock() async def add_listener(self, listener): async with self.lock: self.listeners.add(listener) async def remove_listener(self, listener): async with self.lock: self.listeners.remove(listener) async def notify_listeners(self): async with self.lock: for listener in self.listeners: await listener(self.value) def get(self) -> _VT | None: return self.value def set(self, new_value: _VT, push=True): if push: self.push(new_value) else: self.value = new_value def push(self, value: _VT): pass def pull(self): pass def register(self): pass Explicatis-GmbH-pysmarlaapi-01906c0/pysmarlaapi/federwiege/classes/service.py000066400000000000000000000011701502252323100273070ustar00rootroot00000000000000from .property import Property class Service: def __init__(self): self.registered = False self.props: dict[str, Property] = {} def add_property(self, key: str, prop: Property): self.props[key] = prop def get_properties(self): return self.props def get_property(self, key: str): if key not in self.props: return None return self.props[key] def register(self): for prop in self.props.values(): prop.register() self.registered = True def sync(self): for prop in self.props.values(): prop.pull() Explicatis-GmbH-pysmarlaapi-01906c0/pysmarlaapi/federwiege/services/000077500000000000000000000000001502252323100254645ustar00rootroot00000000000000Explicatis-GmbH-pysmarlaapi-01906c0/pysmarlaapi/federwiege/services/__init__.py000066400000000000000000000002041502252323100275710ustar00rootroot00000000000000from .analyser_service import AnalyserService from .babywiege_service import BabywiegeService from .info_service import InfoService Explicatis-GmbH-pysmarlaapi-01906c0/pysmarlaapi/federwiege/services/analyser_service.py000066400000000000000000000032371502252323100314010ustar00rootroot00000000000000from ...connection_hub import ConnectionHub from ..classes import Property, Service class AnalyserService(Service): def __init__(self, hub: ConnectionHub): super().__init__() self.add_property("oscillation", OscillationProperty(hub)) self.add_property("activity", ActivityProperty(hub)) self.add_property("swing_count", SwingCountProperty(hub)) class OscillationProperty(Property[list[int]]): async def on_callback(self, args): value = args[0]["value"] self.set(value, push=False) await self.notify_listeners() def __init__(self, hub: ConnectionHub): super().__init__(hub) def pull(self): self.hub.send_serialized_data("GetOscillation") def register(self): self.hub.client.on("GetOscillationCallback", self.on_callback) class ActivityProperty(Property[int]): async def on_callback(self, args): value = args[0]["value"] self.set(value, push=False) await self.notify_listeners() def __init__(self, hub: ConnectionHub): super().__init__(hub) def pull(self): self.hub.send_serialized_data("GetActivity") def register(self): self.hub.client.on("GetActivityCallback", self.on_callback) class SwingCountProperty(Property[int]): async def on_callback(self, args): value = args[0]["value"] self.set(value, push=False) await self.notify_listeners() def __init__(self, hub: ConnectionHub): super().__init__(hub) def pull(self): self.hub.send_serialized_data("GetSwingCount") def register(self): self.hub.client.on("GetSwingCountCallback", self.on_callback) Explicatis-GmbH-pysmarlaapi-01906c0/pysmarlaapi/federwiege/services/babywiege_service.py000066400000000000000000000036731502252323100315250ustar00rootroot00000000000000from ...connection_hub import ConnectionHub from ..classes import Property, Service class BabywiegeService(Service): def __init__(self, hub: ConnectionHub): super().__init__() self.add_property("swing_active", SwingActiveProperty(hub)) self.add_property("intensity", IntensityProperty(hub)) self.add_property("smart_mode", SmartModeProperty(hub)) class SwingActiveProperty(Property[bool]): async def on_callback(self, args): value = args[0]["value"] self.set(value, push=False) await self.notify_listeners() def __init__(self, hub: ConnectionHub): super().__init__(hub) def pull(self): self.hub.send_serialized_data("GetSwingActive") def push(self, value: bool): self.hub.send_serialized_data("SetSwingActive", value) def register(self): self.hub.client.on("GetSwingActiveCallback", self.on_callback) class IntensityProperty(Property[int]): async def on_callback(self, args): value = args[0]["value"] self.set(value, push=False) await self.notify_listeners() def __init__(self, hub: ConnectionHub): super().__init__(hub) def pull(self): self.hub.send_serialized_data("GetIntensity") def push(self, value: int): self.hub.send_serialized_data("SetIntensity", value) def register(self): self.hub.client.on("GetIntensityCallback", self.on_callback) class SmartModeProperty(Property[bool]): async def on_callback(self, args): value = args[0]["value"] self.set(value, push=False) await self.notify_listeners() def __init__(self, hub: ConnectionHub): super().__init__(hub) def pull(self): self.hub.send_serialized_data("GetSmartMode") def push(self, value: bool): self.hub.send_serialized_data("SetSmartMode", value) def register(self): self.hub.client.on("GetSmartModeCallback", self.on_callback) Explicatis-GmbH-pysmarlaapi-01906c0/pysmarlaapi/federwiege/services/info_service.py000066400000000000000000000022331502252323100305110ustar00rootroot00000000000000from ...connection_hub import ConnectionHub from ..classes import Property, Service class InfoService(Service): def __init__(self, hub: ConnectionHub): super().__init__() self.add_property("display_name", DisplayNameProperty(hub)) self.add_property("version", VersionProperty(hub)) class DisplayNameProperty(Property[str]): async def on_callback(self, args): value = args[0]["value"] self.set(value, push=False) await self.notify_listeners() def __init__(self, hub: ConnectionHub): super().__init__(hub) def pull(self): self.hub.send_serialized_data("GetDisplayName") def register(self): self.hub.client.on("GetDisplayNameCallback", self.on_callback) class VersionProperty(Property[str]): async def on_callback(self, args): value = args[0]["value"] self.set(value, push=False) await self.notify_listeners() def __init__(self, hub: ConnectionHub): super().__init__(hub) def pull(self): self.hub.send_serialized_data("GetVersion") def register(self): self.hub.client.on("GetVersionCallback", self.on_callback) Explicatis-GmbH-pysmarlaapi-01906c0/requirements.txt000066400000000000000000000000641502252323100224750ustar00rootroot00000000000000aiohttp~=3.11.11 jsonpickle~=4.0.0 pysignalr~=1.1.0 Explicatis-GmbH-pysmarlaapi-01906c0/requirements_dev.txt000066400000000000000000000001231502252323100233270ustar00rootroot00000000000000aiohttp~=3.11.11 flit~=3.12.0 jsonpickle~=4.0.0 pre-commit~=4.0.1 pysignalr~=1.1.0 Explicatis-GmbH-pysmarlaapi-01906c0/tests/000077500000000000000000000000001502252323100203535ustar00rootroot00000000000000Explicatis-GmbH-pysmarlaapi-01906c0/tests/test.py000066400000000000000000000046431502252323100217130ustar00rootroot00000000000000import asyncio import logging import sys import threading import time sys.path.append("../") from pysmarlaapi import Connection, Federwiege try: from config import AUTH_TOKEN_B64, HOST except ImportError: print("config.py or mandatory variables missing, please add in root folder...") sys.exit() logging.basicConfig(level=20) loop = asyncio.get_event_loop() async_thread = threading.Thread(target=loop.run_forever) connection = Connection(url=HOST, token_b64=AUTH_TOKEN_B64) federwiege = Federwiege(loop, connection) def main(): async_thread.start() federwiege.register() federwiege.connect() while not (federwiege.connected and federwiege.available): time.sleep(1) swing_active_prop = federwiege.get_property("babywiege", "swing_active") intensity_prop = federwiege.get_property("babywiege", "intensity") oscillation_prop = federwiege.get_property("analyser", "oscillation") swing_count_prop = federwiege.get_property("analyser", "swing_count") display_name_prop = federwiege.get_property("info", "display_name") version_prop = federwiege.get_property("info", "version") time.sleep(1) print(display_name_prop.get()) print(version_prop.get()) print(swing_count_prop.get()) value = swing_active_prop.get() print(f"Swing Active: {value}") intensity = intensity_prop.get() print(f"Intensity: {intensity}%") oscillation = oscillation_prop.get() or [None, None] print(f"Amplitude: {oscillation[0]}mm Period: {oscillation[1]}ms") swing_active_prop.set(True) intensity_prop.set(60) time.sleep(1) value = swing_active_prop.get() print(f"Swing Active: {value}") intensity = intensity_prop.get() print(f"Intensity: {intensity}%") oscillation = oscillation_prop.get() or [None, None] print(f"Amplitude: {oscillation[0]}mm Period: {oscillation[1]}ms") time.sleep(1) while True: value = swing_active_prop.get() print(f"Swing Active: {value}") intensity = intensity_prop.get() print(f"Intensity: {intensity}%") oscillation = oscillation_prop.get() or [None, None] print(f"Amplitude: {oscillation[0]}mm Period: {oscillation[1]}ms") time.sleep(1) if __name__ == "__main__": try: main() except BaseException: pass federwiege.disconnect() while federwiege.connected: time.sleep(1) loop.call_soon_threadsafe(loop.stop)