fastled 1.2.23__py3-none-any.whl

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,401 @@
1
+ import argparse
2
+ import shutil
3
+ import tempfile
4
+ import threading
5
+ import time
6
+ from multiprocessing import Process
7
+ from pathlib import Path
8
+
9
+ from fastled.compile_server import CompileServer
10
+ from fastled.docker_manager import DockerManager
11
+ from fastled.filewatcher import FileWatcherProcess
12
+ from fastled.keyboard import SpaceBarWatcher
13
+ from fastled.open_browser import open_browser_process
14
+ from fastled.settings import DEFAULT_URL
15
+ from fastled.sketch import looks_like_sketch_directory
16
+ from fastled.types import BuildMode, CompileResult, CompileServerError
17
+ from fastled.web_compile import (
18
+ SERVER_PORT,
19
+ ConnectionResult,
20
+ find_good_connection,
21
+ web_compile,
22
+ )
23
+
24
+
25
+ def _create_error_html(error_message: str) -> str:
26
+ return f"""<!DOCTYPE html>
27
+ <html>
28
+ <head>
29
+ <!-- no cache -->
30
+ <meta http-equiv="Cache-Control" content="no-store" />
31
+ <meta http-equiv="Pragma" content="no-cache" />
32
+ <meta http-equiv="Expires" content="0" />
33
+ <title>FastLED Compilation Error ZACH</title>
34
+ <style>
35
+ body {{
36
+ background-color: #1a1a1a;
37
+ color: #ffffff;
38
+ font-family: Arial, sans-serif;
39
+ margin: 20px;
40
+ padding: 20px;
41
+ }}
42
+ pre {{
43
+ color: #ffffff;
44
+ background-color: #1a1a1a;
45
+ border: 1px solid #444444;
46
+ border-radius: 4px;
47
+ padding: 15px;
48
+ white-space: pre-wrap;
49
+ word-wrap: break-word;
50
+ }}
51
+ </style>
52
+ </head>
53
+ <body>
54
+ <h1>Compilation Failed</h1>
55
+ <pre>{error_message}</pre>
56
+ </body>
57
+ </html>"""
58
+
59
+
60
+ # Override this function in your own code to run tests before compilation
61
+ def TEST_BEFORE_COMPILE(url) -> None:
62
+ pass
63
+
64
+
65
+ def _run_web_compiler(
66
+ directory: Path,
67
+ host: str,
68
+ build_mode: BuildMode,
69
+ profile: bool,
70
+ last_hash_value: str | None,
71
+ ) -> CompileResult:
72
+ input_dir = Path(directory)
73
+ output_dir = input_dir / "fastled_js"
74
+ start = time.time()
75
+ web_result = web_compile(
76
+ directory=input_dir, host=host, build_mode=build_mode, profile=profile
77
+ )
78
+ diff = time.time() - start
79
+ if not web_result.success:
80
+ print("\nWeb compilation failed:")
81
+ print(f"Time taken: {diff:.2f} seconds")
82
+ print(web_result.stdout)
83
+ # Create error page
84
+ output_dir.mkdir(exist_ok=True)
85
+ error_html = _create_error_html(web_result.stdout)
86
+ (output_dir / "index.html").write_text(error_html, encoding="utf-8")
87
+ return web_result
88
+
89
+ def print_results() -> None:
90
+ hash_value = (
91
+ web_result.hash_value
92
+ if web_result.hash_value is not None
93
+ else "NO HASH VALUE"
94
+ )
95
+ print(
96
+ f"\nWeb compilation successful\n Time: {diff:.2f}\n output: {output_dir}\n hash: {hash_value}\n zip size: {len(web_result.zip_bytes)} bytes"
97
+ )
98
+
99
+ # now check to see if the hash value is the same as the last hash value
100
+ if last_hash_value is not None and last_hash_value == web_result.hash_value:
101
+ print("\nSkipping redeploy: No significant changes found.")
102
+ print_results()
103
+ return web_result
104
+
105
+ # Extract zip contents to fastled_js directory
106
+ output_dir.mkdir(exist_ok=True)
107
+ with tempfile.TemporaryDirectory() as temp_dir:
108
+ temp_path = Path(temp_dir)
109
+ temp_zip = temp_path / "result.zip"
110
+ temp_zip.write_bytes(web_result.zip_bytes)
111
+
112
+ # Clear existing contents
113
+ shutil.rmtree(output_dir, ignore_errors=True)
114
+ output_dir.mkdir(exist_ok=True)
115
+
116
+ # Extract zip contents
117
+ shutil.unpack_archive(temp_zip, output_dir, "zip")
118
+
119
+ print(web_result.stdout)
120
+ print_results()
121
+ return web_result
122
+
123
+
124
+ def _try_start_server_or_get_url(
125
+ auto_update: bool, args_web: str | bool, localhost: bool
126
+ ) -> tuple[str, CompileServer | None]:
127
+ is_local_host = localhost or (
128
+ isinstance(args_web, str)
129
+ and ("localhost" in args_web or "127.0.0.1" in args_web)
130
+ )
131
+ # test to see if there is already a local host server
132
+ local_host_needs_server = False
133
+ if is_local_host:
134
+ addr = "localhost" if localhost or not isinstance(args_web, str) else args_web
135
+ urls = [addr]
136
+ if ":" not in addr:
137
+ urls.append(f"{addr}:{SERVER_PORT}")
138
+
139
+ result: ConnectionResult | None = find_good_connection(urls)
140
+ if result is not None:
141
+ print(f"Found local server at {result.host}")
142
+ return (result.host, None)
143
+ else:
144
+ local_host_needs_server = True
145
+
146
+ if not local_host_needs_server and args_web:
147
+ if isinstance(args_web, str):
148
+ return (args_web, None)
149
+ if isinstance(args_web, bool):
150
+ return (DEFAULT_URL, None)
151
+ return (args_web, None)
152
+ else:
153
+ try:
154
+ print("No local server found, starting one...")
155
+ compile_server = CompileServer(auto_updates=auto_update)
156
+ print("Waiting for the local compiler to start...")
157
+ if not compile_server.ping():
158
+ print("Failed to start local compiler.")
159
+ raise CompileServerError("Failed to start local compiler.")
160
+ return (compile_server.url(), compile_server)
161
+ except KeyboardInterrupt:
162
+ raise
163
+ except RuntimeError:
164
+ print("Failed to start local compile server, using web compiler instead.")
165
+ return (DEFAULT_URL, None)
166
+
167
+
168
+ def run_client(
169
+ directory: Path,
170
+ host: str | CompileServer | None,
171
+ open_web_browser: bool = True,
172
+ keep_running: bool = True, # if false, only one compilation will be done.
173
+ build_mode: BuildMode = BuildMode.QUICK,
174
+ profile: bool = False,
175
+ shutdown: threading.Event | None = None,
176
+ ) -> int:
177
+
178
+ compile_server: CompileServer | None = (
179
+ host if isinstance(host, CompileServer) else None
180
+ )
181
+ shutdown = shutdown or threading.Event()
182
+
183
+ def get_url() -> str:
184
+ if compile_server is not None:
185
+ return compile_server.url()
186
+ if isinstance(host, str):
187
+ return host
188
+ return DEFAULT_URL
189
+
190
+ url = get_url()
191
+
192
+ try:
193
+
194
+ def compile_function(
195
+ url: str = url,
196
+ build_mode: BuildMode = build_mode,
197
+ profile: bool = profile,
198
+ last_hash_value: str | None = None,
199
+ ) -> CompileResult:
200
+ TEST_BEFORE_COMPILE(url)
201
+ return _run_web_compiler(
202
+ directory,
203
+ host=url,
204
+ build_mode=build_mode,
205
+ profile=profile,
206
+ last_hash_value=last_hash_value,
207
+ )
208
+
209
+ result: CompileResult = compile_function(last_hash_value=None)
210
+ last_compiled_result: CompileResult = result
211
+
212
+ if not result.success:
213
+ print("\nCompilation failed.")
214
+
215
+ browser_proc: Process | None = None
216
+ if open_web_browser:
217
+ browser_proc = open_browser_process(directory / "fastled_js")
218
+ else:
219
+ print("\nCompilation successful.")
220
+ if compile_server:
221
+ print("Shutting down compile server...")
222
+ compile_server.stop()
223
+ return 0
224
+
225
+ if not keep_running or shutdown.is_set():
226
+ if browser_proc:
227
+ browser_proc.kill()
228
+ return 0 if result.success else 1
229
+ except KeyboardInterrupt:
230
+ print("\nExiting from main")
231
+ return 1
232
+
233
+ sketch_filewatcher = FileWatcherProcess(directory, excluded_patterns=["fastled_js"])
234
+
235
+ source_code_watcher: FileWatcherProcess | None = None
236
+ if compile_server and compile_server.using_fastled_src_dir_volume():
237
+ assert compile_server.fastled_src_dir is not None
238
+ source_code_watcher = FileWatcherProcess(
239
+ compile_server.fastled_src_dir, excluded_patterns=[]
240
+ )
241
+
242
+ def trigger_rebuild_if_sketch_changed(
243
+ last_compiled_result: CompileResult,
244
+ ) -> tuple[bool, CompileResult]:
245
+ changed_files = sketch_filewatcher.get_all_changes()
246
+ if changed_files:
247
+ print(f"\nChanges detected in {changed_files}")
248
+ last_hash_value = last_compiled_result.hash_value
249
+ out = compile_function(last_hash_value=last_hash_value)
250
+ if not out.success:
251
+ print("\nRecompilation failed.")
252
+ else:
253
+ print("\nRecompilation successful.")
254
+ return True, out
255
+ return False, last_compiled_result
256
+
257
+ def print_status() -> None:
258
+ print("Will compile on sketch changes or if you hit the space bar.")
259
+
260
+ print_status()
261
+ print("Press Ctrl+C to stop...")
262
+
263
+ try:
264
+ while True:
265
+ if shutdown.is_set():
266
+ print("\nStopping watch mode...")
267
+ return 0
268
+ if SpaceBarWatcher.watch_space_bar_pressed(timeout=1.0):
269
+ print("Compiling...")
270
+ last_compiled_result = compile_function(last_hash_value=None)
271
+ if not last_compiled_result.success:
272
+ print("\nRecompilation failed.")
273
+ else:
274
+ print("\nRecompilation successful.")
275
+ # drain the space bar queue
276
+ SpaceBarWatcher.watch_space_bar_pressed()
277
+ print_status()
278
+ continue
279
+ changed, last_compiled_result = trigger_rebuild_if_sketch_changed(
280
+ last_compiled_result
281
+ )
282
+ if changed:
283
+ print_status()
284
+ continue
285
+ if compile_server and not compile_server.process_running():
286
+ print("Server process is not running. Exiting...")
287
+ return 1
288
+ if source_code_watcher is not None:
289
+ changed_files = source_code_watcher.get_all_changes()
290
+ # de-duplicate changes
291
+ changed_files = sorted(list(set(changed_files)))
292
+ if changed_files:
293
+ print(f"\nChanges detected in FastLED source code: {changed_files}")
294
+ print("Press space bar to trigger compile.")
295
+ while True:
296
+ space_bar_pressed = SpaceBarWatcher.watch_space_bar_pressed(
297
+ timeout=1.0
298
+ )
299
+ file_changes = source_code_watcher.get_all_changes()
300
+ sketch_files_changed = sketch_filewatcher.get_all_changes()
301
+
302
+ if file_changes:
303
+ print(
304
+ f"Changes detected in {file_changes}\nHit the space bar to trigger compile."
305
+ )
306
+
307
+ if space_bar_pressed or sketch_files_changed:
308
+ if space_bar_pressed:
309
+ print("Space bar pressed, triggering recompile...")
310
+ elif sketch_files_changed:
311
+ print(
312
+ f"Changes detected in {','.join(sketch_files_changed)}, triggering recompile..."
313
+ )
314
+ last_compiled_result = compile_function(
315
+ last_hash_value=None
316
+ )
317
+ print("Finished recompile.")
318
+ # Drain the space bar queue
319
+ SpaceBarWatcher.watch_space_bar_pressed()
320
+ print_status()
321
+ continue
322
+
323
+ except KeyboardInterrupt:
324
+ print("\nStopping watch mode...")
325
+ return 0
326
+ except Exception as e:
327
+ print(f"Error: {e}")
328
+ return 1
329
+ finally:
330
+ sketch_filewatcher.stop()
331
+ if compile_server:
332
+ compile_server.stop()
333
+ if browser_proc:
334
+ browser_proc.kill()
335
+
336
+
337
+ def run_client_server(args: argparse.Namespace) -> int:
338
+ profile = bool(args.profile)
339
+ web: str | bool = args.web if isinstance(args.web, str) else bool(args.web)
340
+ auto_update = bool(args.auto_update)
341
+ localhost = bool(args.localhost)
342
+ directory = Path(args.directory)
343
+ just_compile = bool(args.just_compile)
344
+ interactive = bool(args.interactive)
345
+ force_compile = bool(args.force_compile)
346
+ open_web_browser = not just_compile and not interactive
347
+ build_mode: BuildMode = BuildMode.from_args(args)
348
+
349
+ if not force_compile and not looks_like_sketch_directory(directory):
350
+ # if there is only one directory in the sketch directory, use that
351
+ found_valid_child = False
352
+ if len(list(directory.iterdir())) == 1:
353
+ child_dir = next(directory.iterdir())
354
+ if looks_like_sketch_directory(child_dir):
355
+ found_valid_child = True
356
+ print(
357
+ f"The selected directory is not a valid FastLED sketch directory, the child directory {child_dir} looks like a sketch directory, using that instead."
358
+ )
359
+ directory = child_dir
360
+ if not found_valid_child:
361
+ print(
362
+ f"Error: {directory} is not a valid FastLED sketch directory, if you are sure it is, use --force-compile"
363
+ )
364
+ return 1
365
+
366
+ # If not explicitly using web compiler, check Docker installation
367
+ if not web and not DockerManager.is_docker_installed():
368
+ print(
369
+ "\nDocker is not installed on this system - switching to web compiler instead."
370
+ )
371
+ web = True
372
+
373
+ url: str
374
+ compile_server: CompileServer | None = None
375
+ try:
376
+ url, compile_server = _try_start_server_or_get_url(auto_update, web, localhost)
377
+ except KeyboardInterrupt:
378
+ print("\nExiting from first try...")
379
+ if compile_server:
380
+ compile_server.stop()
381
+ return 1
382
+ except Exception as e:
383
+ print(f"Error: {e}")
384
+ if compile_server:
385
+ compile_server.stop()
386
+ return 1
387
+
388
+ try:
389
+ return run_client(
390
+ directory=directory,
391
+ host=compile_server if compile_server else url,
392
+ open_web_browser=open_web_browser,
393
+ keep_running=not just_compile,
394
+ build_mode=build_mode,
395
+ profile=profile,
396
+ )
397
+ except KeyboardInterrupt:
398
+ return 1
399
+ finally:
400
+ if compile_server:
401
+ compile_server.stop()
@@ -0,0 +1,92 @@
1
+ from pathlib import Path
2
+
3
+ from fastled.types import BuildMode, CompileResult, Platform
4
+
5
+
6
+ class CompileServer:
7
+
8
+ # May throw CompileServerError if auto_start is True.
9
+ def __init__(
10
+ self,
11
+ interactive: bool = False,
12
+ auto_updates: bool | None = None,
13
+ mapped_dir: Path | None = None,
14
+ auto_start: bool = True,
15
+ container_name: str | None = None,
16
+ platform: Platform = Platform.WASM,
17
+ ) -> None:
18
+ from fastled.compile_server_impl import ( # avoid circular import
19
+ CompileServerImpl,
20
+ )
21
+
22
+ assert platform == Platform.WASM, "Only WASM platform is supported right now."
23
+
24
+ self.impl = CompileServerImpl(
25
+ container_name=container_name,
26
+ interactive=interactive,
27
+ auto_updates=auto_updates,
28
+ mapped_dir=mapped_dir,
29
+ auto_start=auto_start,
30
+ )
31
+
32
+ # May throw CompileServerError if server could not be started.
33
+ def start(self, wait_for_startup=True) -> None:
34
+ # from fastled.compile_server_impl import CompileServerImpl # avoid circular import
35
+ self.impl.start(wait_for_startup=wait_for_startup)
36
+
37
+ def web_compile(
38
+ self,
39
+ directory: Path | str,
40
+ build_mode: BuildMode = BuildMode.QUICK,
41
+ profile: bool = False,
42
+ ) -> CompileResult:
43
+ return self.impl.web_compile(
44
+ directory=directory, build_mode=build_mode, profile=profile
45
+ )
46
+
47
+ def project_init(
48
+ self, example: str | None = None, outputdir: Path | None = None
49
+ ) -> None:
50
+ from fastled.project_init import project_init # avoid circular import
51
+
52
+ project_init(example=example, outputdir=outputdir)
53
+
54
+ @property
55
+ def running(self) -> bool:
56
+ return self.impl.running
57
+
58
+ @property
59
+ def fastled_src_dir(self) -> Path | None:
60
+ return self.impl.fastled_src_dir
61
+
62
+ def using_fastled_src_dir_volume(self) -> bool:
63
+ return self.impl.using_fastled_src_dir_volume()
64
+
65
+ def port(self) -> int:
66
+ return self.impl.port()
67
+
68
+ def url(self) -> str:
69
+ return self.impl.url()
70
+
71
+ def ping(self) -> bool:
72
+ return self.impl.ping()
73
+
74
+ # by default this is automatically called by the constructor, unless
75
+ # auto_start is set to False.
76
+ def wait_for_startup(self, timeout: int = 100) -> bool:
77
+ """Wait for the server to start up."""
78
+ return self.impl.wait_for_startup(timeout=timeout)
79
+
80
+ def _start(self) -> int:
81
+ return self.impl._start()
82
+
83
+ def stop(self) -> None:
84
+ try:
85
+ return self.impl.stop()
86
+ except KeyboardInterrupt:
87
+ import _thread
88
+
89
+ _thread.interrupt_main()
90
+
91
+ def process_running(self) -> bool:
92
+ return self.impl.process_running()