chore: move led-simulator in from its submodule

Merges led-simulator (sim-bridge, 4d8aeb5) under led-simulator/ with its history,
in place of the submodule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Opus 5.5 committed 2026-11-16 15:08:49 +13:00
commit 698c1463c0
41 files changed
+4369 -4

No files matched your search

-3
View File
@@ -4,6 +4,3 @@
[submodule "led-tool"]
path = led-tool
url = git@git.technical.kiwi:technicalkiwi/led-tool.git
[submodule "led-simulator"]
path = led-simulator
url = git@git.technical.kiwi:technicalkiwi/led-simulator.git
Submodule led-simulator deleted from 4d8aeb5df8.
+2
View File
@@ -0,0 +1,2 @@
workspace/
__pycache__/
+235
View File
@@ -0,0 +1,235 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based on the Program.
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
led-simulator
Copyright (C) 2026 technicalkiwi
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.
+134
View File
@@ -0,0 +1,134 @@
# led-simulator
A web app that simulates a whole LED rig behind a **Wi‑Fi bridge**.
- To **led-controller** it *is* a `bridge-wifi`: a WebSocket on **`/ws`** with the same downlink
rules (binary wire packets are broadcast; v1 JSON envelopes `{"v":"1","dv":{mac: body}}` are
split per MAC) and the same uplink framing (`0x00 + peer MAC + ESP-NOW packet`).
- In the **browser**, every strip is its own led-driver: a web worker running the real
**`led-driver/src/main.py`** and **`led-driver/src/patterns/`** in [Pyodide](https://pyodide.org),
as [led-editor](https://git.technical.kiwi/technicalkiwi/led-editor) runs MicroPython. Only the
hardware modules are stubbed (`stubs/`: `machine`, `neopixel`, `network`, `espnow`, `utime`,
`urandom`, `ubinascii`).
Strips **register like hardware**: each driver sends its JSON hello once when it powers on, and
the bridge forwards it to the controllers connected at that moment. A strip that booted while no
controller was connected is not registered until you power-cycle it.
## Default rig
16 strips × 119 LEDs in **2 columns × 8 rows**. Each strip runs along its row and **starts in the
middle**: pixel 0 is next to the centre line, so left-column strips run right-to-left and
right-column strips run left-to-right.
| Strip | Name | MAC |
| --- | --- | --- |
| 1 … 16 | `sim-01` … `sim-16` | `02:51:4d:00:00:01` … `02:51:4d:00:00:10` |
| bridge | `bridge-sim` | `02:51:4d:00:00:00` |
Strip 1 is row 1 left, strip 2 row 1 right, and so on (`layout.order`).
## With the simulated controller (no hardware at all)
From the repository root:
```bash
make sim-web # this page at http://localhost:8765/ + led-controller built for the host at :8080
make sim # the same with headless drivers (bridge_sim.py), for tests
make test-sim # API and rig tests (groups, field patterns, sequences) against `make sim`
```
The controller reaches the strips over the **UDP bridge** on port **8766**: each datagram is
`dst_mac(6) + packet` down and `src_mac(6) + packet` up, exactly the frames it would send over ESP-NOW.
A board can use it too: set `"bridge": "<this computer>:8766"` in its settings and restart it.
### Headless
`python3 led-simulator/bridge_sim.py [--udp-port 8766] [--port 8765]` runs every strip as its own
CPython process (`sim_driver.py`, `stubs/_simlink_proc.py`) with no browser. `GET /api/pixels` on its
port returns each strip's place and current RGB frame (`rgb`, hex, pixel 0 first).
## Run
From the repository root (Python 3.10+, no extra packages; Microdot comes from `led-driver/lib`):
```bash
python3 led-simulator/server.py # --port 8765 --host 0.0.0.0 --debug
```
1. Open **http://localhost:8765/** in Chrome, Edge or Firefox **on the same computer**.
Drivers need `SharedArrayBuffer`, which browsers only allow on a cross-origin isolated page in
a secure context: `localhost` or HTTPS, not a plain `http://192.168.…` address.
2. In led-controller add a bridge: transport **`ip`**, address **`127.0.0.1`** (controller on
this computer) or this computer's LAN address, port **`8765`**.
3. Power the strips on (or power-cycle them) once the controller is connected, so their hellos
reach it.
The first boot downloads Pyodide (~10 MB) from the CDN; after that the browser caches it.
Strips boot four at a time (`drivers.boot_concurrency`).
Only one tab runs the rig: opening the page in a second tab powers the first one's strips off.
## Page
- **Power on all / Power cycle all / Power off all**, and *Power on when opened*.
- Click a strip for its details: state, MAC, packets received and sent, power on / reset / off,
and its serial output (what the board would print over USB).
- The dot at each strip's start end shows its state: grey off, amber booting, green running,
red stopped (see its serial log for the traceback).
## Configuration
`workspace/sim.json` overrides `sim.default.json` (keep only the keys you change):
```json
{
"bridge": { "name": "bridge-sim", "host": "0.0.0.0", "ws_port": 8765, "wifi_channel": 5, "debug": false },
"layout": { "rows": 8, "columns": 2, "leds_per_strip": 119, "order": "row", "start": "center" },
"drivers": { "name": "sim-{n:02d}", "fps": 30, "loop_sleep_ms": 2, "boot_concurrency": 4 },
"pyodide_url": "https://cdn.jsdelivr.net/pyodide/v0.26.4/full/"
}
```
- `layout.order`: `row` (1 = row 1 left, 2 = row 1 right, …) or `column` (1–8 down the left
column, 9–16 down the right).
- `layout.start`: `center` (pixel 0 next to the middle), `left`, or `right`.
- `drivers.name`: format for new strips; `{n}`, `{row}`, `{col}`, `{side}` (`left`/`right`).
A name the controller sets is kept.
- `drivers.fps`: how often each strip sends its pixels to the page.
- `drivers.loop_sleep_ms`: sleep per driver main-loop pass (in the `WDT.feed()` stub) so 16
drivers do not pin the CPU.
- `pyodide_url`: point at a local copy of Pyodide (full distribution folder, trailing `/`) to run
offline.
## Simulated flash
Each strip keeps `settings.json` and `presets.json` in **`workspace/drivers/NN/`** on the server:
created from **`settings.default.json`** on first boot, then saved whenever the driver writes
them. `num_leds` always follows the layout. Delete `workspace/drivers/` to factory-reset every
strip.
Driver code and **patterns are always the current `led-driver/src`**, loaded fresh on every
boot. Patterns the controller pushes by OTA live only until that strip powers off.
## How it fits together
```
led-controller ──ws /ws──▶ server.py (bridge rules) ──ws /sim──▶ page ──SharedArrayBuffer──▶ worker × 16
◀── 0x00+mac+pkt ── ◀── mac+pkt ── ◀──── postMessage ──── (Pyodide, main.py)
```
- `server.py` – HTTP + both WebSockets, bridge downlink rules, flash files.
- `web/app.js` – rig canvas, power control, packet routing by MAC.
- `web/driver-worker.js` – loads Pyodide, writes the strip's flash, runs `web/driver_boot.py`.
- `web/ring.js` – the SharedArrayBuffer queue that delivers packets to a driver while `main.py`
runs (it never yields to the JavaScript event loop).
- `stubs/_simlink.py` – the driver side of that link (radio, pixels, flash, sleeps).
## Notes
- `machine.reset()` in a driver reboots that strip.
- The ping reply that led-driver sends from a thread runs from the main loop after the same
50–500 ms delay (Pyodide has no threads).
- Strips do not hear each other's ESP-NOW broadcasts; the bridge forwards driver transmissions to
the controller only.
+782
View File
@@ -0,0 +1,782 @@
"""Simulated Wi-Fi ESP-NOW bridge with a rig of simulated led-drivers behind it.
To led-controller this looks like ``bridge-wifi``: a WebSocket on ``/ws``
with the same downlink handling (binary wire packets are broadcast, v1 JSON
envelopes are split per MAC) and the same uplink framing
(``0x00 + peer_mac + packet``). Add it in the controller as an IP bridge.
Behind the bridge, every strip is a separate process running the real
``led-driver/src/main.py`` (see ``sim_driver.py``), so each strip keeps its
own settings, presets, groups and pattern state, as on hardware.
"""
from __future__ import annotations
import asyncio
import json
import os
import secrets
import shutil
import socket
import subprocess
import sys
import threading
import time
from multiprocessing.connection import Listener, wait
from pathlib import Path
from layout import normalise_layout, side_name, strip_places
from rig_seed import seed, seed_soon
SIM_ROOT = Path(__file__).resolve().parent
WORKSPACE = SIM_ROOT / "workspace"
DRIVERS_DIR = WORKSPACE / "drivers"
SHARED_PATTERNS = WORKSPACE / "patterns"
SIM_DEFAULTS = SIM_ROOT / "sim.default.json"
SIM_CONFIG = WORKSPACE / "sim.json"
DRIVER_SETTINGS_TEMPLATE = SIM_ROOT / "settings.default.json"
DRIVER_ROOT = SIM_ROOT.parent / "led-driver"
DRIVER_SRC = DRIVER_ROOT / "src"
DRIVER_LIB = DRIVER_ROOT / "lib"
SIM_DRIVER = SIM_ROOT / "sim_driver.py"
BROADCAST = b"\xff\xff\xff\xff\xff\xff"
WIRE = 0x4C
MSG_ANNOUNCE = 0x01
MAX_ESPNOW = 250
RESET_EXIT_CODE = 75 # stubs/machine.py: machine.reset()
# Locally administered MACs: 02:51:4d ("QM") : 00 : 00 : NN. The bridge is NN=00.
MAC_PREFIX = bytes([0x02, 0x51, 0x4D, 0x00, 0x00])
BUILTIN_DEFAULTS = {
"bridge": {
"name": "bridge-sim",
"host": "0.0.0.0",
"ws_port": 8765,
"udp_port": 8766,
"wifi_channel": 5,
"debug": False,
},
"layout": {},
"drivers": {
"name": "sim-{n:02d}",
"fps": 30,
"loop_sleep_ms": 2,
},
}
def mac_str(mac: bytes) -> str:
return ":".join("%02x" % b for b in mac)
def driver_mac(index: int) -> bytes:
return MAC_PREFIX + bytes([(index + 1) & 0xFF])
BRIDGE_MAC = MAC_PREFIX + b"\x00"
def _merge(base: dict, extra: dict) -> dict:
out = dict(base)
for k, v in (extra or {}).items():
if isinstance(v, dict) and isinstance(out.get(k), dict):
out[k] = _merge(out[k], v)
else:
out[k] = v
return out
def _read_json(path: Path) -> dict:
try:
with open(path, encoding="utf-8") as f:
data = json.load(f)
return data if isinstance(data, dict) else {}
except (OSError, ValueError):
return {}
def load_config() -> dict:
"""Built-in defaults <- sim.default.json <- workspace/sim.json."""
WORKSPACE.mkdir(parents=True, exist_ok=True)
if not SIM_CONFIG.is_file() and SIM_DEFAULTS.is_file():
shutil.copy2(SIM_DEFAULTS, SIM_CONFIG)
cfg = _merge(BUILTIN_DEFAULTS, _read_json(SIM_DEFAULTS))
cfg = _merge(cfg, _read_json(SIM_CONFIG))
cfg["layout"] = normalise_layout(cfg.get("layout"))
return cfg
def lan_ip() -> str:
"""Best guess at this computer's LAN address (for the controller to dial)."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(("10.255.255.255", 1))
return s.getsockname()[0]
except OSError:
return "127.0.0.1"
finally:
s.close()
def sync_patterns() -> None:
"""Copy led-driver/src/patterns into the shared simulated flash patterns/ folder.
Files the controller pushed by OTA under other names are kept.
"""
SHARED_PATTERNS.mkdir(parents=True, exist_ok=True)
src = DRIVER_SRC / "patterns"
if not src.is_dir():
return
for f in src.glob("*.py"):
dst = SHARED_PATTERNS / f.name
try:
if not dst.exists() or f.stat().st_mtime > dst.stat().st_mtime:
shutil.copy2(f, dst)
except OSError as e:
print("[sim] pattern copy failed:", f.name, e)
class Strip:
def __init__(self, place, name: str):
self.place = place
self.index = place.index
self.mac = driver_mac(place.index)
self.name = name
self.dir = DRIVERS_DIR / ("%02d" % place.number)
self.proc: subprocess.Popen | None = None
self.conn = None
self.frame = bytes(place.leds * 3)
self.hello: bytes | None = None
self.announce: bytes | None = None
self.rx_packets = 0
self.tx_packets = 0
self.reported = False
class BridgeSim:
"""Owns the WebSocket server (asyncio thread) and the driver processes."""
def __init__(self, cfg: dict | None = None):
self.cfg = cfg or load_config()
self.layout = self.cfg["layout"]
self.places = strip_places(self.layout)
dcfg = self.cfg["drivers"]
self.strips: list[Strip] = []
for p in self.places:
name = str(dcfg.get("name", "sim-{n:02d}")).format(
n=p.number,
row=p.row + 1,
col=p.col + 1,
side=side_name(p.col, self.layout["columns"]),
)
self.strips.append(Strip(p, name))
self.by_mac = {s.mac: s for s in self.strips}
self.running = False
self.port = int(self.cfg["bridge"]["ws_port"])
self.error: str | None = None
self.debug = bool(self.cfg["bridge"].get("debug", False))
self._lock = threading.Lock()
self._dirty: set[int] = set()
self._clients: set = set()
self._loop: asyncio.AbstractEventLoop | None = None
self._loop_thread: threading.Thread | None = None
self._reader_thread: threading.Thread | None = None
self._accept_thread: threading.Thread | None = None
self._listener: Listener | None = None
self._authkey = b""
self._stopping = False
self._app = None
self.downlink_count = 0
self.uplink_count = 0
# UDP bridge (led-controller settings.bridge): dst_mac(6)+packet down, src_mac(6)+packet up
self.udp_port = int(self.cfg["bridge"].get("udp_port", 8766))
self._udp: socket.socket | None = None
self._udp_peer = None
self._udp_thread: threading.Thread | None = None
# ----- public -------------------------------------------------------
@property
def client_count(self) -> int:
return len(self._clients)
def take_dirty_frames(self) -> dict[int, bytes]:
with self._lock:
out = {i: self.strips[i].frame for i in self._dirty}
self._dirty.clear()
return out
def alive_count(self) -> int:
return sum(1 for s in self.strips if s.proc is not None and s.proc.poll() is None)
def connected_count(self) -> int:
return sum(1 for s in self.strips if s.conn is not None)
def start(self, port: int | None = None) -> None:
if self.running:
return
if port is not None:
self.port = int(port)
self.error = None
self._stopping = False
self._check_paths()
sync_patterns()
self._prepare_driver_dirs()
# Bind the WebSocket port first so a clash fails before drivers boot.
ready = threading.Event()
self._loop_thread = threading.Thread(
target=self._loop_main, args=(ready,), name="bridge-ws", daemon=True
)
self._loop_thread.start()
ready.wait(5)
if self.error:
raise RuntimeError(self.error)
if self.udp_port:
self._udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self._udp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self._udp.bind((str(self.cfg["bridge"].get("host", "0.0.0.0")), self.udp_port))
self._udp.settimeout(0.5)
self._authkey = secrets.token_bytes(16)
# backlog: all strips connect at once; the default of 1 makes late
# drivers wait on SYN retries.
self._listener = Listener(("127.0.0.1", 0), authkey=self._authkey, backlog=64)
self.running = True
if self._udp is not None:
self._udp_thread = threading.Thread(target=self._udp_main, name="bridge-udp", daemon=True)
self._udp_thread.start()
self._accept_thread = threading.Thread(
target=self._accept_main, name="bridge-accept", daemon=True
)
self._accept_thread.start()
for s in self.strips:
s.reported = False
self._spawn(s)
self._reader_thread = threading.Thread(
target=self._reader_main, name="bridge-drivers", daemon=True
)
self._reader_thread.start()
print(
"[sim] bridge %s ws://%s:%d/ws udp %d %d strips x %d LEDs"
% (
self.cfg["bridge"]["name"],
lan_ip(),
self.port,
self.udp_port,
len(self.strips),
self.layout["leds_per_strip"],
)
)
def stop(self) -> None:
if not self.running and self._loop is None:
return
self._stopping = True
self.running = False
if self._udp is not None:
if self._udp_thread is not None:
self._udp_thread.join(1)
self._udp.close()
self._udp = None
if self._reader_thread is not None:
self._reader_thread.join(1)
self._reader_thread = None
for s in self.strips:
if s.proc is not None and s.proc.poll() is None:
s.proc.terminate()
deadline = time.monotonic() + 3
for s in self.strips:
if s.proc is None:
continue
try:
s.proc.wait(max(0.1, deadline - time.monotonic()))
except subprocess.TimeoutExpired:
s.proc.kill()
s.proc = None
if s.conn is not None:
try:
s.conn.close()
except OSError:
pass
s.conn = None
s.hello = None
s.announce = None
s.frame = bytes(s.place.leds * 3)
with self._lock:
self._dirty.update(range(len(self.strips)))
if self._listener is not None:
# close() does not wake a thread blocked in accept() on Linux;
# a throwaway connection does.
try:
socket.create_connection(self._listener.address, timeout=0.5).close()
except OSError:
pass
try:
self._listener.close()
except OSError:
pass
self._listener = None
loop = self._loop
if loop is not None:
fut = asyncio.run_coroutine_threadsafe(self._shutdown_ws(), loop)
try:
fut.result(3)
except Exception:
pass
if self._loop_thread is not None:
self._loop_thread.join(3)
if self._loop_thread.is_alive():
loop.call_soon_threadsafe(loop.stop)
self._loop_thread.join(1)
self._loop = None
self._clients.clear()
print("[sim] stopped")
# ----- driver processes --------------------------------------------
def _check_paths(self):
if not (DRIVER_SRC / "main.py").is_file():
raise RuntimeError("led-driver/src/main.py not found next to led-simulator")
def _prepare_driver_dirs(self):
template = _read_json(DRIVER_SETTINGS_TEMPLATE)
for s in self.strips:
s.dir.mkdir(parents=True, exist_ok=True)
settings_path = s.dir / "settings.json"
current = _read_json(settings_path)
merged = dict(template)
merged.update(current)
if not current.get("name"):
merged["name"] = s.name
# Strip length is physical: the layout decides it.
merged["num_leds"] = s.place.leds
merged["wifi_channel"] = int(self.cfg["bridge"].get("wifi_channel", 5))
with open(settings_path, "w", encoding="utf-8") as f:
json.dump(merged, f)
s.name = merged["name"]
presets_path = s.dir / "presets.json"
if not presets_path.is_file():
presets_path.write_text("{}\n", encoding="utf-8")
self._link_patterns(s.dir / "patterns")
def _link_patterns(self, link: Path):
if link.is_symlink() or link.exists():
return
try:
link.symlink_to(SHARED_PATTERNS.resolve(), target_is_directory=True)
except OSError:
# No symlinks (e.g. Windows without developer mode): private copy.
shutil.copytree(SHARED_PATTERNS, link)
def _spawn(self, s: Strip):
addr = self._listener.address
env = dict(os.environ)
env.update(
{
"LED_SIM_INDEX": str(s.index),
"LED_SIM_MAC": s.mac.hex(),
"LED_SIM_DIR": str(s.dir),
"LED_SIM_ADDR": "%s:%d" % addr,
"LED_SIM_AUTH": self._authkey.hex(),
"LED_SIM_FPS": str(self.cfg["drivers"].get("fps", 30)),
"LED_SIM_LOOP_SLEEP_MS": str(self.cfg["drivers"].get("loop_sleep_ms", 2)),
"PYTHONDONTWRITEBYTECODE": "1",
"PYTHONUNBUFFERED": "1",
}
)
s.proc = subprocess.Popen(
[sys.executable, str(SIM_DRIVER)],
cwd=str(s.dir),
env=env,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
def _accept_main(self):
listener = self._listener
while self.running and listener is not None:
try:
conn = listener.accept()
except (OSError, EOFError):
if not self.running:
return
# A failed auth handshake (stray client): keep listening.
continue
try:
first = conn.recv_bytes()
except (OSError, EOFError):
continue
if first[:1] != b"H" or len(first) < 2 or first[1] >= len(self.strips):
conn.close()
continue
self.strips[first[1]].conn = conn
def _report_dead(self, s: Strip):
log = s.dir / "driver.log"
tail = ""
try:
tail = log.read_text(encoding="utf-8", errors="replace")[-600:]
except OSError:
pass
print("[sim] strip %d (%s) stopped. Last log lines:\n%s" % (s.place.number, s.name, tail))
def _reader_main(self):
while self.running:
for s in self.strips:
if s.conn is None and not s.reported and s.proc is not None and s.proc.poll() is not None:
s.reported = True
self._report_dead(s)
conns = {s.conn: s for s in self.strips if s.conn is not None}
if not conns:
time.sleep(0.2)
continue
try:
ready = wait(list(conns), timeout=0.2)
except OSError:
continue
for c in ready:
s = conns[c]
try:
frame = c.recv_bytes()
except (OSError, EOFError):
self._driver_gone(s)
continue
kind = frame[:1]
if kind == b"P":
with self._lock:
s.frame = frame[1:]
self._dirty.add(s.index)
elif kind == b"T" and len(frame) >= 7:
s.tx_packets += 1
self._from_driver(s, frame[1:7], frame[7:])
def _driver_gone(self, s: Strip):
if s.conn is not None:
try:
s.conn.close()
except OSError:
pass
s.conn = None
if self._stopping or not self.running:
return
code = None
if s.proc is not None:
try:
code = s.proc.wait(2)
except subprocess.TimeoutExpired:
code = None
if code == RESET_EXIT_CODE:
print("[sim] strip %d reset, booting again" % s.place.number)
self._spawn(s)
return
s.reported = True
self._report_dead(s)
with self._lock:
s.frame = bytes(s.place.leds * 3)
self._dirty.add(s.index)
def _to_driver(self, s: Strip, packet: bytes):
if s.conn is None:
return
try:
s.conn.send_bytes(b"R" + BRIDGE_MAC + packet)
s.rx_packets += 1
except (OSError, EOFError, ValueError):
pass
def _from_driver(self, s: Strip, dest: bytes, packet: bytes):
"""Driver ESP-NOW transmit. The bridge forwards everything it hears."""
if packet[:1] == b"{":
s.hello = packet
elif len(packet) >= 2 and packet[0] == WIRE and packet[1] == MSG_ANNOUNCE:
s.announce = packet
if self.debug:
print("[sim] up %s %d B" % (mac_str(s.mac), len(packet)))
udp, peer = self._udp, self._udp_peer
if udp is not None and peer is not None:
try:
udp.sendto(s.mac + packet, peer)
self.uplink_count += 1
except OSError:
pass
loop = self._loop
if loop is not None:
frame = bytes([0]) + s.mac + packet
loop.call_soon_threadsafe(self._uplink_soon, frame)
# ----- UDP bridge ----------------------------------------------------
def _udp_main(self):
udp = self._udp
while self.running and udp is not None:
try:
data, addr = udp.recvfrom(2048)
except socket.timeout:
continue
except OSError:
return
if len(data) < 7:
continue
if self._udp_peer != addr:
self._udp_peer = addr
print("[sim] udp controller", "%s:%d" % addr)
seed_soon(self.cfg, {st.index: mac_str(st.mac) for st in self.strips}, addr[0])
# A controller that (re)started after the strips booted still gets their hellos
for st in self.strips:
for pkt in (st.hello, st.announce):
if pkt:
try:
udp.sendto(st.mac + pkt, addr)
except OSError:
pass
self.downlink_count += 1
if self.debug:
print("[sim] udp dl %s %d B" % (mac_str(data[:6]), len(data) - 6))
self._deliver(bytes(data[:6]), bytes(data[6:]))
def pixels(self) -> dict:
with self._lock:
frames = [s.frame for s in self.strips]
return {
"layout": self.layout,
"strips": [
{
"n": s.place.number,
"name": s.name,
"mac": mac_str(s.mac),
"row": s.place.row,
"col": s.place.col,
"reversed": s.place.reversed,
"running": s.conn is not None,
"rx": s.rx_packets,
"tx": s.tx_packets,
"place": _read_json(s.dir / "settings.json").get("place"),
"rgb": frames[i].hex(),
}
for i, s in enumerate(self.strips)
],
}
# ----- WebSocket side (asyncio thread) ------------------------------
def _loop_main(self, ready: threading.Event):
for p in (str(DRIVER_LIB),):
if p not in sys.path:
sys.path.insert(0, p)
try:
from microdot import Microdot
from microdot.websocket import WebSocketError, with_websocket
except ImportError as e:
self.error = "Microdot not found in led-driver/lib (%s)" % e
ready.set()
return
app = Microdot()
self._app = app
bridge = self
@app.route("/ws")
@with_websocket
async def ws_handler(request, ws):
bridge._clients.add(ws)
print("[sim] ws client + (%d)" % len(bridge._clients))
# A real bridge forwards boot hellos only to clients that are
# connected at the time. Replay them so the controller learns the
# strips even when it connects after Start.
for s in bridge.strips:
for pkt in (s.hello, s.announce):
if pkt:
try:
await ws.send(bytes([0]) + s.mac + pkt)
except Exception:
pass
try:
while True:
try:
raw = await ws.receive()
except WebSocketError:
break
if not raw:
break
if isinstance(raw, str):
raw = raw.encode("utf-8")
bridge.downlink_count += 1
bridge._downlink(raw)
finally:
bridge._clients.discard(ws)
print("[sim] ws client - (%d)" % len(bridge._clients))
@app.route("/api/pixels")
async def api_pixels(request):
return bridge.pixels()
@app.route("/api/seed-layout", methods=["POST"])
async def api_seed_layout(request):
"""Send the simulator's layout to the controller for every unplaced strip, now."""
if bridge._udp_peer is None:
return {"error": "no controller on the UDP bridge yet"}, 409
macs = {st.index: mac_str(st.mac) for st in bridge.strips}
reply = await asyncio.to_thread(seed, bridge.cfg, macs, bridge._udp_peer[0], print, 30)
return {"sent": reply}
@app.route("/")
async def index(request):
info = {
"bridge": bridge.cfg["bridge"]["name"],
"mac": mac_str(BRIDGE_MAC),
"ws": "/ws",
"strips": [
{"n": s.place.number, "name": s.name, "mac": mac_str(s.mac)}
for s in bridge.strips
],
}
return info
loop = asyncio.new_event_loop()
self._loop = loop
asyncio.set_event_loop(loop)
host = str(self.cfg["bridge"].get("host", "0.0.0.0"))
async def run():
try:
# Probe the port so a clash is reported at Start.
srv = await asyncio.start_server(lambda r, w: None, host, self.port)
srv.close()
await srv.wait_closed()
except OSError as e:
self.error = "Port %d not available: %s" % (self.port, e.strerror or e)
ready.set()
return
ready.set()
await app.start_server(host=host, port=self.port)
try:
loop.run_until_complete(run())
except Exception as e: # noqa: BLE001
if not self._stopping:
self.error = str(e)
print("[sim] ws server error:", e)
finally:
ready.set()
try:
loop.close()
except Exception:
pass
async def _shutdown_ws(self):
for ws in list(self._clients):
try:
await ws.close()
except Exception:
pass
try:
ws.request.sock[1].close()
except Exception:
pass
if self._app is not None and getattr(self._app, "server", None):
self._app.shutdown()
def _uplink_soon(self, frame: bytes):
self.uplink_count += 1
for ws in list(self._clients):
asyncio.ensure_future(self._send_ws(ws, frame))
async def _send_ws(self, ws, frame):
try:
await ws.send(frame)
except Exception:
self._clients.discard(ws)
def _deliver(self, dest: bytes, packet: bytes):
if dest == BROADCAST:
for s in self.strips:
self._to_driver(s, packet)
return
s = self.by_mac.get(dest)
if s is None:
if self.debug:
print("[sim] dl no such peer", mac_str(dest))
return
self._to_driver(s, packet)
def _downlink(self, raw: bytes):
"""Same rules as bridge-wifi/src/main.py ``downlink``."""
n = len(raw)
if not raw:
return
if raw[0] == WIRE:
if n < 2:
return
if n > MAX_ESPNOW:
if self.debug:
print("[sim] dl skip big wire", n)
return
self._deliver(BROADCAST, raw)
return
if n < 8 or raw[:1] != b"{":
return
try:
data = json.loads(raw)
except ValueError:
return
if not isinstance(data, dict):
return
devs = data.get("dv") or data.get("devices")
if data.get("v") != "1" or not isinstance(devs, dict):
return
for mac_s, body in devs.items():
if not isinstance(body, dict):
continue
try:
h = str(mac_s).replace(":", "").replace("-", "").strip().lower()
dest = BROADCAST if h == "ffffffffffff" else bytes.fromhex(h)
if len(dest) != 6:
continue
except ValueError:
continue
msg = {"v": "1"}
msg.update(body)
pkt = json.dumps(msg, separators=(",", ":")).encode()
if len(pkt) > MAX_ESPNOW:
if self.debug:
print("[sim] dl skip big", len(pkt))
continue
self._deliver(dest, pkt)
def main(argv=None):
"""Headless rig: ``python3 led-simulator/bridge_sim.py [--udp-port 8766] [--port 8765]``."""
import argparse
import signal
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("--port", type=int, help="WebSocket/HTTP port (default from sim.json, 8765)")
ap.add_argument("--udp-port", type=int, help="UDP bridge port (default 8766, 0 = off)")
ap.add_argument("--debug", action="store_true")
a = ap.parse_args(argv)
cfg = load_config()
if a.udp_port is not None:
cfg["bridge"]["udp_port"] = a.udp_port
if a.debug:
cfg["bridge"]["debug"] = True
sim = BridgeSim(cfg)
sim.start(a.port)
stop = threading.Event()
signal.signal(signal.SIGTERM, lambda *_: stop.set())
signal.signal(signal.SIGINT, lambda *_: stop.set())
try:
while not stop.wait(5):
print(flush=True, *("[sim] running %d/%d dl %d ul %d" % (sim.connected_count(), len(sim.strips), sim.downlink_count, sim.uplink_count),))
finally:
sim.stop()
if __name__ == "__main__":
main()
+19
View File
@@ -0,0 +1,19 @@
"""Example pattern for led-simulator / led-driver (generator + yield per tick)."""
import utime
class Blink:
def __init__(self, presets):
self.presets = presets
def run(self, preset):
colors = preset.c if preset.c else [(255, 255, 255)]
idx = 0
delay_ms = max(1, int(preset.d))
while True:
rgb = colors[idx % len(colors)]
self.presets.fill(self.presets.apply_brightness(rgb, preset.b))
yield
utime.sleep_ms(delay_ms)
idx += 1
+25
View File
@@ -0,0 +1,25 @@
"""Simple one-pixel chase (uses preset c[0] for the dot, preset n3 as step)."""
import utime
class Chase:
def __init__(self, presets):
self.presets = presets
def run(self, preset):
n = self.presets.num_leds
rgb = preset.c[0] if preset.c else (255, 64, 0)
raw_step = int(getattr(preset, "n3", 1))
step = raw_step if raw_step != 0 else 1
pos = 0
delay_ms = max(1, int(preset.d))
while True:
off = (0, 0, 0)
for i in range(n):
self.presets.n[i] = off
self.presets.n[pos % n] = self.presets.apply_brightness(rgb, preset.b)
self.presets.n.write()
yield
utime.sleep_ms(delay_ms)
pos += step
+264
View File
@@ -0,0 +1,264 @@
#!/usr/bin/env python3
"""
Graphical simulator for an led-controller rig behind a Wi-Fi bridge (CPython).
To led-controller the simulator is a ``bridge-wifi``: a WebSocket on ``/ws``
(add it as an IP bridge). Behind the bridge, every strip runs the real
``led-driver/src/main.py`` in its own process (see ``bridge_sim.py``).
Default rig: 16 strips x 119 LEDs, 2 columns x 8 rows, each strip running
along its row with pixel 0 next to the centre line. Change it in
``workspace/sim.json`` (created from ``sim.default.json``).
"""
from __future__ import annotations
import sys
import tkinter as tk
from pathlib import Path
from tkinter import messagebox, ttk
SIM_ROOT = Path(__file__).resolve().parent
if str(SIM_ROOT) not in sys.path:
sys.path.insert(0, str(SIM_ROOT))
from bridge_sim import ( # noqa: E402
BRIDGE_MAC,
DRIVER_SRC,
SIM_CONFIG,
BridgeSim,
lan_ip,
load_config,
mac_str,
)
from layout import compute_geometry # noqa: E402
BG = "#0e0f12"
LED_OFF = "#1d1f24"
CENTRE = "#2c3038"
LABEL = "#8a909c"
LABEL_ON = "#c9ced8"
FRAME_MS = 33
def _hex(r, g, b):
if r == 0 and g == 0 and b == 0:
return LED_OFF
return "#%02x%02x%02x" % (r, g, b)
class LedSimulatorApp:
def __init__(self):
self.cfg = load_config()
self.sim = BridgeSim(self.cfg)
lay = self.sim.layout
self.root = tk.Tk()
self.root.title("led-simulator: %s" % self.cfg["bridge"]["name"])
self.root.geometry("1280x620")
self.root.minsize(760, 360)
self.root.configure(background=BG)
self._port = tk.IntVar(value=int(self.cfg["bridge"]["ws_port"]))
self._status = tk.StringVar()
self._hint = tk.StringVar()
# canvas item ids per strip / pixel, and last drawn colour per pixel
self._items: list[list[int]] = []
self._drawn: list[list[str]] = []
self._label_items: list[int] = []
self._label_lit: list[bool] = []
self._frames: list[bytes] = [bytes(lay["leds_per_strip"] * 3)] * len(self.sim.strips)
self._resize_job = None
self._last_size = (0, 0)
self._build_ui()
self._update_status()
self.root.after(FRAME_MS, self._tick)
self.root.protocol("WM_DELETE_WINDOW", self._on_quit)
# ----- UI -----------------------------------------------------------
def _build_ui(self):
style = ttk.Style(self.root)
try:
style.theme_use("clam")
except tk.TclError:
pass
top = ttk.Frame(self.root, padding=(10, 8))
top.pack(fill=tk.X)
self._start_btn = ttk.Button(top, text="Start", command=self._on_start)
self._start_btn.pack(side=tk.LEFT, padx=(0, 6))
self._stop_btn = ttk.Button(top, text="Stop", command=self._on_stop, state=tk.DISABLED)
self._stop_btn.pack(side=tk.LEFT, padx=(0, 16))
ttk.Label(top, text="Bridge WebSocket port:").pack(side=tk.LEFT)
self._port_box = ttk.Spinbox(
top, from_=1, to=65535, textvariable=self._port, width=7
)
self._port_box.pack(side=tk.LEFT, padx=4)
ttk.Label(top, textvariable=self._status).pack(side=tk.LEFT, padx=(16, 0))
hint = ttk.Label(self.root, textvariable=self._hint, padding=(10, 0, 10, 6))
hint.pack(fill=tk.X)
self._canvas = tk.Canvas(self.root, background=BG, highlightthickness=0)
self._canvas.pack(fill=tk.BOTH, expand=True)
self._canvas.bind("<Configure>", self._on_resize)
def _update_status(self):
b = self.cfg["bridge"]
lay = self.sim.layout
rig = "%d strips x %d LEDs, %d x %d" % (
len(self.sim.strips),
lay["leds_per_strip"],
lay["columns"],
lay["rows"],
)
if self.sim.running:
self._status.set(
"%s (%s) ws://%s:%d/ws | controller connections: %d | strips up: %d/%d | %s"
% (
b["name"],
mac_str(BRIDGE_MAC),
lan_ip(),
self.sim.port,
self.sim.client_count,
self.sim.connected_count(),
len(self.sim.strips),
rig,
)
)
self._hint.set(
"In led-controller add a bridge with transport IP, address %s "
"(127.0.0.1 on this computer) and port %d. Strips register from their hello."
% (lan_ip(), self.sim.port)
)
else:
self._status.set("Stopped | %s | config: %s" % (rig, SIM_CONFIG))
self._hint.set(
"Start boots the wifi bridge and one led-driver per strip "
"(led-driver/src/main.py, flash in workspace/drivers/NN)."
)
# ----- drawing -------------------------------------------------------
def _on_resize(self, event):
if (event.width, event.height) == self._last_size:
return
if self._resize_job is not None:
self.root.after_cancel(self._resize_job)
self._resize_job = self.root.after(60, self._rebuild)
def _rebuild(self):
self._resize_job = None
c = self._canvas
w, h = c.winfo_width(), c.winfo_height()
if w < 50 or h < 50:
return
self._last_size = (w, h)
c.delete("all")
geo = compute_geometry(self.sim.places, self.sim.layout, w, h)
for x in geo.centre_lines:
c.create_line(x, 6, x, h - 6, fill=CENTRE, dash=(4, 4))
self._items = []
self._drawn = []
self._label_items = []
self._label_lit = []
font = ("TkDefaultFont", 8)
for s, rects, (lx, ly, anchor) in zip(self.sim.strips, geo.rects, geo.labels):
if anchor == "e":
text = "%s %d ◂" % (s.name, s.place.number)
else:
text = "▸ %d %s" % (s.place.number, s.name)
self._label_items.append(
c.create_text(lx, ly, text=text, anchor=anchor, fill=LABEL, font=font)
)
ids = []
for x0, y0, x1, y1 in rects:
ids.append(c.create_rectangle(x0, y0, x1, y1, fill=LED_OFF, width=0))
self._items.append(ids)
self._drawn.append([LED_OFF] * len(ids))
self._label_lit.append(False)
for i, frame in enumerate(self._frames):
self._paint(i, frame)
def _paint(self, strip_index: int, frame: bytes):
if strip_index >= len(self._items):
return
ids = self._items[strip_index]
drawn = self._drawn[strip_index]
itemconfig = self._canvas.itemconfigure
lit = False
for i in range(min(len(ids), len(frame) // 3)):
j = i * 3
col = _hex(frame[j], frame[j + 1], frame[j + 2])
if col != LED_OFF:
lit = True
if drawn[i] != col:
itemconfig(ids[i], fill=col)
drawn[i] = col
if self._label_lit[strip_index] != lit:
self._label_lit[strip_index] = lit
itemconfig(self._label_items[strip_index], fill=LABEL_ON if lit else LABEL)
def _tick(self):
try:
for i, frame in self.sim.take_dirty_frames().items():
self._frames[i] = frame
self._paint(i, frame)
finally:
self.root.after(FRAME_MS, self._tick)
def _status_tick(self):
self._update_status()
if self.sim.running:
self.root.after(1000, self._status_tick)
# ----- actions -------------------------------------------------------
def _on_start(self):
if self.sim.running:
return
try:
port = int(self._port.get())
except (tk.TclError, ValueError):
messagebox.showerror("Simulator", "Port must be a number.")
return
try:
self.sim.start(port=port)
except Exception as e: # noqa: BLE001
self.sim.stop()
messagebox.showerror("Simulator", str(e))
return
self._start_btn.configure(state=tk.DISABLED)
self._stop_btn.configure(state=tk.NORMAL)
self._port_box.configure(state=tk.DISABLED)
self._status_tick()
def _on_stop(self):
self.sim.stop()
self._start_btn.configure(state=tk.NORMAL)
self._stop_btn.configure(state=tk.DISABLED)
self._port_box.configure(state=tk.NORMAL)
self._update_status()
def _on_quit(self):
try:
self.sim.stop()
finally:
self.root.destroy()
def run(self):
self.root.mainloop()
def main():
if not (DRIVER_SRC / "main.py").is_file():
print("led-driver/src/main.py not found next to led-simulator.", file=sys.stderr)
sys.exit(1)
LedSimulatorApp().run()
if __name__ == "__main__":
main()
+114
View File
@@ -0,0 +1,114 @@
"""Physical strip layout for led-simulator (server side; the page draws it in web/layout.js).
The default rig is 16 strips of 119 LEDs in 2 columns x 8 rows. Each strip
runs along its row, and pixel 0 sits next to the centre line between the
columns: left-column strips run right-to-left, right-column strips run
left-to-right.
"""
from __future__ import annotations
from dataclasses import dataclass
DEFAULT_LAYOUT = {
"rows": 8,
"columns": 2,
"leds_per_strip": 119,
# "row": strip 1 = row 1 left, strip 2 = row 1 right, strip 3 = row 2 left, ...
# "column": strips 1-8 = left column top to bottom, 9-16 = right column.
"order": "row",
# "center": pixel 0 next to the middle of the columns (default rig).
# "left": every strip starts at its left end. "right": at its right end.
"start": "center",
}
@dataclass(frozen=True)
class StripPlace:
index: int # 0-based strip number
row: int # 0-based, top row first
col: int # 0-based, left column first
leds: int
reversed: bool # True: pixel 0 is at the strip's right end
@property
def number(self) -> int:
return self.index + 1
def normalise_layout(raw: dict | None) -> dict:
lay = dict(DEFAULT_LAYOUT)
if isinstance(raw, dict):
lay.update({k: v for k, v in raw.items() if v is not None})
lay["rows"] = max(1, int(lay["rows"]))
lay["columns"] = max(1, int(lay["columns"]))
lay["leds_per_strip"] = max(1, min(2048, int(lay["leds_per_strip"])))
lay["order"] = "column" if str(lay["order"]).lower() == "column" else "row"
start = str(lay["start"]).lower()
lay["start"] = start if start in ("center", "left", "right") else "center"
return lay
def strip_count(layout: dict) -> int:
lay = normalise_layout(layout)
return lay["rows"] * lay["columns"]
def _reversed_for_column(col: int, columns: int, start: str) -> bool:
if start == "left":
return False
if start == "right":
return True
# centre-out: columns left of the middle run leftwards from their right end.
# With an odd column count the middle column runs left-to-right.
return col < columns // 2
def strip_places(layout: dict) -> list[StripPlace]:
lay = normalise_layout(layout)
rows, cols = lay["rows"], lay["columns"]
out = []
for i in range(rows * cols):
if lay["order"] == "column":
row, col = i % rows, i // rows
else:
row, col = i // cols, i % cols
out.append(
StripPlace(
index=i,
row=row,
col=col,
leds=lay["leds_per_strip"],
reversed=_reversed_for_column(col, cols, lay["start"]),
)
)
return out
def side_name(col: int, columns: int) -> str:
if columns == 2:
return "left" if col == 0 else "right"
return "c%d" % (col + 1)
# Rig coordinates for led-controller's rig layout (POST /devices/layout): the same 1000 x 700 canvas as its
# rig-layout editor, y up. Each strip runs along its row inside its column; x0,y0 is pixel 0's end.
RIG_W = 1000
RIG_H = 700
RIG_GAP = 20 # space between a strip's end and its column's edge
def rig_placements(layout: dict) -> tuple[dict[int, dict], dict]:
"""({strip index: {x0, y0, x1, y1}}, centre {x, y}) for the controller's rig layout."""
lay = normalise_layout(layout)
rows, cols = lay["rows"], lay["columns"]
col_w = RIG_W / cols
row_h = RIG_H / rows
out = {}
for p in strip_places(lay):
y = round(RIG_H - (p.row + 0.5) * row_h, 1) # row 1 at the top
left = round(p.col * col_w + RIG_GAP, 1)
right = round((p.col + 1) * col_w - RIG_GAP, 1)
x0, x1 = (right, left) if p.reversed else (left, right)
out[p.index] = {"x0": x0, "y0": y, "x1": x1, "y1": y}
return out, {"x": RIG_W / 2, "y": RIG_H / 2}
+17
View File
@@ -0,0 +1,17 @@
"""Host-only: led-simulator registers the Microdot app so Stop can call shutdown()."""
_app = None
def register_app(app):
global _app
_app = app
def get_app():
return _app
def clear_app():
global _app
_app = None
+85
View File
@@ -0,0 +1,85 @@
"""Give led-controller the simulator's rig layout once its strips have registered.
The layout is the simulator's (``layout`` in sim.json, see ``layout.rig_placements``). Only strips the
controller has no placement for are sent, so moving bars in the controller's rig-layout page sticks:
the simulator page then draws them where the controller put them (each driver's ``place``).
"""
from __future__ import annotations
import json
import threading
import time
import urllib.request
from layout import rig_placements
def _get(url: str, timeout: float = 3):
with urllib.request.urlopen(url, timeout=timeout) as r:
return json.loads(r.read())
def _post(url: str, body: dict, timeout: float = 15):
req = urllib.request.Request(
url, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}, method="POST"
)
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read())
def controller_url(cfg: dict, peer_ip: str) -> str | None:
"""The controller's web API: ``controller.url`` in sim.json, else the bridge peer on 8080 or 80."""
url = (cfg.get("controller") or {}).get("url")
candidates = [url] if url else ["http://%s:8080" % peer_ip, "http://%s" % peer_ip]
for base in candidates:
try:
_get(base.rstrip("/") + "/status", timeout=2)
return base.rstrip("/")
except (OSError, ValueError):
continue
return None
def seed(cfg: dict, macs: dict[int, str], peer_ip: str, log=print, wait_s: float = 180) -> dict | None:
"""Wait for the strips to register, then send placements for the unplaced ones. Returns the reply."""
if (cfg.get("controller") or {}).get("seed_layout", True) is False:
return None
base = controller_url(cfg, peer_ip)
if base is None:
log("[layout] controller web API not found at %s (set controller.url in sim.json)" % peer_ip)
return None
want = {i: m.replace(":", "").lower() for i, m in macs.items()}
end = time.monotonic() + wait_s
devs = {}
while time.monotonic() < end:
try:
devs = _get(base + "/devices")
except (OSError, ValueError):
devs = {}
if all(m in devs for m in want.values()):
break
time.sleep(1)
places, center = rig_placements(cfg["layout"])
todo = {
m: places[i]
for i, m in want.items()
if m in devs and not isinstance(devs[m].get("placement"), dict)
}
if not todo:
log("[layout] controller already has every strip placed")
return None
body = {"placements": todo}
if not any(isinstance(d, dict) and isinstance(d.get("placement"), dict) for d in devs.values()):
body["center"] = center # a fresh rig: the simulator's centre too
try:
reply = _post(base + "/devices/layout", body)
except (OSError, ValueError) as e:
log("[layout] sending the rig layout failed: %s" % e)
return None
log("[layout] sent %d strip placements to %s: %s" % (len(todo), base, reply))
return reply
def seed_soon(cfg: dict, macs: dict[int, str], peer_ip: str, log=print) -> None:
threading.Thread(target=seed, args=(cfg, macs, peer_ip, log), name="rig-seed", daemon=True).start()
+541
View File
@@ -0,0 +1,541 @@
#!/usr/bin/env python3
"""led-simulator web app: a simulated Wi-Fi ESP-NOW bridge plus a browser rig.
One Microdot server (from ``led-driver/lib``, no extra installs) provides:
- UDP ``8766`` the bridge for led-controller's ``settings.bridge`` (and its host build,
``sim-controller/``): ``dst_mac + packet`` down, ``src_mac + packet`` up.
- ``/ws`` the older bridge WebSocket, same protocol as
``bridge-wifi``: binary wire packets are broadcast, v1 JSON envelopes are
split per MAC, and driver transmissions go up as ``0x00 + mac + packet``.
- ``/`` the simulator page. Every strip is a led-driver running the real
``led-driver/src/main.py`` and patterns in Pyodide, one web worker each.
- ``/sim`` the page's radio link: the server hands it the ESP-NOW packets the
bridge would transmit and takes back what the drivers transmit.
Strips register with the controller the way hardware does: each driver sends
its JSON hello once when it powers on. A strip that boots while no controller
is connected has to be power-cycled to register.
Run from the repository root::
python3 led-simulator/server.py # http://localhost:8765/
"""
from __future__ import annotations
import argparse
import asyncio
import json
import socket
import sys
from pathlib import Path
SIM_ROOT = Path(__file__).resolve().parent
REPO_ROOT = SIM_ROOT.parent
DRIVER_ROOT = REPO_ROOT / "led-driver"
DRIVER_SRC = DRIVER_ROOT / "src"
DRIVER_LIB = DRIVER_ROOT / "lib"
WEB_ROOT = SIM_ROOT / "web"
STUBS_ROOT = SIM_ROOT / "stubs"
WORKSPACE = SIM_ROOT / "workspace"
DRIVERS_DIR = WORKSPACE / "drivers"
SIM_DEFAULTS = SIM_ROOT / "sim.default.json"
SIM_CONFIG = WORKSPACE / "sim.json"
DRIVER_SETTINGS_TEMPLATE = SIM_ROOT / "settings.default.json"
sys.path.insert(0, str(SIM_ROOT))
sys.path.insert(0, str(DRIVER_LIB))
from layout import normalise_layout, side_name, strip_places # noqa: E402
from rig_seed import seed, seed_soon # noqa: E402
BROADCAST = b"\xff\xff\xff\xff\xff\xff"
WIRE = 0x4C
MAX_ESPNOW = 250
# Locally administered MACs 02:51:4d:00:00:NN. The bridge is NN=00.
MAC_PREFIX = bytes([0x02, 0x51, 0x4D, 0x00, 0x00])
BRIDGE_MAC = MAC_PREFIX + b"\x00"
# Files a driver may persist in its simulated flash (workspace/drivers/NN/).
# Patterns are not persisted: every boot loads led-driver/src/patterns.
FLASH_FILES = ("settings.json", "presets.json")
BUILTIN_DEFAULTS = {
"bridge": {
"name": "bridge-sim",
"host": "0.0.0.0",
"ws_port": 8765,
"wifi_channel": 5,
"debug": False,
},
"layout": {},
"drivers": {
"name": "sim-{n:02d}",
"fps": 30,
"loop_sleep_ms": 2,
"boot_concurrency": 4,
},
"pyodide_url": "https://cdn.jsdelivr.net/pyodide/v0.26.4/full/",
}
CONTENT_TYPES = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".mjs": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json",
".svg": "image/svg+xml",
".png": "image/png",
".ico": "image/x-icon",
".py": "text/x-python; charset=utf-8",
}
def mac_str(mac: bytes) -> str:
return ":".join("%02x" % b for b in mac)
def driver_mac(index: int) -> bytes:
return MAC_PREFIX + bytes([(index + 1) & 0xFF])
def _merge(base: dict, extra: dict) -> dict:
out = dict(base)
for k, v in (extra or {}).items():
if isinstance(v, dict) and isinstance(out.get(k), dict):
out[k] = _merge(out[k], v)
else:
out[k] = v
return out
def _read_json(path: Path) -> dict:
try:
with open(path, encoding="utf-8") as f:
data = json.load(f)
return data if isinstance(data, dict) else {}
except (OSError, ValueError):
return {}
def load_config() -> dict:
"""Built-in defaults <- sim.default.json <- workspace/sim.json."""
WORKSPACE.mkdir(parents=True, exist_ok=True)
cfg = _merge(BUILTIN_DEFAULTS, _read_json(SIM_DEFAULTS))
cfg = _merge(cfg, _read_json(SIM_CONFIG))
cfg["layout"] = normalise_layout(cfg.get("layout"))
return cfg
def lan_ip() -> str:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(("10.255.255.255", 1))
return s.getsockname()[0]
except OSError:
return "127.0.0.1"
finally:
s.close()
def bridge_downlink(raw: bytes, debug: bool = False) -> list[tuple[bytes, bytes]]:
"""What the bridge transmits for one controller WebSocket message.
Same rules as ``bridge-wifi/src/main.py`` ``downlink``. Returns a list of
``(dest_mac, espnow_packet)``.
"""
out: list[tuple[bytes, bytes]] = []
n = len(raw)
if not raw:
return out
if raw[0] == WIRE:
if n < 2 or n > MAX_ESPNOW:
if debug:
print("[bridge] dl skip wire", n)
return out
out.append((BROADCAST, bytes(raw)))
return out
if n < 8 or raw[:1] != b"{":
return out
try:
data = json.loads(raw)
except ValueError:
return out
if not isinstance(data, dict):
return out
devs = data.get("dv") or data.get("devices")
if data.get("v") != "1" or not isinstance(devs, dict):
return out
for mac_s, body in devs.items():
if not isinstance(body, dict):
continue
h = str(mac_s).replace(":", "").replace("-", "").strip().lower()
try:
dest = BROADCAST if h == "ffffffffffff" else bytes.fromhex(h)
except ValueError:
continue
if len(dest) != 6:
continue
msg = {"v": "1"}
msg.update(body)
pkt = json.dumps(msg, separators=(",", ":")).encode()
if len(pkt) > MAX_ESPNOW:
if debug:
print("[bridge] dl skip big", len(pkt))
continue
out.append((dest, pkt))
return out
class Rig:
"""Strip list, simulated flash on disk, and the two WebSocket sides."""
def __init__(self, cfg: dict):
self.cfg = cfg
self.layout = cfg["layout"]
self.debug = bool(cfg["bridge"].get("debug", False))
self.places = strip_places(self.layout)
self.strips = []
name_fmt = str(cfg["drivers"].get("name", "sim-{n:02d}"))
for p in self.places:
default_name = name_fmt.format(
n=p.number,
row=p.row + 1,
col=p.col + 1,
side=side_name(p.col, self.layout["columns"]),
)
self.strips.append(
{
"index": p.index,
"n": p.number,
"row": p.row,
"col": p.col,
"leds": p.leds,
"reversed": p.reversed,
"mac": mac_str(driver_mac(p.index)),
"default_name": default_name,
"dir": DRIVERS_DIR / ("%02d" % p.number),
}
)
self.controllers: set = set()
self.page = None
self.udp = None # asyncio datagram transport
self.udp_peer = None # the controller that last sent a datagram
self.hellos: dict[bytes, bytes] = {} # mac -> boot hello, replayed to a new UDP controller
self.port = int(cfg["bridge"]["ws_port"])
# ----- flash ----------------------------------------------------------
def flash(self, index: int) -> dict:
"""Read (creating on first use) a strip's settings.json and presets.json."""
s = self.strips[index]
d: Path = s["dir"]
d.mkdir(parents=True, exist_ok=True)
template = _read_json(DRIVER_SETTINGS_TEMPLATE)
current = _read_json(d / "settings.json")
settings = dict(template)
settings.update(current)
if not current.get("name"):
settings["name"] = s["default_name"]
# Strip length is physical: the layout decides it.
settings["num_leds"] = s["leds"]
settings["wifi_channel"] = int(self.cfg["bridge"].get("wifi_channel", 5))
settings_text = json.dumps(settings)
(d / "settings.json").write_text(settings_text, encoding="utf-8")
presets_path = d / "presets.json"
if not presets_path.is_file():
presets_path.write_text("{}", encoding="utf-8")
return {
"settings.json": settings_text,
"presets.json": presets_path.read_text(encoding="utf-8"),
}
def write_flash(self, index, path, data) -> bool:
try:
index = int(index)
except (TypeError, ValueError):
return False
if not (0 <= index < len(self.strips)) or path not in FLASH_FILES:
return False
if not isinstance(data, str) or len(data) > 512 * 1024:
return False
d: Path = self.strips[index]["dir"]
d.mkdir(parents=True, exist_ok=True)
tmp = d / (path + ".tmp")
tmp.write_text(data, encoding="utf-8")
tmp.replace(d / path)
return True
def bundle(self) -> dict:
"""Files for a driver's flash: led-driver/src (with patterns) and stubs."""
driver = {}
for f in sorted(DRIVER_SRC.rglob("*.py")):
rel = f.relative_to(DRIVER_SRC).as_posix()
if "__pycache__" in rel:
continue
driver[rel] = f.read_text(encoding="utf-8")
stubs = {}
for f in sorted(STUBS_ROOT.glob("*.py")):
stubs[f.name] = f.read_text(encoding="utf-8")
return {"driver": driver, "stubs": stubs}
def public_config(self) -> dict:
return {
"bridge": {
"name": self.cfg["bridge"]["name"],
"mac": mac_str(BRIDGE_MAC),
"port": self.port,
"udp_port": int(self.cfg["bridge"].get("udp_port", 8766)),
"lan_ip": lan_ip(),
"wifi_channel": int(self.cfg["bridge"].get("wifi_channel", 5)),
},
"layout": self.layout,
"drivers": {
k: self.cfg["drivers"][k]
for k in ("fps", "loop_sleep_ms", "boot_concurrency")
if k in self.cfg["drivers"]
},
"pyodide_url": self.cfg["pyodide_url"],
"strips": [
dict({k: v for k, v in s.items() if k != "dir"},
place=_read_json(s["dir"] / "settings.json").get("place"))
for s in self.strips
],
}
# ----- radio ------------------------------------------------------------
async def to_page(self, frame):
page = self.page
if page is None:
return
try:
await page.send(frame)
except Exception:
if self.page is page:
self.page = None
async def page_status(self):
n = len(self.controllers) + (1 if self.udp_peer is not None else 0)
await self.to_page(json.dumps({"t": "status", "controllers": n}))
async def from_controller(self, raw: bytes):
for dest, pkt in bridge_downlink(raw, self.debug):
if self.debug:
print("[bridge] dl", mac_str(dest), len(pkt))
# Nobody listening (page closed) = radio packet lost, as on air.
await self.to_page(dest + pkt)
def from_udp(self, data: bytes, addr):
if len(data) < 7:
return
if addr != self.udp_peer:
self.udp_peer = addr
print("[bridge] udp controller %s:%d" % addr)
seed_soon(self.cfg, {s["index"]: s["mac"] for s in self.strips}, addr[0])
asyncio.ensure_future(self.page_status())
for mac, pkt in self.hellos.items():
self.udp.sendto(mac + pkt, addr)
if self.debug:
print("[bridge] udp dl", mac_str(data[:6]), len(data) - 6)
asyncio.ensure_future(self.to_page(bytes(data)))
async def from_page(self, frame: bytes):
"""``src_mac + packet`` from a driver: the bridge forwards it up."""
if len(frame) < 7:
return
if frame[6:7] == b"{" or frame[6:8] == bytes([0x4C, 0x01]):
self.hellos[frame[:6]] = frame[6:]
if self.udp is not None and self.udp_peer is not None:
self.udp.sendto(frame, self.udp_peer)
up = bytes([0]) + frame
if self.debug:
print("[bridge] up", mac_str(frame[:6]), len(frame) - 6)
for ws in list(self.controllers):
try:
await ws.send(up)
except Exception:
self.controllers.discard(ws)
def build_app(rig: Rig):
from microdot import Microdot, Response, send_file
from microdot.websocket import WebSocketError, with_websocket
app = Microdot()
@app.after_request
async def isolation_headers(request, response):
# SharedArrayBuffer (driver packet rings) needs a cross-origin isolated
# page. credentialless keeps the Pyodide CDN loading, as in led-editor.
if response is not None and response is not Response.already_handled:
response.headers["Cross-Origin-Opener-Policy"] = "same-origin"
response.headers["Cross-Origin-Embedder-Policy"] = "credentialless"
response.headers["Cache-Control"] = "no-cache"
return response
def static(path: Path):
try:
path = path.resolve()
path.relative_to(WEB_ROOT.resolve())
except (OSError, ValueError):
return "Not found", 404
if not path.is_file():
return "Not found", 404
ctype = CONTENT_TYPES.get(path.suffix.lower(), "application/octet-stream")
return send_file(str(path), content_type=ctype)
@app.route("/")
async def index(request):
return static(WEB_ROOT / "index.html")
@app.route("/web/<path:path>")
async def web(request, path):
return static(WEB_ROOT / path)
@app.route("/api/seed-layout", methods=["POST"])
async def api_seed_layout(request):
"""Send the simulator's layout to the controller for every unplaced strip, now."""
if rig.udp_peer is None:
return {"error": "no controller on the UDP bridge yet"}, 409
macs = {s["index"]: s["mac"] for s in rig.strips}
reply = await asyncio.to_thread(seed, rig.cfg, macs, rig.udp_peer[0], print, 30)
return {"sent": reply}
@app.route("/api/config")
async def api_config(request):
return rig.public_config()
@app.route("/api/bundle")
async def api_bundle(request):
return rig.bundle()
@app.route("/api/flash/<int:index>")
async def api_flash(request, index):
if not (0 <= index < len(rig.strips)):
return {"error": "no such strip"}, 404
return rig.flash(index)
@app.route("/ws")
@with_websocket
async def controller_ws(request, ws):
rig.controllers.add(ws)
print("[bridge] controller + (%d)" % len(rig.controllers))
await rig.page_status()
try:
while True:
try:
raw = await ws.receive()
except WebSocketError:
break
if not raw:
break
if isinstance(raw, str):
raw = raw.encode("utf-8")
await rig.from_controller(raw)
finally:
rig.controllers.discard(ws)
print("[bridge] controller - (%d)" % len(rig.controllers))
await rig.page_status()
@app.route("/sim")
@with_websocket
async def page_ws(request, ws):
old = rig.page
rig.page = ws
if old is not None:
try:
await old.send(json.dumps({"t": "takeover"}))
await old.close()
except Exception:
pass
print("[sim] page connected")
await rig.page_status()
try:
while True:
try:
msg = await ws.receive()
except WebSocketError:
break
if not msg:
break
if rig.page is not ws:
break
if isinstance(msg, (bytes, bytearray)):
await rig.from_page(bytes(msg))
continue
try:
data = json.loads(msg)
except ValueError:
continue
if isinstance(data, dict) and data.get("t") == "flash":
rig.write_flash(data.get("n"), data.get("path"), data.get("data"))
finally:
if rig.page is ws:
rig.page = None
print("[sim] page disconnected")
return app
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("--port", type=int, help="HTTP + bridge WebSocket port (default 8765)")
ap.add_argument("--host", help="listen address (default 0.0.0.0)")
ap.add_argument("--udp-port", type=int, help="UDP bridge port (default 8766, 0 = off)")
ap.add_argument("--debug", action="store_true", help="log every bridge packet")
args = ap.parse_args(argv)
if not (DRIVER_SRC / "main.py").is_file():
print("led-driver/src/main.py not found next to led-simulator.", file=sys.stderr)
return 1
try:
import microdot # noqa: F401
except ImportError:
print("Microdot not found in led-driver/lib.", file=sys.stderr)
return 1
cfg = load_config()
if args.port:
cfg["bridge"]["ws_port"] = args.port
if args.host:
cfg["bridge"]["host"] = args.host
if args.debug:
cfg["bridge"]["debug"] = True
if args.udp_port is not None:
cfg["bridge"]["udp_port"] = args.udp_port
rig = Rig(cfg)
app = build_app(rig)
udp_port = int(cfg["bridge"].get("udp_port", 8766))
host = str(cfg["bridge"]["host"])
port = rig.port
lay = rig.layout
print(
"led-simulator: %d strips x %d LEDs (%d x %d)"
% (len(rig.strips), lay["leds_per_strip"], lay["columns"], lay["rows"])
)
print(" simulator page: http://localhost:%d/" % port)
if udp_port:
print(" bridge for led-controller: settings.bridge \"%s:%d\" (or 127.0.0.1:%d)" % (lan_ip(), udp_port, udp_port))
class Udp(asyncio.DatagramProtocol):
def datagram_received(self, data, addr):
rig.from_udp(data, addr)
async def run():
if udp_port:
rig.udp, _ = await asyncio.get_running_loop().create_datagram_endpoint(
Udp, local_addr=(host, udp_port)
)
await app.start_server(host=host, port=port)
try:
asyncio.run(run())
except KeyboardInterrupt:
pass
return 0
if __name__ == "__main__":
sys.exit(main())
+13
View File
@@ -0,0 +1,13 @@
{
"led_pin": 10,
"num_leds": 119,
"color_order": "rgb",
"debug": false,
"default": "on",
"last_preset": "",
"startup_mode": "default",
"brightness": 255,
"reversed": false,
"wifi_channel": 5,
"groups": []
}
+28
View File
@@ -0,0 +1,28 @@
{
"bridge": {
"name": "bridge-sim",
"host": "0.0.0.0",
"ws_port": 8765,
"udp_port": 8766,
"wifi_channel": 5,
"debug": false
},
"layout": {
"rows": 8,
"columns": 2,
"leds_per_strip": 119,
"order": "row",
"start": "center"
},
"drivers": {
"name": "sim-{n:02d}",
"fps": 30,
"loop_sleep_ms": 2,
"boot_concurrency": 4
},
"pyodide_url": "https://cdn.jsdelivr.net/pyodide/v0.26.4/full/",
"controller": {
"url": null,
"seed_layout": true
}
}
+83
View File
@@ -0,0 +1,83 @@
#!/usr/bin/env python3
"""Run one simulated led-driver (one strip) in its own process.
Started by ``bridge_sim.py``; not normally run by hand. Runs the real
``led-driver/src/main.py`` as ``__main__``, with:
- ``stubs/`` first on ``sys.path`` (machine, neopixel, network, espnow, ...)
- the driver's own folder ``workspace/drivers/NN`` as its flash root (cwd):
``settings.json``, ``presets.json`` and ``patterns/`` live there
- ESP-NOW and pixel output carried to the bridge simulator by ``_simlink``
Environment (set by the bridge): ``LED_SIM_INDEX``, ``LED_SIM_MAC``,
``LED_SIM_DIR``, ``LED_SIM_ADDR`` (host:port), ``LED_SIM_AUTH`` (hex),
``LED_SIM_FPS``, ``LED_SIM_LOOP_SLEEP_MS``.
"""
import os
import runpy
import sys
from pathlib import Path
SIM_ROOT = Path(__file__).resolve().parent
STUBS_ROOT = SIM_ROOT / "stubs"
DRIVER_ROOT = SIM_ROOT.parent / "led-driver"
DRIVER_SRC = DRIVER_ROOT / "src"
DRIVER_LIB = DRIVER_ROOT / "lib"
DRIVER_MAIN = DRIVER_SRC / "main.py"
def main():
index = int(os.environ["LED_SIM_INDEX"])
drv_dir = Path(os.environ["LED_SIM_DIR"]).resolve()
host, port = os.environ["LED_SIM_ADDR"].rsplit(":", 1)
authkey = bytes.fromhex(os.environ["LED_SIM_AUTH"])
fps = float(os.environ.get("LED_SIM_FPS", "30"))
os.chdir(drv_dir)
log = open(drv_dir / "driver.log", "w", buffering=1, encoding="utf-8")
sys.stdout = log
sys.stderr = log
import faulthandler
import signal
faulthandler.register(signal.SIGUSR1, file=log, all_threads=True) # kill -USR1 <pid>: stacks to driver.log
# MicroPython search order is cwd (flash root) then /lib. Stubs go first so
# they replace the hardware modules; the driver folder comes before src so
# its patterns/ package (OTA target) wins over led-driver/src/patterns.
sys.path[:] = [
str(STUBS_ROOT),
str(drv_dir),
str(DRIVER_LIB),
str(DRIVER_SRC),
] + [p for p in sys.path[1:] if p]
import gc
if not hasattr(gc, "mem_free"):
gc.mem_free = lambda: 256 * 1024
gc.mem_alloc = lambda: 64 * 1024
import _simlink
_simlink.connect((host, int(port)), authkey, index, fps=fps)
import settings as led_settings
led_settings.Settings.SETTINGS_FILE = str(drv_dir / "settings.json")
runpy.run_path(str(DRIVER_MAIN), run_name="__main__")
if __name__ == "__main__":
try:
main()
except SystemExit:
raise
except BaseException:
import traceback
traceback.print_exc()
sys.stdout.flush()
raise SystemExit(1)
+12
View File
@@ -0,0 +1,12 @@
"""Driver side of the simulator link: radio, pixels, flash and sleeps.
In the browser (Pyodide) this is ``_simlink_web``. Under CPython (``bridge_sim.py`` /
``sim_driver.py``) it is ``_simlink_proc``: a multiprocessing connection to the bridge.
"""
try:
import js # noqa: F401 (Pyodide only)
except ImportError:
from _simlink_proc import * # noqa: F401,F403
else:
from _simlink_web import * # noqa: F401,F403
+111
View File
@@ -0,0 +1,111 @@
"""CPython link between one simulated led-driver process and ``bridge_sim.py``.
Frames on the multiprocessing connection (first byte is the kind):
- driver -> bridge: ``H`` + index (once), ``P`` + RGB bytes, ``T`` + dest_mac(6) + packet
- bridge -> driver: ``R`` + src_mac(6) + packet
"""
import threading
import time
from collections import deque
from multiprocessing.connection import Client
_conn = None
_rx = deque()
_rx_cond = threading.Condition()
_tx_lock = threading.Lock()
_px_period = 1 / 30.0
_last_px = 0.0
_pixels = None
_pixels_dirty = False
def connect(address, authkey, index, fps=30):
global _conn, _px_period
_px_period = 1.0 / max(1.0, float(fps))
_conn = Client(address, authkey=authkey)
_conn.send_bytes(b"H" + bytes([index]))
threading.Thread(target=_reader, daemon=True).start()
def _reader():
import os
while True:
try:
frame = _conn.recv_bytes()
except (EOFError, OSError):
os._exit(0) # bridge gone: power off
if frame[:1] == b"R" and len(frame) >= 7:
with _rx_cond:
_rx.append((frame[1:7], frame[7:]))
_rx_cond.notify()
def connected():
return _conn is not None
def real_sleep(seconds):
if seconds > 0:
time.sleep(seconds)
def recv_nowait():
with _rx_cond:
if _rx:
return _rx.popleft()
return (None, None)
def recv(timeout_ms=0):
with _rx_cond:
if not _rx and timeout_ms:
_rx_cond.wait(None if timeout_ms < 0 else timeout_ms / 1000.0)
if _rx:
return _rx.popleft()
return (None, None)
def pending():
return len(_rx)
def send_tx(dest_mac, packet):
with _tx_lock:
_conn.send_bytes(b"T" + bytes(dest_mac) + bytes(packet))
def _send_pixels():
global _pixels_dirty, _last_px
_pixels_dirty = False
_last_px = time.monotonic()
with _tx_lock:
_conn.send_bytes(b"P" + _pixels)
def push_pixels(buf):
global _pixels, _pixels_dirty
data = bytearray(len(buf) * 3)
j = 0
for r, g, b in buf:
data[j] = r
data[j + 1] = g
data[j + 2] = b
j += 3
_pixels = bytes(data)
_pixels_dirty = True
if time.monotonic() - _last_px >= _px_period:
_send_pixels()
def start_new_thread(fn, args, kwargs=None):
t = threading.Thread(target=fn, args=tuple(args), kwargs=kwargs or {}, daemon=True)
t.start()
return t.ident
def on_feed():
if _pixels_dirty and time.monotonic() - _last_px >= _px_period:
_send_pixels()
+177
View File
@@ -0,0 +1,177 @@
"""Link between one simulated led-driver (Pyodide, in a web worker) and the page (via ``_simlink``).
Not a MicroPython module. ``web/driver-worker.js`` defines these functions on
the worker global before the driver boots:
- ``simRecv()`` next received ESP-NOW frame ``src_mac(6) + packet`` as a
Uint8Array, or ``undefined``. Frames come from a
SharedArrayBuffer ring the page writes, so they arrive even
though ``main.py`` never yields to the JS event loop.
- ``simPending()`` number of frames waiting in the ring
- ``simTx(u8)`` transmit ``dest_mac(6) + packet``
- ``simPixels(u8)`` latest strip frame, RGB bytes
- ``simFlash(path, text)`` persist a flash file (settings.json, presets.json)
- ``simSleep(ms)`` block without spinning (``Atomics.wait``)
``machine.WDT.feed()`` calls :func:`on_feed` once per driver main-loop pass.
"""
import os
import random
import time
import js
FLASH_FILES = ("settings.json", "presets.json")
_fps = max(1.0, float(os.environ.get("LED_SIM_FPS", "30")))
_px_period = 1.0 / _fps
_pixels = None
_pixels_dirty = False
_last_px = 0.0
_jobs = [] # [due, fn, args]
_in_job = False
_flash_seen = {}
_last_flash_check = 0.0
def _u8(data):
arr = js.Uint8Array.new(len(data))
arr.assign(data)
return arr
def connected():
return True
# ----- time ---------------------------------------------------------------
def real_sleep(seconds):
"""Replacement for ``time.sleep``. Skipped inside deferred jobs (see defer)."""
if _in_job or seconds <= 0:
return
js.simSleep(float(seconds) * 1000.0)
# ----- radio --------------------------------------------------------------
def recv_nowait():
frame = js.simRecv()
if frame is None:
return (None, None)
data = bytes(frame.to_bytes())
if len(data) < 6:
return (None, None)
return (data[:6], data[6:])
def recv(timeout_ms=0):
host, msg = recv_nowait()
if host is not None or timeout_ms == 0:
return host, msg
deadline = None if timeout_ms is None or timeout_ms < 0 else time.monotonic() + timeout_ms / 1000.0
while True:
real_sleep(0.001)
host, msg = recv_nowait()
if host is not None:
return host, msg
if deadline is not None and time.monotonic() >= deadline:
return (None, None)
def pending():
return int(js.simPending())
def send_tx(dest_mac, packet):
js.simTx(_u8(bytes(dest_mac) + bytes(packet)))
# ----- pixels -------------------------------------------------------------
def _send_pixels():
global _pixels_dirty, _last_px
_pixels_dirty = False
_last_px = time.monotonic()
js.simPixels(_u8(_pixels))
def push_pixels(buf):
"""``buf``: list of (r, g, b). Sent at most ``LED_SIM_FPS`` times a second."""
global _pixels, _pixels_dirty
data = bytearray(len(buf) * 3)
j = 0
for r, g, b in buf:
data[j] = r
data[j + 1] = g
data[j + 2] = b
j += 3
_pixels = bytes(data)
_pixels_dirty = True
if time.monotonic() - _last_px >= _px_period:
_send_pixels()
# ----- background work ----------------------------------------------------
def start_new_thread(fn, args, kwargs=None):
"""``_thread.start_new_thread`` stand-in: there are no threads in Pyodide.
led-driver uses a thread only to answer pings after a random 50-500 ms
delay. The job runs from the main loop after a delay in that range, with
its own sleeps skipped so the strip keeps animating meanwhile.
"""
_jobs.append([time.monotonic() + random.uniform(0.05, 0.5), fn, tuple(args), kwargs or {}])
return len(_jobs)
def _run_jobs(now):
global _in_job
if not _jobs:
return
due = [j for j in _jobs if j[0] <= now]
if not due:
return
for j in due:
_jobs.remove(j)
_in_job = True
try:
j[1](*j[2], **j[3])
except Exception as e: # noqa: BLE001
print("sim job error:", e)
finally:
_in_job = False
def _check_flash(now):
global _last_flash_check
if now - _last_flash_check < 1.0:
return
_last_flash_check = now
for name in FLASH_FILES:
try:
with open(name, "r") as f:
text = f.read()
except OSError:
continue
if name not in _flash_seen:
_flash_seen[name] = text
continue
if _flash_seen[name] != text:
_flash_seen[name] = text
js.simFlash(name, text)
def on_feed():
now = time.monotonic()
if _pixels_dirty and now - _last_px >= _px_period:
_send_pixels()
_run_jobs(now)
_check_flash(now)
+79
View File
@@ -0,0 +1,79 @@
"""MicroPython ``espnow`` stub for led-simulator (Pyodide).
Packets go to and from the simulated bridge through ``_simlink``. ``irq()`` is
not supported, so ``main.py`` falls back to polling ``any()`` / ``recv(0)`` in
its main loop, as it does on boards without the irq callback.
"""
import _simlink
MAX_DATA_LEN = 250
ESP_ERR_ESPNOW_EXIST = -12395
ESP_ERR_ESPNOW_NOT_FOUND = -12393
_BROADCAST = b"\xff\xff\xff\xff\xff\xff"
class ESPNow:
def __init__(self):
self._active = False
self._peers = set()
self._timeout_ms = 300000
def active(self, flag=None):
if flag is None:
return self._active
self._active = bool(flag)
return self._active
def config(self, *args, **kwargs):
if "timeout_ms" in kwargs:
self._timeout_ms = int(kwargs["timeout_ms"])
return None
def add_peer(self, mac, *args, **kwargs):
mac = bytes(mac)
if mac in self._peers:
raise OSError(ESP_ERR_ESPNOW_EXIST, "ESP_ERR_ESPNOW_EXIST")
self._peers.add(mac)
def del_peer(self, mac):
mac = bytes(mac)
if mac not in self._peers:
raise OSError(ESP_ERR_ESPNOW_NOT_FOUND, "ESP_ERR_ESPNOW_NOT_FOUND")
self._peers.discard(mac)
def get_peers(self):
return tuple((m, b"", 0, 0, False) for m in self._peers)
def send(self, mac, msg=None, sync=True):
if msg is None:
# send(msg): to every registered peer
msg, dests = mac, list(self._peers) or [_BROADCAST]
else:
dests = [_BROADCAST if mac is None else bytes(mac)]
if isinstance(msg, str):
msg = msg.encode("utf-8")
msg = bytes(msg)
if len(msg) > MAX_DATA_LEN:
raise ValueError("ESP_ERR_ESPNOW_ARG")
for dest in dests:
_simlink.send_tx(dest, msg)
return True
def recv(self, timeout_ms=None):
if timeout_ms is None:
timeout_ms = self._timeout_ms
return _simlink.recv(timeout_ms)
irecv = recv
def any(self):
return _simlink.pending() > 0
def irq(self, callback):
# main.py treats AttributeError as "firmware without irq support" and polls instead
raise AttributeError("espnow irq not available in led-simulator (polling)")
def stats(self):
return (0, 0, 0, 0, 0)
+89
View File
@@ -0,0 +1,89 @@
"""MicroPython ``machine`` stub for led-simulator (Pyodide)."""
import os
import time
try:
import _simlink
except ImportError: # outside the simulator
_simlink = None
PWRON_RESET = 1
HARD_RESET = 2
WDT_RESET = 3
DEEPSLEEP_RESET = 4
SOFT_RESET = 5
# SystemExit code that tells the page to boot this driver again (machine.reset()).
RESET_EXIT_CODE = 75
# The driver main loop calls wdt.feed() once per pass with no sleep. A short
# sleep here keeps 16 simulated drivers from pinning every CPU core, and the
# feed is where the simulator flushes pixels and flash writes.
_LOOP_SLEEP_S = max(0.0, float(os.environ.get("LED_SIM_LOOP_SLEEP_MS", "2")) / 1000.0)
_freq = 160000000
class Pin:
OUT = 1
IN = 0
PULL_UP = 1
PULL_DOWN = 2
def __init__(self, pin_id, mode=None, *, pull=None, value=None):
self.id = pin_id
self.mode = mode
self._value = value or 0
def value(self, v=None):
if v is None:
return self._value
self._value = 1 if v else 0
return None
def on(self):
self._value = 1
def off(self):
self._value = 0
class WDT:
def __init__(self, id=0, timeout=10000):
self._timeout = timeout
def feed(self):
if _LOOP_SLEEP_S:
time.sleep(_LOOP_SLEEP_S)
if _simlink is not None:
_simlink.on_feed()
def freq(hz=None):
global _freq
if hz is None:
return _freq
_freq = int(hz)
return None
def reset():
raise SystemExit(RESET_EXIT_CODE)
def soft_reset():
raise SystemExit(RESET_EXIT_CODE)
def reset_cause():
return PWRON_RESET
def unique_id():
mac = os.environ.get("LED_SIM_MAC", "aabbccddeeff")
return bytes.fromhex(mac)
def idle():
time.sleep(0.001)
+52
View File
@@ -0,0 +1,52 @@
"""Host NeoPixel with MicroPython's semantics: a ``buf`` bytearray in ``ORDER`` (GRB), which led-driver
writes directly. ``write()`` sends the frame to the simulator as RGB."""
import _simlink
# Optional extra hook: callable(list[tuple[int, int, int]]) -> None
PIXEL_SINK = None
class NeoPixel:
ORDER = (1, 0, 2, 3) # as MicroPython: buf holds G, R, B (, W)
def __init__(self, pin, n, bpp=3, timing=1):
self.pin = pin
self.n = n
self.bpp = bpp
self.timing = timing
self.buf = bytearray(n * bpp)
def __len__(self):
return self.n
def __setitem__(self, index, value):
if index < 0:
index += self.n
off = index * self.bpp
for j in range(self.bpp):
self.buf[off + self.ORDER[j]] = int(value[j]) & 255
def __getitem__(self, index):
if index < 0:
index += self.n
off = index * self.bpp
return tuple(self.buf[off + self.ORDER[j]] for j in range(self.bpp))
def fill(self, color):
px = bytearray(self.bpp)
for j in range(self.bpp):
px[self.ORDER[j]] = int(color[j]) & 255
self.buf[:] = px * self.n
def _rgb(self):
b, bpp, o = self.buf, self.bpp, self.ORDER
return [(b[i + o[0]], b[i + o[1]], b[i + o[2]]) for i in range(0, self.n * bpp, bpp)]
def write(self):
if _simlink.connected() or PIXEL_SINK is not None:
px = self._rgb()
if _simlink.connected():
_simlink.push_pixels(px)
if PIXEL_SINK is not None:
PIXEL_SINK(px)
+57
View File
@@ -0,0 +1,57 @@
"""Minimal ``network`` stub so imports succeed (led-simulator).
Each simulated driver gets its own MAC from ``LED_SIM_MAC`` (12 hex digits).
"""
import os
STA_IF = 0
AP_IF = 1
_SIM_MAC = bytes.fromhex(os.environ.get("LED_SIM_MAC", "aabbccddeeff"))
_channel = 1
class WLAN:
PM_NONE = 0
PM_PERFORMANCE = 1
PM_POWERSAVE = 2
def __init__(self, interface=STA_IF):
self._interface = interface
self._active = False
def active(self, is_active=None):
if is_active is None:
return self._active
self._active = bool(is_active)
return None
def config(self, param=None, **kwargs):
global _channel
if "channel" in kwargs:
_channel = int(kwargs["channel"])
if param == "mac":
return _SIM_MAC
if param == "channel":
return _channel
if param == "essid":
return ""
return None
def connect(self, *args, **kwargs):
return None
def disconnect(self):
return None
def isconnected(self):
return True
def status(self, param=None):
return 1010 # STAT_GOT_IP
def ifconfig(self, config_tuple=None):
if config_tuple is None:
return ("192.168.4.%d" % (10 + _SIM_MAC[-1] % 200), "255.255.255.0", "192.168.4.1", "8.8.8.8")
return None
+6
View File
@@ -0,0 +1,6 @@
"""Map MicroPython `ubinascii` to CPython `binascii`."""
import binascii
hexlify = binascii.hexlify
unhexlify = binascii.unhexlify
+8
View File
@@ -0,0 +1,8 @@
"""Map MicroPython ``urandom`` to CPython ``random`` (led-simulator)."""
from random import choice, randint, random, randrange, seed, uniform # noqa: F401
from random import getrandbits as _getrandbits
def getrandbits(n):
return _getrandbits(int(n)) if n > 0 else 0
+49
View File
@@ -0,0 +1,49 @@
"""CPython stub for MicroPython ``utime`` (led-simulator)."""
import time as _time
_MS_PERIOD = 1 << 30
_MS_MASK = _MS_PERIOD - 1
_HALF = _MS_PERIOD // 2
_T0 = _time.monotonic()
def sleep_ms(ms):
_time.sleep(max(0, ms) / 1000.0)
def sleep_us(us):
_time.sleep(max(0, us) / 1000000.0)
def sleep(s):
_time.sleep(s)
def ticks_ms():
return int((_time.monotonic() - _T0) * 1000) & _MS_MASK
def ticks_us():
return int((_time.monotonic() - _T0) * 1000000) & _MS_MASK
ticks_cpu = ticks_us
def ticks_add(ticks, delta):
return (int(ticks) + int(delta)) & _MS_MASK
def ticks_diff(t1, t0):
"""Signed difference with wrap-around, like MicroPython."""
return ((int(t1) - int(t0) + _HALF) & _MS_MASK) - _HALF
def time():
"""Whole seconds, like MicroPython."""
return int(_time.time())
def time_ns():
return _time.time_ns()
+816
View File
@@ -0,0 +1,816 @@
/* led-simulator page: the rig of simulated led-drivers behind the bridge.
*
* Each strip is a web worker running led-driver/src/main.py in Pyodide
* (driver-worker.js). The page is the radio between them and the bridge
* (server.py, WebSocket /sim):
* server -> page binary dest_mac(6) + ESP-NOW packet (bridge transmit)
* page -> server binary src_mac(6) + ESP-NOW packet (driver transmit)
* server -> page text {"t":"status","controllers":n} | {"t":"takeover"}
* page -> server text {"t":"flash","n":i,"path":..,"data":..}
* Received packets reach a driver through its SharedArrayBuffer ring.
*/
/* global SimRing, RigLayout */
(function () {
'use strict';
const OFF_COLOUR = '#1d1f24';
const LABEL = '#8a909c';
const LABEL_LIT = '#d6dae2';
const CENTRE = '#2c3038';
const SELECT = '#5aa9ff';
const STATE_COLOUR = {
off: '#4b505b',
queued: '#f2b84b',
loading: '#f2b84b',
running: '#3ecf8e',
crashed: '#ff6b6b',
};
const LOG_LINES = 600;
const BROADCAST = 'ff:ff:ff:ff:ff:ff';
const AUTO_KEY = 'ledsim.autoPower';
const $ = (id) => document.getElementById(id);
const params = new URLSearchParams(location.search);
// Test hook: a stand-in worker script under /web/.
const workerUrl = /^\/web\/[\w.-]+\.js$/.test(params.get('worker') || '')
? params.get('worker')
: '/web/driver-worker.js';
const app = {
cfg: null,
bundle: null,
bundleAt: 0,
bootPy: '',
bridgeMac: null,
strips: [],
byMac: new Map(),
ws: null,
wsOpen: false,
takenOver: false,
controllers: 0,
queue: [],
booting: 0,
geo: null,
fullRedraw: true,
selected: null,
canvas: null,
ctx: null,
dpr: 1,
};
// ----- helpers -----------------------------------------------------------
function macBytes(s) {
return new Uint8Array(s.split(':').map((h) => parseInt(h, 16)));
}
function macOf(u8, off = 0) {
const parts = [];
for (let i = off; i < off + 6; i += 1) {
parts.push(u8[i].toString(16).padStart(2, '0'));
}
return parts.join(':');
}
function banner(text, kind) {
const el = $('banner');
if (!text) {
el.hidden = true;
return;
}
el.textContent = text;
el.className = `banner${kind ? ` ${kind}` : ''}`;
el.hidden = false;
}
function readAuto() {
try {
const v = localStorage.getItem(AUTO_KEY);
return v === null ? true : v === '1';
} catch (_e) {
return true;
}
}
function writeAuto(on) {
try {
localStorage.setItem(AUTO_KEY, on ? '1' : '0');
} catch (_e) {
// storage unavailable: setting lasts for this page only
}
}
// ----- strips: power and workers ------------------------------------------
function validPlace(p) {
return Array.isArray(p) && p.length === 4 && p.every((v) => typeof v === 'number') ? p : null;
}
/** A driver's settings.json changed (or was read): pick up its place in the rig. */
function notePlace(s, settingsText) {
let place = null;
try {
place = validPlace(JSON.parse(settingsText).place);
} catch (_e) {
return;
}
if (JSON.stringify(place) !== JSON.stringify(s.place)) {
s.place = place;
resize();
}
}
function makeStrip(info) {
return {
info,
index: info.index,
mac: info.mac,
macBytes: macBytes(info.mac),
name: info.default_name,
state: 'off',
worker: null,
ring: null,
frame: new Uint8Array(info.leds * 3),
place: validPlace(info.place),
lit: false,
dirty: true,
logs: [],
rx: 0,
tx: 0,
error: '',
};
}
function setState(s, state, error = '') {
s.state = state;
s.error = error;
s.dirty = true;
updateChips();
if (app.selected === s) {
renderDrawer();
}
}
function addLog(s, text) {
const lines = String(text).split('\n');
for (const line of lines) {
s.logs.push(line);
}
if (s.logs.length > LOG_LINES) {
s.logs.splice(0, s.logs.length - LOG_LINES);
}
if (app.selected === s) {
const el = $('d-log');
const atBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 8;
el.textContent = s.logs.join('\n');
if (atBottom) {
el.scrollTop = el.scrollHeight;
}
}
}
function powerOn(s) {
if (!self.crossOriginIsolated || app.takenOver) {
return;
}
if (s.state !== 'off' && s.state !== 'crashed') {
return;
}
setState(s, 'queued');
app.queue.push(s);
pumpQueue();
}
function powerOff(s) {
const i = app.queue.indexOf(s);
if (i >= 0) {
app.queue.splice(i, 1);
}
if (s.worker) {
s.worker.terminate();
s.worker = null;
if (s.state === 'loading') {
app.booting = Math.max(0, app.booting - 1);
}
}
s.ring = null;
s.frame = new Uint8Array(s.info.leds * 3);
setState(s, 'off');
pumpQueue();
}
function reset(s) {
powerOff(s);
addLog(s, '--- reset ---');
powerOn(s);
}
async function ensureBundle() {
// Re-read led-driver/src (main.py, patterns/) for each batch of boots.
if (app.bundle && Date.now() - app.bundleAt < 3000) {
return;
}
const [bundle, bootPy] = await Promise.all([
fetch('/api/bundle').then((r) => r.json()),
fetch('/web/driver_boot.py').then((r) => r.text()),
]);
app.bundle = bundle;
app.bootPy = bootPy;
app.bundleAt = Date.now();
}
async function pumpQueue() {
const limit = Math.max(1, Number(app.cfg.drivers.boot_concurrency) || 4);
while (app.queue.length && app.booting < limit) {
const s = app.queue.shift();
app.booting += 1;
try {
await ensureBundle();
if (s.state !== 'queued') {
app.booting -= 1;
continue;
}
await startWorker(s);
} catch (err) {
app.booting = Math.max(0, app.booting - 1);
addLog(s, `boot failed: ${err}`);
setState(s, 'crashed', String(err));
}
}
}
async function startWorker(s) {
const flash = await fetch(`/api/flash/${s.index}`).then((r) => r.json());
notePlace(s, flash['settings.json']);
try {
s.name = JSON.parse(flash['settings.json']).name || s.name;
} catch (_e) {
// keep the default name
}
if (s.state !== 'queued') {
app.booting -= 1;
return;
}
s.ring = SimRing.create(64 * 1024);
const worker = new Worker(workerUrl);
s.worker = worker;
setState(s, 'loading');
worker.onmessage = (ev) => onWorkerMessage(s, worker, ev.data || {});
worker.onerror = (ev) => {
if (s.worker !== worker) {
return;
}
ev.preventDefault();
addLog(s, `worker error: ${ev.message || ev}`);
driverStopped(s, worker, String(ev.message || 'worker error'), false);
};
worker.postMessage({
t: 'boot',
index: s.index,
ringSab: s.ring.sab,
sleepSab: new SharedArrayBuffer(4),
pyodideUrl: app.cfg.pyodide_url,
files: app.bundle,
flash: { 'settings.json': flash['settings.json'], 'presets.json': flash['presets.json'] },
bootPy: app.bootPy,
env: {
LED_SIM_MAC: s.mac.replace(/:/g, ''),
LED_SIM_FPS: String(app.cfg.drivers.fps ?? 30),
LED_SIM_LOOP_SLEEP_MS: String(app.cfg.drivers.loop_sleep_ms ?? 2),
LED_SIM_FLASH: '/flash',
LED_SIM_STUBS: '/stubs',
},
});
}
function driverStopped(s, worker, error, isReset) {
if (s.worker !== worker) {
return;
}
if (s.state === 'loading') {
app.booting = Math.max(0, app.booting - 1);
}
worker.terminate();
s.worker = null;
s.ring = null;
if (isReset) {
s.frame = new Uint8Array(s.info.leds * 3);
setState(s, 'off');
addLog(s, '--- machine.reset() ---');
powerOn(s);
return;
}
setState(s, 'crashed', error);
pumpQueue();
}
function onWorkerMessage(s, worker, m) {
if (s.worker !== worker) {
return;
}
switch (m.t) {
case 'state':
if (m.state === 'running' && s.state === 'loading') {
app.booting = Math.max(0, app.booting - 1);
setState(s, 'running');
pumpQueue();
}
break;
case 'log':
addLog(s, m.text);
break;
case 'tx': {
// dest(6) + packet. The bridge forwards everything it hears upstream.
const data = m.data;
if (data.length <= 6) {
break;
}
s.tx += 1;
const up = new Uint8Array(data.length);
up.set(s.macBytes, 0);
up.set(data.subarray(6), 6);
if (app.wsOpen) {
app.ws.send(up);
}
if (app.selected === s) {
renderFacts();
}
break;
}
case 'px':
s.frame = m.data;
s.dirty = true;
break;
case 'flash':
if (app.wsOpen) {
app.ws.send(JSON.stringify({ t: 'flash', n: s.index, path: m.path, data: m.data }));
}
if (m.path === 'settings.json') {
notePlace(s, m.data);
try {
const name = JSON.parse(m.data).name;
if (name && name !== s.name) {
s.name = name;
s.dirty = true;
app.fullRedraw = true;
}
} catch (_e) {
// ignore
}
}
break;
case 'exit':
driverStopped(s, worker, m.error || 'stopped', Boolean(m.reset));
break;
default:
break;
}
}
// ----- bridge link ---------------------------------------------------------
function deliver(s, payload) {
if (s.state !== 'running' || !s.ring) {
return; // powered off or still booting: the packet is lost, as on air
}
if (s.ring.push(payload)) {
s.rx += 1;
if (app.selected === s) {
renderFacts();
}
}
}
function onDownlink(u8) {
if (u8.length < 7) {
return;
}
const dest = macOf(u8, 0);
// The driver sees the bridge as the sender.
const payload = new Uint8Array(u8.length);
payload.set(app.bridgeMac, 0);
payload.set(u8.subarray(6), 6);
if (dest === BROADCAST) {
for (const s of app.strips) {
deliver(s, payload);
}
return;
}
const s = app.byMac.get(dest);
if (s) {
deliver(s, payload);
}
}
function connectBridge() {
if (app.takenOver) {
return;
}
const proto = location.protocol === 'https:' ? 'wss' : 'ws';
const ws = new WebSocket(`${proto}://${location.host}/sim`);
ws.binaryType = 'arraybuffer';
app.ws = ws;
ws.onopen = () => {
app.wsOpen = true;
if (!app.takenOver && self.crossOriginIsolated) {
banner('');
}
updateChips();
};
ws.onmessage = (ev) => {
if (typeof ev.data === 'string') {
let m = null;
try {
m = JSON.parse(ev.data);
} catch (_e) {
return;
}
if (m.t === 'status') {
app.controllers = Number(m.controllers) || 0;
updateChips();
} else if (m.t === 'takeover') {
app.takenOver = true;
for (const s of app.strips) {
powerOff(s);
}
banner('The rig is running in another tab. This page has powered its strips off; reload to take it back.', 'info');
setButtons();
}
return;
}
onDownlink(new Uint8Array(ev.data));
};
ws.onclose = () => {
app.wsOpen = false;
updateChips();
if (app.takenOver) {
return;
}
banner('Lost the simulator server. Reconnecting…');
setTimeout(connectBridge, 2000);
};
}
// ----- UI: chips, drawer ---------------------------------------------------
function updateChips() {
if (!app.cfg) {
return;
}
const b = app.cfg.bridge;
$('bridge-chip').textContent = `${b.name} · ${b.mac}`;
const cc = $('controller-chip');
cc.textContent = app.wsOpen
? `controller: ${app.controllers ? `${app.controllers} connected` : 'not connected'}`
: 'controller: –';
cc.className = `chip ${app.controllers ? 'ok' : 'warn'}`;
const running = app.strips.filter((s) => s.state === 'running').length;
const booting = app.strips.filter((s) => s.state === 'queued' || s.state === 'loading').length;
const crashed = app.strips.filter((s) => s.state === 'crashed').length;
let text = `strips: ${running}/${app.strips.length} running`;
if (booting) {
text += ` · ${booting} booting`;
}
if (crashed) {
text += ` · ${crashed} stopped`;
}
const sc = $('strips-chip');
sc.textContent = text;
sc.className = `chip ${crashed ? 'warn' : running ? 'ok' : ''}`;
}
function renderFacts() {
const s = app.selected;
if (!s) {
return;
}
const st = $('d-state');
st.textContent = s.state + (s.error && s.state === 'crashed' ? ` – ${s.error.split('\n').slice(-2).join(' ')}` : '');
st.className = `state-${s.state}`;
const lay = app.cfg.layout;
const side = lay.columns === 2 ? (s.info.col === 0 ? 'left' : 'right') : `column ${s.info.col + 1}`;
$('d-pos').textContent = `row ${s.info.row + 1}, ${side} · ${s.info.leds} LEDs · pixel 0 ${s.info.reversed ? 'at right end' : 'at left end'}`;
$('d-packets').textContent = `${s.rx} received · ${s.tx} sent`;
}
function renderDrawer() {
const s = app.selected;
$('drawer').hidden = !s;
if (!s) {
return;
}
$('d-name').textContent = s.name;
$('d-meta').textContent = `strip ${s.info.n} · ${s.mac}`;
renderFacts();
const off = s.state === 'off' || s.state === 'crashed';
$('d-on').disabled = !off || !self.crossOriginIsolated || app.takenOver;
$('d-off').disabled = off;
$('d-reset').disabled = !self.crossOriginIsolated || app.takenOver;
const el = $('d-log');
el.textContent = s.logs.join('\n');
el.scrollTop = el.scrollHeight;
}
function select(s) {
app.selected = app.selected === s ? null : s;
app.fullRedraw = true;
renderDrawer();
requestAnimationFrame(resize);
}
function setButtons() {
const ok = self.crossOriginIsolated && !app.takenOver;
for (const id of ['power-on-all', 'power-cycle-all', 'power-off-all']) {
$(id).disabled = !ok;
}
renderDrawer();
}
// ----- canvas ----------------------------------------------------------------
function resize() {
const c = app.canvas;
const rect = c.getBoundingClientRect();
app.dpr = window.devicePixelRatio || 1;
c.width = Math.max(1, Math.round(rect.width * app.dpr));
c.height = Math.max(1, Math.round(rect.height * app.dpr));
// Drawn where the controller placed each bar once every bar has a place, else as the layout grid
app.geo = app.strips.length && app.strips.every((s) => s.place)
? RigLayout.computePlaced(
app.strips.map((s) => ({ place: s.place, leds: s.info.leds })),
rect.width,
rect.height,
)
: RigLayout.computeGeometry(
app.cfg.layout,
app.strips.map((s) => s.info),
rect.width,
rect.height,
);
app.fullRedraw = true;
}
function colourAt(frame, i) {
const j = i * 3;
const r = frame[j] | 0;
const g = frame[j + 1] | 0;
const b = frame[j + 2] | 0;
if (r === 0 && g === 0 && b === 0) {
return null;
}
return `rgb(${r},${g},${b})`;
}
function drawLabel(s, sg) {
const ctx = app.ctx;
const pad = 4;
// clear the label band for this strip
ctx.fillStyle = '#0e0f12';
ctx.fillRect(sg.x0 - 1, sg.top, sg.w + 2, sg.y - sg.top - 1);
ctx.font = '11px system-ui, -apple-system, Segoe UI, Roboto, sans-serif';
ctx.textBaseline = 'middle';
ctx.textAlign = sg.labelAlign;
const arrow = sg.reversed ? '◂' : '▸';
const text = sg.reversed ? `${s.name} ${s.info.n} ${arrow}` : `${arrow} ${s.info.n} ${s.name}`;
ctx.fillStyle = s.lit ? LABEL_LIT : LABEL;
const dot = 7;
let tx = sg.labelX;
if (sg.reversed) {
tx -= dot + pad;
} else {
tx += dot + pad;
}
ctx.fillText(text, tx, sg.labelY);
// power state dot at the strip's start end
ctx.fillStyle = STATE_COLOUR[s.state] || STATE_COLOUR.off;
ctx.beginPath();
const dx = sg.reversed ? sg.labelX - dot / 2 : sg.labelX + dot / 2;
ctx.arc(dx, sg.labelY, dot / 2, 0, Math.PI * 2);
ctx.fill();
}
function drawPlaced(s) {
const ctx = app.ctx;
const geo = app.geo;
const sg = geo.strips[s.index];
const leds = s.info.leds;
const gap = sg.pitch >= 3 ? 1 : 0;
let lit = false;
ctx.save();
ctx.translate(sg.ax, sg.ay);
ctx.rotate(sg.ang);
for (let i = 0; i < leds; i += 1) {
const col = colourAt(s.frame, i);
if (col) {
lit = true;
}
ctx.fillStyle = col || OFF_COLOUR;
ctx.fillRect(i * sg.pitch, -geo.ledH / 2, Math.max(1, sg.pitch - gap), geo.ledH);
}
if (app.selected === s) {
ctx.strokeStyle = SELECT;
ctx.lineWidth = 1.5;
ctx.strokeRect(-1.5, -geo.ledH / 2 - 1.5, sg.len + 3, geo.ledH + 3);
}
// power state dot just before pixel 0 (the data-in head)
ctx.fillStyle = STATE_COLOUR[s.state] || STATE_COLOUR.off;
ctx.beginPath();
ctx.arc(-7, 0, 3.5, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
ctx.font = '11px system-ui, -apple-system, Segoe UI, Roboto, sans-serif';
ctx.textBaseline = 'middle';
ctx.textAlign = 'center';
ctx.fillStyle = lit ? LABEL_LIT : LABEL;
ctx.fillText(`${s.info.n} ${s.name}`, sg.labelX, sg.labelY);
s.lit = lit;
}
function drawStrip(s) {
const ctx = app.ctx;
const geo = app.geo;
const sg = geo.strips[s.index];
const leds = s.info.leds;
ctx.fillStyle = '#0e0f12';
ctx.fillRect(sg.x0 - 2, sg.y - 2, sg.w + 4, sg.h + 4);
let lit = false;
for (let i = 0; i < leds; i += 1) {
const col = colourAt(s.frame, i);
if (col) {
lit = true;
}
ctx.fillStyle = col || OFF_COLOUR;
ctx.fillRect(RigLayout.pixelX(geo, sg, i, leds), sg.y, geo.ledW, sg.h);
}
if (app.selected === s) {
ctx.strokeStyle = SELECT;
ctx.lineWidth = 1.5;
ctx.strokeRect(sg.x0 - 1.5, sg.y - 1.5, sg.w + 3, sg.h + 3);
}
s.lit = lit;
drawLabel(s, sg);
}
function frame() {
if (app.geo) {
const ctx = app.ctx;
ctx.setTransform(app.dpr, 0, 0, app.dpr, 0, 0);
if (app.geo.placed) {
// rotated bars overlap their neighbours' clear boxes: redraw everything when anything changed
if (app.fullRedraw || app.strips.some((s) => s.dirty)) {
const c = app.canvas;
ctx.fillStyle = '#0e0f12';
ctx.fillRect(0, 0, c.width / app.dpr, c.height / app.dpr);
ctx.fillStyle = CENTRE;
ctx.beginPath();
ctx.arc(app.geo.centre.x, app.geo.centre.y, 3, 0, Math.PI * 2);
ctx.fill();
for (const s of app.strips) {
s.dirty = false;
drawPlaced(s);
}
app.fullRedraw = false;
}
requestAnimationFrame(frame);
return;
}
if (app.fullRedraw) {
const c = app.canvas;
ctx.fillStyle = '#0e0f12';
ctx.fillRect(0, 0, c.width / app.dpr, c.height / app.dpr);
ctx.strokeStyle = CENTRE;
ctx.setLineDash([4, 4]);
ctx.lineWidth = 1;
for (const x of app.geo.centreLines) {
ctx.beginPath();
ctx.moveTo(x + 0.5, 6);
ctx.lineTo(x + 0.5, c.height / app.dpr - 6);
ctx.stroke();
}
ctx.setLineDash([]);
for (const s of app.strips) {
s.dirty = true;
}
app.fullRedraw = false;
}
for (const s of app.strips) {
if (s.dirty) {
s.dirty = false;
drawStrip(s);
}
}
}
requestAnimationFrame(frame);
}
function stripAt(x, y) {
const geo = app.geo;
if (!geo) {
return null;
}
if (geo.placed) {
let best = null;
let bestD = 12;
for (const s of app.strips) {
const sg = geo.strips[s.index];
const dx = sg.bx - sg.ax;
const dy = sg.by - sg.ay;
const t = Math.max(0, Math.min(1, ((x - sg.ax) * dx + (y - sg.ay) * dy) / (dx * dx + dy * dy || 1)));
const d = Math.hypot(x - (sg.ax + t * dx), y - (sg.ay + t * dy));
if (d < bestD) {
bestD = d;
best = s;
}
}
return best;
}
for (const s of app.strips) {
const sg = geo.strips[s.index];
if (x >= sg.x0 - 4 && x <= sg.x0 + sg.w + 4 && y >= sg.top && y <= sg.top + sg.rowH) {
return s;
}
}
return null;
}
// ----- boot --------------------------------------------------------------------
function wireUi() {
$('power-on-all').onclick = () => app.strips.forEach(powerOn);
$('power-off-all').onclick = () => app.strips.forEach(powerOff);
$('power-cycle-all').onclick = () => {
app.strips.forEach(powerOff);
app.strips.forEach(powerOn);
};
const auto = $('auto-power');
auto.checked = readAuto();
auto.onchange = () => writeAuto(auto.checked);
$('d-close').onclick = () => select(app.selected);
$('d-on').onclick = () => app.selected && powerOn(app.selected);
$('d-off').onclick = () => app.selected && powerOff(app.selected);
$('d-reset').onclick = () => app.selected && reset(app.selected);
$('d-clear').onclick = () => {
if (app.selected) {
app.selected.logs = [];
$('d-log').textContent = '';
}
};
app.canvas.addEventListener('click', (ev) => {
const r = app.canvas.getBoundingClientRect();
const s = stripAt(ev.clientX - r.left, ev.clientY - r.top);
if (s) {
select(s);
}
});
new ResizeObserver(() => resize()).observe($('rig'));
window.addEventListener('keydown', (ev) => {
if (ev.key === 'Escape' && app.selected) {
select(app.selected);
}
});
}
async function main() {
app.canvas = $('rig-canvas');
app.ctx = app.canvas.getContext('2d');
try {
app.cfg = await fetch('/api/config').then((r) => r.json());
} catch (err) {
banner(`Could not load /api/config: ${err}`);
return;
}
app.bridgeMac = macBytes(app.cfg.bridge.mac);
app.strips = app.cfg.strips.map(makeStrip);
for (const s of app.strips) {
app.byMac.set(s.mac, s);
}
const b = app.cfg.bridge;
const lay = app.cfg.layout;
document.title = `${b.name} · LED Rig Simulator`;
$('hint').innerHTML =
`${app.strips.length} strips × ${lay.leds_per_strip} LEDs, ${lay.columns} × ${lay.rows}. ` +
(b.udp_port
? `In led-controller set <code>"bridge": "${b.lan_ip}:${b.udp_port}"</code> (or <code>127.0.0.1:${b.udp_port}</code>) ` +
'in settings and restart it, or run its host build (<code>make sim</code>). '
: `In led-controller add a bridge: transport <code>ip</code>, address <code>${b.lan_ip}</code> ` +
`(or <code>127.0.0.1</code>), port <code>${b.port}</code>. `) +
'Strips register with their hello when they power on; power-cycle a strip to register it again.';
wireUi();
resize();
requestAnimationFrame(frame);
updateChips();
if (!self.crossOriginIsolated) {
banner(
`This page is not cross-origin isolated, so drivers cannot run (they need SharedArrayBuffer). ` +
`Open it as http://localhost:${b.port}/ on the computer running server.py, or over HTTPS.`,
);
}
setButtons();
connectBridge();
if (self.crossOriginIsolated && readAuto()) {
app.strips.forEach(powerOn);
}
}
main();
})();
+84
View File
@@ -0,0 +1,84 @@
/* One simulated led-driver: Pyodide running led-driver/src/main.py.
*
* The page posts {t: 'boot', ...} once. The worker loads Pyodide, writes the
* strip's flash (driver source, patterns, settings.json, presets.json) and the
* stubs into the Pyodide filesystem, then runs web/driver_boot.py, which never
* returns while the driver is powered. Power-off is Worker.terminate().
*
* Messages to the page:
* {t:'state', state} loading | running
* {t:'log', text} driver serial output (one line)
* {t:'tx', data} Uint8Array dest_mac(6) + ESP-NOW packet
* {t:'px', data} Uint8Array RGB frame
* {t:'flash', path, data} settings.json / presets.json changed
* {t:'exit', error, reset} main.py stopped (reset: machine.reset())
*/
/* global importScripts, loadPyodide, SimRing */
importScripts('/web/ring.js');
let ring = null;
let sleepView = null;
self.simRecv = () => (ring ? ring.pop() : undefined);
self.simPending = () => (ring ? ring.count() : 0);
self.simTx = (u8) => self.postMessage({ t: 'tx', data: u8 }, [u8.buffer]);
self.simPixels = (u8) => self.postMessage({ t: 'px', data: u8 }, [u8.buffer]);
self.simFlash = (path, text) =>
self.postMessage({ t: 'flash', path: String(path), data: String(text) });
self.simSleep = (ms) => {
if (ms > 0 && sleepView) {
// Nobody notifies this slot: it is a plain blocking sleep.
Atomics.wait(sleepView, 0, 0, ms);
}
};
function log(text) {
self.postMessage({ t: 'log', text: String(text) });
}
function writeTree(FS, root, files) {
for (const [rel, body] of Object.entries(files)) {
const path = `${root}/${String(rel).replace(/^\/+/, '')}`;
const dir = path.slice(0, path.lastIndexOf('/'));
if (dir) {
FS.mkdirTree(dir);
}
FS.writeFile(path, String(body));
}
}
self.onmessage = async (event) => {
const m = event.data || {};
if (m.t !== 'boot') {
return;
}
ring = new SimRing(m.ringSab);
sleepView = new Int32Array(m.sleepSab);
self.postMessage({ t: 'state', state: 'loading' });
try {
importScripts(`${m.pyodideUrl}pyodide.js`);
const py = await loadPyodide({
indexURL: m.pyodideUrl,
stdout: log,
stderr: log,
});
const FS = py.FS;
writeTree(FS, '/flash', m.files.driver);
writeTree(FS, '/flash', m.flash);
writeTree(FS, '/stubs', m.files.stubs);
FS.writeFile('/boot.py', m.bootPy);
py.globals.set('__sim_env', py.toPy(m.env));
py.runPython('import os\nos.environ.update({str(k): str(v) for k, v in __sim_env.items()})\ndel __sim_env');
self.postMessage({ t: 'state', state: 'running' });
// Blocks until main.py exits (it normally never does).
py.runPython('import runpy\nrunpy.run_path("/boot.py", run_name="__boot__")');
self.postMessage({ t: 'exit', error: 'main.py returned', reset: false });
} catch (err) {
const msg = String((err && err.message) || err);
const reset = /SystemExit:\s*75\b/.test(msg);
if (!reset) {
log(msg);
}
self.postMessage({ t: 'exit', error: reset ? 'machine.reset()' : msg, reset });
}
};
+49
View File
@@ -0,0 +1,49 @@
"""Boot one simulated led-driver inside Pyodide (run by web/driver-worker.js).
The worker has already written the strip's flash into ``LED_SIM_FLASH``
(``led-driver/src`` including ``patterns/``, plus this strip's
``settings.json`` and ``presets.json``) and the stubs into ``LED_SIM_STUBS``.
This then runs the real ``main.py`` as ``__main__``, as the board does at
power-on: settings, presets, startup preset, ESP-NOW hello, main loop.
"""
import gc
import os
import runpy
import sys
import time
def boot():
flash = os.environ.get("LED_SIM_FLASH", "/flash")
stubs = os.environ.get("LED_SIM_STUBS", "/stubs")
# Stubs replace the hardware modules; the flash root plays the device's
# "/" (cwd), where main.py, settings.json, presets.json and patterns/ live.
for p in (flash, stubs):
while p in sys.path:
sys.path.remove(p)
sys.path[:0] = [stubs, flash]
os.chdir(flash)
import _simlink
# No threads and no event loop turns while main.py runs: sleeps block on
# Atomics.wait, and the ping-reply "thread" runs from the main loop.
time.sleep = _simlink.real_sleep
import _thread
_thread.start_new_thread = _simlink.start_new_thread
if not hasattr(gc, "mem_free"):
gc.mem_free = lambda: 256 * 1024
gc.mem_alloc = lambda: 64 * 1024
import settings as led_settings
led_settings.Settings.SETTINGS_FILE = flash.rstrip("/") + "/settings.json"
runpy.run_path(flash.rstrip("/") + "/main.py", run_name="__main__")
boot()
+71
View File
@@ -0,0 +1,71 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#0e0f12">
<title>LED Rig Simulator</title>
<link rel="icon" href="data:,">
<link rel="stylesheet" href="/web/styles.css">
</head>
<body>
<header class="topbar">
<div class="brand">
<span class="brand-mark" aria-hidden="true"></span>
<span class="brand-name">led-simulator</span>
</div>
<div class="chips">
<span class="chip" id="bridge-chip" title="Simulated Wi-Fi bridge">bridge</span>
<span class="chip" id="controller-chip">controller: –</span>
<span class="chip" id="strips-chip">strips: –</span>
</div>
<div class="actions">
<button type="button" id="power-on-all">Power on all</button>
<button type="button" id="power-cycle-all">Power cycle all</button>
<button type="button" id="power-off-all" class="secondary">Power off all</button>
<label class="toggle" title="Boot every strip when this page opens">
<input type="checkbox" id="auto-power"> Power on when opened
</label>
</div>
</header>
<div id="banner" class="banner" hidden></div>
<main class="stage">
<div class="rig" id="rig">
<canvas id="rig-canvas" aria-label="LED rig"></canvas>
</div>
<aside class="drawer" id="drawer" hidden aria-label="Strip details">
<div class="drawer-head">
<div>
<div class="drawer-title" id="d-name">sim-01</div>
<div class="drawer-sub" id="d-meta">02:51:4d:00:00:01</div>
</div>
<button type="button" class="icon" id="d-close" aria-label="Close">×</button>
</div>
<dl class="facts">
<dt>State</dt><dd id="d-state">off</dd>
<dt>Position</dt><dd id="d-pos">–</dd>
<dt>Packets</dt><dd id="d-packets">–</dd>
</dl>
<div class="drawer-actions">
<button type="button" id="d-on">Power on</button>
<button type="button" id="d-reset">Reset</button>
<button type="button" id="d-off" class="secondary">Power off</button>
</div>
<div class="log-head">
<span>Serial</span>
<button type="button" class="link" id="d-clear">clear</button>
</div>
<pre class="log" id="d-log"></pre>
</aside>
</main>
<footer class="hint" id="hint">Loading…</footer>
<script src="/web/ring.js"></script>
<script src="/web/layout.js"></script>
<script src="/web/app.js"></script>
</body>
</html>
+103
View File
@@ -0,0 +1,103 @@
/* Rig geometry for the canvas: strips along their rows, pixel 0 at the
* strip's start end (next to the centre line for start: "center").
* Strip placement (row, col, reversed) comes from the server (layout.py).
*/
(function (g) {
'use strict';
/**
* @param {object} layout {rows, columns, leds_per_strip}
* @param {Array} strips [{row, col, leds, reversed}]
* @returns {object} {ledPitch, ledW, ledH, strips:[{x0, y, w, labelX, labelY, labelAlign}], centreLines}
*/
function computeGeometry(layout, strips, width, height, opts = {}) {
const margin = opts.margin ?? 16;
const colGap = opts.colGap ?? 32;
const labelH = opts.labelH ?? 16;
const rows = layout.rows;
const cols = layout.columns;
const n = layout.leds_per_strip;
const usableW = Math.max(cols * n, width - 2 * margin - (cols - 1) * colGap);
const colW = usableW / cols;
const pitch = colW / n;
const rowH = Math.max(labelH + 6, (height - 2 * margin) / rows);
const ledH = Math.max(6, Math.min(rowH - labelH - 10, 18));
const gap = pitch >= 3 ? 1 : 0;
const ledW = Math.max(1, pitch - gap);
const out = strips.map((s) => {
const x0 = margin + s.col * (colW + colGap);
const yTop = margin + s.row * rowH;
// strip sits just under its label; leftover row space goes below it
const y = yTop + labelH + 4;
return {
x0,
y,
w: colW,
h: ledH,
top: yTop,
rowH,
reversed: Boolean(s.reversed),
labelX: s.reversed ? x0 + colW : x0,
labelY: yTop + labelH / 2 + 2,
labelAlign: s.reversed ? 'right' : 'left',
};
});
const centreLines = [];
for (let c = 1; c < cols; c += 1) {
centreLines.push(margin + c * (colW + colGap) - colGap / 2);
}
return { ledPitch: pitch, ledW, ledH, strips: out, centreLines };
}
/**
* Geometry from each strip's rig place [x0, y0, x1, y1] (y up, centre 0, as the controller sends it),
* fitted to the canvas with one scale. Used once every strip has a place.
* @returns {object} {placed: true, ledH, strips: [{ax, ay, bx, by, ang, len, pitch, labelX, labelY}], centre}
*/
function computePlaced(strips, width, height, opts = {}) {
const margin = opts.margin ?? 28;
const ledH = opts.ledH ?? 12;
let lo = [Infinity, Infinity];
let hi = [-Infinity, -Infinity];
for (const s of strips) {
const p = s.place;
for (let k = 0; k < 4; k += 2) {
lo = [Math.min(lo[0], p[k]), Math.min(lo[1], p[k + 1])];
hi = [Math.max(hi[0], p[k]), Math.max(hi[1], p[k + 1])];
}
}
const spanX = Math.max(hi[0] - lo[0], 1e-3);
const spanY = Math.max(hi[1] - lo[1], 1e-3);
const scale = Math.min((width - 2 * margin) / spanX, (height - 2 * margin) / spanY);
const ox = width / 2 - ((lo[0] + hi[0]) / 2) * scale;
const oy = height / 2 + ((lo[1] + hi[1]) / 2) * scale;
const tx = (x) => ox + x * scale;
const ty = (y) => oy - y * scale;
const out = strips.map((s) => {
const [x0, y0, x1, y1] = s.place;
const ax = tx(x0);
const ay = ty(y0);
const bx = tx(x1);
const by = ty(y1);
const len = Math.hypot(bx - ax, by - ay);
const n = s.leds;
return {
ax, ay, bx, by, len,
ang: Math.atan2(by - ay, bx - ax),
pitch: len / n,
labelX: (ax + bx) / 2,
labelY: (ay + by) / 2 - ledH / 2 - 9,
};
});
return { placed: true, ledH, strips: out, centre: { x: tx(0), y: ty(0) } };
}
/** x of pixel i of a strip (pixel 0 at the start end). */
function pixelX(geo, sg, i, leds) {
const pos = sg.reversed ? leds - 1 - i : i;
return sg.x0 + pos * geo.ledPitch;
}
g.RigLayout = { computeGeometry, computePlaced, pixelX };
})(typeof self !== 'undefined' ? self : globalThis);
+93
View File
@@ -0,0 +1,93 @@
/* SharedArrayBuffer message ring: the page pushes received ESP-NOW frames,
* the driver worker pops them while main.py runs (it never yields to the JS
* event loop, so postMessage cannot reach it).
*
* Layout: Int32[4] header {head, tail, dropped, count} then `capacity` bytes.
* Each message is a little-endian u16 length followed by the bytes.
* One producer (page) and one consumer (worker).
*
* Loaded as a classic script by both the page and the worker.
*/
(function (g) {
'use strict';
const HEADER = 16;
const HEAD = 0;
const TAIL = 1;
const DROPPED = 2;
const COUNT = 3;
class SimRing {
constructor(sab) {
this.sab = sab;
this.idx = new Int32Array(sab, 0, 4);
this.cap = sab.byteLength - HEADER;
this.data = new Uint8Array(sab, HEADER, this.cap);
}
static create(capacity = 65536) {
return new SimRing(new SharedArrayBuffer(HEADER + capacity));
}
used() {
const h = Atomics.load(this.idx, HEAD);
const t = Atomics.load(this.idx, TAIL);
return (h - t + this.cap) % this.cap;
}
count() {
return Atomics.load(this.idx, COUNT);
}
dropped() {
return Atomics.load(this.idx, DROPPED);
}
/** Producer: false (and counted as dropped) when the ring is full. */
push(bytes) {
const n = bytes.length;
if (n > 0xffff || n + 2 >= this.cap - this.used()) {
Atomics.add(this.idx, DROPPED, 1);
return false;
}
const cap = this.cap;
const data = this.data;
let h = Atomics.load(this.idx, HEAD);
data[h] = n & 0xff;
h = (h + 1) % cap;
data[h] = n >> 8;
h = (h + 1) % cap;
for (let i = 0; i < n; i += 1) {
data[h] = bytes[i];
h = (h + 1) % cap;
}
Atomics.store(this.idx, HEAD, h);
Atomics.add(this.idx, COUNT, 1);
return true;
}
/** Consumer: next message as a Uint8Array, or undefined when empty. */
pop() {
let t = Atomics.load(this.idx, TAIL);
if (t === Atomics.load(this.idx, HEAD)) {
return undefined;
}
const cap = this.cap;
const data = this.data;
const lo = data[t];
t = (t + 1) % cap;
const hi = data[t];
t = (t + 1) % cap;
const n = lo | (hi << 8);
const out = new Uint8Array(n);
for (let i = 0; i < n; i += 1) {
out[i] = data[t];
t = (t + 1) % cap;
}
Atomics.store(this.idx, TAIL, t);
Atomics.sub(this.idx, COUNT, 1);
return out;
}
}
g.SimRing = SimRing;
})(typeof self !== 'undefined' ? self : globalThis);
+169
View File
@@ -0,0 +1,169 @@
:root {
--bg: #0e0f12;
--panel: #15171c;
--panel-2: #1b1e24;
--line: #2a2e36;
--text: #d6dae2;
--muted: #8a909c;
--accent: #5aa9ff;
--ok: #3ecf8e;
--warn: #f2b84b;
--bad: #ff6b6b;
--off: #4b505b;
color-scheme: dark;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
height: 100%;
background: var(--bg);
color: var(--text);
font: 13px/1.4 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
}
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
button {
font: inherit;
color: var(--text);
background: #253041;
border: 1px solid #34465f;
border-radius: 6px;
padding: 5px 11px;
cursor: pointer;
}
button:hover:not(:disabled) { background: #2d3b50; }
button:disabled { opacity: .45; cursor: default; }
button.secondary { background: var(--panel-2); border-color: var(--line); }
button.secondary:hover:not(:disabled) { background: #232730; }
button.icon {
background: none; border: none; font-size: 20px; line-height: 1;
padding: 0 4px; color: var(--muted);
}
button.link {
background: none; border: none; padding: 0; color: var(--muted);
text-decoration: underline;
}
.topbar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px 18px;
padding: 10px 16px;
border-bottom: 1px solid var(--line);
background: var(--panel);
}
.brand { display: flex; align-items: center; gap: 8px; font-weight: 600; }
.brand-mark {
width: 14px; height: 14px; border-radius: 3px;
background: linear-gradient(90deg, #ff3b3b, #ffd23b, #3bff8a, #3bb2ff, #b03bff);
}
.chips { display: flex; flex-wrap: wrap; gap: 6px; }
.chip {
border: 1px solid var(--line);
background: var(--panel-2);
border-radius: 999px;
padding: 2px 10px;
color: var(--muted);
white-space: nowrap;
}
.chip.ok { color: var(--ok); border-color: #22533f; }
.chip.warn { color: var(--warn); border-color: #5a4720; }
.actions { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin-left: auto; }
.toggle { display: flex; align-items: center; gap: 5px; color: var(--muted); margin-left: 6px; }
.banner {
padding: 8px 16px;
background: #3a1d22;
color: #ffd6d6;
border-bottom: 1px solid #5c2a31;
}
.banner.info { background: #1d2a3a; color: #d6e8ff; border-color: #2a405c; }
.stage {
flex: 1;
display: flex;
min-height: 0;
}
.rig {
flex: 1;
position: relative;
min-width: 0;
min-height: 360px;
}
.rig canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
cursor: pointer;
}
.drawer {
width: 360px;
max-width: 100%;
border-left: 1px solid var(--line);
background: var(--panel);
display: flex;
flex-direction: column;
padding: 12px 14px;
gap: 10px;
min-height: 0;
}
.drawer[hidden] { display: none; }
.drawer-head { display: flex; justify-content: space-between; align-items: flex-start; }
.drawer-title { font-size: 16px; font-weight: 600; }
.drawer-sub { color: var(--muted); font-family: ui-monospace, Menlo, Consolas, monospace; }
.facts {
display: grid;
grid-template-columns: 80px 1fr;
gap: 4px 10px;
margin: 0;
}
.facts dt { color: var(--muted); }
.facts dd { margin: 0; }
.drawer-actions { display: flex; gap: 6px; flex-wrap: wrap; }
.log-head { display: flex; justify-content: space-between; color: var(--muted); }
.log {
flex: 1;
min-height: 120px;
margin: 0;
overflow: auto;
background: #0b0c0f;
border: 1px solid var(--line);
border-radius: 6px;
padding: 8px;
font: 11px/1.45 ui-monospace, Menlo, Consolas, monospace;
color: #b9c0cc;
white-space: pre-wrap;
word-break: break-all;
}
.state-off { color: var(--off); }
.state-queued, .state-loading { color: var(--warn); }
.state-running { color: var(--ok); }
.state-crashed { color: var(--bad); }
.hint {
padding: 8px 16px;
border-top: 1px solid var(--line);
color: var(--muted);
background: var(--panel);
}
.hint code {
color: var(--text);
font-family: ui-monospace, Menlo, Consolas, monospace;
}
@media (max-width: 760px) {
.stage { flex-direction: column; }
.drawer { width: auto; border-left: none; border-top: 1px solid var(--line); max-height: 50vh; }
.actions { margin-left: 0; }
}
@@ -0,0 +1 @@
@@ -0,0 +1 @@
# Host package mirror of device flash `patterns/` (pattern modules).