dlight-client 1.2.0__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,121 @@
1
+ Creative Commons Legal Code
2
+
3
+ CC0 1.0 Universal
4
+
5
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6
+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9
+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10
+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11
+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12
+ HEREUNDER.
13
+
14
+ Statement of Purpose
15
+
16
+ The laws of most jurisdictions throughout the world automatically confer
17
+ exclusive Copyright and Related Rights (defined below) upon the creator
18
+ and subsequent owner(s) (each and all, an "owner") of an original work of
19
+ authorship and/or a database (each, a "Work").
20
+
21
+ Certain owners wish to permanently relinquish those rights to a Work for
22
+ the purpose of contributing to a commons of creative, cultural and
23
+ scientific works ("Commons") that the public can reliably and without fear
24
+ of later claims of infringement build upon, modify, incorporate in other
25
+ works, reuse and redistribute as freely as possible in any form whatsoever
26
+ and for any purposes, including without limitation commercial purposes.
27
+ These owners may contribute to the Commons to promote the ideal of a free
28
+ culture and the further production of creative, cultural and scientific
29
+ works, or to gain reputation or greater distribution for their Work in
30
+ part through the use and efforts of others.
31
+
32
+ For these and/or other purposes and motivations, and without any
33
+ expectation of additional consideration or compensation, the person
34
+ associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35
+ is an owner of Copyright and Related Rights in the Work, voluntarily
36
+ elects to apply CC0 to the Work and publicly distribute the Work under its
37
+ terms, with knowledge of his or her Copyright and Related Rights in the
38
+ Work and the meaning and intended legal effect of CC0 on those rights.
39
+
40
+ 1. Copyright and Related Rights. A Work made available under CC0 may be
41
+ protected by copyright and related or neighboring rights ("Copyright and
42
+ Related Rights"). Copyright and Related Rights include, but are not
43
+ limited to, the following:
44
+
45
+ i. the right to reproduce, adapt, distribute, perform, display,
46
+ communicate, and translate a Work;
47
+ ii. moral rights retained by the original author(s) and/or performer(s);
48
+ iii. publicity and privacy rights pertaining to a person's image or
49
+ likeness depicted in a Work;
50
+ iv. rights protecting against unfair competition in regards to a Work,
51
+ subject to the limitations in paragraph 4(a), below;
52
+ v. rights protecting the extraction, dissemination, use and reuse of data
53
+ in a Work;
54
+ vi. database rights (such as those arising under Directive 96/9/EC of the
55
+ European Parliament and of the Council of 11 March 1996 on the legal
56
+ protection of databases, and under any national implementation
57
+ thereof, including any amended or successor version of such
58
+ directive); and
59
+ vii. other similar, equivalent or corresponding rights throughout the
60
+ world based on applicable law or treaty, and any national
61
+ implementations thereof.
62
+
63
+ 2. Waiver. To the greatest extent permitted by, but not in contravention
64
+ of, applicable law, Affirmer hereby overtly, fully, permanently,
65
+ irrevocably and unconditionally waives, abandons, and surrenders all of
66
+ Affirmer's Copyright and Related Rights and associated claims and causes
67
+ of action, whether now known or unknown (including existing as well as
68
+ future claims and causes of action), in the Work (i) in all territories
69
+ worldwide, (ii) for the maximum duration provided by applicable law or
70
+ treaty (including future time extensions), (iii) in any current or future
71
+ medium and for any number of copies, and (iv) for any purpose whatsoever,
72
+ including without limitation commercial, advertising or promotional
73
+ purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74
+ member of the public at large and to the detriment of Affirmer's heirs and
75
+ successors, fully intending that such Waiver shall not be subject to
76
+ revocation, rescission, cancellation, termination, or any other legal or
77
+ equitable action to disrupt the quiet enjoyment of the Work by the public
78
+ as contemplated by Affirmer's express Statement of Purpose.
79
+
80
+ 3. Public License Fallback. Should any part of the Waiver for any reason
81
+ be judged legally invalid or ineffective under applicable law, then the
82
+ Waiver shall be preserved to the maximum extent permitted taking into
83
+ account Affirmer's express Statement of Purpose. In addition, to the
84
+ extent the Waiver is so judged Affirmer hereby grants to each affected
85
+ person a royalty-free, non transferable, non sublicensable, non exclusive,
86
+ irrevocable and unconditional license to exercise Affirmer's Copyright and
87
+ Related Rights in the Work (i) in all territories worldwide, (ii) for the
88
+ maximum duration provided by applicable law or treaty (including future
89
+ time extensions), (iii) in any current or future medium and for any number
90
+ of copies, and (iv) for any purpose whatsoever, including without
91
+ limitation commercial, advertising or promotional purposes (the
92
+ "License"). The License shall be deemed effective as of the date CC0 was
93
+ applied by Affirmer to the Work. Should any part of the License for any
94
+ reason be judged legally invalid or ineffective under applicable law, such
95
+ partial invalidity or ineffectiveness shall not invalidate the remainder
96
+ of the License, and in such case Affirmer hereby affirms that he or she
97
+ will not (i) exercise any of his or her remaining Copyright and Related
98
+ Rights in the Work or (ii) assert any associated claims and causes of
99
+ action with respect to the Work, in either case contrary to Affirmer's
100
+ express Statement of Purpose.
101
+
102
+ 4. Limitations and Disclaimers.
103
+
104
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
105
+ surrendered, licensed or otherwise affected by this document.
106
+ b. Affirmer offers the Work as-is and makes no representations or
107
+ warranties of any kind concerning the Work, express, implied,
108
+ statutory or otherwise, including without limitation warranties of
109
+ title, merchantability, fitness for a particular purpose, non
110
+ infringement, or the absence of latent or other defects, accuracy, or
111
+ the present or absence of errors, whether or not discoverable, all to
112
+ the greatest extent permissible under applicable law.
113
+ c. Affirmer disclaims responsibility for clearing rights of other persons
114
+ that may apply to the Work or any use thereof, including without
115
+ limitation any person's Copyright and Related Rights in the Work.
116
+ Further, Affirmer disclaims responsibility for obtaining any necessary
117
+ consents, permissions or other rights required for any use of the
118
+ Work.
119
+ d. Affirmer understands and acknowledges that Creative Commons is not a
120
+ party to this document and has no duty or obligation with respect to
121
+ this CC0 or use of the Work.
@@ -0,0 +1,348 @@
1
+ Metadata-Version: 2.4
2
+ Name: dlight-client
3
+ Version: 1.2.0
4
+ Summary: A Python client for the dLight smart lamp API.
5
+ Author-email: David Kernan <dave@paddez.com>
6
+ License: Creative Commons Legal Code
7
+
8
+ CC0 1.0 Universal
9
+
10
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
11
+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
12
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
13
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
14
+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
15
+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
16
+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
17
+ HEREUNDER.
18
+
19
+ Statement of Purpose
20
+
21
+ The laws of most jurisdictions throughout the world automatically confer
22
+ exclusive Copyright and Related Rights (defined below) upon the creator
23
+ and subsequent owner(s) (each and all, an "owner") of an original work of
24
+ authorship and/or a database (each, a "Work").
25
+
26
+ Certain owners wish to permanently relinquish those rights to a Work for
27
+ the purpose of contributing to a commons of creative, cultural and
28
+ scientific works ("Commons") that the public can reliably and without fear
29
+ of later claims of infringement build upon, modify, incorporate in other
30
+ works, reuse and redistribute as freely as possible in any form whatsoever
31
+ and for any purposes, including without limitation commercial purposes.
32
+ These owners may contribute to the Commons to promote the ideal of a free
33
+ culture and the further production of creative, cultural and scientific
34
+ works, or to gain reputation or greater distribution for their Work in
35
+ part through the use and efforts of others.
36
+
37
+ For these and/or other purposes and motivations, and without any
38
+ expectation of additional consideration or compensation, the person
39
+ associating CC0 with a Work (the "Affirmer"), to the extent that he or she
40
+ is an owner of Copyright and Related Rights in the Work, voluntarily
41
+ elects to apply CC0 to the Work and publicly distribute the Work under its
42
+ terms, with knowledge of his or her Copyright and Related Rights in the
43
+ Work and the meaning and intended legal effect of CC0 on those rights.
44
+
45
+ 1. Copyright and Related Rights. A Work made available under CC0 may be
46
+ protected by copyright and related or neighboring rights ("Copyright and
47
+ Related Rights"). Copyright and Related Rights include, but are not
48
+ limited to, the following:
49
+
50
+ i. the right to reproduce, adapt, distribute, perform, display,
51
+ communicate, and translate a Work;
52
+ ii. moral rights retained by the original author(s) and/or performer(s);
53
+ iii. publicity and privacy rights pertaining to a person's image or
54
+ likeness depicted in a Work;
55
+ iv. rights protecting against unfair competition in regards to a Work,
56
+ subject to the limitations in paragraph 4(a), below;
57
+ v. rights protecting the extraction, dissemination, use and reuse of data
58
+ in a Work;
59
+ vi. database rights (such as those arising under Directive 96/9/EC of the
60
+ European Parliament and of the Council of 11 March 1996 on the legal
61
+ protection of databases, and under any national implementation
62
+ thereof, including any amended or successor version of such
63
+ directive); and
64
+ vii. other similar, equivalent or corresponding rights throughout the
65
+ world based on applicable law or treaty, and any national
66
+ implementations thereof.
67
+
68
+ 2. Waiver. To the greatest extent permitted by, but not in contravention
69
+ of, applicable law, Affirmer hereby overtly, fully, permanently,
70
+ irrevocably and unconditionally waives, abandons, and surrenders all of
71
+ Affirmer's Copyright and Related Rights and associated claims and causes
72
+ of action, whether now known or unknown (including existing as well as
73
+ future claims and causes of action), in the Work (i) in all territories
74
+ worldwide, (ii) for the maximum duration provided by applicable law or
75
+ treaty (including future time extensions), (iii) in any current or future
76
+ medium and for any number of copies, and (iv) for any purpose whatsoever,
77
+ including without limitation commercial, advertising or promotional
78
+ purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
79
+ member of the public at large and to the detriment of Affirmer's heirs and
80
+ successors, fully intending that such Waiver shall not be subject to
81
+ revocation, rescission, cancellation, termination, or any other legal or
82
+ equitable action to disrupt the quiet enjoyment of the Work by the public
83
+ as contemplated by Affirmer's express Statement of Purpose.
84
+
85
+ 3. Public License Fallback. Should any part of the Waiver for any reason
86
+ be judged legally invalid or ineffective under applicable law, then the
87
+ Waiver shall be preserved to the maximum extent permitted taking into
88
+ account Affirmer's express Statement of Purpose. In addition, to the
89
+ extent the Waiver is so judged Affirmer hereby grants to each affected
90
+ person a royalty-free, non transferable, non sublicensable, non exclusive,
91
+ irrevocable and unconditional license to exercise Affirmer's Copyright and
92
+ Related Rights in the Work (i) in all territories worldwide, (ii) for the
93
+ maximum duration provided by applicable law or treaty (including future
94
+ time extensions), (iii) in any current or future medium and for any number
95
+ of copies, and (iv) for any purpose whatsoever, including without
96
+ limitation commercial, advertising or promotional purposes (the
97
+ "License"). The License shall be deemed effective as of the date CC0 was
98
+ applied by Affirmer to the Work. Should any part of the License for any
99
+ reason be judged legally invalid or ineffective under applicable law, such
100
+ partial invalidity or ineffectiveness shall not invalidate the remainder
101
+ of the License, and in such case Affirmer hereby affirms that he or she
102
+ will not (i) exercise any of his or her remaining Copyright and Related
103
+ Rights in the Work or (ii) assert any associated claims and causes of
104
+ action with respect to the Work, in either case contrary to Affirmer's
105
+ express Statement of Purpose.
106
+
107
+ 4. Limitations and Disclaimers.
108
+
109
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
110
+ surrendered, licensed or otherwise affected by this document.
111
+ b. Affirmer offers the Work as-is and makes no representations or
112
+ warranties of any kind concerning the Work, express, implied,
113
+ statutory or otherwise, including without limitation warranties of
114
+ title, merchantability, fitness for a particular purpose, non
115
+ infringement, or the absence of latent or other defects, accuracy, or
116
+ the present or absence of errors, whether or not discoverable, all to
117
+ the greatest extent permissible under applicable law.
118
+ c. Affirmer disclaims responsibility for clearing rights of other persons
119
+ that may apply to the Work or any use thereof, including without
120
+ limitation any person's Copyright and Related Rights in the Work.
121
+ Further, Affirmer disclaims responsibility for obtaining any necessary
122
+ consents, permissions or other rights required for any use of the
123
+ Work.
124
+ d. Affirmer understands and acknowledges that Creative Commons is not a
125
+ party to this document and has no duty or obligation with respect to
126
+ this CC0 or use of the Work.
127
+
128
+ Project-URL: Homepage, https://github.com/irishsmurf/dlight-client
129
+ Project-URL: Bug Tracker, https://github.com/irishsmurf/dlight-client/issues
130
+ Keywords: dlight,smart home,lighting,api,iot
131
+ Classifier: Programming Language :: Python :: 3
132
+ Classifier: License :: OSI Approved :: MIT License
133
+ Classifier: Operating System :: OS Independent
134
+ Classifier: Intended Audience :: Developers
135
+ Classifier: Topic :: Home Automation
136
+ Classifier: Topic :: System :: Networking
137
+ Requires-Python: >=3.7
138
+ Description-Content-Type: text/markdown
139
+ License-File: LICENSE
140
+ Dynamic: license-file
141
+
142
+ # python-dlight-client - Async Python Client for dLight API
143
+
144
+ [![PyPI version](https://badge.fury.io/py/dlight-client.svg)](https://badge.fury.io/py/dlight-client)
145
+ [![Python Versions](https://img.shields.io/pypi/pyversions/dlight-client.svg)](https://pypi.org/project/dlight-client/)
146
+
147
+ This Python package provides an asynchronous client library (`asyncio`) for interacting with the dLight smart lamp API, based on the documentation dated 2023-01-04. It allows discovering dLight devices using UDP broadcasts and controlling them over a local Wi-Fi network using TCP commands.
148
+
149
+ The library has been refactored for better organization:
150
+ * `dlightclient.client`: Contains the `AsyncDLightClient` for TCP control.
151
+ * `dlightclient.discovery`: Provides the `discover_devices` function for UDP discovery.
152
+ * `dlightclient.exceptions`: Defines custom error types.
153
+ * `dlightclient.constants`: Holds shared constants.
154
+ * `dlightclient.cli`: Offers a basic command-line interface.
155
+
156
+ ## Features
157
+
158
+ * **Asynchronous:** Built with `asyncio` for non-blocking network operations.
159
+ * **Discover Devices:** Find dLight devices on the local network via UDP broadcast (`discover_devices`).
160
+ * **Control Light State:**
161
+ * Turn On/Off (`AsyncDLightClient.set_light_state`)
162
+ * Set Brightness (0-100%) (`AsyncDLightClient.set_brightness`)
163
+ * Set Color Temperature (2600K-6000K) (`AsyncDLightClient.set_color_temperature`)
164
+ * **Query Device:**
165
+ * Get current state (`AsyncDLightClient.query_device_state`).
166
+ * Get device information (`AsyncDLightClient.query_device_info`).
167
+ * **Wi-Fi Provisioning:** Support for sending Wi-Fi credentials (`AsyncDLightClient.connect_to_wifi` - typically used when device is in SoftAP mode).
168
+ * **Robust Communication:** Handles the specific dLight TCP response format (4-byte length prefix + JSON payload) and includes timeouts.
169
+ * **Error Handling:** Custom exceptions for specific error conditions (e.g., `DLightError`, `DLightTimeoutError`, `DLightConnectionError`).
170
+ * **Command-Line Tool:** A basic CLI (`cli.py`) for discovery and interaction.
171
+
172
+ ## Prerequisites
173
+
174
+ * A dLight device connected to your local Wi-Fi network (or in SoftAP mode for initial setup).
175
+ * Python 3.9+ (due to `asyncio` features used)
176
+
177
+ ## Installation
178
+
179
+ ```bash
180
+ pip install dlight-client
181
+ ```
182
+
183
+ ## Usage
184
+
185
+ You can use this package as a library in your Python projects or via the included command-line tool.As a LibraryFirst, discover your dLight device(s) to get their IP address and Device ID. Then, use these details to send commands via an AsyncDLightClient instance within an async function.import asyncio
186
+
187
+ ```py
188
+ import logging
189
+ import time # For delays in example
190
+
191
+ # Import the public interface
192
+ from dlightclient import (
193
+ AsyncDLightClient,
194
+ discover_devices,
195
+ DLightError,
196
+ DLightTimeoutError,
197
+ DLightConnectionError
198
+ )
199
+
200
+ # Configure logging
201
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
202
+ log = logging.getLogger(__name__)
203
+
204
+ async def run_example():
205
+ log.info("--- Async dLight Python Client Example ---")
206
+
207
+ log.info("\n--- Discovering Devices (3 seconds) ---")
208
+ try:
209
+ # Use the discover_devices function directly
210
+ devices = await discover_devices(discovery_duration=3.0)
211
+ except Exception as e:
212
+ log.exception(f"Discovery failed with an unexpected error: {e}")
213
+ devices = []
214
+
215
+ if not devices:
216
+ log.warning("\nNo dLight devices found on the network.")
217
+ log.warning("Ensure dLight is powered on and connected to the same network.")
218
+ # Add Wi-Fi connect example if needed (see cli.py or client.py for details)
219
+ return
220
+
221
+ # --- Interact with the first discovered device ---
222
+ target_device = devices[0]
223
+ target_ip = target_device.get('ip_address')
224
+ # Handle potential case difference for deviceId from discovery
225
+ device_id = target_device.get('deviceId') or target_device.get('deviceid')
226
+
227
+ if not target_ip or not device_id:
228
+ log.error(f"Could not get IP address or Device ID from discovered device: {target_device}")
229
+ return
230
+
231
+ log.info(f"\n--- Interacting with: {device_id} at {target_ip} ---")
232
+ client = AsyncDLightClient(default_timeout=5.0) # Adjust timeout if needed
233
+
234
+ try:
235
+ # Query Info
236
+ log.info("\nQuerying Device Info...")
237
+ info = await client.query_device_info(target_ip, device_id)
238
+ log.info(f" Info: {info}")
239
+
240
+ # Query State
241
+ log.info("\nQuerying Device State...")
242
+ state_resp = await client.query_device_state(target_ip, device_id)
243
+ current_state = state_resp.get('states', {})
244
+ log.info(f" Current State: {current_state}")
245
+
246
+ # Turn On
247
+ log.info("\nTurning Light ON...")
248
+ await client.set_light_state(target_ip, device_id, True)
249
+ await asyncio.sleep(0.5) # Give device time to react
250
+
251
+ # Set Brightness
252
+ log.info("\nSetting Brightness to 60%...")
253
+ await client.set_brightness(target_ip, device_id, 60)
254
+ await asyncio.sleep(0.5)
255
+
256
+ # Set Color Temperature
257
+ log.info("\nSetting Color Temperature to 4500K...")
258
+ await client.set_color_temperature(target_ip, device_id, 4500)
259
+ await asyncio.sleep(0.5)
260
+
261
+ # Query State Again
262
+ log.info("\nQuerying Device State Again...")
263
+ state_resp = await client.query_device_state(target_ip, device_id)
264
+ new_state = state_resp.get('states', {})
265
+ log.info(f" New State: {new_state}")
266
+
267
+ # Turn Off
268
+ log.info("\nTurning Light OFF...")
269
+ await client.set_light_state(target_ip, device_id, False)
270
+
271
+ except (DLightTimeoutError, DLightConnectionError) as e:
272
+ log.error(f"\n--- Network Error during interaction ---")
273
+ log.error(e)
274
+ except DLightError as e:
275
+ log.error(f"\n--- A dLight error occurred during interaction ---")
276
+ log.error(e)
277
+ except ValueError as e:
278
+ log.error(f"\n--- Invalid value provided during interaction ---")
279
+ log.error(e)
280
+ except Exception as e:
281
+ log.exception(f"\n--- An unexpected error occurred during interaction ---")
282
+
283
+
284
+ if __name__ == "__main__":
285
+ try:
286
+ asyncio.run(run_example())
287
+ except KeyboardInterrupt:
288
+ print("Example stopped.")
289
+ ```
290
+
291
+ ### Using the Command-Line Tool (cli.py)
292
+
293
+ The package includes a basic command-line tool for common operations. You can run it as a module:
294
+
295
+ ```py
296
+ python -m dlightclient.cli [OPTIONS]
297
+ ```
298
+
299
+ ### Common Commands:
300
+
301
+ - **Discover devices:**
302
+ - `python -m dlightclient.cli --discover`
303
+ - `python -m dlightclient.cli --discover --discover-duration <DURATION>`
304
+ - **Interact with a device (requires IP and ID):**
305
+ - *Replace <IP_ADDRESS> and <DEVICE_ID> with actual values*
306
+ - `python -m dlightclient.cli --ip <IP_ADDRESS> --id <DEVICE_ID>`
307
+ - **Send Wi-Fi credentials (for setup):**
308
+ - *Warning: Use this only when the device is in SoftAP mode and your computer is connected to its network.*
309
+ - ```
310
+ # Replace <DEVICE_ID>, <YOUR_WIFI_SSID>, <YOUR_WIFI_PASSWORD>
311
+ python -m dlightclient.cli --connect-wifi --id <DEVICE_ID> --ssid "<YOUR_WIFI_SSID>" --password "<YOUR_WIFI_PASSWORD>"
312
+ ```
313
+ - **Get Help:**
314
+ - python -m dlightclient.cli --help
315
+ - **Increase Verbosity:**
316
+ - Use -v for INFO level logging, -vv for DEBUG level.# Discover with DEBUG logging
317
+ - `python -m dlightclient.cli --discover -vv`
318
+
319
+ # Interact with DEBUG logging
320
+ `python -m dlightclient.cli --ip <IP_ADDRESS> --id <DEVICE_ID> -vv`
321
+
322
+ # API Details
323
+ - **TCP Commands:** Sent to device IP on port 3333 (default). Handled by `AsyncDLightClient.`
324
+ - **UDP Discovery:** Broadcast sent to 255.255.255.255 (default) on port 9478. Responses listened for on port 9487. Handled by `discover_devices`.
325
+
326
+ # Development and Testing
327
+
328
+ 1. Setup Virtual Environment:
329
+ ```sh
330
+ python -m venv .venv
331
+ source .venv/bin/activate # or .\.venv\Scripts\activate on Windows
332
+ ```
333
+
334
+ 2. Install Dependencies (if any beyond standard library):
335
+ ```sh
336
+ # Add requirements-dev.txt if needed for linters, pytest, etc.
337
+ # pip install -r requirements-dev.txt
338
+ ```
339
+
340
+ 3. Install in Editable Mode:
341
+ ```sh
342
+ pip install -e .
343
+ ```
344
+
345
+ # Testing
346
+ Note: The test suite (tests/test_dlight.py) needs to be updated to reflect the refactored code structure (module paths for patching, imports, etc.).Once updated, you can run tests using:python -m unittest discover -s tests/ -p 'test_*.py'
347
+ # Or potentially targeting the specific test file if structure changed:
348
+ # python -m unittest tests.test_dlight
@@ -0,0 +1,207 @@
1
+ # python-dlight-client - Async Python Client for dLight API
2
+
3
+ [![PyPI version](https://badge.fury.io/py/dlight-client.svg)](https://badge.fury.io/py/dlight-client)
4
+ [![Python Versions](https://img.shields.io/pypi/pyversions/dlight-client.svg)](https://pypi.org/project/dlight-client/)
5
+
6
+ This Python package provides an asynchronous client library (`asyncio`) for interacting with the dLight smart lamp API, based on the documentation dated 2023-01-04. It allows discovering dLight devices using UDP broadcasts and controlling them over a local Wi-Fi network using TCP commands.
7
+
8
+ The library has been refactored for better organization:
9
+ * `dlightclient.client`: Contains the `AsyncDLightClient` for TCP control.
10
+ * `dlightclient.discovery`: Provides the `discover_devices` function for UDP discovery.
11
+ * `dlightclient.exceptions`: Defines custom error types.
12
+ * `dlightclient.constants`: Holds shared constants.
13
+ * `dlightclient.cli`: Offers a basic command-line interface.
14
+
15
+ ## Features
16
+
17
+ * **Asynchronous:** Built with `asyncio` for non-blocking network operations.
18
+ * **Discover Devices:** Find dLight devices on the local network via UDP broadcast (`discover_devices`).
19
+ * **Control Light State:**
20
+ * Turn On/Off (`AsyncDLightClient.set_light_state`)
21
+ * Set Brightness (0-100%) (`AsyncDLightClient.set_brightness`)
22
+ * Set Color Temperature (2600K-6000K) (`AsyncDLightClient.set_color_temperature`)
23
+ * **Query Device:**
24
+ * Get current state (`AsyncDLightClient.query_device_state`).
25
+ * Get device information (`AsyncDLightClient.query_device_info`).
26
+ * **Wi-Fi Provisioning:** Support for sending Wi-Fi credentials (`AsyncDLightClient.connect_to_wifi` - typically used when device is in SoftAP mode).
27
+ * **Robust Communication:** Handles the specific dLight TCP response format (4-byte length prefix + JSON payload) and includes timeouts.
28
+ * **Error Handling:** Custom exceptions for specific error conditions (e.g., `DLightError`, `DLightTimeoutError`, `DLightConnectionError`).
29
+ * **Command-Line Tool:** A basic CLI (`cli.py`) for discovery and interaction.
30
+
31
+ ## Prerequisites
32
+
33
+ * A dLight device connected to your local Wi-Fi network (or in SoftAP mode for initial setup).
34
+ * Python 3.9+ (due to `asyncio` features used)
35
+
36
+ ## Installation
37
+
38
+ ```bash
39
+ pip install dlight-client
40
+ ```
41
+
42
+ ## Usage
43
+
44
+ You can use this package as a library in your Python projects or via the included command-line tool.As a LibraryFirst, discover your dLight device(s) to get their IP address and Device ID. Then, use these details to send commands via an AsyncDLightClient instance within an async function.import asyncio
45
+
46
+ ```py
47
+ import logging
48
+ import time # For delays in example
49
+
50
+ # Import the public interface
51
+ from dlightclient import (
52
+ AsyncDLightClient,
53
+ discover_devices,
54
+ DLightError,
55
+ DLightTimeoutError,
56
+ DLightConnectionError
57
+ )
58
+
59
+ # Configure logging
60
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
61
+ log = logging.getLogger(__name__)
62
+
63
+ async def run_example():
64
+ log.info("--- Async dLight Python Client Example ---")
65
+
66
+ log.info("\n--- Discovering Devices (3 seconds) ---")
67
+ try:
68
+ # Use the discover_devices function directly
69
+ devices = await discover_devices(discovery_duration=3.0)
70
+ except Exception as e:
71
+ log.exception(f"Discovery failed with an unexpected error: {e}")
72
+ devices = []
73
+
74
+ if not devices:
75
+ log.warning("\nNo dLight devices found on the network.")
76
+ log.warning("Ensure dLight is powered on and connected to the same network.")
77
+ # Add Wi-Fi connect example if needed (see cli.py or client.py for details)
78
+ return
79
+
80
+ # --- Interact with the first discovered device ---
81
+ target_device = devices[0]
82
+ target_ip = target_device.get('ip_address')
83
+ # Handle potential case difference for deviceId from discovery
84
+ device_id = target_device.get('deviceId') or target_device.get('deviceid')
85
+
86
+ if not target_ip or not device_id:
87
+ log.error(f"Could not get IP address or Device ID from discovered device: {target_device}")
88
+ return
89
+
90
+ log.info(f"\n--- Interacting with: {device_id} at {target_ip} ---")
91
+ client = AsyncDLightClient(default_timeout=5.0) # Adjust timeout if needed
92
+
93
+ try:
94
+ # Query Info
95
+ log.info("\nQuerying Device Info...")
96
+ info = await client.query_device_info(target_ip, device_id)
97
+ log.info(f" Info: {info}")
98
+
99
+ # Query State
100
+ log.info("\nQuerying Device State...")
101
+ state_resp = await client.query_device_state(target_ip, device_id)
102
+ current_state = state_resp.get('states', {})
103
+ log.info(f" Current State: {current_state}")
104
+
105
+ # Turn On
106
+ log.info("\nTurning Light ON...")
107
+ await client.set_light_state(target_ip, device_id, True)
108
+ await asyncio.sleep(0.5) # Give device time to react
109
+
110
+ # Set Brightness
111
+ log.info("\nSetting Brightness to 60%...")
112
+ await client.set_brightness(target_ip, device_id, 60)
113
+ await asyncio.sleep(0.5)
114
+
115
+ # Set Color Temperature
116
+ log.info("\nSetting Color Temperature to 4500K...")
117
+ await client.set_color_temperature(target_ip, device_id, 4500)
118
+ await asyncio.sleep(0.5)
119
+
120
+ # Query State Again
121
+ log.info("\nQuerying Device State Again...")
122
+ state_resp = await client.query_device_state(target_ip, device_id)
123
+ new_state = state_resp.get('states', {})
124
+ log.info(f" New State: {new_state}")
125
+
126
+ # Turn Off
127
+ log.info("\nTurning Light OFF...")
128
+ await client.set_light_state(target_ip, device_id, False)
129
+
130
+ except (DLightTimeoutError, DLightConnectionError) as e:
131
+ log.error(f"\n--- Network Error during interaction ---")
132
+ log.error(e)
133
+ except DLightError as e:
134
+ log.error(f"\n--- A dLight error occurred during interaction ---")
135
+ log.error(e)
136
+ except ValueError as e:
137
+ log.error(f"\n--- Invalid value provided during interaction ---")
138
+ log.error(e)
139
+ except Exception as e:
140
+ log.exception(f"\n--- An unexpected error occurred during interaction ---")
141
+
142
+
143
+ if __name__ == "__main__":
144
+ try:
145
+ asyncio.run(run_example())
146
+ except KeyboardInterrupt:
147
+ print("Example stopped.")
148
+ ```
149
+
150
+ ### Using the Command-Line Tool (cli.py)
151
+
152
+ The package includes a basic command-line tool for common operations. You can run it as a module:
153
+
154
+ ```py
155
+ python -m dlightclient.cli [OPTIONS]
156
+ ```
157
+
158
+ ### Common Commands:
159
+
160
+ - **Discover devices:**
161
+ - `python -m dlightclient.cli --discover`
162
+ - `python -m dlightclient.cli --discover --discover-duration <DURATION>`
163
+ - **Interact with a device (requires IP and ID):**
164
+ - *Replace <IP_ADDRESS> and <DEVICE_ID> with actual values*
165
+ - `python -m dlightclient.cli --ip <IP_ADDRESS> --id <DEVICE_ID>`
166
+ - **Send Wi-Fi credentials (for setup):**
167
+ - *Warning: Use this only when the device is in SoftAP mode and your computer is connected to its network.*
168
+ - ```
169
+ # Replace <DEVICE_ID>, <YOUR_WIFI_SSID>, <YOUR_WIFI_PASSWORD>
170
+ python -m dlightclient.cli --connect-wifi --id <DEVICE_ID> --ssid "<YOUR_WIFI_SSID>" --password "<YOUR_WIFI_PASSWORD>"
171
+ ```
172
+ - **Get Help:**
173
+ - python -m dlightclient.cli --help
174
+ - **Increase Verbosity:**
175
+ - Use -v for INFO level logging, -vv for DEBUG level.# Discover with DEBUG logging
176
+ - `python -m dlightclient.cli --discover -vv`
177
+
178
+ # Interact with DEBUG logging
179
+ `python -m dlightclient.cli --ip <IP_ADDRESS> --id <DEVICE_ID> -vv`
180
+
181
+ # API Details
182
+ - **TCP Commands:** Sent to device IP on port 3333 (default). Handled by `AsyncDLightClient.`
183
+ - **UDP Discovery:** Broadcast sent to 255.255.255.255 (default) on port 9478. Responses listened for on port 9487. Handled by `discover_devices`.
184
+
185
+ # Development and Testing
186
+
187
+ 1. Setup Virtual Environment:
188
+ ```sh
189
+ python -m venv .venv
190
+ source .venv/bin/activate # or .\.venv\Scripts\activate on Windows
191
+ ```
192
+
193
+ 2. Install Dependencies (if any beyond standard library):
194
+ ```sh
195
+ # Add requirements-dev.txt if needed for linters, pytest, etc.
196
+ # pip install -r requirements-dev.txt
197
+ ```
198
+
199
+ 3. Install in Editable Mode:
200
+ ```sh
201
+ pip install -e .
202
+ ```
203
+
204
+ # Testing
205
+ Note: The test suite (tests/test_dlight.py) needs to be updated to reflect the refactored code structure (module paths for patching, imports, etc.).Once updated, you can run tests using:python -m unittest discover -s tests/ -p 'test_*.py'
206
+ # Or potentially targeting the specific test file if structure changed:
207
+ # python -m unittest tests.test_dlight