aiokwikset 0.3.0a9__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,148 @@
1
+ Metadata-Version: 2.4
2
+ Name: aiokwikset
3
+ Version: 0.3.0a9
4
+ Summary: Python interface for Kwikset Smart Locks
5
+ Home-page: https://github.com/explosivo22/aiokwikset
6
+ Author: Brad Barbour
7
+ Author-email: explosivo22@protonmail.com
8
+ License: Apache Software License
9
+ Keywords: kwikset,home automation,kwikset halo,kwikset smart lock
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Operating System :: OS Independent
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: aiohttp>=3.6.1
16
+ Requires-Dist: pycognito==2024.5.1
17
+ Dynamic: author
18
+ Dynamic: author-email
19
+ Dynamic: classifier
20
+ Dynamic: description
21
+ Dynamic: description-content-type
22
+ Dynamic: home-page
23
+ Dynamic: keywords
24
+ Dynamic: license
25
+ Dynamic: license-file
26
+ Dynamic: requires-dist
27
+ Dynamic: summary
28
+
29
+
30
+ # aiokwikset - Python interface for the Kwikset API
31
+
32
+ Python library for communicating with the [Kwikset Smart Locks](https://www.kwikset.com/products/electronic/electronic-smart-locks) via the Kwikset cloud API.
33
+
34
+ ***WARNING***
35
+ * This library only works if you have signed up for and created a home/had a home shared with you from the Kwikset Application.
36
+ * [IOS](https://apps.apple.com/us/app/kwikset/id1465996742)
37
+ * [Android](https://play.google.com/store/apps/details?id=com.kwikset.blewifi)
38
+
39
+ NOTE:
40
+
41
+ * This library is community supported, please submit changes and improvements.
42
+ * This is a very basic interface, not well thought out at this point, but works for the use cases that initially prompted spitting this out from.
43
+
44
+ ## Supports
45
+
46
+ - locking/unlocking
47
+ - retrieving basic information
48
+ - Multi-Factor Authentication (MFA) support (SMS and Software Token)
49
+
50
+ ## Installation
51
+
52
+ ```
53
+ pip install aiokwikset
54
+ ```
55
+
56
+ ## Examples
57
+
58
+ ### Basic Usage (No MFA)
59
+
60
+ ```python
61
+ import asyncio
62
+
63
+ from aiokwikset import API
64
+
65
+
66
+ async def main() -> None:
67
+ """Run!"""
68
+ #initialize the API
69
+ api = API()
70
+
71
+ #start auth
72
+ await api.async_login('username','password')
73
+
74
+ # Get user account information:
75
+ user_info = await api.user.get_info()
76
+
77
+ # Get the homes
78
+ homes = await api.user.get_homes()
79
+
80
+ # Get the devices for the first home
81
+ devices = await api.device.get_devices(homes[0]['homeid'])
82
+
83
+ # Get information for a specific device
84
+ device_info = await api.device.get_device_info(devices[0]['deviceid'])
85
+
86
+ # Lock the specific device
87
+ lock = await api.device.lock_device(device_info, user_info)
88
+
89
+ # Set led status
90
+ led = await api.device.set_ledstatus(device_info, "false")
91
+
92
+ # Set audio status
93
+ audio = await api.device.set_audiostatus(device_info, "false")
94
+
95
+ # Set secure screen status
96
+ screen = await api.device.set_securescreenstatus(device_info, "false")
97
+
98
+
99
+ asyncio.run(main())
100
+ ```
101
+
102
+ ### Usage with MFA (Multi-Factor Authentication)
103
+
104
+ If your account has MFA enabled, you need to handle the MFA challenge:
105
+
106
+ ```python
107
+ import asyncio
108
+
109
+ from aiokwikset import API, MFAChallengeRequired
110
+
111
+
112
+ async def main() -> None:
113
+ """Run with MFA support!"""
114
+ api = API()
115
+
116
+ try:
117
+ # Attempt to login
118
+ await api.async_login('username', 'password')
119
+
120
+ except MFAChallengeRequired as mfa_error:
121
+ # MFA is required - prompt user for code
122
+ print(f"MFA Required: {mfa_error.mfa_type}")
123
+ mfa_code = input("Enter your MFA code: ")
124
+
125
+ # Complete MFA authentication
126
+ await api.async_respond_to_mfa_challenge(
127
+ mfa_code=mfa_code,
128
+ mfa_type=mfa_error.mfa_type,
129
+ mfa_tokens=mfa_error.mfa_tokens
130
+ )
131
+
132
+ print("Successfully authenticated with MFA!")
133
+
134
+ # Continue with normal API usage
135
+ user_info = await api.user.get_info()
136
+ homes = await api.user.get_homes()
137
+
138
+ # ... rest of your code
139
+
140
+
141
+ asyncio.run(main())
142
+ ```
143
+
144
+ For detailed MFA documentation and advanced usage examples, see [MFA_USAGE.md](./MFA_USAGE.md).
145
+
146
+ ## Known Issues
147
+
148
+ * not all APIs supported
@@ -0,0 +1,119 @@
1
+ # aiokwikset - Python interface for the Kwikset API
2
+
3
+ Python library for communicating with the [Kwikset Smart Locks](https://www.kwikset.com/products/electronic/electronic-smart-locks) via the Kwikset cloud API.
4
+
5
+ ***WARNING***
6
+ * This library only works if you have signed up for and created a home/had a home shared with you from the Kwikset Application.
7
+ * [IOS](https://apps.apple.com/us/app/kwikset/id1465996742)
8
+ * [Android](https://play.google.com/store/apps/details?id=com.kwikset.blewifi)
9
+
10
+ NOTE:
11
+
12
+ * This library is community supported, please submit changes and improvements.
13
+ * This is a very basic interface, not well thought out at this point, but works for the use cases that initially prompted spitting this out from.
14
+
15
+ ## Supports
16
+
17
+ - locking/unlocking
18
+ - retrieving basic information
19
+ - Multi-Factor Authentication (MFA) support (SMS and Software Token)
20
+
21
+ ## Installation
22
+
23
+ ```
24
+ pip install aiokwikset
25
+ ```
26
+
27
+ ## Examples
28
+
29
+ ### Basic Usage (No MFA)
30
+
31
+ ```python
32
+ import asyncio
33
+
34
+ from aiokwikset import API
35
+
36
+
37
+ async def main() -> None:
38
+ """Run!"""
39
+ #initialize the API
40
+ api = API()
41
+
42
+ #start auth
43
+ await api.async_login('username','password')
44
+
45
+ # Get user account information:
46
+ user_info = await api.user.get_info()
47
+
48
+ # Get the homes
49
+ homes = await api.user.get_homes()
50
+
51
+ # Get the devices for the first home
52
+ devices = await api.device.get_devices(homes[0]['homeid'])
53
+
54
+ # Get information for a specific device
55
+ device_info = await api.device.get_device_info(devices[0]['deviceid'])
56
+
57
+ # Lock the specific device
58
+ lock = await api.device.lock_device(device_info, user_info)
59
+
60
+ # Set led status
61
+ led = await api.device.set_ledstatus(device_info, "false")
62
+
63
+ # Set audio status
64
+ audio = await api.device.set_audiostatus(device_info, "false")
65
+
66
+ # Set secure screen status
67
+ screen = await api.device.set_securescreenstatus(device_info, "false")
68
+
69
+
70
+ asyncio.run(main())
71
+ ```
72
+
73
+ ### Usage with MFA (Multi-Factor Authentication)
74
+
75
+ If your account has MFA enabled, you need to handle the MFA challenge:
76
+
77
+ ```python
78
+ import asyncio
79
+
80
+ from aiokwikset import API, MFAChallengeRequired
81
+
82
+
83
+ async def main() -> None:
84
+ """Run with MFA support!"""
85
+ api = API()
86
+
87
+ try:
88
+ # Attempt to login
89
+ await api.async_login('username', 'password')
90
+
91
+ except MFAChallengeRequired as mfa_error:
92
+ # MFA is required - prompt user for code
93
+ print(f"MFA Required: {mfa_error.mfa_type}")
94
+ mfa_code = input("Enter your MFA code: ")
95
+
96
+ # Complete MFA authentication
97
+ await api.async_respond_to_mfa_challenge(
98
+ mfa_code=mfa_code,
99
+ mfa_type=mfa_error.mfa_type,
100
+ mfa_tokens=mfa_error.mfa_tokens
101
+ )
102
+
103
+ print("Successfully authenticated with MFA!")
104
+
105
+ # Continue with normal API usage
106
+ user_info = await api.user.get_info()
107
+ homes = await api.user.get_homes()
108
+
109
+ # ... rest of your code
110
+
111
+
112
+ asyncio.run(main())
113
+ ```
114
+
115
+ For detailed MFA documentation and advanced usage examples, see [MFA_USAGE.md](./MFA_USAGE.md).
116
+
117
+ ## Known Issues
118
+
119
+ * not all APIs supported
@@ -0,0 +1,8 @@
1
+ """
2
+ apikwikset -- Python client for the Kwikset Halo API
3
+ """
4
+
5
+ from aiokwikset.api import API
6
+ from aiokwikset.errors import MFAChallengeRequired, RequestError, KwiksetError
7
+
8
+ __all__ = ["API", "MFAChallengeRequired", "RequestError", "KwiksetError"]
@@ -0,0 +1,351 @@
1
+ import asyncio
2
+ from functools import lru_cache, partial
3
+
4
+ import boto3
5
+ import botocore
6
+ from botocore.exceptions import BotoCoreError, ClientError
7
+ import pycognito
8
+ from pycognito.exceptions import (
9
+ SoftwareTokenMFAChallengeException,
10
+ SMSMFAChallengeException,
11
+ )
12
+ import attr
13
+
14
+ from typing import Any, Optional
15
+ from urllib.parse import urlparse
16
+
17
+ from aiohttp import ClientSession
18
+ from aiohttp.client_exceptions import (
19
+ ClientResponseError,
20
+ ClientConnectorError,
21
+ ServerConnectionError,
22
+ ClientPayloadError
23
+ )
24
+
25
+ from .errors import RequestError, MFAChallengeRequired
26
+ from .device import Device
27
+ from .user import User
28
+
29
+ from aiokwikset.const import (
30
+ LOGGER,
31
+ POOL_ID,
32
+ CLIENT_ID,
33
+ POOL_REGION
34
+ )
35
+
36
+ LOGIN_HEADER_USER_AGENT = 'aws-sdk-kotlin/1.3.81 ua/2.1 api/cognito-identity-provider#1.3.81'
37
+ DEFAULT_HEADER_USER_AGENT = 'okhttp/5.0.0-alpha.14'
38
+ DEFAULT_HEADER_ACCEPT_ENCODING = 'gzip'
39
+
40
+ class CloudError(Exception):
41
+ """Base class for cloud related errors."""
42
+
43
+
44
+ class Unauthenticated(CloudError):
45
+ """Raised when authentication failed."""
46
+
47
+
48
+ class UserNotFound(CloudError):
49
+ """Raised when a user is not found."""
50
+
51
+
52
+ class UserExists(CloudError):
53
+ """Raised when a username already exists."""
54
+
55
+
56
+ class UserNotConfirmed(CloudError):
57
+ """Raised when a user has not confirmed email yet."""
58
+
59
+
60
+ class PasswordChangeRequired(CloudError):
61
+ """Raised when a password change is required."""
62
+
63
+ # https://github.com/PyCQA/pylint/issues/1085
64
+ # pylint: disable=useless-super-delegation
65
+ def __init__(self, message: str = "Password change required.") -> None:
66
+ """Initialize a password change required error."""
67
+ super().__init__(message)
68
+
69
+
70
+ class UnknownError(CloudError):
71
+ """Raised when an unknown error occurs."""
72
+
73
+ AWS_EXCEPTIONS: dict[str, type[CloudError]] = {
74
+ "UserNotFoundException": UserNotFound,
75
+ "UserNotConfirmedException": UserNotConfirmed,
76
+ "UsernameExistsException": UserExists,
77
+ "NotAuthorizedException": Unauthenticated,
78
+ "PasswordResetRequiredException": PasswordChangeRequired,
79
+ }
80
+
81
+ @attr.s
82
+ class API(object):
83
+ user_pool_region = attr.ib()
84
+ username = attr.ib(default=None)
85
+ code_type = attr.ib(default=None)
86
+ id_token = attr.ib(default=None)
87
+ access_token = attr.ib(default=None)
88
+ refresh_token = attr.ib(default=None)
89
+ client_secret = attr.ib(default=None)
90
+ expires_at = attr.ib(default=None)
91
+ access_key = attr.ib(default=None)
92
+ secret_key = attr.ib(default=None)
93
+ client_callback = attr.ib(default=None)
94
+
95
+ user_pool_id = POOL_ID
96
+ client_id = CLIENT_ID
97
+ pool_region = POOL_REGION
98
+ aws = None
99
+ loop = None
100
+ session: boto3.Session | None = None
101
+ _request_lock = asyncio.Lock()
102
+
103
+ device: Optional[Device] = None
104
+ user: Optional[User] = None
105
+
106
+ def get_session(self):
107
+ return ClientSession()
108
+
109
+ async def _request(self, method: str, url: str, **kwargs) -> dict:
110
+ """Make a request against the API."""
111
+ await self.async_check_token()
112
+
113
+ kwargs.setdefault("headers", {})
114
+ kwargs["headers"].update(
115
+ {
116
+ "Host": urlparse(url).netloc,
117
+ "User-Agent": DEFAULT_HEADER_USER_AGENT,
118
+ "Accept-Encoding": DEFAULT_HEADER_ACCEPT_ENCODING
119
+ }
120
+ )
121
+
122
+ if self.id_token:
123
+ kwargs["headers"]["Authorization"] = "Bearer {}".format(self.id_token)
124
+
125
+ session = self.get_session()
126
+
127
+ try:
128
+ async with session.request(method, url, **kwargs) as resp:
129
+ data: dict = await resp.json(content_type=None)
130
+ resp.raise_for_status()
131
+ return data
132
+
133
+ except ClientResponseError as err:
134
+ raise RequestError(f"There was a response error while requesting {url}: {err}") from err
135
+ except ClientConnectorError as err:
136
+ raise RequestError(f"There was a client connection error while requesting {url}: {err}") from err
137
+ except ServerConnectionError as err:
138
+ raise RequestError(f"There was a server connection error while requesting {url}: {err}") from err
139
+ except ClientPayloadError as err:
140
+ raise RequestError(f"There was a client payload error while requesting {url}: {err}") from err
141
+ except ClientError as err:
142
+ raise RequestError(f"There was the following error while requesting {url}: {err}") from err
143
+ finally:
144
+ await session.close()
145
+
146
+ async def update_token(
147
+ self,
148
+ id_token: str,
149
+ access_token: str,
150
+ refresh_token: str | None = None,
151
+ ) -> asyncio.Task | None:
152
+ self.id_token = id_token
153
+ self.access_token = access_token
154
+ if refresh_token is not None:
155
+ self.refresh_token = refresh_token
156
+
157
+ if not self.device:
158
+ self.device = Device(self._request)
159
+
160
+ if not self.user:
161
+ self.user = User(self._request)
162
+
163
+ return None
164
+
165
+ async def async_login(self, email: str, password: str = None, access_token: str = None, refresh_token: str = None) -> None:
166
+ self.loop = asyncio.get_event_loop()
167
+
168
+ try:
169
+ cognito = await self.loop.run_in_executor(None, partial(self._create_cognito_client, username=email),)
170
+ await self.loop.run_in_executor(None, partial(cognito.authenticate,password=password),)
171
+
172
+ task = await self.update_token(cognito.id_token, cognito.access_token, cognito.refresh_token)
173
+
174
+ if task:
175
+ await task
176
+
177
+ except SoftwareTokenMFAChallengeException as err:
178
+ # Store the cognito instance for later MFA response
179
+ self._mfa_cognito = cognito
180
+ raise MFAChallengeRequired(
181
+ message="Software Token MFA challenge required. Please provide the MFA code.",
182
+ mfa_type="SOFTWARE_TOKEN_MFA",
183
+ mfa_tokens=err.get_tokens()
184
+ ) from err
185
+
186
+ except SMSMFAChallengeException as err:
187
+ # Store the cognito instance for later MFA response
188
+ self._mfa_cognito = cognito
189
+ raise MFAChallengeRequired(
190
+ message="SMS MFA challenge required. Please provide the MFA code.",
191
+ mfa_type="SMS_MFA",
192
+ mfa_tokens=err.get_tokens()
193
+ ) from err
194
+
195
+ except ClientError as err:
196
+ raise _map_aws_exception(err) from err
197
+
198
+ except BotoCoreError as err:
199
+ raise UnknownError from err
200
+
201
+ async def async_respond_to_mfa_challenge(self, mfa_code: str, mfa_type: Optional[str] = None, mfa_tokens: Optional[dict] = None) -> None:
202
+ """
203
+ Respond to an MFA challenge with the user's MFA code.
204
+
205
+ :param mfa_code: The MFA code from the user's authenticator app or SMS
206
+ :param mfa_type: The type of MFA challenge ('SMS_MFA' or 'SOFTWARE_TOKEN_MFA')
207
+ :param mfa_tokens: Optional tokens from the MFA exception if cognito instance was recreated
208
+ """
209
+ if self.loop is None:
210
+ self.loop = asyncio.get_event_loop()
211
+
212
+ try:
213
+ # If we have mfa_tokens, we need to recreate the cognito instance
214
+ if mfa_tokens:
215
+ cognito = await self.loop.run_in_executor(
216
+ None,
217
+ partial(self._create_cognito_client, username=self.username)
218
+ )
219
+ elif hasattr(self, '_mfa_cognito'):
220
+ cognito = self._mfa_cognito
221
+ else:
222
+ raise Unauthenticated("No MFA challenge in progress. Please login first.")
223
+
224
+ # Respond to the appropriate MFA challenge
225
+ if mfa_type == "SOFTWARE_TOKEN_MFA" or (not mfa_type and hasattr(self, '_mfa_cognito')):
226
+ await self.loop.run_in_executor(
227
+ None,
228
+ partial(cognito.respond_to_software_token_mfa_challenge, mfa_code, mfa_tokens)
229
+ )
230
+ elif mfa_type == "SMS_MFA":
231
+ await self.loop.run_in_executor(
232
+ None,
233
+ partial(cognito.respond_to_sms_mfa_challenge, mfa_code, mfa_tokens)
234
+ )
235
+ else:
236
+ raise UnknownError("Unknown MFA type")
237
+
238
+ # Update tokens after successful MFA verification
239
+ task = await self.update_token(cognito.id_token, cognito.access_token, cognito.refresh_token)
240
+
241
+ if task:
242
+ await task
243
+
244
+ # Clean up stored cognito instance
245
+ if hasattr(self, '_mfa_cognito'):
246
+ delattr(self, '_mfa_cognito')
247
+
248
+ except ClientError as err:
249
+ raise _map_aws_exception(err) from err
250
+
251
+ except BotoCoreError as err:
252
+ raise UnknownError from err
253
+
254
+ async def async_check_token(self) -> None:
255
+ """Check that the token is valid and renew if necessary."""
256
+ async with self._request_lock:
257
+ cognito = await self._async_authenticated_cognito()
258
+ if not cognito.check_token(renew=False):
259
+ return
260
+
261
+ try:
262
+ await self.async_renew_access_token()
263
+ except (Unauthenticated, UserNotFound) as err:
264
+ LOGGER.error("Unable to refresh token: %s", err)
265
+
266
+ raise
267
+
268
+ async def async_renew_access_token(self, access_token: str = None, refresh_token: str = None) -> None:
269
+ if self.loop is None:
270
+ self.loop = asyncio.get_event_loop()
271
+ if access_token is not None:
272
+ self.access_token = access_token
273
+ if refresh_token is not None:
274
+ self.refresh_token = refresh_token
275
+
276
+ cognito = await self._async_authenticated_cognito()
277
+
278
+ try:
279
+ await self.loop.run_in_executor(None, cognito.renew_access_token)
280
+ await self.update_token(cognito.id_token, cognito.access_token)
281
+
282
+ except ClientError as err:
283
+ raise _map_aws_exception(err) from err
284
+
285
+ except BotoCoreError as err:
286
+ raise UnknownError from err
287
+
288
+ async def _async_authenticated_cognito(self) -> pycognito.Cognito:
289
+ """Return an authenticated cognito instance."""
290
+ if self.access_token is None or self.refresh_token is None:
291
+ raise Unauthenticated("No authentication found")
292
+
293
+ return await self.loop.run_in_executor(
294
+ None,
295
+ partial(
296
+ self._create_cognito_client,
297
+ access_token=self.access_token,
298
+ refresh_token=self.refresh_token,
299
+ ),
300
+ )
301
+
302
+ def _create_cognito_client(self, **kwargs: Any) -> pycognito.Cognito:
303
+ """Create a new cognito client.
304
+
305
+ NOTE: This will do I/O
306
+ """
307
+ if self.session is None:
308
+ self.session = boto3.session.Session()
309
+
310
+ # Add custom user agent
311
+ config = botocore.config.Config(
312
+ signature_version=botocore.UNSIGNED,
313
+ user_agent_extra=LOGIN_HEADER_USER_AGENT
314
+ )
315
+
316
+ return _cached_cognito(
317
+ user_pool_id=self.user_pool_id,
318
+ client_id=self.client_id,
319
+ user_pool_region=self.pool_region,
320
+ botocore_config=config,
321
+ session=self.session,
322
+ **kwargs,
323
+ )
324
+
325
+ def _map_aws_exception(err: ClientError) -> CloudError:
326
+ """Map AWS exception to our exceptions."""
327
+ ex = AWS_EXCEPTIONS.get(err.response["Error"]["Code"], UnknownError)
328
+ print(ex)
329
+ return ex(err.response["Error"]["Message"])
330
+
331
+ @lru_cache(maxsize=2)
332
+ def _cached_cognito(
333
+ user_pool_id: str,
334
+ client_id: str,
335
+ user_pool_region: str,
336
+ botocore_config: Any,
337
+ session: Any,
338
+ **kwargs: Any,
339
+ ) -> pycognito.Cognito:
340
+ """Create a cached cognito client.
341
+
342
+ NOTE: This will do I/O
343
+ """
344
+ return pycognito.Cognito(
345
+ user_pool_id=user_pool_id,
346
+ client_id=client_id,
347
+ user_pool_region=user_pool_region,
348
+ botocore_config=botocore_config,
349
+ session=session,
350
+ **kwargs,
351
+ )
@@ -0,0 +1,17 @@
1
+ """Constants used by Kwikset Halo API"""
2
+
3
+ import logging
4
+
5
+ LOGGER = logging.getLogger(__name__)
6
+
7
+ POOL_ID = 'us-east-1_6B3uo6uKN'
8
+ CLIENT_ID = '5eu1cdkjp1itd1fi7b91m6g79s'
9
+ POOL_REGION = 'us-east-1'
10
+
11
+ GET_USER_URL = 'https://ynk95r1v52.execute-api.us-east-1.amazonaws.com/prod_v1/users/me'
12
+ GET_HOMES_URL = 'https://ynk95r1v52.execute-api.us-east-1.amazonaws.com/prod_v1/users/me/homes?top=200'
13
+ GET_HOME_DEVICES_URL = 'https://ynk95r1v52.execute-api.us-east-1.amazonaws.com/prod_v1/homes/%s/devices'
14
+ GET_DEVICE_URL = 'https://ynk95r1v52.execute-api.us-east-1.amazonaws.com/prod_v1/devices_v2/%s'
15
+
16
+ LOCK_COMMAND_URL = 'https://ynk95r1v52.execute-api.us-east-1.amazonaws.com/prod_v1/devices/%s/status'
17
+ ACCESSORY_COMMAND_URL = 'https://ynk95r1v52.execute-api.us-east-1.amazonaws.com/prod_v1/devices/%s/%s'
@@ -0,0 +1,80 @@
1
+ """Define /device endpoints."""
2
+ from typing import Awaitable, Callable
3
+ import json
4
+
5
+ from .const import LOCK_COMMAND_URL, ACCESSORY_COMMAND_URL, GET_HOME_DEVICES_URL, GET_DEVICE_URL
6
+
7
+
8
+ class Device(): # pylint: disable=too-few-public-methods
9
+ """Define an object to handle the endpoints."""
10
+
11
+ def __init__(self, request: Callable[..., Awaitable]) -> None:
12
+ """Initialize."""
13
+ self._request: Callable[..., Awaitable] = request
14
+
15
+ async def get_devices(self, home_id: str) -> dict:
16
+ """Return device specific data.
17
+ :param home_id: Unique identifier for the device
18
+ :type home_id: ``str``
19
+ :rtype: ``dict``
20
+ """
21
+ devices: dict = await self._request(
22
+ "get",
23
+ GET_HOME_DEVICES_URL % (home_id)
24
+ )
25
+
26
+ return devices['data']
27
+
28
+ async def get_device_info(self, device_id: str) -> dict:
29
+ """Return device specific data.
30
+ :param home_id: Unique identifier for the device
31
+ :type home_id: ``str``
32
+ :rtype: ``dict``
33
+ """
34
+ device_info: dict = await self._request(
35
+ "get",
36
+ GET_DEVICE_URL % (device_id)
37
+ )
38
+
39
+ for items in device_info['data']:
40
+ return items
41
+
42
+ async def _lock_action(self, dev, user, action: str):
43
+ data = json.dumps({
44
+ "action": action,
45
+ "source": "{\"name\":\"%s\",\"device\":\"%s\"}"
46
+ }) % ((user['firstname']+user['lastname'])[0:7],'apikwikset'[0:7])
47
+
48
+ r = await self._request(
49
+ 'patch',
50
+ LOCK_COMMAND_URL % (dev['serialnumber']),
51
+ data=data,
52
+ )
53
+ return r['data']
54
+
55
+ async def _set_action(self, dev, action, status):
56
+ data = json.dumps({
57
+ action: status,
58
+ })
59
+
60
+ r = await self._request(
61
+ 'patch',
62
+ ACCESSORY_COMMAND_URL % (dev['serialnumber'], action),
63
+ data=data,
64
+ )
65
+ return r['data']
66
+
67
+ async def lock_device(self, dev, user):
68
+ return await self._lock_action(dev, user, 'lock')
69
+
70
+ async def unlock_device(self, dev, user):
71
+ return await self._lock_action(dev, user, 'unlock')
72
+
73
+ async def set_ledstatus(self, dev, status):
74
+ return await self._set_action(dev, 'ledstatus', status)
75
+
76
+ async def set_audiostatus(self, dev, status):
77
+ return await self._set_action(dev, 'audiostatus', status)
78
+
79
+ async def set_securescreenstatus(self, dev, status):
80
+ return await self._set_action(dev, 'securescreenstatus', status)
@@ -0,0 +1,25 @@
1
+ """Define package errors."""
2
+
3
+ from typing import Optional
4
+
5
+
6
+ class KwiksetError(Exception):
7
+ """Define a base error."""
8
+
9
+ pass
10
+
11
+
12
+ class RequestError(KwiksetError):
13
+ """Define an error related to invalid requests."""
14
+
15
+ pass
16
+
17
+
18
+ class MFAChallengeRequired(KwiksetError):
19
+ """Define an error when MFA challenge is required."""
20
+
21
+ def __init__(self, message: str = "MFA challenge required.", mfa_type: Optional[str] = None, mfa_tokens: Optional[dict] = None) -> None:
22
+ """Initialize an MFA challenge required error."""
23
+ super().__init__(message)
24
+ self.mfa_type = mfa_type # 'SMS_MFA' or 'SOFTWARE_TOKEN_MFA'
25
+ self.mfa_tokens = mfa_tokens or {}
@@ -0,0 +1,44 @@
1
+ """Define /user endpoints."""
2
+ from typing import Awaitable, Callable
3
+
4
+ from .const import GET_HOMES_URL, GET_USER_URL
5
+
6
+
7
+ class User: # pylint: disable=too-few-public-methods
8
+ """Define an object to handle the endpoints."""
9
+
10
+ def __init__(self, request: Callable[..., Awaitable]) -> None:
11
+ """Initialize."""
12
+ self._request: Callable[..., Awaitable] = request
13
+
14
+ async def get_info(
15
+ self
16
+ ) -> dict:
17
+ """Return user account data.
18
+
19
+ :rtype: ``dict``
20
+ """
21
+
22
+
23
+ user_info: dict = await self._request(
24
+ "get",
25
+ GET_USER_URL
26
+ )
27
+
28
+ for items in user_info['data']:
29
+ return items
30
+
31
+ async def get_homes(
32
+ self
33
+ ) -> dict:
34
+ """Return user homes data
35
+
36
+ :rtype: ``dict``
37
+ """
38
+
39
+ homes_info: dict = await self._request(
40
+ "get",
41
+ GET_HOMES_URL
42
+ )
43
+
44
+ return homes_info['data']
@@ -0,0 +1,148 @@
1
+ Metadata-Version: 2.4
2
+ Name: aiokwikset
3
+ Version: 0.3.0a9
4
+ Summary: Python interface for Kwikset Smart Locks
5
+ Home-page: https://github.com/explosivo22/aiokwikset
6
+ Author: Brad Barbour
7
+ Author-email: explosivo22@protonmail.com
8
+ License: Apache Software License
9
+ Keywords: kwikset,home automation,kwikset halo,kwikset smart lock
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Operating System :: OS Independent
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: aiohttp>=3.6.1
16
+ Requires-Dist: pycognito==2024.5.1
17
+ Dynamic: author
18
+ Dynamic: author-email
19
+ Dynamic: classifier
20
+ Dynamic: description
21
+ Dynamic: description-content-type
22
+ Dynamic: home-page
23
+ Dynamic: keywords
24
+ Dynamic: license
25
+ Dynamic: license-file
26
+ Dynamic: requires-dist
27
+ Dynamic: summary
28
+
29
+
30
+ # aiokwikset - Python interface for the Kwikset API
31
+
32
+ Python library for communicating with the [Kwikset Smart Locks](https://www.kwikset.com/products/electronic/electronic-smart-locks) via the Kwikset cloud API.
33
+
34
+ ***WARNING***
35
+ * This library only works if you have signed up for and created a home/had a home shared with you from the Kwikset Application.
36
+ * [IOS](https://apps.apple.com/us/app/kwikset/id1465996742)
37
+ * [Android](https://play.google.com/store/apps/details?id=com.kwikset.blewifi)
38
+
39
+ NOTE:
40
+
41
+ * This library is community supported, please submit changes and improvements.
42
+ * This is a very basic interface, not well thought out at this point, but works for the use cases that initially prompted spitting this out from.
43
+
44
+ ## Supports
45
+
46
+ - locking/unlocking
47
+ - retrieving basic information
48
+ - Multi-Factor Authentication (MFA) support (SMS and Software Token)
49
+
50
+ ## Installation
51
+
52
+ ```
53
+ pip install aiokwikset
54
+ ```
55
+
56
+ ## Examples
57
+
58
+ ### Basic Usage (No MFA)
59
+
60
+ ```python
61
+ import asyncio
62
+
63
+ from aiokwikset import API
64
+
65
+
66
+ async def main() -> None:
67
+ """Run!"""
68
+ #initialize the API
69
+ api = API()
70
+
71
+ #start auth
72
+ await api.async_login('username','password')
73
+
74
+ # Get user account information:
75
+ user_info = await api.user.get_info()
76
+
77
+ # Get the homes
78
+ homes = await api.user.get_homes()
79
+
80
+ # Get the devices for the first home
81
+ devices = await api.device.get_devices(homes[0]['homeid'])
82
+
83
+ # Get information for a specific device
84
+ device_info = await api.device.get_device_info(devices[0]['deviceid'])
85
+
86
+ # Lock the specific device
87
+ lock = await api.device.lock_device(device_info, user_info)
88
+
89
+ # Set led status
90
+ led = await api.device.set_ledstatus(device_info, "false")
91
+
92
+ # Set audio status
93
+ audio = await api.device.set_audiostatus(device_info, "false")
94
+
95
+ # Set secure screen status
96
+ screen = await api.device.set_securescreenstatus(device_info, "false")
97
+
98
+
99
+ asyncio.run(main())
100
+ ```
101
+
102
+ ### Usage with MFA (Multi-Factor Authentication)
103
+
104
+ If your account has MFA enabled, you need to handle the MFA challenge:
105
+
106
+ ```python
107
+ import asyncio
108
+
109
+ from aiokwikset import API, MFAChallengeRequired
110
+
111
+
112
+ async def main() -> None:
113
+ """Run with MFA support!"""
114
+ api = API()
115
+
116
+ try:
117
+ # Attempt to login
118
+ await api.async_login('username', 'password')
119
+
120
+ except MFAChallengeRequired as mfa_error:
121
+ # MFA is required - prompt user for code
122
+ print(f"MFA Required: {mfa_error.mfa_type}")
123
+ mfa_code = input("Enter your MFA code: ")
124
+
125
+ # Complete MFA authentication
126
+ await api.async_respond_to_mfa_challenge(
127
+ mfa_code=mfa_code,
128
+ mfa_type=mfa_error.mfa_type,
129
+ mfa_tokens=mfa_error.mfa_tokens
130
+ )
131
+
132
+ print("Successfully authenticated with MFA!")
133
+
134
+ # Continue with normal API usage
135
+ user_info = await api.user.get_info()
136
+ homes = await api.user.get_homes()
137
+
138
+ # ... rest of your code
139
+
140
+
141
+ asyncio.run(main())
142
+ ```
143
+
144
+ For detailed MFA documentation and advanced usage examples, see [MFA_USAGE.md](./MFA_USAGE.md).
145
+
146
+ ## Known Issues
147
+
148
+ * not all APIs supported
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ README.md
3
+ setup.py
4
+ aiokwikset/__init__.py
5
+ aiokwikset/api.py
6
+ aiokwikset/const.py
7
+ aiokwikset/device.py
8
+ aiokwikset/errors.py
9
+ aiokwikset/user.py
10
+ aiokwikset.egg-info/PKG-INFO
11
+ aiokwikset.egg-info/SOURCES.txt
12
+ aiokwikset.egg-info/dependency_links.txt
13
+ aiokwikset.egg-info/requires.txt
14
+ aiokwikset.egg-info/top_level.txt
15
+ aiokwikset.egg-info/zip-safe
@@ -0,0 +1,2 @@
1
+ aiohttp>=3.6.1
2
+ pycognito==2024.5.1
@@ -0,0 +1 @@
1
+ aiokwikset
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,33 @@
1
+ import io
2
+ import os
3
+
4
+ from setuptools import setup
5
+
6
+ # The text of the README file
7
+ here = os.path.abspath(os.path.dirname(__file__))
8
+ try:
9
+ with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f:
10
+ long_description = '\n' + f.read()
11
+ except FileNotFoundError:
12
+ long_description = DESCRIPTION
13
+
14
+ setup(
15
+ name="aiokwikset",
16
+ version="0.3.0a9",
17
+ description="Python interface for Kwikset Smart Locks",
18
+ long_description=long_description,
19
+ long_description_content_type='text/markdown',
20
+ url="https://github.com/explosivo22/aiokwikset",
21
+ author="Brad Barbour",
22
+ author_email="explosivo22@protonmail.com",
23
+ license='Apache Software License',
24
+ install_requires=[ 'aiohttp>=3.6.1', 'pycognito==2024.5.1' ],
25
+ keywords=[ 'kwikset', 'home automation', 'kwikset halo', 'kwikset smart lock' ],
26
+ packages=[ 'aiokwikset' ],
27
+ zip_safe=True,
28
+ classifiers=[
29
+ "Programming Language :: Python :: 3",
30
+ "License :: OSI Approved :: Apache Software License",
31
+ "Operating System :: OS Independent",
32
+ ],
33
+ )