pax_global_header00006660000000000000000000000064147370237230014522gustar00rootroot0000000000000052 comment=29e60222160ce0c2a9d4cb30efc563d65934136c ualex73-goslide-api-29e6022/000077500000000000000000000000001473702372300154605ustar00rootroot00000000000000ualex73-goslide-api-29e6022/.github/000077500000000000000000000000001473702372300170205ustar00rootroot00000000000000ualex73-goslide-api-29e6022/.github/workflows/000077500000000000000000000000001473702372300210555ustar00rootroot00000000000000ualex73-goslide-api-29e6022/.github/workflows/pythonpublish.yml000066400000000000000000000015431473702372300245130ustar00rootroot00000000000000# This workflows will upload a Python Package using Twine when a release is created # For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries name: Upload Python Package on: release: types: [published] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.x' - name: Install dependencies run: | python -m pip install --upgrade pip pip install setuptools wheel twine - name: Build and publish env: TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} run: | python setup.py sdist bdist_wheel twine upload dist/* ualex73-goslide-api-29e6022/LICENSE000066400000000000000000000261351473702372300164740ustar00rootroot00000000000000 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. ualex73-goslide-api-29e6022/README.md000066400000000000000000000027541473702372300167470ustar00rootroot00000000000000 # GoSlide API Python API to utilise the GoSlide Local JSON API and Open Cloud API ## Requirements - Python >= 3.5.2 ## Usage Local API ```python import asyncio from goslideapi import GoSlideLocal loop = asyncio.get_event_loop() goslide = GoSlideLocal() result = loop.run_until_complete(goslide.slide_add("192.168.1.1", "anypassword", 2)) slide = loop.run_until_complete(goslide.slide_info("192.168.1.1")) loop.run_until_complete(goslide.slide_open("192.168.1.1")) loop.run_until_complete(goslide.slide_close("192.168.1.1")) ``` ## Usage Cloud API (deprecated) ```python import asyncio from goslideapi import GoSlideCloud loop = asyncio.get_event_loop() goslide = GoSlideCloud('email', 'password') login = loop.run_until_complete(goslide.login()) if login: # Get the slide list slides = loop.run_until_complete(goslide.slides_overview()) if slides: for slidedev in slides: print(slidedev['device_id'], slidedev['device_name']) print(' ', slidedev['device_info']['pos']) else: print('Something went wrong while retrieving the slide information') # Open slide with id 1 result = loop.run_until_complete(goslide.slide_open(1)) if result: print('Succesfully opened slide 1') else: print('Failed opened slide 1') # Close slide with id 1 result = loop.run_until_complete(goslide.slide_close(1)) loop.run_until_complete(goslide.logout()) else: print('login failed') ``` ## License Apache License 2.0 ualex73-goslide-api-29e6022/README.pypi000066400000000000000000000003311473702372300173150ustar00rootroot00000000000000 # GoSlide Open Cloud API Python API to utilise the GoSlide Local and Cloud API ## Requirements - Python >= 3.5.2 ## Usage See https://github.com/ualex73/goslide-api for examples ## License Apache License 2.0 ualex73-goslide-api-29e6022/goslideapi/000077500000000000000000000000001473702372300176005ustar00rootroot00000000000000ualex73-goslide-api-29e6022/goslideapi/__init__.py000066400000000000000000000001201473702372300217020ustar00rootroot00000000000000"""Init for Go Slide API.""" from .goslideapi import GoSlideCloud, GoSlideLocal ualex73-goslide-api-29e6022/goslideapi/goslideapi.py000066400000000000000000000676721473702372300223140ustar00rootroot00000000000000"""Python wrapper for Go Slide API.""" import aiohttp import asyncio import hashlib import json import logging import os import re import time _LOGGER = logging.getLogger(__name__) # API Link: https://documenter.getpostman.com/view/6223391/S1Lu2pSf BASEURL = "https://api.goslide.io/api/{}" DEFAULT_TIMEOUT_CLOUD = 10 DEFAULT_TIMEOUT_LOCAL = 5 class AuthenticationFailed(Exception): """Error to indicate that authentication with Slide API has failed.""" pass class ClientConnectionError(Exception): """Error to indicate to connection issues with the Slide API.""" pass class ClientTimeoutError(Exception): """Error to indicate to timeout issues with the Slide API.""" pass class DigestAuthCalcError(Exception): """Error to indicate an error that the digest authentication calculation went wrong.""" pass class GoSlideCloud: """API Wrapper for the Go Slide devices.""" def __init__( self, username, password, timeout=DEFAULT_TIMEOUT_CLOUD, url=BASEURL, authexception=True, verify_ssl=True, ): """Create the object with required parameters.""" self._username = username self._password = password self._timeout = timeout self._url = url self._authenticated = False self._accesstoken = "" self._authfailed = False self._expiretoken = None self._authexception = authexception self._requestcount = 0 self._verify_ssl = verify_ssl async def _dorequest(self, reqtype, urlsuffix, data=None): """HTTPS request handler.""" # Increment request counter for logging purpose self._requestcount += 1 if self._requestcount > 99999: self._requestcount = 1 headers = {"Content-Type": "application/json", "Accept": "application/json"} self._authfailed = False if self._authenticated: headers["Authorization"] = "Bearer {}".format(self._accesstoken) _LOGGER.debug( "REQ-C%d: API=%s, type=%s, data=%s", self._requestcount, self._url.format(urlsuffix), reqtype, json.dumps(data), ) # Set a reasonable timeout, otherwise it can take > 300 seconds atimeout = aiohttp.ClientTimeout(total=self._timeout) # Known error codes from the Cloud API: # 401 - Authentication failed # 403 - Forbidden, most likely we want to control a slide # which isn't in our account # 404 - Can't find API endpoint # 422 - The given data was invalid # 424 - If one or multiple Slides are offline. The 'device_info' # will contain code=500, 'Device unavailable' for those slides # aiohttp.client_exceptions.ClientConnectorError: No IP, timeout try: connector = None if not self._verify_ssl: connector = aiohttp.TCPConnector(verify_ssl=False) async with aiohttp.request( reqtype, self._url.format(urlsuffix), headers=headers, json=data, timeout=atimeout, connector=connector, ) as resp: if resp.status in [200, 424]: textdata = await resp.text() _LOGGER.debug( "RES-C%d: API=%s, type=%s, HTTPCode=%s, Data=%s", self._requestcount, self._url.format(urlsuffix), reqtype, resp.status, textdata, ) try: jsondata = json.loads(textdata) except json.decoder.JSONDecodeError: _LOGGER.error( "RES-C%d: API=%s, type=%s, INVALID JSON=%s", self._requestcount, self._url.format(urlsuffix), reqtype, textdata, ) jsondata = None return jsondata else: textdata = await resp.text() _LOGGER.error( "RES-C%d: API=%s, type=%s, HTTPCode=%s, Data=%s", self._requestcount, self._url.format(urlsuffix), reqtype, resp.status, textdata, ) if resp.status in [401, 422]: # Raise exception, normally used by Home Assistant if self._authexception: raise AuthenticationFailed self._authfailed = True return None except ( aiohttp.client_exceptions.ClientConnectionError, aiohttp.client_exceptions.ClientConnectorError, ) as err: raise ClientConnectionError(str(err)) from None except asyncio.TimeoutError as err: raise ClientTimeoutError("Connection Timeout") from None async def _request(self, reqtype, urlsuffix, data=None): """Retry authentication around dorequest.""" resp = await self._dorequest(reqtype, urlsuffix, data) if self._authfailed: _LOGGER.warning("Retrying request, because authentication " "failed") resp = None if await self.login(): resp = await self._dorequest(reqtype, urlsuffix, data) if self._authfailed: _LOGGER.error("Failed request. API=%s", self._url.format(urlsuffix)) return resp async def _checkauth(self): """Check if we are authenticated.""" if self._authenticated: from datetime import datetime, timezone if self._expiretoken is not None: diff = self._expiretoken - datetime.now(timezone.utc) # Reauthenticate if token is less then 7 days valid if diff.days <= 7: _LOGGER.info( "Authentication token will expire in %s " "days, renewing it", int(diff.days), ) return await self.login() _LOGGER.debug("Authentication token valid for %s days", int(diff.days)) return True return await self.login() async def login(self): """Login to the Cloud API and retrieve a token.""" from datetime import datetime self._authenticated = False self._accesstoken = "" # Call dorequest, because if auth fails, it won't work second time. result = await self._dorequest( "POST", "auth/login", {"email": self._username, "password": self._password} ) if result: if "access_token" in result: self._authenticated = True self._accesstoken = result["access_token"] # Token format is in UTC if "expires_at" in result: self._expiretoken = datetime.strptime( result["expires_at"] + " +0000", "%Y-%m-%d %H:%M:%S %z" ) _LOGGER.debug( "Authentication token expiry: %s", result["expires_at"] ) else: self._expiretoken = None _LOGGER.error( "Auth login JSON is missing the " "'expires_at' field in %s", result, ) return self._authenticated async def logout(self): """Logout of the Cloud API.""" resp = False if self._authenticated: # Call dorequest, because we don't want retry resp = await self._dorequest("POST", "auth/logout") resp = bool(resp) self._authenticated = False self._accesstoken = "" return resp async def slides_overview(self): """Retrieve the slides overview list.""" # { # "slides": [ # { # "id": 1, # "device_name": "Living Room", # "slide_setup": "middle", # "curtain_type": "rail", # "device_id": "slide_300000000000", # "household_id": 1, # "zone_id": 1, # "touch_go": true, # "device_info": { # "pos": 0.0 # }, # "routines": [], # }, # { # "id": 2, # "device_name": "Study Room", # "slide_setup": "middle", # "curtain_type": "rail", # "device_id": "slide_300000000001", # "household_id": 1, # "zone_id": 2, # "touch_go": false, # "device_info": { # "message": "No response from device.", # "code": 500 # }, # "routines": { # "message": "No response from device.", # "code": 500 # }, # {...}, # ] # } if not await self._checkauth(): return None result = await self._request("GET", "slides/overview") if result and "slides" in result: return result["slides"] _LOGGER.error("Missing key 'slides' in JSON=%s", json.dumps(result)) return None async def slide_info(self, slideid): """Retrieve the slide info.""" # The format is: # { # "data": { # "board_rev": 1, # "calib_time": 10239, # "curtain_type": 0, # deprecated # "device_name": "Living Room", # deprecated # "mac": "300000000000", # "pos": 0.0, # "slide_id": "slide_300000000000", # "touch_go": true, # "zone_name": "" # deprecated # }, # "error": null # } if not await self._checkauth(): return None result = await self._request("GET", "slide/{}/info".format(slideid)) if result and "data" in result: return result["data"] _LOGGER.error("Missing key 'data' in JSON=%s", json.dumps(result)) return None async def slide_config(self, slideid): """Retrieve the slide configuration.""" # The format is: # { # tbd # "error": null # } if not await self._checkauth(): return None result = await self._request("GET", "slides/{}".format(slideid)) if result and "data" in result: return result["data"] _LOGGER.error("Missing key 'data' in JSON=%s", json.dumps(result)) return None async def slide_get_position(self, slideid): """Retrieve the slide position.""" result = await self.slide_info(slideid) if result: if "pos" in result: return result["pos"] _LOGGER.error( "SlideGetPosition: Missing key 'pos' in JSON=%s", json.dumps(result) ) return None async def slide_set_position(self, slideid, posin): """Set the slide position, only 0.0 - 1.0 is allowed.""" try: pos = float(posin) except ValueError: _LOGGER.error("SlideSetPosition: '%s' has to be numeric", posin) return False if pos < 0 or pos > 1: _LOGGER.error("SlideSetPosition: '%s' has to be between 0.0-1.0", pos) return False if not await self._checkauth(): return False resp = await self._request( "POST", "slide/{}/position".format(slideid), {"pos": pos} ) return bool(resp) async def slide_open(self, slideid): """Open a slide.""" if not await self._checkauth(): return False resp = await self._request( "POST", "slide/{}/position".format(slideid), {"pos": 0.0} ) return bool(resp) async def slide_close(self, slideid): """Close a slide.""" if not await self._checkauth(): return False resp = await self._request( "POST", "slide/{}/position".format(slideid), {"pos": 1.0} ) return bool(resp) async def slide_stop(self, slideid): """Stop a slide.""" if not await self._checkauth(): return False resp = await self._request("POST", "slide/{}/stop".format(slideid)) return bool(resp) async def slide_calibrate(self, slideid): """Calibrate a slide.""" if not await self._checkauth(): return False resp = await self._request("POST", "slide/{}/calibrate".format(slideid)) return bool(resp) async def household_get(self): """Return household information.""" if not await self._checkauth(): return False resp = await self._request("GET", "households") return resp async def household_set(self, name, address, lat, lon): """Set household information.""" if not await self._checkauth(): return False resp = await self._request( "PATCH", "households", {"name": name, "address": address, "lat": lat, "lon": lon}, ) return bool(resp) class GoSlideLocal: """API Wrapper for the Go Slide devices, local connectivity.""" def __init__(self, timeout=DEFAULT_TIMEOUT_LOCAL, authexception=True): """Create the object with required parameters.""" self._timeout = timeout self._authexception = authexception self._cnoncecount = 0 self._requestcount = 0 self._slide_passwd = {} self._slide_api = {} def _md5_utf8(self, x): if isinstance(x, str): x = x.encode("utf-8") return hashlib.md5(x).hexdigest() def _make_digest_auth(self, username, password, method, uri, my_auth): nonce = re.findall(r'nonce="(.*?)"', my_auth)[0] realm = re.findall(r'realm="(.*?)"', my_auth)[0] qop = re.findall(r'qop="(.*?)"', my_auth)[0] nc = "00000001" # Generate cnonce value self._cnoncecount += 1 s = str(self._cnoncecount).encode("utf-8") s += nonce.encode("utf-8") s += time.ctime().encode("utf-8") s += os.urandom(8) cnonce = hashlib.sha1(s).hexdigest()[:8] # calculate HA1 HA1 = self._md5_utf8(username + ":" + realm + ":" + password) # calculate HA2 HA2 = self._md5_utf8(method + ":" + uri) if qop == "auth" or "auth" in qop.split(","): # calculate client response response = self._md5_utf8( HA1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + HA2 ) else: # Raise error, this situation shouldn't happe. Slide should always use qop=auth _LOGGER.error("Invalid digest authentication qop=%s found", qop) raise DigestAuthCalcError return 'Digest username="{}", realm="{}", nonce="{}", uri="{}", algorithm="MD5", qop=auth, nc={}, cnonce="{}", response="{}"'.format( username, realm, nonce, uri, nc, cnonce, response ) async def _dorequest(self, reqtype, url, digestauth=None, data=None): """HTTP request handler.""" # Increment request counter for logging purpose self._requestcount += 1 if self._requestcount > 99999: self._requestcount = 1 headers = {"Content-Type": "application/json", "Accept": "application/json"} if digestauth: headers["Authorization"] = digestauth _LOGGER.debug( "REQ-L%d: API=%s, type=%s, data=%s", self._requestcount, url, reqtype, json.dumps(data), ) # Set a reasonable timeout, otherwise it can take > 300 seconds atimeout = aiohttp.ClientTimeout(total=self._timeout) # Known error codes from the Local API: # 401 - Digest challenge # aiohttp.client_exceptions.ClientConnectorError: No IP, timeout try: async with aiohttp.request( reqtype, url, headers=headers, json=data, timeout=atimeout ) as resp: if resp.status == 200: textdata = await resp.text() _LOGGER.debug( "RES-L%d: API=%s, type=%s, HTTPCode=%s, Data=%s", self._requestcount, url, reqtype, resp.status, textdata, ) try: jsondata = json.loads(textdata) except json.decoder.JSONDecodeError: _LOGGER.error( "RES-L%d: API=%s, type=%s, INVALID JSON=%s", self._requestcount, url, reqtype, textdata, ) jsondata = None return resp.status, jsondata if resp.status == 401: if "WWW-Authenticate" in resp.headers: headerdata = resp.headers["WWW-Authenticate"] else: headerdata = None _LOGGER.debug( "RES-L%d: API=%s, type=%s, HTTPCode=%s, WWW-Authenticate=%s", self._requestcount, url, reqtype, resp.status, headerdata, ) return resp.status, headerdata else: textdata = await resp.text() _LOGGER.error( "RES-L%d: API=%s, type=%s, HTTPCode=%s, Data=%s", self._requestcount, url, reqtype, resp.status, textdata, ) return resp.status, None except ( aiohttp.client_exceptions.ClientConnectionError, aiohttp.client_exceptions.ClientConnectorError, ) as err: raise ClientConnectionError(str(err)) from None except asyncio.TimeoutError as err: raise ClientTimeoutError("Connection Timeout") from None async def _request(self, hostname, password, apiversion, reqtype, uri, data=None): """Digest authentication using dorequest.""" # Local API uses digest authentication: # https://en.wikipedia.org/wiki/Digest_access_authentication # We need to send 2 requests: # - first request will result in a 401 with a response header "WWW-Authenticate" # - second request will add "Authorization" header calculated from "WWW-Authenticate" # format URL with hostname/ip and uri value url = "http://{}{}".format(hostname, uri) # First request, should return a 401 error for v1 # First request is not required for v2 # Default is version 1, when we do WWW-Authentication if apiversion == 1: # do request to obtain a WWW-authentication header: respstatus, resptext = await self._dorequest(reqtype, url, data=data) # Authentication was not needed. Slide has been upgraded. if respstatus == 200: _LOGGER.debug("Slide %s updated to API version 2", hostname) self._slide_api[hostname] = 2 return resptext # Otherwise, we should have a 401 response if respstatus == 401: # The resptext contains the WWW-Authentication header auth = self._make_digest_auth("user", password, reqtype, uri, resptext) respstatus, resptext = await self._dorequest( reqtype, url, digestauth=auth, data=data ) if respstatus == 200: return resptext # Anything else is an error _LOGGER.error( "Failed request with Local API Digest Authentication challenge. HTTPCode=%s", respstatus, ) else: # We expected a 401 Digest Auth here _LOGGER.error( "Failed request with Local API v1. Received HTTPCode=%s, expected HTTPCode=401. Maybe try switching to api version 2?", respstatus, ) elif apiversion == 2: respstatus, resptext = await self._dorequest(reqtype, url, data=data) if respstatus == 200: return resptext # Anything else is an error _LOGGER.error( "Failed request Local API v2. HTTPCode=%s", respstatus, ) else: _LOGGER.error( "Only v1 and v2 is supported.", ) return None async def slide_add(self, hostname, password, api=2): """Add slide to internal table, then you can use the local API.""" self._slide_passwd[hostname] = password self._slide_api[hostname] = api async def slide_del(self, hostname): """Delete slide from internal table.""" if hostname in self._slide_passwd: del self._slide_passwd[hostname] if hostname in self._slide_api: del self._slide_api[hostname] else: _LOGGER.error("Tried to delete none-existing '%s' from list", hostname) async def slide_list(self): """List all registered slides.""" return list(self._slide_passwd.keys()) async def _slide_exist(self, hostname): """Function to check if slide exist in internal table.""" if hostname in self._slide_passwd: return True else: _LOGGER.error( "Cannot find hostname '%s' in list, forgot to call 'slide_add'?", hostname, ) return False async def slide_info(self, hostname): """Retrieve the slide info.""" # The format is: # { # "slide_id": "slide_300000000000", # "mac": "300000000000", # "board_rev": 1, # "device_name": "", # "zone_name": "", # "curtain_type": 0, # "calib_time": 10239, # "pos": 0.0, # "touch_go": true # } if not await self._slide_exist(hostname): return None result = await self._request( hostname, self._slide_passwd[hostname], self._slide_api[hostname], "POST", "/rpc/Slide.GetInfo", ) return result async def slide_get_position(self, hostname): """Retrieve the slide position.""" result = await self.slide_info(hostname) if result: if "pos" in result: return result["pos"] _LOGGER.error( "SlideGetPosition: Missing key 'pos' in JSON=%s", json.dumps(result) ) return None async def slide_set_position(self, hostname, posin): """Set the slide position, only 0.0 - 1.0 is allowed.""" try: pos = float(posin) except ValueError: _LOGGER.error("SlideSetPosition: '%s' has to be numeric", posin) return False if pos < 0 or pos > 1: _LOGGER.error("SlideSetPosition: '%s' has to be between 0.0-1.0", pos) return False if not await self._slide_exist(hostname): return False resp = await self._request( hostname, self._slide_passwd[hostname], self._slide_api[hostname], "POST", "/rpc/Slide.SetPos", data={"pos": pos}, ) return bool(resp) async def slide_open(self, hostname): """Open a slide.""" if not await self._slide_exist(hostname): return False resp = await self._request( hostname, self._slide_passwd[hostname], self._slide_api[hostname], "POST", "/rpc/Slide.SetPos", data={"pos": 0.0}, ) return bool(resp) async def slide_close(self, hostname): """Close a slide.""" if not await self._slide_exist(hostname): return False resp = await self._request( hostname, self._slide_passwd[hostname], self._slide_api[hostname], "POST", "/rpc/Slide.SetPos", data={"pos": 1.0}, ) return bool(resp) async def slide_stop(self, hostname): """Stop a slide.""" if not await self._slide_exist(hostname): return False resp = await self._request( hostname, self._slide_passwd[hostname], self._slide_api[hostname], "POST", "/rpc/Slide.Stop", ) return bool(resp) async def slide_calibrate(self, hostname): """Calibrate a slide.""" if not await self._slide_exist(hostname): return False resp = await self._request( hostname, self._slide_passwd[hostname], self._slide_api[hostname], "POST", "/rpc/Slide.Calibrate", ) return bool(resp) async def slide_configwifi(self, hostname, ssid, password): """Configure slide wifi.""" if not await self._slide_exist(hostname): return False resp = await self._request( hostname, self._slide_passwd[hostname], self._slide_api[hostname], "POST", "/rpc/Slide.Config.Wifi", data={"ssid": ssid, "pass": password}, ) return bool(resp) async def slide_get_touchgo(self, hostname): """Retrieve the slide TouchGo setting.""" result = await self.slide_info(hostname) if result: if "touch_go" in result: return result["touch_go"] _LOGGER.error( "SlideGetTouchGo: Missing key 'touch_go' in JSON=%s", json.dumps(result) ) return None async def slide_set_touchgo(self, hostname, value): """Change Touch-Go of a slide.""" if not await self._slide_exist(hostname): return False resp = await self._request( hostname, self._slide_passwd[hostname], self._slide_api[hostname], "POST", "/rpc/Slide.touchGo", data={"touch_go": value}, ) return bool(resp) async def slide_set_motor_strength(self, hostname, maxcurrent, calib_current): """Change Motor Strength a slide.""" if not await self._slide_exist(hostname): return False # *** Do NOT go over 1450 *** # Light: maxcurrent=900, calib_current=850 # Medium: maxcurrent=1250, calib_current=1200 # Strong: maxcurrent=1500, calib_current=1450 if maxcurrent > 1500: _LOGGER.error( "Slide.Config.Motor: 'maxcurrent=%s' has to be lower than 1500", maxcurrent, ) return False if calib_current > 1450: _LOGGER.error( "Slide.Config.Motor: 'calib_current=%s' has to be lower than 1450", calib_current, ) return False resp = await self._request( hostname, self._slide_passwd[hostname], self._slide_api[hostname], "POST", "/rpc/Slide.Config.Motor", data={"maxcurrent": maxcurrent, "calib_current": calib_current}, ) return bool(resp) ualex73-goslide-api-29e6022/setup.py000066400000000000000000000021141473702372300171700ustar00rootroot00000000000000''' Install Slide Open Cloud and Local API ''' import setuptools with open('README.pypi') as f: LONG_DESCRIPTION = f.read() setuptools.setup( name='goslide-api', version='0.7.3', url='https://github.com/ualex73/goslide-api', license='Apache License 2.0', author='Alexander Kuiper', author_email='ualex73@gmail.com', description='Python API to utilise the Slide Open Cloud and Local API', long_description=LONG_DESCRIPTION, long_description_content_type='text/markdown', packages=setuptools.find_packages(), install_requires=['aiohttp'], python_requires='>=3.5.2', classifiers=[ 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: 3.11', 'Programming Language :: Python :: 3.12', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', ], )