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,247 @@
1
+ import subprocess
2
+ import time
3
+ import warnings
4
+ from datetime import datetime, timezone
5
+ from pathlib import Path
6
+
7
+ import httpx
8
+
9
+ from fastled.docker_manager import (
10
+ DISK_CACHE,
11
+ Container,
12
+ DockerManager,
13
+ RunningContainer,
14
+ )
15
+ from fastled.settings import DEFAULT_CONTAINER_NAME, IMAGE_NAME, SERVER_PORT
16
+ from fastled.sketch import looks_like_fastled_repo
17
+ from fastled.types import BuildMode, CompileResult, CompileServerError
18
+
19
+ SERVER_OPTIONS = [
20
+ "--allow-shutdown", # Allow the server to be shut down without a force kill.
21
+ "--no-auto-update", # Don't auto live updates from the git repo.
22
+ ]
23
+
24
+
25
+ def _try_get_fastled_src(path: Path) -> Path | None:
26
+ fastled_src_dir: Path | None = None
27
+ if looks_like_fastled_repo(path):
28
+ print(
29
+ "Looks like a FastLED repo, using it as the source directory and mapping it into the server."
30
+ )
31
+ fastled_src_dir = path / "src"
32
+ return fastled_src_dir
33
+ return None
34
+
35
+
36
+ class CompileServerImpl:
37
+ def __init__(
38
+ self,
39
+ interactive: bool = False,
40
+ auto_updates: bool | None = None,
41
+ mapped_dir: Path | None = None,
42
+ auto_start: bool = True,
43
+ container_name: str | None = None,
44
+ ) -> None:
45
+ container_name = container_name or DEFAULT_CONTAINER_NAME
46
+ if interactive and not mapped_dir:
47
+ raise ValueError(
48
+ "Interactive mode requires a mapped directory point to a sketch"
49
+ )
50
+ if not interactive and mapped_dir:
51
+ raise ValueError("Mapped directory is only used in interactive mode")
52
+ self.container_name = container_name
53
+ self.mapped_dir = mapped_dir
54
+ self.docker = DockerManager()
55
+ self.fastled_src_dir: Path | None = _try_get_fastled_src(Path(".").resolve())
56
+ self.interactive = interactive
57
+ self.running_container: RunningContainer | None = None
58
+ self.auto_updates = auto_updates
59
+ self._port = 0 # 0 until compile server is started
60
+ if auto_start:
61
+ self.start()
62
+
63
+ def start(self, wait_for_startup=True) -> None:
64
+ if not DockerManager.is_docker_installed():
65
+ raise CompileServerError("Docker is not installed")
66
+ if self._port != 0:
67
+ warnings.warn("Server has already been started")
68
+ self._port = self._start()
69
+ if wait_for_startup:
70
+ ok = self.wait_for_startup()
71
+ if not ok:
72
+ raise CompileServerError("Server did not start")
73
+ if not self.interactive:
74
+ msg = f"# FastLED Compile Server started at {self.url()} #"
75
+ print("\n" + "#" * len(msg))
76
+ print(msg)
77
+ print("#" * len(msg) + "\n")
78
+
79
+ def web_compile(
80
+ self,
81
+ directory: Path | str,
82
+ build_mode: BuildMode = BuildMode.QUICK,
83
+ profile: bool = False,
84
+ ) -> CompileResult:
85
+ from fastled.web_compile import web_compile # avoid circular import
86
+
87
+ if not self._port:
88
+ raise RuntimeError("Server has not been started yet")
89
+ if not self.ping():
90
+ raise RuntimeError("Server is not running")
91
+ out: CompileResult = web_compile(
92
+ directory, host=self.url(), build_mode=build_mode, profile=profile
93
+ )
94
+ return out
95
+
96
+ def project_init(
97
+ self, example: str | None = None, outputdir: Path | None = None
98
+ ) -> None:
99
+ from fastled.project_init import project_init # avoid circular import
100
+
101
+ project_init(example=example, outputdir=outputdir)
102
+
103
+ @property
104
+ def running(self) -> bool:
105
+ if not self._port:
106
+ return False
107
+ if not DockerManager.is_docker_installed():
108
+ return False
109
+ if not DockerManager.is_running():
110
+ return False
111
+ return self.docker.is_container_running(self.container_name)
112
+
113
+ def using_fastled_src_dir_volume(self) -> bool:
114
+ return self.fastled_src_dir is not None
115
+
116
+ def port(self) -> int:
117
+ if self._port == 0:
118
+ warnings.warn("Server has not been started yet")
119
+ return self._port
120
+
121
+ def url(self) -> str:
122
+ if self._port == 0:
123
+ warnings.warn("Server has not been started yet")
124
+ return f"http://localhost:{self._port}"
125
+
126
+ def ping(self) -> bool:
127
+ try:
128
+ response = httpx.get(
129
+ f"http://localhost:{self._port}", follow_redirects=True
130
+ )
131
+ if response.status_code < 400:
132
+ return True
133
+ except KeyboardInterrupt:
134
+ raise
135
+ except Exception:
136
+ pass
137
+ return False
138
+
139
+ # by default this is automatically called by the constructor, unless
140
+ # auto_start is set to False.
141
+ def wait_for_startup(self, timeout: int = 100) -> bool:
142
+ """Wait for the server to start up."""
143
+ start_time = time.time()
144
+ while time.time() - start_time < timeout:
145
+ # ping the server to see if it's up
146
+ if not self._port:
147
+ return False
148
+ # use httpx to ping the server
149
+ # if successful, return True
150
+ if self.ping():
151
+ return True
152
+ time.sleep(0.1)
153
+ if not self.docker.is_container_running(self.container_name):
154
+ return False
155
+ return False
156
+
157
+ def _start(self) -> int:
158
+ print("Compiling server starting")
159
+
160
+ # Ensure Docker is running
161
+ if not self.docker.is_running():
162
+ if not self.docker.start():
163
+ print("Docker could not be started. Exiting.")
164
+ raise RuntimeError("Docker could not be started. Exiting.")
165
+ now = datetime.now(timezone.utc)
166
+ now_str = now.strftime("%Y-%m-%d")
167
+
168
+ upgrade = False
169
+ if self.auto_updates is None:
170
+ prev_date_str = DISK_CACHE.get("last-update")
171
+ if prev_date_str != now_str:
172
+ print("One day has passed, checking docker for updates")
173
+ upgrade = True
174
+ else:
175
+ upgrade = self.auto_updates
176
+ self.docker.validate_or_download_image(
177
+ image_name=IMAGE_NAME, tag="main", upgrade=upgrade
178
+ )
179
+ DISK_CACHE.put("last-update", now_str)
180
+
181
+ print("Docker image now validated")
182
+ port = SERVER_PORT
183
+ if self.interactive:
184
+ server_command = ["/bin/bash"]
185
+ else:
186
+ server_command = ["python", "/js/run.py", "server"] + SERVER_OPTIONS
187
+ ports = {80: port}
188
+ volumes = None
189
+ if self.fastled_src_dir:
190
+ print(
191
+ f"Mounting FastLED source directory {self.fastled_src_dir} into container /host/fastled/src"
192
+ )
193
+ volumes = {
194
+ str(self.fastled_src_dir): {"bind": "/host/fastled/src", "mode": "ro"}
195
+ }
196
+ if self.interactive:
197
+ # add the mapped directory to the container
198
+ print(f"Mounting {self.mapped_dir} into container /mapped")
199
+ # volumes = {str(self.mapped_dir): {"bind": "/mapped", "mode": "rw"}}
200
+ # add it
201
+ assert self.mapped_dir is not None
202
+ dir_name = self.mapped_dir.name
203
+ if not volumes:
204
+ volumes = {}
205
+ volumes[str(self.mapped_dir)] = {
206
+ "bind": f"/mapped/{dir_name}",
207
+ "mode": "rw",
208
+ }
209
+
210
+ cmd_str = subprocess.list2cmdline(server_command)
211
+ if not self.interactive:
212
+ container: Container = self.docker.run_container_detached(
213
+ image_name=IMAGE_NAME,
214
+ tag="main",
215
+ container_name=self.container_name,
216
+ command=cmd_str,
217
+ ports=ports,
218
+ volumes=volumes,
219
+ remove_previous=self.interactive,
220
+ )
221
+ self.running_container = self.docker.attach_and_run(container)
222
+ assert self.running_container is not None, "Container should be running"
223
+ print("Compile server starting")
224
+ return port
225
+ else:
226
+ self.docker.run_container_interactive(
227
+ image_name=IMAGE_NAME,
228
+ tag="main",
229
+ container_name=self.container_name,
230
+ command=cmd_str,
231
+ ports=ports,
232
+ volumes=volumes,
233
+ )
234
+
235
+ print("Exiting interactive mode")
236
+ return port
237
+
238
+ def process_running(self) -> bool:
239
+ return self.docker.is_container_running(self.container_name)
240
+
241
+ def stop(self) -> None:
242
+ if self.running_container:
243
+ self.running_container.detach()
244
+ self.running_container = None
245
+ self.docker.suspend_container(self.container_name)
246
+ self._port = 0
247
+ print("Compile server stopped")