fastled 1.2.96__py3-none-any.whl → 1.2.98__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.
fastled/client_server.py CHANGED
@@ -1,513 +1,513 @@
1
- import shutil
2
- import tempfile
3
- import threading
4
- import time
5
- import warnings
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 DebouncedFileWatcherProcess, FileWatcherProcess
12
- from fastled.keyboard import SpaceBarWatcher
13
- from fastled.open_browser import spawn_http_server
14
- from fastled.parse_args import Args
15
- from fastled.settings import DEFAULT_URL, IMAGE_NAME
16
- from fastled.sketch import looks_like_sketch_directory
17
- from fastled.types import BuildMode, CompileResult, CompileServerError
18
- from fastled.web_compile import (
19
- SERVER_PORT,
20
- ConnectionResult,
21
- find_good_connection,
22
- web_compile,
23
- )
24
-
25
-
26
- def _create_error_html(error_message: str) -> str:
27
- return f"""<!DOCTYPE html>
28
- <html>
29
- <head>
30
- <!-- no cache -->
31
- <meta http-equiv="Cache-Control" content="no-store" />
32
- <meta http-equiv="Pragma" content="no-cache" />
33
- <meta http-equiv="Expires" content="0" />
34
- <title>FastLED Compilation Error ZACH</title>
35
- <style>
36
- body {{
37
- background-color: #1a1a1a;
38
- color: #ffffff;
39
- font-family: Arial, sans-serif;
40
- margin: 20px;
41
- padding: 20px;
42
- }}
43
- pre {{
44
- color: #ffffff;
45
- background-color: #1a1a1a;
46
- border: 1px solid #444444;
47
- border-radius: 4px;
48
- padding: 15px;
49
- white-space: pre-wrap;
50
- word-wrap: break-word;
51
- }}
52
- </style>
53
- </head>
54
- <body>
55
- <h1>Compilation Failed</h1>
56
- <pre>{error_message}</pre>
57
- </body>
58
- </html>"""
59
-
60
-
61
- # Override this function in your own code to run tests before compilation
62
- def TEST_BEFORE_COMPILE(url) -> None:
63
- pass
64
-
65
-
66
- def _chunked_print(stdout: str) -> None:
67
- lines = stdout.splitlines()
68
- for line in lines:
69
- print(line)
70
-
71
-
72
- def _run_web_compiler(
73
- directory: Path,
74
- host: str,
75
- build_mode: BuildMode,
76
- profile: bool,
77
- last_hash_value: str | None,
78
- ) -> CompileResult:
79
- input_dir = Path(directory)
80
- output_dir = input_dir / "fastled_js"
81
- start = time.time()
82
- web_result = web_compile(
83
- directory=input_dir, host=host, build_mode=build_mode, profile=profile
84
- )
85
- diff = time.time() - start
86
- if not web_result.success:
87
- print("\nWeb compilation failed:")
88
- print(f"Time taken: {diff:.2f} seconds")
89
- _chunked_print(web_result.stdout)
90
- # Create error page
91
- output_dir.mkdir(exist_ok=True)
92
- error_html = _create_error_html(web_result.stdout)
93
- (output_dir / "index.html").write_text(error_html, encoding="utf-8")
94
- return web_result
95
-
96
- def print_results() -> None:
97
- hash_value = (
98
- web_result.hash_value
99
- if web_result.hash_value is not None
100
- else "NO HASH VALUE"
101
- )
102
- print(
103
- 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"
104
- )
105
-
106
- # now check to see if the hash value is the same as the last hash value
107
- if last_hash_value is not None and last_hash_value == web_result.hash_value:
108
- print("\nSkipping redeploy: No significant changes found.")
109
- print_results()
110
- return web_result
111
-
112
- # Extract zip contents to fastled_js directory
113
- output_dir.mkdir(exist_ok=True)
114
- with tempfile.TemporaryDirectory() as temp_dir:
115
- temp_path = Path(temp_dir)
116
- temp_zip = temp_path / "result.zip"
117
- temp_zip.write_bytes(web_result.zip_bytes)
118
-
119
- # Clear existing contents
120
- shutil.rmtree(output_dir, ignore_errors=True)
121
- output_dir.mkdir(exist_ok=True)
122
-
123
- # Extract zip contents
124
- shutil.unpack_archive(temp_zip, output_dir, "zip")
125
-
126
- _chunked_print(web_result.stdout)
127
- print_results()
128
- return web_result
129
-
130
-
131
- def _try_start_server_or_get_url(
132
- auto_update: bool, args_web: str | bool, localhost: bool
133
- ) -> tuple[str, CompileServer | None]:
134
- is_local_host = localhost or (
135
- isinstance(args_web, str)
136
- and ("localhost" in args_web or "127.0.0.1" in args_web)
137
- )
138
- # test to see if there is already a local host server
139
- local_host_needs_server = False
140
- if is_local_host:
141
- addr = "localhost" if localhost or not isinstance(args_web, str) else args_web
142
- urls = [addr]
143
- if ":" not in addr:
144
- urls.append(f"{addr}:{SERVER_PORT}")
145
-
146
- result: ConnectionResult | None = find_good_connection(urls)
147
- if result is not None:
148
- print(f"Found local server at {result.host}")
149
- return (result.host, None)
150
- else:
151
- local_host_needs_server = True
152
-
153
- if not local_host_needs_server and args_web:
154
- if isinstance(args_web, str):
155
- return (args_web, None)
156
- if isinstance(args_web, bool):
157
- return (DEFAULT_URL, None)
158
- return (args_web, None)
159
- else:
160
- try:
161
- print("No local server found, starting one...")
162
- compile_server = CompileServer(auto_updates=auto_update)
163
- print("Waiting for the local compiler to start...")
164
- if not compile_server.ping():
165
- print("Failed to start local compiler.")
166
- raise CompileServerError("Failed to start local compiler.")
167
- return (compile_server.url(), compile_server)
168
- except KeyboardInterrupt:
169
- raise
170
- except RuntimeError:
171
- print("Failed to start local compile server, using web compiler instead.")
172
- return (DEFAULT_URL, None)
173
-
174
-
175
- def _try_make_compile_server() -> CompileServer | None:
176
- if not DockerManager.is_docker_installed():
177
- return None
178
- try:
179
- print(
180
- "\nNo host specified, but Docker is installed, attempting to start a compile server using Docker."
181
- )
182
- from fastled.util import find_free_port
183
-
184
- free_port = find_free_port(start_port=9723, end_port=9743)
185
- if free_port is None:
186
- return None
187
- compile_server = CompileServer(auto_updates=False)
188
- print("Waiting for the local compiler to start...")
189
- if not compile_server.ping():
190
- print("Failed to start local compiler.")
191
- raise CompileServerError("Failed to start local compiler.")
192
- return compile_server
193
- except KeyboardInterrupt:
194
- import _thread
195
-
196
- _thread.interrupt_main()
197
- raise
198
- except Exception as e:
199
- warnings.warn(f"Error starting local compile server: {e}")
200
- return None
201
-
202
-
203
- def _is_local_host(host: str) -> bool:
204
- return (
205
- host.startswith("http://localhost")
206
- or host.startswith("http://127.0.0.1")
207
- or host.startswith("http://0.0.0.0")
208
- or host.startswith("http://[::]")
209
- or host.startswith("http://[::1]")
210
- or host.startswith("http://[::ffff:127.0.0.1]")
211
- )
212
-
213
-
214
- def run_client(
215
- directory: Path,
216
- host: str | CompileServer | None,
217
- open_web_browser: bool = True,
218
- keep_running: bool = True, # if false, only one compilation will be done.
219
- build_mode: BuildMode = BuildMode.QUICK,
220
- profile: bool = False,
221
- shutdown: threading.Event | None = None,
222
- http_port: (
223
- int | None
224
- ) = None, # None means auto select a free port, http_port < 0 means no server.
225
- ) -> int:
226
- has_checked_newer_version_yet = False
227
- compile_server: CompileServer | None = None
228
-
229
- if host is None:
230
- # attempt to start a compile server if docker is installed.
231
- compile_server = _try_make_compile_server()
232
- if compile_server is None:
233
- host = DEFAULT_URL
234
- elif isinstance(host, CompileServer):
235
- # if the host is a compile server, use that
236
- compile_server = host
237
-
238
- shutdown = shutdown or threading.Event()
239
-
240
- def get_url(host=host, compile_server=compile_server) -> str:
241
- if compile_server is not None:
242
- return compile_server.url()
243
- if isinstance(host, str):
244
- return host
245
- return DEFAULT_URL
246
-
247
- url = get_url()
248
- is_local_host = _is_local_host(url)
249
- # parse out the port from the url
250
- # use a standard host address parser to grab it
251
- import urllib.parse
252
-
253
- parsed_url = urllib.parse.urlparse(url)
254
- if parsed_url.port is not None:
255
- port = parsed_url.port
256
- else:
257
- if is_local_host:
258
- raise ValueError(
259
- "Cannot use local host without a port. Please specify a port."
260
- )
261
- # Assume default port for www
262
- port = 80
263
-
264
- try:
265
-
266
- def compile_function(
267
- url: str = url,
268
- build_mode: BuildMode = build_mode,
269
- profile: bool = profile,
270
- last_hash_value: str | None = None,
271
- ) -> CompileResult:
272
- TEST_BEFORE_COMPILE(url)
273
- return _run_web_compiler(
274
- directory,
275
- host=url,
276
- build_mode=build_mode,
277
- profile=profile,
278
- last_hash_value=last_hash_value,
279
- )
280
-
281
- result: CompileResult = compile_function(last_hash_value=None)
282
- last_compiled_result: CompileResult = result
283
-
284
- if not result.success:
285
- print("\nCompilation failed.")
286
-
287
- use_http_server = http_port is None or http_port >= 0
288
- if not use_http_server and open_web_browser:
289
- warnings.warn(
290
- f"Warning: --http-port={http_port} specified but open_web_browser is False, ignoring --http-port."
291
- )
292
- use_http_server = False
293
-
294
- http_proc: Process | None = None
295
- if use_http_server:
296
- http_proc = spawn_http_server(
297
- directory / "fastled_js",
298
- port=http_port,
299
- compile_server_port=port,
300
- open_browser=open_web_browser,
301
- )
302
- else:
303
- print("\nCompilation successful.")
304
- if compile_server:
305
- print("Shutting down compile server...")
306
- compile_server.stop()
307
- return 0
308
-
309
- if not keep_running or shutdown.is_set():
310
- if http_proc:
311
- http_proc.kill()
312
- return 0 if result.success else 1
313
- except KeyboardInterrupt:
314
- print("\nExiting from main")
315
- return 1
316
-
317
- excluded_patterns = ["fastled_js"]
318
- debounced_sketch_watcher = DebouncedFileWatcherProcess(
319
- FileWatcherProcess(directory, excluded_patterns=excluded_patterns),
320
- )
321
-
322
- source_code_watcher: FileWatcherProcess | None = None
323
- if compile_server and compile_server.using_fastled_src_dir_volume():
324
- assert compile_server.fastled_src_dir is not None
325
- source_code_watcher = FileWatcherProcess(
326
- compile_server.fastled_src_dir, excluded_patterns=excluded_patterns
327
- )
328
-
329
- def trigger_rebuild_if_sketch_changed(
330
- last_compiled_result: CompileResult,
331
- ) -> tuple[bool, CompileResult]:
332
- changed_files = debounced_sketch_watcher.get_all_changes()
333
- if changed_files:
334
- print(f"\nChanges detected in {changed_files}")
335
- last_hash_value = last_compiled_result.hash_value
336
- out = compile_function(last_hash_value=last_hash_value)
337
- if not out.success:
338
- print("\nRecompilation failed.")
339
- else:
340
- print("\nRecompilation successful.")
341
- return True, out
342
- return False, last_compiled_result
343
-
344
- def print_status() -> None:
345
- print("Will compile on sketch changes or if you hit the space bar.")
346
-
347
- print_status()
348
- print("Press Ctrl+C to stop...")
349
-
350
- try:
351
- while True:
352
- if shutdown.is_set():
353
- print("\nStopping watch mode...")
354
- return 0
355
-
356
- # Check for newer Docker image version after first successful compilation
357
- if (
358
- not has_checked_newer_version_yet
359
- and last_compiled_result.success
360
- and is_local_host
361
- ):
362
- has_checked_newer_version_yet = True
363
- try:
364
-
365
- docker_manager = DockerManager()
366
- has_update, message = docker_manager.has_newer_version(
367
- image_name=IMAGE_NAME, tag="latest"
368
- )
369
- if has_update:
370
- print(f"\n🔄 {message}")
371
- print(
372
- "Run with --auto-update to automatically update to the latest version."
373
- )
374
- except Exception as e:
375
- # Don't let Docker check failures interrupt the main flow
376
- warnings.warn(f"Failed to check for Docker image updates: {e}")
377
-
378
- if SpaceBarWatcher.watch_space_bar_pressed(timeout=1.0):
379
- print("Compiling...")
380
- last_compiled_result = compile_function(last_hash_value=None)
381
- if not last_compiled_result.success:
382
- print("\nRecompilation failed.")
383
- else:
384
- print("\nRecompilation successful.")
385
- # drain the space bar queue
386
- SpaceBarWatcher.watch_space_bar_pressed()
387
- print_status()
388
- continue
389
- changed, last_compiled_result = trigger_rebuild_if_sketch_changed(
390
- last_compiled_result
391
- )
392
- if changed:
393
- print_status()
394
- continue
395
- if compile_server and not compile_server.process_running():
396
- print("Server process is not running. Exiting...")
397
- return 1
398
- if source_code_watcher is not None:
399
- changed_files = source_code_watcher.get_all_changes()
400
- # de-duplicate changes
401
- changed_files = sorted(list(set(changed_files)))
402
- if changed_files:
403
- print(f"\nChanges detected in FastLED source code: {changed_files}")
404
- print("Press space bar to trigger compile.")
405
- while True:
406
- space_bar_pressed = SpaceBarWatcher.watch_space_bar_pressed(
407
- timeout=1.0
408
- )
409
- file_changes = source_code_watcher.get_all_changes()
410
- sketch_files_changed = (
411
- debounced_sketch_watcher.get_all_changes()
412
- )
413
-
414
- if file_changes:
415
- print(
416
- f"Changes detected in {file_changes}\nHit the space bar to trigger compile."
417
- )
418
-
419
- if space_bar_pressed or sketch_files_changed:
420
- if space_bar_pressed:
421
- print("Space bar pressed, triggering recompile...")
422
- elif sketch_files_changed:
423
- print(
424
- f"Changes detected in {','.join(sketch_files_changed)}, triggering recompile..."
425
- )
426
- last_compiled_result = compile_function(
427
- last_hash_value=None
428
- )
429
- print("Finished recompile.")
430
- # Drain the space bar queue
431
- SpaceBarWatcher.watch_space_bar_pressed()
432
- print_status()
433
- continue
434
-
435
- except KeyboardInterrupt:
436
- print("\nStopping watch mode...")
437
- return 0
438
- except Exception as e:
439
- print(f"Error: {e}")
440
- return 1
441
- finally:
442
- debounced_sketch_watcher.stop()
443
- if compile_server:
444
- compile_server.stop()
445
- if http_proc:
446
- http_proc.kill()
447
-
448
-
449
- def run_client_server(args: Args) -> int:
450
- profile = bool(args.profile)
451
- web: str | bool = args.web if isinstance(args.web, str) else bool(args.web)
452
- auto_update = bool(args.auto_update)
453
- localhost = bool(args.localhost)
454
- directory = args.directory if args.directory else Path(".")
455
- just_compile = bool(args.just_compile)
456
- interactive = bool(args.interactive)
457
- force_compile = bool(args.force_compile)
458
- open_web_browser = not just_compile and not interactive
459
- build_mode: BuildMode = BuildMode.from_args(args)
460
-
461
- if not force_compile and not looks_like_sketch_directory(directory):
462
- # if there is only one directory in the sketch directory, use that
463
- found_valid_child = False
464
- if len(list(directory.iterdir())) == 1:
465
- child_dir = next(directory.iterdir())
466
- if looks_like_sketch_directory(child_dir):
467
- found_valid_child = True
468
- print(
469
- f"The selected directory is not a valid FastLED sketch directory, the child directory {child_dir} looks like a sketch directory, using that instead."
470
- )
471
- directory = child_dir
472
- if not found_valid_child:
473
- print(
474
- f"Error: {directory} is not a valid FastLED sketch directory, if you are sure it is, use --force-compile"
475
- )
476
- return 1
477
-
478
- # If not explicitly using web compiler, check Docker installation
479
- if not web and not DockerManager.is_docker_installed():
480
- print(
481
- "\nDocker is not installed on this system - switching to web compiler instead."
482
- )
483
- web = True
484
-
485
- url: str
486
- compile_server: CompileServer | None = None
487
- try:
488
- url, compile_server = _try_start_server_or_get_url(auto_update, web, localhost)
489
- except KeyboardInterrupt:
490
- print("\nExiting from first try...")
491
- if compile_server is not None:
492
- compile_server.stop()
493
- return 1
494
- except Exception as e:
495
- print(f"Error: {e}")
496
- if compile_server is not None:
497
- compile_server.stop()
498
- return 1
499
-
500
- try:
501
- return run_client(
502
- directory=directory,
503
- host=compile_server if compile_server else url,
504
- open_web_browser=open_web_browser,
505
- keep_running=not just_compile,
506
- build_mode=build_mode,
507
- profile=profile,
508
- )
509
- except KeyboardInterrupt:
510
- return 1
511
- finally:
512
- if compile_server:
513
- compile_server.stop()
1
+ import shutil
2
+ import tempfile
3
+ import threading
4
+ import time
5
+ import warnings
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 DebouncedFileWatcherProcess, FileWatcherProcess
12
+ from fastled.keyboard import SpaceBarWatcher
13
+ from fastled.open_browser import spawn_http_server
14
+ from fastled.parse_args import Args
15
+ from fastled.settings import DEFAULT_URL, IMAGE_NAME
16
+ from fastled.sketch import looks_like_sketch_directory
17
+ from fastled.types import BuildMode, CompileResult, CompileServerError
18
+ from fastled.web_compile import (
19
+ SERVER_PORT,
20
+ ConnectionResult,
21
+ find_good_connection,
22
+ web_compile,
23
+ )
24
+
25
+
26
+ def _create_error_html(error_message: str) -> str:
27
+ return f"""<!DOCTYPE html>
28
+ <html>
29
+ <head>
30
+ <!-- no cache -->
31
+ <meta http-equiv="Cache-Control" content="no-store" />
32
+ <meta http-equiv="Pragma" content="no-cache" />
33
+ <meta http-equiv="Expires" content="0" />
34
+ <title>FastLED Compilation Error ZACH</title>
35
+ <style>
36
+ body {{
37
+ background-color: #1a1a1a;
38
+ color: #ffffff;
39
+ font-family: Arial, sans-serif;
40
+ margin: 20px;
41
+ padding: 20px;
42
+ }}
43
+ pre {{
44
+ color: #ffffff;
45
+ background-color: #1a1a1a;
46
+ border: 1px solid #444444;
47
+ border-radius: 4px;
48
+ padding: 15px;
49
+ white-space: pre-wrap;
50
+ word-wrap: break-word;
51
+ }}
52
+ </style>
53
+ </head>
54
+ <body>
55
+ <h1>Compilation Failed</h1>
56
+ <pre>{error_message}</pre>
57
+ </body>
58
+ </html>"""
59
+
60
+
61
+ # Override this function in your own code to run tests before compilation
62
+ def TEST_BEFORE_COMPILE(url) -> None:
63
+ pass
64
+
65
+
66
+ def _chunked_print(stdout: str) -> None:
67
+ lines = stdout.splitlines()
68
+ for line in lines:
69
+ print(line)
70
+
71
+
72
+ def _run_web_compiler(
73
+ directory: Path,
74
+ host: str,
75
+ build_mode: BuildMode,
76
+ profile: bool,
77
+ last_hash_value: str | None,
78
+ ) -> CompileResult:
79
+ input_dir = Path(directory)
80
+ output_dir = input_dir / "fastled_js"
81
+ start = time.time()
82
+ web_result = web_compile(
83
+ directory=input_dir, host=host, build_mode=build_mode, profile=profile
84
+ )
85
+ diff = time.time() - start
86
+ if not web_result.success:
87
+ print("\nWeb compilation failed:")
88
+ print(f"Time taken: {diff:.2f} seconds")
89
+ _chunked_print(web_result.stdout)
90
+ # Create error page
91
+ output_dir.mkdir(exist_ok=True)
92
+ error_html = _create_error_html(web_result.stdout)
93
+ (output_dir / "index.html").write_text(error_html, encoding="utf-8")
94
+ return web_result
95
+
96
+ def print_results() -> None:
97
+ hash_value = (
98
+ web_result.hash_value
99
+ if web_result.hash_value is not None
100
+ else "NO HASH VALUE"
101
+ )
102
+ print(
103
+ 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"
104
+ )
105
+
106
+ # now check to see if the hash value is the same as the last hash value
107
+ if last_hash_value is not None and last_hash_value == web_result.hash_value:
108
+ print("\nSkipping redeploy: No significant changes found.")
109
+ print_results()
110
+ return web_result
111
+
112
+ # Extract zip contents to fastled_js directory
113
+ output_dir.mkdir(exist_ok=True)
114
+ with tempfile.TemporaryDirectory() as temp_dir:
115
+ temp_path = Path(temp_dir)
116
+ temp_zip = temp_path / "result.zip"
117
+ temp_zip.write_bytes(web_result.zip_bytes)
118
+
119
+ # Clear existing contents
120
+ shutil.rmtree(output_dir, ignore_errors=True)
121
+ output_dir.mkdir(exist_ok=True)
122
+
123
+ # Extract zip contents
124
+ shutil.unpack_archive(temp_zip, output_dir, "zip")
125
+
126
+ _chunked_print(web_result.stdout)
127
+ print_results()
128
+ return web_result
129
+
130
+
131
+ def _try_start_server_or_get_url(
132
+ auto_update: bool, args_web: str | bool, localhost: bool
133
+ ) -> tuple[str, CompileServer | None]:
134
+ is_local_host = localhost or (
135
+ isinstance(args_web, str)
136
+ and ("localhost" in args_web or "127.0.0.1" in args_web)
137
+ )
138
+ # test to see if there is already a local host server
139
+ local_host_needs_server = False
140
+ if is_local_host:
141
+ addr = "localhost" if localhost or not isinstance(args_web, str) else args_web
142
+ urls = [addr]
143
+ if ":" not in addr:
144
+ urls.append(f"{addr}:{SERVER_PORT}")
145
+
146
+ result: ConnectionResult | None = find_good_connection(urls)
147
+ if result is not None:
148
+ print(f"Found local server at {result.host}")
149
+ return (result.host, None)
150
+ else:
151
+ local_host_needs_server = True
152
+
153
+ if not local_host_needs_server and args_web:
154
+ if isinstance(args_web, str):
155
+ return (args_web, None)
156
+ if isinstance(args_web, bool):
157
+ return (DEFAULT_URL, None)
158
+ return (args_web, None)
159
+ else:
160
+ try:
161
+ print("No local server found, starting one...")
162
+ compile_server = CompileServer(auto_updates=auto_update)
163
+ print("Waiting for the local compiler to start...")
164
+ if not compile_server.ping():
165
+ print("Failed to start local compiler.")
166
+ raise CompileServerError("Failed to start local compiler.")
167
+ return (compile_server.url(), compile_server)
168
+ except KeyboardInterrupt:
169
+ raise
170
+ except RuntimeError:
171
+ print("Failed to start local compile server, using web compiler instead.")
172
+ return (DEFAULT_URL, None)
173
+
174
+
175
+ def _try_make_compile_server() -> CompileServer | None:
176
+ if not DockerManager.is_docker_installed():
177
+ return None
178
+ try:
179
+ print(
180
+ "\nNo host specified, but Docker is installed, attempting to start a compile server using Docker."
181
+ )
182
+ from fastled.util import find_free_port
183
+
184
+ free_port = find_free_port(start_port=9723, end_port=9743)
185
+ if free_port is None:
186
+ return None
187
+ compile_server = CompileServer(auto_updates=False)
188
+ print("Waiting for the local compiler to start...")
189
+ if not compile_server.ping():
190
+ print("Failed to start local compiler.")
191
+ raise CompileServerError("Failed to start local compiler.")
192
+ return compile_server
193
+ except KeyboardInterrupt:
194
+ import _thread
195
+
196
+ _thread.interrupt_main()
197
+ raise
198
+ except Exception as e:
199
+ warnings.warn(f"Error starting local compile server: {e}")
200
+ return None
201
+
202
+
203
+ def _is_local_host(host: str) -> bool:
204
+ return (
205
+ host.startswith("http://localhost")
206
+ or host.startswith("http://127.0.0.1")
207
+ or host.startswith("http://0.0.0.0")
208
+ or host.startswith("http://[::]")
209
+ or host.startswith("http://[::1]")
210
+ or host.startswith("http://[::ffff:127.0.0.1]")
211
+ )
212
+
213
+
214
+ def run_client(
215
+ directory: Path,
216
+ host: str | CompileServer | None,
217
+ open_web_browser: bool = True,
218
+ keep_running: bool = True, # if false, only one compilation will be done.
219
+ build_mode: BuildMode = BuildMode.QUICK,
220
+ profile: bool = False,
221
+ shutdown: threading.Event | None = None,
222
+ http_port: (
223
+ int | None
224
+ ) = None, # None means auto select a free port, http_port < 0 means no server.
225
+ ) -> int:
226
+ has_checked_newer_version_yet = False
227
+ compile_server: CompileServer | None = None
228
+
229
+ if host is None:
230
+ # attempt to start a compile server if docker is installed.
231
+ compile_server = _try_make_compile_server()
232
+ if compile_server is None:
233
+ host = DEFAULT_URL
234
+ elif isinstance(host, CompileServer):
235
+ # if the host is a compile server, use that
236
+ compile_server = host
237
+
238
+ shutdown = shutdown or threading.Event()
239
+
240
+ def get_url(host=host, compile_server=compile_server) -> str:
241
+ if compile_server is not None:
242
+ return compile_server.url()
243
+ if isinstance(host, str):
244
+ return host
245
+ return DEFAULT_URL
246
+
247
+ url = get_url()
248
+ is_local_host = _is_local_host(url)
249
+ # parse out the port from the url
250
+ # use a standard host address parser to grab it
251
+ import urllib.parse
252
+
253
+ parsed_url = urllib.parse.urlparse(url)
254
+ if parsed_url.port is not None:
255
+ port = parsed_url.port
256
+ else:
257
+ if is_local_host:
258
+ raise ValueError(
259
+ "Cannot use local host without a port. Please specify a port."
260
+ )
261
+ # Assume default port for www
262
+ port = 80
263
+
264
+ try:
265
+
266
+ def compile_function(
267
+ url: str = url,
268
+ build_mode: BuildMode = build_mode,
269
+ profile: bool = profile,
270
+ last_hash_value: str | None = None,
271
+ ) -> CompileResult:
272
+ TEST_BEFORE_COMPILE(url)
273
+ return _run_web_compiler(
274
+ directory,
275
+ host=url,
276
+ build_mode=build_mode,
277
+ profile=profile,
278
+ last_hash_value=last_hash_value,
279
+ )
280
+
281
+ result: CompileResult = compile_function(last_hash_value=None)
282
+ last_compiled_result: CompileResult = result
283
+
284
+ if not result.success:
285
+ print("\nCompilation failed.")
286
+
287
+ use_http_server = http_port is None or http_port >= 0
288
+ if not use_http_server and open_web_browser:
289
+ warnings.warn(
290
+ f"Warning: --http-port={http_port} specified but open_web_browser is False, ignoring --http-port."
291
+ )
292
+ use_http_server = False
293
+
294
+ http_proc: Process | None = None
295
+ if use_http_server:
296
+ http_proc = spawn_http_server(
297
+ directory / "fastled_js",
298
+ port=http_port,
299
+ compile_server_port=port,
300
+ open_browser=open_web_browser,
301
+ )
302
+ else:
303
+ print("\nCompilation successful.")
304
+ if compile_server:
305
+ print("Shutting down compile server...")
306
+ compile_server.stop()
307
+ return 0
308
+
309
+ if not keep_running or shutdown.is_set():
310
+ if http_proc:
311
+ http_proc.kill()
312
+ return 0 if result.success else 1
313
+ except KeyboardInterrupt:
314
+ print("\nExiting from main")
315
+ return 1
316
+
317
+ excluded_patterns = ["fastled_js"]
318
+ debounced_sketch_watcher = DebouncedFileWatcherProcess(
319
+ FileWatcherProcess(directory, excluded_patterns=excluded_patterns),
320
+ )
321
+
322
+ source_code_watcher: FileWatcherProcess | None = None
323
+ if compile_server and compile_server.using_fastled_src_dir_volume():
324
+ assert compile_server.fastled_src_dir is not None
325
+ source_code_watcher = FileWatcherProcess(
326
+ compile_server.fastled_src_dir, excluded_patterns=excluded_patterns
327
+ )
328
+
329
+ def trigger_rebuild_if_sketch_changed(
330
+ last_compiled_result: CompileResult,
331
+ ) -> tuple[bool, CompileResult]:
332
+ changed_files = debounced_sketch_watcher.get_all_changes()
333
+ if changed_files:
334
+ print(f"\nChanges detected in {changed_files}")
335
+ last_hash_value = last_compiled_result.hash_value
336
+ out = compile_function(last_hash_value=last_hash_value)
337
+ if not out.success:
338
+ print("\nRecompilation failed.")
339
+ else:
340
+ print("\nRecompilation successful.")
341
+ return True, out
342
+ return False, last_compiled_result
343
+
344
+ def print_status() -> None:
345
+ print("Will compile on sketch changes or if you hit the space bar.")
346
+
347
+ print_status()
348
+ print("Press Ctrl+C to stop...")
349
+
350
+ try:
351
+ while True:
352
+ if shutdown.is_set():
353
+ print("\nStopping watch mode...")
354
+ return 0
355
+
356
+ # Check for newer Docker image version after first successful compilation
357
+ if (
358
+ not has_checked_newer_version_yet
359
+ and last_compiled_result.success
360
+ and is_local_host
361
+ ):
362
+ has_checked_newer_version_yet = True
363
+ try:
364
+
365
+ docker_manager = DockerManager()
366
+ has_update, message = docker_manager.has_newer_version(
367
+ image_name=IMAGE_NAME, tag="latest"
368
+ )
369
+ if has_update:
370
+ print(f"\n🔄 {message}")
371
+ print(
372
+ "Run with --auto-update to automatically update to the latest version."
373
+ )
374
+ except Exception as e:
375
+ # Don't let Docker check failures interrupt the main flow
376
+ warnings.warn(f"Failed to check for Docker image updates: {e}")
377
+
378
+ if SpaceBarWatcher.watch_space_bar_pressed(timeout=1.0):
379
+ print("Compiling...")
380
+ last_compiled_result = compile_function(last_hash_value=None)
381
+ if not last_compiled_result.success:
382
+ print("\nRecompilation failed.")
383
+ else:
384
+ print("\nRecompilation successful.")
385
+ # drain the space bar queue
386
+ SpaceBarWatcher.watch_space_bar_pressed()
387
+ print_status()
388
+ continue
389
+ changed, last_compiled_result = trigger_rebuild_if_sketch_changed(
390
+ last_compiled_result
391
+ )
392
+ if changed:
393
+ print_status()
394
+ continue
395
+ if compile_server and not compile_server.process_running():
396
+ print("Server process is not running. Exiting...")
397
+ return 1
398
+ if source_code_watcher is not None:
399
+ changed_files = source_code_watcher.get_all_changes()
400
+ # de-duplicate changes
401
+ changed_files = sorted(list(set(changed_files)))
402
+ if changed_files:
403
+ print(f"\nChanges detected in FastLED source code: {changed_files}")
404
+ print("Press space bar to trigger compile.")
405
+ while True:
406
+ space_bar_pressed = SpaceBarWatcher.watch_space_bar_pressed(
407
+ timeout=1.0
408
+ )
409
+ file_changes = source_code_watcher.get_all_changes()
410
+ sketch_files_changed = (
411
+ debounced_sketch_watcher.get_all_changes()
412
+ )
413
+
414
+ if file_changes:
415
+ print(
416
+ f"Changes detected in {file_changes}\nHit the space bar to trigger compile."
417
+ )
418
+
419
+ if space_bar_pressed or sketch_files_changed:
420
+ if space_bar_pressed:
421
+ print("Space bar pressed, triggering recompile...")
422
+ elif sketch_files_changed:
423
+ print(
424
+ f"Changes detected in {','.join(sketch_files_changed)}, triggering recompile..."
425
+ )
426
+ last_compiled_result = compile_function(
427
+ last_hash_value=None
428
+ )
429
+ print("Finished recompile.")
430
+ # Drain the space bar queue
431
+ SpaceBarWatcher.watch_space_bar_pressed()
432
+ print_status()
433
+ continue
434
+
435
+ except KeyboardInterrupt:
436
+ print("\nStopping watch mode...")
437
+ return 0
438
+ except Exception as e:
439
+ print(f"Error: {e}")
440
+ return 1
441
+ finally:
442
+ debounced_sketch_watcher.stop()
443
+ if compile_server:
444
+ compile_server.stop()
445
+ if http_proc:
446
+ http_proc.kill()
447
+
448
+
449
+ def run_client_server(args: Args) -> int:
450
+ profile = bool(args.profile)
451
+ web: str | bool = args.web if isinstance(args.web, str) else bool(args.web)
452
+ auto_update = bool(args.auto_update)
453
+ localhost = bool(args.localhost)
454
+ directory = args.directory if args.directory else Path(".")
455
+ just_compile = bool(args.just_compile)
456
+ interactive = bool(args.interactive)
457
+ force_compile = bool(args.force_compile)
458
+ open_web_browser = not just_compile and not interactive
459
+ build_mode: BuildMode = BuildMode.from_args(args)
460
+
461
+ if not force_compile and not looks_like_sketch_directory(directory):
462
+ # if there is only one directory in the sketch directory, use that
463
+ found_valid_child = False
464
+ if len(list(directory.iterdir())) == 1:
465
+ child_dir = next(directory.iterdir())
466
+ if looks_like_sketch_directory(child_dir):
467
+ found_valid_child = True
468
+ print(
469
+ f"The selected directory is not a valid FastLED sketch directory, the child directory {child_dir} looks like a sketch directory, using that instead."
470
+ )
471
+ directory = child_dir
472
+ if not found_valid_child:
473
+ print(
474
+ f"Error: {directory} is not a valid FastLED sketch directory, if you are sure it is, use --force-compile"
475
+ )
476
+ return 1
477
+
478
+ # If not explicitly using web compiler, check Docker installation
479
+ if not web and not DockerManager.is_docker_installed():
480
+ print(
481
+ "\nDocker is not installed on this system - switching to web compiler instead."
482
+ )
483
+ web = True
484
+
485
+ url: str
486
+ compile_server: CompileServer | None = None
487
+ try:
488
+ url, compile_server = _try_start_server_or_get_url(auto_update, web, localhost)
489
+ except KeyboardInterrupt:
490
+ print("\nExiting from first try...")
491
+ if compile_server is not None:
492
+ compile_server.stop()
493
+ return 1
494
+ except Exception as e:
495
+ print(f"Error: {e}")
496
+ if compile_server is not None:
497
+ compile_server.stop()
498
+ return 1
499
+
500
+ try:
501
+ return run_client(
502
+ directory=directory,
503
+ host=compile_server if compile_server else url,
504
+ open_web_browser=open_web_browser,
505
+ keep_running=not just_compile,
506
+ build_mode=build_mode,
507
+ profile=profile,
508
+ )
509
+ except KeyboardInterrupt:
510
+ return 1
511
+ finally:
512
+ if compile_server:
513
+ compile_server.stop()