├── .github └── workflows │ ├── arduino_lint.yml │ ├── build.yml │ └── build_examples.yml ├── .gitignore ├── LICENSE ├── README.md ├── data ├── .eslintrc.js ├── config.txt ├── edit.htm.gz ├── favicon.ico ├── index.css ├── index.htm ├── index.js └── index.png ├── examples ├── BasicExample │ ├── Animations │ │ ├── Confetti.h │ │ ├── Gradient.h │ │ ├── RGBWave.h │ │ └── Rainbow.h │ └── BasicExample.ino ├── ColorPickers │ ├── Animations │ │ └── Gradient.h │ └── ColorPickers.ino ├── Sliders │ ├── Animations │ │ └── Rainbow.h │ └── Sliders.ino └── Spectrogram │ ├── Animations │ └── Spectrogram.h │ └── Spectrogram.ino ├── library.json ├── library.properties └── src ├── Animation.cpp ├── Animation.h ├── Animations └── Color.h ├── ColorPicker.h ├── ColorUtils.cpp ├── ColorUtils.h ├── Config.cpp ├── Config.h ├── FWebserver.cpp ├── FWebserver.h ├── Fade.cpp ├── Fade.h ├── FastLEDHub.cpp ├── FastLEDHub.h ├── SerialOut.h ├── Slider.h ├── WebSocket.cpp └── WebSocket.h /.github/workflows/arduino_lint.yml: -------------------------------------------------------------------------------- 1 | name: Arduino lint 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | lint: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v2 10 | - uses: arduino/arduino-lint-action@v1 11 | with: 12 | library-manager: update 13 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build library 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | strategy: 10 | fail-fast: false 11 | matrix: 12 | board: 13 | - "nodemcuv2" 14 | - "lolin32" 15 | 16 | steps: 17 | - uses: actions/checkout@v4 18 | - name: Set up Python 19 | uses: actions/setup-python@v5 20 | with: 21 | python-version: '3.10' 22 | - name: Install PlatformIO 23 | run: | 24 | python -m pip install --upgrade pip 25 | pip install --upgrade platformio 26 | - name: Install 3rd party dependencies 27 | run: | 28 | pio lib install \ 29 | ArduinoJson \ 30 | FastLED \ 31 | LinkedList \ 32 | WebSockets \ 33 | https://github.com/tzapu/WiFiManager \ 34 | https://github.com/srwi/ESPEssentials 35 | - name: Create main file 36 | run: | 37 | echo "#include " >> main.ino 38 | echo "void setup() { }" >> main.ino 39 | echo "void loop() { }" >> main.ino 40 | - name: Run PlatformIO 41 | run: pio ci --board=${{ matrix.board }} . 42 | -------------------------------------------------------------------------------- /.github/workflows/build_examples.yml: -------------------------------------------------------------------------------- 1 | name: Build examples 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | strategy: 10 | fail-fast: false 11 | matrix: 12 | board: 13 | - "nodemcuv2" 14 | - "lolin32" 15 | example: 16 | - "examples/BasicExample" 17 | - "examples/ColorPickers" 18 | - "examples/Sliders" 19 | 20 | steps: 21 | - uses: actions/checkout@v4 22 | - name: Set up Python 23 | uses: actions/setup-python@v5 24 | with: 25 | python-version: '3.10' 26 | - name: Install PlatformIO 27 | run: | 28 | python -m pip install --upgrade pip 29 | pip install --upgrade platformio 30 | - name: Install 3rd party dependencies 31 | run: | 32 | pio lib -g install \ 33 | ArduinoJson \ 34 | FastLED \ 35 | LinkedList \ 36 | WebSockets \ 37 | https://github.com/tzapu/WiFiManager \ 38 | https://github.com/srwi/ESPEssentials \ 39 | https://github.com/srwi/FastLEDHub 40 | - name: Run PlatformIO examples 41 | run: pio ci --board=${{ matrix.board }} 42 | env: 43 | PLATFORMIO_CI_SRC: ${{ matrix.example }} 44 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | node_modules 3 | package-lock.json 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | [This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.] 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | 474 | Copyright (C) 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 489 | 490 | Also add information on how to contact you by electronic and paper mail. 491 | 492 | You should also get your employer (if you work as a programmer) or your 493 | school, if any, to sign a "copyright disclaimer" for the library, if 494 | necessary. Here is a sample; alter the names: 495 | 496 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 497 | library `Frob' (a library for tweaking knobs) written by James Random Hacker. 498 | 499 | , 1 April 1990 500 | Ty Coon, President of Vice 501 | 502 | That's all there is to it! 503 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # FastLEDHub 2 | 3 | ![ESP8266](https://img.shields.io/badge/ESP-8266-000000.svg?colorB=blue) 4 | ![ESP32](https://img.shields.io/badge/ESP-32-000000.svg?colorB=blue) 5 | [![LGPL-2.1 license](https://img.shields.io/github/license/srwi/FastLEDHub)](https://github.com/srwi/FastLEDHub/blob/master/LICENSE) 6 | 7 | FastLEDHub allows you to manage all of your [FastLED]([FastLED](https://github.com/FastLED/FastLED)) sketches on the ESP8266 and ESP32 with minimal changes to your existing code. It requires little knowledge about the ESP8266/ESP32 platform making it an ideal playground for beginners getting started with FastLED animations. 8 | 9 | ## Features 10 | 11 | - Control multiple animations via an intuitive web interface 12 | - Adjust brightness and animation speed globally 13 | - Add widgets like color pickers or sliders to control complex animations 14 | - Alarm: Be woken up to an animation slowly fading in 15 | - Sunset: Automatically fade in an animation when the sun sets at your location 16 | - Control animations and brightness using hardware inputs 17 | - Incorporate audio spectrum data into your animations 18 | - Control animations using HTTP requests for easy automation 19 | 20 | ## Demo 21 | 22 | ![FastLEDHub web app screenshot](https://user-images.githubusercontent.com/17520641/163568239-527e2239-536c-4324-8e0f-5c712b3d4635.gif) 23 | 24 | 25 | ## Installation 26 | 27 | ### Library dependencies 28 | 29 | - ArduinoJson ≥ 7.0 30 | - ESPEssentials ≥ 2.1 31 | - FastLED 32 | - LinkedList 33 | - WebSockets 34 | - WiFiManager ≥ 2.0 35 | 36 | ### Official releases via the Arduino IDE v1.8+ 37 | 1. Open the Arduino IDE 38 | 2. Navigate to _"Sketch"_ → _"Include Library"_ → _"Manage Libraries..."_ 39 | 3. Search for `FastLEDHub` and install the desired version 40 | 41 | ### Manual Installation 42 | 43 | 1. Make sure you have installed the dependencies above 44 | 2. Download the desired version from the [releases](https://github.com/srwi/FastLEDHub/releases) page 45 | 3. Extract the contents of the downloaded zip file 46 | 4. Rename the extracted folder to `FastLEDHub` 47 | 5. Move this folder to your libraries directory `~/Arduino/libraries`) 48 | 6. Restart your Arduino IDE 49 | 50 | ### Using Git 51 | 52 | ```bash 53 | cd ~/Arduino/libraries 54 | git clone https://github.com/srwi/FastLEDHub.git 55 | ``` 56 | 57 | To update to the latest version of the library 58 | 59 | ```bash 60 | cd ~/Arduino/libraries/FastLEDHub && git pull 61 | ``` 62 | 63 | ## Usage 64 | 65 | Using FastLEDHub to manage your FastLED animations requires mainly four steps: 66 | 67 | - Creating the main sketch to initialize your lightstrip with FastLEDHub 68 | - Creating an animation or modifying an existing sketch to be compatible with FastLEDHub 69 | - Registering your animations in the main sketch 70 | - Uploading the web interface files to the flash storage 71 | 72 | ### Creating the main sketch 73 | 74 | ```cpp 75 | #include 76 | 77 | #define NUM_LEDS 100 78 | #define LED_TYPE WS2812B 79 | #define LIGHTSTRIP_PIN 5 80 | 81 | CRGB leds[NUM_LEDS]; 82 | 83 | void setup() 84 | { 85 | FastLEDHub.initialize("Project Name"); 86 | FastLEDHub.addLeds(leds, NUM_LEDS); 87 | } 88 | 89 | void loop() 90 | { 91 | FastLEDHub.handle(); 92 | } 93 | ``` 94 | 95 | Change `NUM_LEDS`, `LED_TYPE` and `LIGHTSTRIP_PIN` according to your hardware configuration. You may notice that this is not different than setting up a regular FastLED sketch apart from using `FastLEDHub` instead of `FastLED`. 96 | 97 | *Note:* By default FastLEDHub will apply gamma correction to the brightness value. To disable this behavior call `FastLEDHub.initialize("Project Name", false)` instead. 98 | 99 | ### Adding a new animation 100 | 101 | Create a new animation file `Animations/ExampleAnimation.h`: 102 | 103 | ```cpp 104 | #pragma once 105 | 106 | #include 107 | 108 | extern CRGB leds[]; 109 | 110 | class ExampleAnimation : public Animation 111 | { 112 | public: 113 | using Animation::Animation; 114 | 115 | // add variables and other functions if needed 116 | 117 | void reset() 118 | { 119 | // set initial state variables 120 | } 121 | 122 | void loop() 123 | { 124 | // animate leds 125 | } 126 | }; 127 | ``` 128 | 129 | While creating your animation proceed as you usually would with FastLED by defining the `reset` and `loop` functions. `reset` will be called each time an animation gets started. Use this function to reset the state variables of your animation to its starting values. It will not be called when resuming the animation from the paused status. `loop` will be called repeatedly as long as the animation is running. 130 | 131 | Keep in mind the following important differences to just using FastLED: 132 | - The regular `setup` function is called `reset` to emphasize its purpose. 133 | - Since `leds` has already been defined in the main sketch, simply indicate its existence with `extern CRGB leds[]`. 134 | - Within your animation use `FastLEDHub[0].size()` instead of `NUM_LEDS` to get the number of leds. If you are using multiple lightstrips change the index accordingly. 135 | - Every time you may want to use `FastLED` use `FastLEDHub` instead. Since `FastLEDHub` inherits from `FastLED` all member functions will be available just like before. FastLEDHub just adds some stuff on top of that. 136 | 137 | If you want to convert an existing FastLED sketch (e.g. from [atuline/FastLED-Demos](https://github.com/atuline/FastLED-Demos)), so it can be handled by FastLEDHub, generally those are the necessary changes you have to perform. Have a look at the examples for further insights. 138 | 139 | ### Registering animations 140 | 141 | In your main sketch include your animations and register them at the end of the `setup` function: 142 | 143 | ```cpp 144 | #include "Animations/ExampleAnimation.h" 145 | 146 | ... 147 | 148 | FastLEDHub.registerAnimation(new ExampleAnimation("Example animation name")); 149 | ``` 150 | 151 | The animation name can be any unique string and will be used to identify animations in the web interface. 152 | 153 | ### Uploading web interface files 154 | 155 | To be able to access the web interface, several files have to be uploaded to the flash storage. They are located within the `data` folder inside FastLEDHub's library folder. To upload those files there are two easy options: 156 | 157 | - Copy the whole `data` folder into your sketch directory and upload the files using the Arduino filesystem uploader ([ESP8266](https://github.com/esp8266/arduino-esp8266fs-plugin), [ESP32](https://github.com/me-no-dev/arduino-esp32fs-plugin)). 158 | - After the sketch has been flashed to the device upload each file within the `data` folder individually by accessing `http:///edit`. 159 | 160 | ## Additional features 161 | 162 | ### Custom color pickers 163 | 164 | FastLEDHub allows you to register multiple color pickers to use as parameters for your animations. This allows you to integrate custom colors, gradients and more. 165 | 166 | To add a color picker use 167 | 168 | ```cpp 169 | FastLEDHub.registerColorPicker(new ColorPicker("Primary Color", CRGB(255, 0, 0))); 170 | FastLEDHub.registerColorPicker(new ColorPicker("Secondary Color", CRGB(0, 255, 0), "paint-bucket")); 171 | ``` 172 | 173 | Within the web interface FastLEDHub uses [Bootstrap icons](https://icons.getbootstrap.com/#icons) to allow you to further differentiate between color pickers. Here `paint-bucket` refers to the respective icon class. 174 | 175 | To access those colors within your animation use 176 | 177 | ```cpp 178 | CRGB primaryColor = FastLEDHub.getColorPicker("Primary Color")->value; // access by name 179 | CRGB secondaryColor = FastLEDHub.getColorPicker(1)->value; // access by index 180 | ``` 181 | 182 | ### Pre-defined and custom sliders 183 | 184 | You can add custom numeric sliders of type `int16_t` to adjust variables of animations dynamically. FastLEDHub automatically adds two sliders for brightness (0-255, default: 127) and animation speed (0-255, default: 127). Both of these fixed sliders have been integrated tightly into FastLEDHub and don't require any further attention. By default changing the brightness will apply gamma correction automatically. Adjusting the speed will affect the effective delay of `FastLEDHub.delay()` to speed up or slow down animations. To prevent this explicitly use `FastLED.delay()`. 185 | 186 | To add more custom sliders simply register them in the main sketch via 187 | 188 | ```cpp 189 | FastLEDHub.registerSlider(new Slider("Hue", 0, 359, 180, 1)); 190 | FastLEDHub.registerSlider(new Slider("Saturation", 150, 255, 200, 1, "palette")); 191 | ``` 192 | 193 | Again `"palette"` refers to an optional [Bootstrap icon](https://icons.getbootstrap.com/#icons) and the slider name can be any unique string identifying the slider in the web interface. 194 | 195 | To access custom slider values inside of your animation use 196 | 197 | ```cpp 198 | int16_t hue = FastLEDHub.getSlider(2)->value; // access by index 199 | int16_t saturation = FastLEDHub.getSlider("Saturation")->value; // access by name 200 | ``` 201 | 202 | *Remember:* Since FastLEDHub comes with two pre-defined sliders `Brightness` and `Speed` the first custom slider will have index `2`. 203 | 204 | ### Hardware inputs 205 | 206 | FastLEDHub supports a potentiometer for brightness adjustments and push buttons to play/pause and cycle through animations. They have to be specifically enabled with 207 | 208 | ```cpp 209 | FastLEDHub.enablePotentiometer(potentiometerPin); 210 | FastLEDHub.enableToggleButton(togglePin); 211 | FastLEDHub.enableCycleButton(cyclePin); 212 | ``` 213 | 214 | ### Alarm and sunset 215 | 216 | Setting up an alarm in the web interface will fade in a user defined animation over any period of time to wake you up in the morning. You can optionally set a different animation to be started after the fade in period has ended (i.e. full brightness has been reached). 217 | 218 | Similarly the sunset feature will fade in an animation as soon as the sun sets at your location. Please configure latitude, longitude and time zone in the web interface beforehand. 219 | 220 | ### Audio spectrum data 221 | 222 | [FastLEDHub-AudioViz](https://github.com/srwi/FastLEDHub_AudioViz) allows you to send audio spectrum data from a Windows audio device to your ESP32/ESP8266. The transmitted data consists of 16 bins corresponding to different frequency ranges in the audio spectrum. Data is transmitted via a websocket connection and can be used by accessing the `FastLEDHub.spectrumData` array from within your animation: 223 | 224 | ```cpp 225 | uint8_t lowFrequencies = FastLEDHub.spectrumData[0]; 226 | uint8_t highFrequencies = FastLEDHub.spectrumData[SPECTRUM_LENGTH - 1]; 227 | ``` 228 | 229 | `SPECTRUM_LENGTH` defines the number of bins (16). The `Spectrogram` example shows one way to use the spectrum data in your animations. 230 | 231 | ### Control via HTTP requests 232 | 233 | Most functions can be triggered via HTTP requests: 234 | 235 | - Begin animation by name: `http:///begin?animation=` 236 | - Begin animation by index: `http:///begin?index=` 237 | - Stop animation: `http:///stop` 238 | - Pause animation: `http:///pause` 239 | - Resume animation: `http:///resume` 240 | - Toggle animation: `http:///toggle` 241 | - Restart animation: `http:///restart` 242 | - Trigger sunset: `http:///sunset` 243 | - Trigger alarm: `http:///alarm` 244 | - Reset device: `http:///reboot` 245 | 246 | ## License & Attribution 247 | 248 | FastLEDHub is licensed under LGPL-2.1 and uses the [sunrise-sunset.org](https://sunrise-sunset.org/api) api to retrieve sunset times. 249 | -------------------------------------------------------------------------------- /data/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | browser: true, 4 | es6: true, 5 | }, 6 | parserOptions: { 7 | ecmaVersion: 11, 8 | }, 9 | rules: { 10 | semi: ["error", "always"], 11 | quotes: ["error", "double"], 12 | eqeqeq: "error", 13 | "no-undef": "off", 14 | }, 15 | extends: "eslint:recommended", 16 | }; 17 | -------------------------------------------------------------------------------- /data/config.txt: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /data/edit.htm.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srwi/FastLEDHub/79fec5edbe546e8fc42b3589e81288894c665e20/data/edit.htm.gz -------------------------------------------------------------------------------- /data/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srwi/FastLEDHub/79fec5edbe546e8fc42b3589e81288894c665e20/data/favicon.ico -------------------------------------------------------------------------------- /data/index.css: -------------------------------------------------------------------------------- 1 | html { 2 | height: 100%; 3 | } 4 | body { 5 | height: 100%; 6 | padding-top: 56px; 7 | color: #e2e1e6; 8 | background-color: #141414; 9 | } 10 | h6 { 11 | color: #5990eb; 12 | margin-top: 25px; 13 | margin-bottom: 10px; 14 | } 15 | #animationButtons { 16 | display: grid; 17 | grid-template-columns: 1fr 1fr; 18 | grid-gap: 1.125rem; 19 | } 20 | #animationButtons button { 21 | display: flex; 22 | justify-content: space-between; 23 | vertical-align: middle; 24 | } 25 | #animationButtons button i { 26 | font-size: 1.25rem; 27 | margin: -0.188rem 0rem; 28 | } 29 | #colorPickersWrapper { 30 | margin: 10px 8px; 31 | } 32 | .colorPickerLabel label i { 33 | margin-right: 1.5rem; 34 | font-size: 1.25rem; 35 | } 36 | .colorPickerButton { 37 | transition: none; 38 | height: 2.5rem; 39 | width: 2.5rem; 40 | border-radius: 50%; 41 | } 42 | #slidersWrapper { 43 | margin: 21px 8px; 44 | } 45 | #slidersWrapper label i { 46 | display: inline-block; 47 | margin-right: 1.5rem; 48 | min-width: 1rem; 49 | font-size: 1.25rem; 50 | } 51 | #slidersWrapper input { 52 | margin: 0.625rem 0; 53 | } 54 | body .navbar { 55 | background-color: #28292e; 56 | } 57 | .btn-rounded { 58 | border-radius: 15px; 59 | padding: 15px 20px 18px; 60 | } 61 | .btn { 62 | border-width: 0px; 63 | outline:0px; 64 | } 65 | #settingsOffcanvas { 66 | background-color: #141414; 67 | } 68 | .btn:focus { 69 | box-shadow: none; 70 | } 71 | .form-select { 72 | background-color: #1d1d1f; 73 | border-color: #1d1d1f; 74 | color: rgb(241, 241, 241); 75 | border-radius: 50vh; 76 | border-width: 0px; 77 | } 78 | .form-select[disabled] { 79 | background-color: #1d1d1f !important; 80 | border-width: 0px; 81 | } 82 | input, textarea { 83 | background-color: #1d1d1f !important; 84 | color: rgb(241, 241, 241) !important; 85 | border-radius: 50vh !important; 86 | } 87 | .input-group { 88 | background-color: #1d1d1f; 89 | border-radius: 50vh; 90 | } 91 | .input-group button { 92 | color: white; 93 | } 94 | .input-group-addon { 95 | padding: 0px 15px; 96 | margin: auto; 97 | } 98 | .input-group-btn { 99 | margin: 0px 4px; 100 | } 101 | .form-control { 102 | border-width: 0px !important; 103 | } 104 | .form-check { 105 | margin-top: 20px; 106 | } 107 | .form-check-input { 108 | border-color: transparent !important; 109 | height: 25px !important; 110 | width: 42px !important; 111 | } 112 | .form-check-input:checked { 113 | background-color: #365078 !important; 114 | } 115 | .form-check-label { 116 | margin: 4px 13px; 117 | } 118 | .form-label { 119 | margin: 10px 0px; 120 | } 121 | body .form-range { 122 | background: transparent !important; 123 | } 124 | input[type=range]::-webkit-slider-runnable-track { 125 | cursor: pointer; 126 | background: #3e3e3e; 127 | height: 6px; 128 | } 129 | input[type=range]::-moz-range-track { 130 | cursor: pointer; 131 | background: #3e3e3e; 132 | height: 6px; 133 | } 134 | input[type=range]::-moz-range-thumb { 135 | height: 28px; 136 | width: 28px; 137 | border-radius: 50%; 138 | background: #5990eb; 139 | cursor: pointer; 140 | } 141 | input[type=range]::-webkit-slider-thumb { 142 | height: 28px; 143 | width: 28px; 144 | border-radius: 50%; 145 | background: #5990eb; 146 | cursor: pointer; 147 | -webkit-appearance: none; 148 | margin-top: -11.5px; 149 | } 150 | body .form-range::-moz-range-progress { 151 | background-color: #365078; 152 | height:6px; 153 | border-radius: 50vh; 154 | } 155 | #controlsWrapper, #navbarContent, #settingsContent { 156 | max-width: 450px; 157 | margin: auto; 158 | } 159 | .spinner { 160 | padding: 10px 0px; 161 | } 162 | .spinner .btn-spinner { 163 | padding: 0px 5px; 164 | font-size: 19px; 165 | font-weight: bold; 166 | cursor: pointer; 167 | user-select: none; 168 | vertical-align: middle; 169 | } 170 | .spinner .btn-spinner:hover { 171 | color: white; 172 | } 173 | .spinner .spinner-input { 174 | -moz-appearance: textfield; 175 | -webkit-appearance: none; 176 | width: 100px; 177 | height: 32px; 178 | border: 1px solid #6E6F7A; 179 | border-radius: 5px; 180 | color: #000; 181 | text-align: center; 182 | padding: 0.375rem 0.75rem; 183 | line-height: 1.5; 184 | } 185 | .spinner input::-webkit-outer-spin-button, 186 | .spinner input::-webkit-inner-spin-button { 187 | -webkit-appearance: none; 188 | margin: 0; 189 | } 190 | .spinner input[type=number]{ 191 | -moz-appearance: textfield; 192 | } 193 | .form-spinner-label { 194 | flex: 1; 195 | padding-top: 4px; 196 | } -------------------------------------------------------------------------------- /data/index.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | FastLEDHub 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 28 | 29 |
30 | 31 |
32 | 36 |
37 | 38 |
39 | 40 |
41 | 42 |
43 | 44 |
45 | 46 |
47 |
Settings
48 | 49 |
50 |
51 | 52 |
Time
53 |
54 | 55 | 56 |
57 |
58 | 59 | 60 |
61 | 62 |
Alarm
63 |
64 | 65 | 66 |
67 |
68 | 69 | 70 |
71 | 72 | 73 |
74 | 75 | 76 | 77 | 78 |
79 | 80 |
Sunset
81 |
82 | 83 | 84 |
85 |
86 |
87 | 88 | 89 |
90 |
91 | 92 | 93 |
94 | 95 | 96 | 97 | 98 | 99 | 100 |
101 | 102 |
Startup animation
103 |
104 | 105 | 106 |
107 |
108 | 109 | 110 |
111 |
112 | 113 |
114 | 115 | 121 | 122 | 130 | 131 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | -------------------------------------------------------------------------------- /data/index.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | let connection; 4 | let queue; 5 | let cooldownTimer; 6 | 7 | function openWebsocket(uri) { 8 | const ws = new WebSocket(uri, ["arduino"]); 9 | ws.binaryType = "arraybuffer"; 10 | return ws; 11 | } 12 | 13 | function openMainWebsocket() { 14 | connection = openWebsocket(`ws://${location.hostname}:81/`); 15 | connection.onopen = function () { 16 | displayConnectedState(true); 17 | }; 18 | connection.onclose = function () { 19 | displayConnectedState(false); 20 | }; 21 | connection.onmessage = function (e) { 22 | console.log("Received: ", e.data); 23 | handleJsonData(JSON.parse(e.data)); 24 | }; 25 | connection.onerror = function (e) { 26 | console.log("WebSocket Error", e); 27 | }; 28 | } 29 | 30 | function setupSpinners() { 31 | const spinners = document.getElementsByClassName("spinner"); 32 | [].forEach.call(spinners, (spinnerDiv) => { 33 | const inputElement = spinnerDiv.getElementsByTagName("input")[0]; 34 | inputElement.classList.add("spinner-input"); 35 | 36 | const buttonDec = document.createElement("span"); 37 | buttonDec.classList.add("btn-spinner", "btn-spinner-dec"); 38 | buttonDec.innerHTML = "−"; 39 | buttonDec.addEventListener("click", () => { 40 | const attrMin = inputElement.getAttribute("min"); 41 | const attrStep = inputElement.getAttribute("step"); 42 | const value = Number(inputElement.value); 43 | const step = attrStep ? Number(attrStep) : 1; 44 | const newValue = value - step; 45 | if (value !== newValue) { 46 | inputElement.value = attrMin 47 | ? Math.max(Number(attrMin), newValue) 48 | : newValue; 49 | } 50 | }); 51 | 52 | const buttonInc = document.createElement("span"); 53 | buttonInc.classList.add("btn-spinner", "btn-spinner-inc"); 54 | buttonInc.innerHTML = "+"; 55 | buttonInc.addEventListener("click", () => { 56 | const attrMin = inputElement.getAttribute("max"); 57 | const attrStep = inputElement.getAttribute("step"); 58 | const value = Number(inputElement.value); 59 | const step = attrStep ? Number(attrStep) : 1; 60 | const newValue = value + step; 61 | if (value !== newValue) { 62 | inputElement.value = attrMin 63 | ? Math.min(Number(attrMin), newValue) 64 | : newValue; 65 | } 66 | }); 67 | 68 | inputElement.insertAdjacentElement("beforebegin", buttonDec); 69 | inputElement.insertAdjacentElement("afterend", buttonInc); 70 | }); 71 | } 72 | 73 | function displayConnectedState(connected) { 74 | document.getElementById("navbarTitle").innerHTML = connected ? "FastLEDHub" : "Disconnected..."; 75 | document.getElementById("refreshButton").classList.toggle("d-none", connected); 76 | document.getElementById("stopButton").classList.toggle("d-none", !connected); 77 | document.getElementById("settingsButton").classList.toggle("d-none", !connected); 78 | } 79 | 80 | function registerColorPicker(colorPicker, idx) { 81 | const template = document.getElementById("colorPickerTemplate").innerHTML; 82 | const colorPickerId = "colorPicker" + idx; 83 | const colorPickerButtonId = "colorPickerButton" + idx; 84 | const colorPickersWrapper = document.getElementById("colorPickersWrapper"); 85 | colorPickersWrapper.insertAdjacentHTML( 86 | "beforeend", 87 | eval("`" + template + "`") 88 | ); 89 | const cp = new iro.ColorPicker("#" + colorPickerId, { 90 | width: 250, 91 | color: colorPicker.value, 92 | display: "inline-block", 93 | layout: [ 94 | { 95 | component: iro.ui.Wheel, 96 | options: {}, 97 | }, 98 | ], 99 | }); 100 | cp.on("color:change", function (color) { 101 | document.getElementById(colorPickerButtonId).style.backgroundColor = 102 | color.hexString; 103 | sendBytes([0, idx, color.red, color.green, color.blue]); 104 | }); 105 | document.getElementById(colorPickerButtonId).style.backgroundColor = 106 | cp.color.hexString; 107 | } 108 | 109 | // eslint-disable-next-line no-unused-vars 110 | function registerAnimation(animation, idx) { 111 | document.getElementById("alarmAnimation").add(new Option(animation)); 112 | document.getElementById("postAlarmAnimation").add(new Option(animation)); 113 | document.getElementById("sunsetAnimation").add(new Option(animation)); 114 | document.getElementById("startupAnimation").add(new Option(animation)); 115 | 116 | const template = document.getElementById("animationButtonTemplate").innerHTML; 117 | const animationButtons = document.getElementById("animationButtons"); 118 | animationButtons.lastElementChild.insertAdjacentHTML( 119 | "beforebegin", 120 | eval("`" + template + "`") 121 | ); 122 | } 123 | 124 | // eslint-disable-next-line no-unused-vars 125 | function registerSlider(slider, idx) { 126 | const template = document.getElementById("sliderTemplate").innerHTML; 127 | document.getElementById("slidersWrapper").insertAdjacentHTML("beforeend", eval("`" + template + "`")); 128 | } 129 | 130 | function handleJsonData(data) { 131 | data.animations?.forEach((animation, idx) => { 132 | registerAnimation(animation, idx); 133 | }); 134 | data.sliders?.forEach((slider, idx) => { 135 | registerSlider(slider, idx); 136 | }); 137 | data.colorPickers?.forEach((colorPicker, idx) => { 138 | registerColorPicker(colorPicker, idx); 139 | }); 140 | if (Object.prototype.hasOwnProperty.call(data, "startupAnimation")) { 141 | document.getElementById("startupAnimation").value = data.startupAnimation; 142 | document.getElementById("useStartupAnimation").checked = data.startupAnimation !== ""; 143 | if (data.startupAnimation !== "") 144 | new bootstrap.Collapse( 145 | document.getElementById("useStartupAnimationCollapse"), 146 | { toggle: false } 147 | ).show(); 148 | } 149 | if (Object.prototype.hasOwnProperty.call(data, "alarmEnabled")) { 150 | document.getElementById("alarmEnabled").checked = data.alarmEnabled; 151 | if (data.alarmEnabled) 152 | new bootstrap.Collapse(document.getElementById("alarmEnabledCollapse"), { 153 | toggle: false, 154 | }).show(); 155 | } 156 | if (Object.prototype.hasOwnProperty.call(data, "sunsetEnabled")) { 157 | document.getElementById("sunsetEnabled").checked = data.sunsetEnabled; 158 | if (data.sunsetEnabled) 159 | new bootstrap.Collapse(document.getElementById("sunsetEnabledCollapse"), { 160 | toggle: false, 161 | }).show(); 162 | } 163 | if (Object.prototype.hasOwnProperty.call(data, "alarmAnimation")) 164 | document.getElementById("alarmAnimation").value = data.alarmAnimation; 165 | if (Object.prototype.hasOwnProperty.call(data, "postAlarmAnimation")) 166 | document.getElementById("postAlarmAnimation").value = data.postAlarmAnimation; 167 | if (Object.prototype.hasOwnProperty.call(data, "sunsetAnimation")) 168 | document.getElementById("sunsetAnimation").value = data.sunsetAnimation; 169 | if (Object.prototype.hasOwnProperty.call(data, "sunsetDuration")) 170 | document.getElementById("sunsetDuration").value = data.sunsetDuration; 171 | if (Object.prototype.hasOwnProperty.call(data, "sunsetOffset")) 172 | document.getElementById("sunsetOffset").value = data.sunsetOffset; 173 | if (Object.prototype.hasOwnProperty.call(data, "timeZone")) 174 | document.getElementById("timeZone").value = data.timeZone; 175 | if (Object.prototype.hasOwnProperty.call(data, "summerTime")) 176 | document.getElementById("summerTime").checked = data.summerTime; 177 | if (Object.prototype.hasOwnProperty.call(data, "longitude")) 178 | document.getElementById("longitude").value = data.longitude; 179 | if (Object.prototype.hasOwnProperty.call(data, "latitude")) 180 | document.getElementById("latitude").value = data.latitude; 181 | if (Object.prototype.hasOwnProperty.call(data, "alarmDuration")) 182 | document.getElementById("alarmDuration").value = data.alarmDuration; 183 | if ( 184 | Object.prototype.hasOwnProperty.call(data, "alarmHour") && 185 | Object.prototype.hasOwnProperty.call(data, "alarmMinute") 186 | ) 187 | document.getElementById("alarmTime").value = 188 | (data.alarmHour < 10 ? "0" + data.alarmHour.toString() : data.alarmHour) + ":" + 189 | (data.alarmMinute < 10 ? "0" + data.alarmMinute.toString() : data.alarmMinute); 190 | if ( 191 | Object.prototype.hasOwnProperty.call(data, "status") && 192 | Object.prototype.hasOwnProperty.call(data, "currentAnimation") 193 | ) { 194 | updateAnimationButtons(data.status, data.currentAnimation); 195 | } 196 | } 197 | 198 | function updateAnimationButtons(status, animation) { 199 | const animationButtons = document.querySelectorAll("#animationButtons button"); 200 | animationButtons.forEach((btn, idx) => { 201 | const buttonIcon = btn.querySelector("div i"); 202 | const buttonContent = btn.querySelector("div span").innerHTML; 203 | if (animation === buttonContent) { 204 | if (status === 2) { 205 | buttonIcon.classList = "bi bi-play-fill"; 206 | } else if (status === 1) { 207 | buttonIcon.classList = "bi bi-pause"; 208 | } 209 | } else if (idx === animationButtons.length - 1 && status === 0) { 210 | buttonIcon.classList = "bi bi-stop-fill"; 211 | } else { 212 | buttonIcon.classList = "bi"; 213 | } 214 | }); 215 | } 216 | 217 | function sendConfig() { 218 | const time = alarmTime.value.split(":"); 219 | const json = JSON.stringify( 220 | { 221 | alarmHour: time[0], 222 | alarmMinute: time[1], 223 | alarmEnabled: document.getElementById("alarmEnabled").checked, 224 | alarmDuration: document.getElementById("alarmDuration").value, 225 | alarmAnimation: document.getElementById("alarmAnimation").value, 226 | postAlarmAnimation: document.getElementById("postAlarmAnimation").value, 227 | timeZone: document.getElementById("timeZone").value, 228 | summerTime: document.getElementById("summerTime").checked, 229 | longitude: document.getElementById("longitude").value, 230 | latitude: document.getElementById("latitude").value, 231 | sunsetEnabled: document.getElementById("sunsetEnabled").checked, 232 | sunsetDuration: document.getElementById("sunsetDuration").value, 233 | sunsetOffset: document.getElementById("sunsetOffset").value, 234 | sunsetAnimation: document.getElementById("sunsetAnimation").value, 235 | startupAnimation: document.getElementById("useStartupAnimation").checked 236 | ? document.getElementById("startupAnimation").value 237 | : "", 238 | }, 239 | null, 240 | 2 241 | ); 242 | sendText(json); 243 | } 244 | 245 | function sendBytes(bytes) { 246 | queue = bytes; 247 | 248 | if (cooldownTimer) return; 249 | 250 | sendBytesQueue(); 251 | cooldownTimer = setTimeout(() => { 252 | cooldownTimer = null; 253 | sendBytesQueue(); 254 | }, 15); 255 | } 256 | 257 | function sendBytesQueue() { 258 | if (!queue || connection.readyState !== 1) return; 259 | 260 | const data = Uint8Array.from(queue); 261 | connection.send(data.buffer); 262 | console.log("Sent bytes: " + data); 263 | 264 | queue = null; 265 | } 266 | 267 | function sendText(text) { 268 | if (connection.readyState !== 1) { 269 | console.log("Not connected. Text not sent!"); 270 | return; 271 | } 272 | 273 | connection.send(text); 274 | console.log("Sent text: " + text); 275 | } 276 | 277 | window.onload = () => { 278 | openMainWebsocket(); 279 | setupSpinners(); 280 | document.getElementById("settingsOffcanvas").addEventListener("hidden.bs.offcanvas", function () { 281 | sendConfig(); 282 | }); 283 | }; 284 | -------------------------------------------------------------------------------- /data/index.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srwi/FastLEDHub/79fec5edbe546e8fc42b3589e81288894c665e20/data/index.png -------------------------------------------------------------------------------- /examples/BasicExample/Animations/Confetti.h: -------------------------------------------------------------------------------- 1 | /// This animation has been taken from https://github.com/atuline/FastLED-Demos and 2 | /// modified to be used with FastLEDHub. 3 | /// It is licensed under the GNU General Public License v3.0. 4 | 5 | #pragma once 6 | 7 | #include 8 | 9 | extern CRGB leds[]; 10 | 11 | class Confetti : public Animation 12 | { 13 | public: 14 | using Animation::Animation; 15 | 16 | uint8_t fade = 8; 17 | uint8_t inc = 1; 18 | uint8_t saturation = 100; 19 | uint8_t brightness = 255; 20 | int hue = 50; 21 | int hueDiff = 256; 22 | 23 | void reset() 24 | { 25 | } 26 | 27 | void loop() 28 | { 29 | uint8_t secondHand = (millis() / 1000) % 15; 30 | static uint8_t lastSecond = 99; 31 | if (lastSecond != secondHand) 32 | { 33 | lastSecond = secondHand; 34 | switch(secondHand) 35 | { 36 | case 0: inc = 1; hue = 192; saturation = 255; fade = 2; hueDiff = 256; break; 37 | case 5: inc = 2; hue = 128; fade = 8; hueDiff = 64; break; 38 | case 10: inc = 1; hue = random16(255); fade = 1; hueDiff = 16; break; 39 | case 15: break; 40 | } 41 | } 42 | 43 | fadeToBlackBy(leds, FastLEDHub[0].size(), fade); 44 | int pos = random16(FastLEDHub[0].size()); 45 | leds[pos] += CHSV((hue + random16(hueDiff))/4 , saturation, brightness); 46 | hue = hue + inc; 47 | 48 | FastLEDHub.delay(5); 49 | FastLEDHub.show(); 50 | } 51 | 52 | }; 53 | -------------------------------------------------------------------------------- /examples/BasicExample/Animations/Gradient.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | extern CRGB leds[]; 6 | 7 | class Gradient : public Animation 8 | { 9 | public: 10 | using Animation::Animation; 11 | 12 | uint16_t NUM_LEDS; 13 | 14 | void reset() 15 | { 16 | NUM_LEDS = FastLEDHub[0].size(); 17 | } 18 | 19 | void loop() 20 | { 21 | for(uint16_t i = 0; i < NUM_LEDS; i++) 22 | { 23 | leds[i] = blend(FastLEDHub.getColorPicker(0)->value, FastLEDHub.getColorPicker(1)->value, 255 * i / NUM_LEDS); 24 | } 25 | 26 | FastLEDHub.show(); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /examples/BasicExample/Animations/RGBWave.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | extern CRGB leds[]; 6 | 7 | class RGBWave : public Animation 8 | { 9 | public: 10 | using Animation::Animation; 11 | 12 | uint8_t ledDiv = HSV2RGB_SMOOTH_RANGE / FastLEDHub.size(); 13 | uint16_t step; 14 | 15 | void reset() 16 | { 17 | step = 0; 18 | } 19 | 20 | void loop() 21 | { 22 | for (uint16_t i = 0; i < FastLEDHub.size(); i++) 23 | { 24 | leds[i] = hsv2rgb_smooth((ledDiv * i + step) % HSV2RGB_SMOOTH_RANGE, FastLEDHub.getSlider("Saturation")->value, 255); 25 | } 26 | 27 | step++; 28 | if (step == HSV2RGB_SMOOTH_RANGE) 29 | step = 0; 30 | 31 | FastLEDHub.delay(5); 32 | FastLEDHub.show(); 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /examples/BasicExample/Animations/Rainbow.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | extern CRGB leds[]; 6 | 7 | class Rainbow : public Animation 8 | { 9 | public: 10 | using Animation::Animation; 11 | 12 | void reset() 13 | { 14 | } 15 | 16 | void loop() 17 | { 18 | // Since we use beatsin88 to generate a sine wave we need to incorporate the speed slider without using delay(): 19 | uint16_t speed = FastLEDHub.getSlider("Speed")->value; 20 | uint16_t startHue = beatsin16(speed / 16 / 5, 0, 1535); 21 | uint16_t endHue = beatsin16(speed / 16 / 2, 0, 1535); 22 | 23 | if (startHue < endHue) 24 | { 25 | for(int16_t i = 0; i < FastLEDHub[0].size(); i++) 26 | { 27 | leds[i] = hsv2rgb_smooth(startHue + (endHue - startHue) * i / FastLEDHub[0].size(), FastLEDHub.getSlider("Saturation")->value, 255); 28 | } 29 | } 30 | else 31 | { 32 | for(int16_t i = FastLEDHub[0].size() - 1; i >= 0; i--) 33 | { 34 | leds[i] = hsv2rgb_smooth(startHue + (endHue - startHue) * i / FastLEDHub[0].size(), FastLEDHub.getSlider("Saturation")->value, 255); 35 | } 36 | } 37 | 38 | FastLEDHub.show(); 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /examples/BasicExample/BasicExample.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "Animations/Confetti.h" 4 | #include "Animations/Color.h" 5 | #include "Animations/Gradient.h" 6 | #include "Animations/Rainbow.h" 7 | #include "Animations/RGBWave.h" 8 | 9 | #define NUM_LEDS 100 10 | #define LIGHTSTRIP_PIN 5 11 | #define LED_TYPE WS2812B 12 | 13 | CRGB leds[NUM_LEDS]; 14 | 15 | void setup() 16 | { 17 | FastLEDHub.initialize("Basic Example"); 18 | FastLEDHub.addLeds(leds, NUM_LEDS); 19 | 20 | FastLEDHub.registerAnimation(new Color("Color")); 21 | FastLEDHub.registerAnimation(new Gradient("Gradient")); 22 | FastLEDHub.registerAnimation(new Rainbow("Rainbow")); 23 | FastLEDHub.registerAnimation(new RGBWave("RGB Wave")); 24 | FastLEDHub.registerAnimation(new Confetti("Confetti")); 25 | 26 | FastLEDHub.registerSlider(new Slider("Saturation", 0, 255, 255, 1, "palette2")); 27 | 28 | FastLEDHub.registerColorPicker(new ColorPicker("Primary Color", CRGB(255, 0, 0))); 29 | FastLEDHub.registerColorPicker(new ColorPicker("Secondary Color", CRGB(0, 255, 0))); 30 | } 31 | 32 | void loop() 33 | { 34 | FastLEDHub.handle(); 35 | } 36 | -------------------------------------------------------------------------------- /examples/ColorPickers/Animations/Gradient.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | extern CRGB leds[]; 6 | 7 | class Gradient : public Animation 8 | { 9 | public: 10 | using Animation::Animation; 11 | 12 | uint16_t NUM_LEDS; 13 | 14 | void reset() 15 | { 16 | NUM_LEDS = FastLEDHub[0].size(); 17 | } 18 | 19 | void loop() 20 | { 21 | for(uint16_t i = 0; i < NUM_LEDS; i++) 22 | { 23 | leds[i] = blend(FastLEDHub.getColorPicker(0)->value, FastLEDHub.getColorPicker(1)->value, 255 * i / NUM_LEDS); 24 | } 25 | 26 | FastLEDHub.show(); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /examples/ColorPickers/ColorPickers.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include // This animation comes with FastLEDHub 4 | #include "Animations/Gradient.h" 5 | 6 | #define NUM_LEDS 100 7 | #define LIGHTSTRIP_PIN 5 8 | #define LED_TYPE WS2812B 9 | 10 | CRGB leds[NUM_LEDS]; 11 | 12 | void setup() 13 | { 14 | FastLEDHub.initialize("Color Pickers Example"); 15 | FastLEDHub.addLeds(leds, NUM_LEDS); 16 | 17 | FastLEDHub.registerAnimation(new Color("Color")); 18 | FastLEDHub.registerAnimation(new Gradient("Gradient")); 19 | 20 | FastLEDHub.registerColorPicker(new ColorPicker("Primary Color", CRGB(255, 0, 0))); 21 | FastLEDHub.registerColorPicker(new ColorPicker("Secondary Color", CRGB(255, 0, 0))); 22 | } 23 | 24 | void loop() 25 | { 26 | FastLEDHub.handle(); 27 | } 28 | -------------------------------------------------------------------------------- /examples/Sliders/Animations/Rainbow.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | extern CRGB leds[]; 6 | 7 | class Rainbow : public Animation 8 | { 9 | public: 10 | using Animation::Animation; 11 | 12 | void reset() 13 | { 14 | } 15 | 16 | void loop() 17 | { 18 | // Since we use beatsin88 to generate a sine wave we need to incorporate the speed slider without using delay(): 19 | uint16_t speed = FastLEDHub.getSlider("Speed")->value; 20 | uint16_t startHue = beatsin16(speed / 16 / 5, 0, 1535); 21 | uint16_t endHue = beatsin16(speed / 16 / 2, 0, 1535); 22 | 23 | if (startHue < endHue) 24 | { 25 | for(int16_t i = 0; i < FastLEDHub[0].size(); i++) 26 | { 27 | leds[i] = hsv2rgb_smooth(startHue + (endHue - startHue) * i / FastLEDHub[0].size(), FastLEDHub.getSlider("Saturation")->value, 255); 28 | } 29 | } 30 | else 31 | { 32 | for(int16_t i = FastLEDHub[0].size() - 1; i >= 0; i--) 33 | { 34 | leds[i] = hsv2rgb_smooth(startHue + (endHue - startHue) * i / FastLEDHub[0].size(), FastLEDHub.getSlider("Saturation")->value, 255); 35 | } 36 | } 37 | 38 | FastLEDHub.show(); 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /examples/Sliders/Sliders.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "Animations/Rainbow.h" 4 | 5 | #define NUM_LEDS 100 6 | #define LIGHTSTRIP_PIN 5 7 | #define LED_TYPE WS2812B 8 | 9 | CRGB leds[NUM_LEDS]; 10 | 11 | void setup() 12 | { 13 | FastLEDHub.initialize("Sliders Example"); 14 | FastLEDHub.addLeds(leds, NUM_LEDS); 15 | 16 | FastLEDHub.registerAnimation(new Rainbow("Rainbow")); 17 | 18 | FastLEDHub.registerSlider(new Slider("Saturation", 0, 255, 255, 1, "palette2")); 19 | } 20 | 21 | void loop() 22 | { 23 | FastLEDHub.handle(); 24 | } 25 | -------------------------------------------------------------------------------- /examples/Spectrogram/Animations/Spectrogram.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | // This example requires the use of https://github.com/srwi/FastLEDHub_AudioViz to send 4 | // spectrum data to the ESP32/ESP8266 running FastLEDHub. 5 | 6 | #include 7 | 8 | #include 9 | 10 | extern CRGB leds[]; 11 | 12 | class Spectrogram : public Animation 13 | { 14 | public: 15 | using Animation::Animation; 16 | 17 | uint8_t interpolateSpectrum(uint16_t led) 18 | { 19 | float stepSize = (float)(SPECTRUM_LENGTH - 1) / ((float)FastLEDHub.size() - 1); 20 | float spectrumPosition = led * stepSize; 21 | int16_t spectrumFloorIndex = (int16_t)spectrumPosition % SPECTRUM_LENGTH; 22 | int16_t spectrumFloor = FastLEDHub.spectrumData[spectrumFloorIndex]; 23 | int16_t spectrumCeil = FastLEDHub.spectrumData[(spectrumFloorIndex + 1) % SPECTRUM_LENGTH]; 24 | uint8_t intensity = spectrumFloor + fmod(spectrumPosition, 1) * (spectrumCeil - spectrumFloor); 25 | return intensity; 26 | } 27 | 28 | void reset() 29 | { 30 | } 31 | 32 | void loop() 33 | { 34 | for (uint16_t i = 0; i < FastLEDHub.size(); i++) 35 | { 36 | CRGB color = CRGB::White; 37 | leds[i] = color.nscale8(interpolateSpectrum(i)); 38 | } 39 | 40 | FastLEDHub.show(); 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /examples/Spectrogram/Spectrogram.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "Animations/Spectrogram.h" 4 | 5 | #define NUM_LEDS 100 6 | #define LIGHTSTRIP_PIN 5 7 | #define LED_TYPE WS2812B 8 | 9 | CRGB leds[NUM_LEDS]; 10 | 11 | void setup() 12 | { 13 | FastLEDHub.initialize("Spectrogram Example"); 14 | FastLEDHub.addLeds(leds, NUM_LEDS); 15 | 16 | FastLEDHub.registerAnimation(new Spectrogram("Spectrogram")); 17 | } 18 | 19 | void loop() 20 | { 21 | FastLEDHub.handle(); 22 | } 23 | -------------------------------------------------------------------------------- /library.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "FastLEDHub", 3 | "description": "Control multiple FastLED lightstrip animations on the ESP8266/ESP32 without reuploading.", 4 | "repository": 5 | { 6 | "type": "git", 7 | "url": "https://github.com/srwi/FastLEDHub.git" 8 | }, 9 | "frameworks": "arduino", 10 | "platforms": [ 11 | "espressif8266", 12 | "espressif32" 13 | ], 14 | "authors": 15 | { 16 | "name": "Stephan Rumswinkel", 17 | "maintainer": true, 18 | "url": "https://github.com/srwi" 19 | }, 20 | "license": "LGPL-2.1-or-later", 21 | "version": "2.2.0" 22 | } 23 | -------------------------------------------------------------------------------- /library.properties: -------------------------------------------------------------------------------- 1 | name=FastLEDHub 2 | version=2.2.0 3 | author=Stephan Rumswinkel 4 | maintainer=Stephan Rumswinkel 5 | sentence=Control multiple FastLED lightstrip animations on the ESP8266 and ESP32 without reuploading. 6 | paragraph=FastLEDHub allows you to manage all of your FastLED sketches on the ESP8266 and ESP32 with minimal changes to your existing code. It requires little knowledge about the ESP8266/ESP32 platform making in an ideal playground for beginners getting started with FastLED animations. 7 | url=https://github.com/srwi/FastLEDHub.git 8 | category=Display 9 | architectures=esp8266,esp32 10 | depends=WiFiManager (>=2.0.0),ESPEssentials (>=2.1.0),ArduinoJson (>=7.0.0),LinkedList,FastLED,WebSockets 11 | -------------------------------------------------------------------------------- /src/Animation.cpp: -------------------------------------------------------------------------------- 1 | #include "Animation.h" 2 | 3 | Animation::Animation(String name) : m_name(name) 4 | { 5 | } 6 | 7 | String Animation::getName() 8 | { 9 | return m_name; 10 | } 11 | -------------------------------------------------------------------------------- /src/Animation.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | class Animation 6 | { 7 | public: 8 | Animation() = delete; 9 | 10 | /// Constructor 11 | /// @param name Unique animation name 12 | Animation(String name); 13 | 14 | /// Get the animation name 15 | /// @return Animation name 16 | String getName(); 17 | 18 | /// Loop method gets called repeatedly while running 19 | /// the animation. This method needs to be implemented. 20 | virtual void loop() = 0; 21 | 22 | /// Setup method gets called when the animation starts. 23 | /// This method needs to be implemented. 24 | virtual void reset() = 0; 25 | 26 | private: 27 | String m_name; 28 | }; 29 | -------------------------------------------------------------------------------- /src/Animations/Color.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "ColorUtils.h" 4 | 5 | #include 6 | 7 | class Color : public Animation 8 | { 9 | public: 10 | using Animation::Animation; 11 | 12 | void reset() 13 | { 14 | } 15 | 16 | void loop() 17 | { 18 | CRGB color = FastLEDHub.getColorPicker(0)->value; 19 | FastLEDHub.showColor(color); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /src/ColorPicker.h: -------------------------------------------------------------------------------- 1 | #include 2 | #define FASTLED_INTERNAL 3 | #include 4 | 5 | class ColorPicker 6 | { 7 | public: 8 | String name; 9 | CRGB value; 10 | String icon; 11 | 12 | ColorPicker(String _name, CRGB _value, String _icon = "eyedropper") 13 | { 14 | name = _name; 15 | value = _value; 16 | icon = _icon; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /src/ColorUtils.cpp: -------------------------------------------------------------------------------- 1 | #include "ColorUtils.h" 2 | 3 | CRGB hsv2rgb_smooth(uint16_t hue, uint8_t sat, uint8_t val) 4 | { 5 | uint8_t fractHue = hue / 6; 6 | uint8_t fractBlend = hue % 6; 7 | 8 | CRGB leftColor, rightColor; 9 | hsv2rgb_rainbow(CHSV(fractHue, sat, val), leftColor); 10 | hsv2rgb_rainbow(CHSV(fractHue + 1, sat, val), rightColor); 11 | 12 | return blend(leftColor, rightColor, 42 * fractBlend); 13 | } 14 | 15 | String rgb2hex(CRGB rgb) 16 | { 17 | String output = ""; 18 | 19 | if (rgb.r == 0) 20 | output += "00"; 21 | else 22 | output += (rgb.r < 16 ? "0" : "") + String(rgb.r, HEX); 23 | 24 | if (rgb.g == 0) 25 | output += "00"; 26 | else 27 | output += (rgb.g < 16 ? "0" : "") + String(rgb.g, HEX); 28 | 29 | if (rgb.b == 0) 30 | output += "00"; 31 | else 32 | output += (rgb.b < 16 ? "0" : "") + String(rgb.b, HEX); 33 | 34 | return output; 35 | } 36 | 37 | CRGB hex2rgb(String hex) 38 | { 39 | return strtol(hex.c_str(), NULL, 16); 40 | } -------------------------------------------------------------------------------- /src/ColorUtils.h: -------------------------------------------------------------------------------- 1 | #include 2 | #define FASTLED_INTERNAL 3 | #include 4 | 5 | #define HSV2RGB_SMOOTH_RANGE 1535 6 | 7 | /// Convert a hue, saturation and value to RGB by using a higher resolution 8 | /// of 0 - 1535 which allows for very smooth hue transitions without 9 | /// noticeable steps. The number 1535 is also defined by HSV2RGB_SMOOTH_RANGE. 10 | /// @param hue hue value (0 - 1535) 11 | /// @param sat saturation value (0 - 255) 12 | /// @param val color value (0 - 255) 13 | /// @return CRGB color 14 | CRGB hsv2rgb_smooth(uint16_t hue, uint8_t sat, uint8_t val); 15 | 16 | /// Convert RGB color to hex string representation 17 | /// @param rgb CRGB color 18 | /// @return Hex string representation 19 | String rgb2hex(CRGB rgb); 20 | 21 | /// Convert hex string representation of a color to RGB color 22 | /// @param hex Hex string 23 | /// @return CRGB color 24 | CRGB hex2rgb(String hex); 25 | -------------------------------------------------------------------------------- /src/Config.cpp: -------------------------------------------------------------------------------- 1 | #include "Config.h" 2 | 3 | #include "ColorUtils.h" 4 | #include "SerialOut.h" 5 | #include "FastLEDHub.h" 6 | 7 | #if defined(USE_SPIFFS) 8 | #if defined(ESP32) 9 | #include 10 | #elif defined(ESP8266) 11 | #include 12 | #endif 13 | #define FILESYSTEM SPIFFS 14 | #else 15 | #include 16 | #define FILESYSTEM LittleFS 17 | #endif 18 | 19 | #include 20 | 21 | bool ConfigClass::initialize() 22 | { 23 | if (!FILESYSTEM.begin()) 24 | { 25 | PRINTLN("[FastLEDHub] Couldn't mount file system."); 26 | return false; 27 | } 28 | 29 | SUSPEND_TIMER1(); 30 | File configFile = FILESYSTEM.open(m_configFilename, "r"); 31 | if (!configFile) 32 | { 33 | PRINTLN("[FastLEDHub] Opening file '" + m_configFilename + "' failed."); 34 | return false; 35 | } 36 | 37 | String content; 38 | if (configFile.available()) 39 | { 40 | content = configFile.readString(); 41 | } 42 | configFile.close(); 43 | RESUME_TIMER1(); 44 | 45 | char json[content.length()]; 46 | content.toCharArray(json, content.length()); 47 | 48 | return parseJson(json); 49 | } 50 | 51 | bool ConfigClass::parseJson(const char *input) 52 | { 53 | JsonDocument doc; 54 | DeserializationError error = deserializeJson(doc, input); 55 | 56 | if (doc.containsKey("timeZone")) 57 | timeZone = doc["timeZone"]; 58 | if (doc.containsKey("summerTime")) 59 | summerTime = doc["summerTime"]; 60 | if (doc.containsKey("longitude")) 61 | longitude = doc["longitude"]; 62 | if (doc.containsKey("latitude")) 63 | latitude = doc["latitude"]; 64 | if (doc.containsKey("alarmEnabled")) 65 | alarmEnabled = doc["alarmEnabled"]; 66 | if (doc.containsKey("alarmDuration")) 67 | alarmDuration = doc["alarmDuration"]; 68 | if (doc.containsKey("alarmHour")) 69 | alarmHour = doc["alarmHour"]; 70 | if (doc.containsKey("alarmMinute")) 71 | alarmMinute = doc["alarmMinute"]; 72 | if (doc.containsKey("alarmAnimation")) 73 | alarmAnimation = doc["alarmAnimation"].as(); 74 | if (doc.containsKey("postAlarmAnimation")) 75 | postAlarmAnimation = doc["postAlarmAnimation"].as(); 76 | if (doc.containsKey("sunsetEnabled")) 77 | sunsetEnabled = doc["sunsetEnabled"]; 78 | if (doc.containsKey("sunsetHour")) 79 | sunsetHour = doc["sunsetHour"]; 80 | if (doc.containsKey("sunsetMinute")) 81 | sunsetMinute = doc["sunsetMinute"]; 82 | if (doc.containsKey("sunsetDuration")) 83 | sunsetDuration = doc["sunsetDuration"]; 84 | if (doc.containsKey("sunsetOffset")) 85 | sunsetOffset = doc["sunsetOffset"]; 86 | if (doc.containsKey("sunsetAnimation")) 87 | sunsetAnimation = doc["sunsetAnimation"].as(); 88 | if (doc.containsKey("startupAnimation")) 89 | startupAnimation = doc["startupAnimation"].as(); 90 | if (doc.containsKey("sliderValues")) 91 | { 92 | sliderValues.clear(); 93 | JsonArray sliderValueArray = doc["sliderValues"].as(); 94 | for (uint16_t i = 0; i < sliderValueArray.size(); i++) 95 | { 96 | sliderValues.add(sliderValueArray[i]); 97 | } 98 | } 99 | if (doc.containsKey("colorPickerValues")) 100 | { 101 | colorPickerValues.clear(); 102 | JsonArray colorPickerValueArray = doc["colorPickerValues"].as(); 103 | for (uint16_t i = 0; i < colorPickerValueArray.size(); i++) 104 | { 105 | colorPickerValues.add(hex2rgb(colorPickerValueArray[i])); 106 | } 107 | } 108 | 109 | return !error; 110 | } 111 | 112 | void ConfigClass::getUserConfigJson(JsonDocument &doc) 113 | { 114 | doc["timeZone"] = timeZone; 115 | doc["summerTime"] = summerTime; 116 | doc["longitude"] = longitude; 117 | doc["latitude"] = latitude; 118 | doc["alarmEnabled"] = alarmEnabled; 119 | doc["alarmHour"] = alarmHour; 120 | doc["alarmMinute"] = alarmMinute; 121 | doc["alarmDuration"] = alarmDuration; 122 | doc["alarmAnimation"] = alarmAnimation; 123 | doc["postAlarmAnimation"] = postAlarmAnimation; 124 | doc["sunsetEnabled"] = sunsetEnabled; 125 | doc["sunsetHour"] = sunsetHour; 126 | doc["sunsetMinute"] = sunsetMinute; 127 | doc["sunsetDuration"] = sunsetDuration; 128 | doc["sunsetOffset"] = sunsetOffset; 129 | doc["sunsetAnimation"] = sunsetAnimation; 130 | doc["startupAnimation"] = startupAnimation; 131 | JsonArray sliderValueArray = doc["sliderValues"].to(); 132 | for (uint16_t i = 0; i < sliderValues.size(); i++) 133 | { 134 | sliderValueArray.add(sliderValues.get(i)); 135 | } 136 | JsonArray colorPickerValueArray = doc["colorPickerValues"].to(); 137 | for (uint16_t i = 0; i < colorPickerValues.size(); i++) 138 | { 139 | colorPickerValueArray.add(rgb2hex(colorPickerValues.get(i))); 140 | } 141 | } 142 | 143 | void ConfigClass::getApplicationStateJson(JsonDocument &doc) 144 | { 145 | doc["status"] = FastLEDHub.getStatus(); 146 | doc["currentAnimation"] = FastLEDHub.getCurrentAnimationName(); 147 | JsonArray animations = doc["animations"].to(); 148 | for (uint8_t i = 0; i < FastLEDHub.animations.size(); i++) 149 | { 150 | animations.add(FastLEDHub.animations.get(i)->getName()); 151 | } 152 | JsonArray sliders = doc["sliders"].to(); 153 | for (uint8_t i = 0; i < FastLEDHub.sliders.size(); i++) 154 | { 155 | JsonObject slider = sliders.add(); 156 | slider["name"] = FastLEDHub.sliders.get(i)->name; 157 | slider["min"] = FastLEDHub.sliders.get(i)->min; 158 | slider["max"] = FastLEDHub.sliders.get(i)->max; 159 | slider["step"] = FastLEDHub.sliders.get(i)->step; 160 | slider["value"] = FastLEDHub.sliders.get(i)->value; 161 | slider["icon"] = FastLEDHub.sliders.get(i)->icon; 162 | } 163 | JsonArray colorPickers = doc["colorPickers"].to(); 164 | for (uint8_t i = 0; i < FastLEDHub.colorPickers.size(); i++) 165 | { 166 | JsonObject colorPicker = colorPickers.add(); 167 | colorPicker["name"] = FastLEDHub.colorPickers.get(i)->name; 168 | colorPicker["value"] = rgb2hex(FastLEDHub.colorPickers.get(i)->value); 169 | colorPicker["icon"] = FastLEDHub.colorPickers.get(i)->icon; 170 | } 171 | } 172 | 173 | String ConfigClass::asString(bool includeApplicationState) 174 | { 175 | JsonDocument doc; 176 | 177 | getUserConfigJson(doc); 178 | 179 | if (includeApplicationState) 180 | { 181 | getApplicationStateJson(doc); 182 | } 183 | 184 | String buffer = ""; 185 | serializeJsonPretty(doc, buffer); 186 | return buffer; 187 | } 188 | 189 | bool ConfigClass::save() 190 | { 191 | SUSPEND_TIMER1(); 192 | File configFile = FILESYSTEM.open(m_configFilename, "w"); 193 | if (!configFile) 194 | { 195 | PRINTLN("[FastLEDHub] Opening file " + m_configFilename + " for saving failed."); 196 | return false; 197 | } 198 | 199 | configFile.println(asString()); 200 | configFile.close(); 201 | 202 | return true; 203 | } 204 | 205 | ConfigClass Config; 206 | -------------------------------------------------------------------------------- /src/Config.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #define FASTLED_INTERNAL 6 | #include 7 | #include 8 | 9 | class ConfigClass 10 | { 11 | public: 12 | int8_t timeZone = 0; 13 | int8_t summerTime = 0; 14 | float longitude = 0; 15 | float latitude = 0; 16 | bool alarmEnabled = false; 17 | uint16_t alarmDuration = 1; 18 | uint8_t alarmHour = 0; 19 | uint8_t alarmMinute = 0; 20 | String alarmAnimation = ""; 21 | String postAlarmAnimation = ""; 22 | bool sunsetEnabled = false; 23 | uint16_t sunsetDuration = 1; 24 | int8_t sunsetHour = 0; 25 | int8_t sunsetMinute = 0; 26 | int16_t sunsetOffset = 0; 27 | String sunsetAnimation = ""; 28 | String startupAnimation = ""; 29 | LinkedList sliderValues; 30 | LinkedList colorPickerValues; 31 | 32 | /// Initialize config object by reading the config file. 33 | /// @return True if successful 34 | bool initialize(); 35 | 36 | /// Save config to file system 37 | /// @return True if successful 38 | bool save(); 39 | 40 | /// Parse a JSON char array and apply its values to the config. 41 | /// @param input JSON char array 42 | /// @return True if successful 43 | bool parseJson(const char *input); 44 | 45 | /// Get config and (optional) application state as JSON String. 46 | /// @param includeApplicationState Include application state (default: false) 47 | /// @return JSON String 48 | String asString(bool includeApplicationState = false); 49 | 50 | private: 51 | const String m_configFilename = "/config.txt"; 52 | 53 | void getUserConfigJson(JsonDocument &doc); 54 | void getApplicationStateJson(JsonDocument &doc); 55 | }; 56 | 57 | extern ConfigClass Config; 58 | -------------------------------------------------------------------------------- /src/FWebserver.cpp: -------------------------------------------------------------------------------- 1 | #include "FWebserver.h" 2 | 3 | #include "Animation.h" 4 | #include "Fade.h" 5 | #include "FastLEDHub.h" 6 | 7 | #include 8 | #include 9 | 10 | namespace Webserver 11 | { 12 | 13 | void initialize() 14 | { 15 | ESPEssentials::WebServer.on("/reboot", HTTP_GET, [&]() 16 | { ESP.restart(); }); 17 | ESPEssentials::WebServer.on("/sunset", HTTP_GET, [&]() 18 | { 19 | Fade::begin(Fade::FadeMode::SUNSET); 20 | ESPEssentials::WebServer.send(200, "text/plain", "Starting sunset."); 21 | }); 22 | ESPEssentials::WebServer.on("/alarm", HTTP_GET, [&]() 23 | { 24 | Fade::begin(Fade::FadeMode::ALARM); 25 | ESPEssentials::WebServer.send(200, "text/plain", "Starting alarm."); 26 | }); 27 | ESPEssentials::WebServer.on("/stop", HTTP_GET, [&]() 28 | { 29 | Fade::stop(); 30 | FastLEDHub.stop(); 31 | ESPEssentials::WebServer.send(200, "text/plain", "Animation stopped."); 32 | }); 33 | ESPEssentials::WebServer.on("/pause", HTTP_GET, [&]() 34 | { 35 | FastLEDHub.pause(); 36 | ESPEssentials::WebServer.send(200, "text/plain", "Animation paused."); 37 | }); 38 | ESPEssentials::WebServer.on("/resume", HTTP_GET, [&]() 39 | { 40 | FastLEDHub.resume(); 41 | ESPEssentials::WebServer.send(200, "text/plain", "Animation resumed."); 42 | }); 43 | ESPEssentials::WebServer.on("/toggle", HTTP_GET, [&]() 44 | { 45 | FastLEDHub.toggle(); 46 | ESPEssentials::WebServer.send(200, "text/plain", "Animation toggled."); 47 | }); 48 | ESPEssentials::WebServer.on("/restart", HTTP_GET, [&]() 49 | { 50 | FastLEDHub.restart(); 51 | ESPEssentials::WebServer.send(200, "text/plain", "Animation restarted."); 52 | }); 53 | ESPEssentials::WebServer.on("/status", HTTP_GET, [&]() 54 | { 55 | String statusMsg = "{\"status\": " + String((int) FastLEDHub.getStatus()) + ", \"currentAnimation\": \"" + FastLEDHub.getCurrentAnimationName() + "\"}"; 56 | ESPEssentials::WebServer.send(200, "text/plain", statusMsg.c_str()); 57 | }); 58 | ESPEssentials::WebServer.on("/begin", HTTP_GET, [&]() 59 | { 60 | if (ESPEssentials::WebServer.hasArg("animation")) 61 | { 62 | String animationName = String(ESPEssentials::WebServer.arg("animation")); 63 | FastLEDHub.begin(FastLEDHub.getAnimation(animationName)); 64 | ESPEssentials::WebServer.send(200, "text/plain", "Started '" + animationName + "'"); 65 | } 66 | else if (ESPEssentials::WebServer.hasArg("index")) 67 | { 68 | uint8_t animationIndex = ESPEssentials::WebServer.arg("index").toInt(); 69 | FastLEDHub.begin(FastLEDHub.getAnimation(animationIndex)); 70 | ESPEssentials::WebServer.send(200, "text/plain", "Started animation #" + String(animationIndex)); 71 | } 72 | else if (Config.startupAnimation != "") 73 | { 74 | FastLEDHub.begin(FastLEDHub.getAnimation(Config.startupAnimation)); 75 | ESPEssentials::WebServer.send(200, "text/plain", "Started '" + Config.startupAnimation + "'"); 76 | } 77 | else 78 | { 79 | ESPEssentials::WebServer.send(200, "text/plain", "No startup animation defined."); 80 | } 81 | }); 82 | } 83 | 84 | } // namespace Webserver 85 | -------------------------------------------------------------------------------- /src/FWebserver.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace Webserver 4 | { 5 | 6 | /// Register web server routes 7 | void initialize(); 8 | 9 | } // namespace Webserver 10 | -------------------------------------------------------------------------------- /src/Fade.cpp: -------------------------------------------------------------------------------- 1 | #include "Fade.h" 2 | #include "FastLEDHub.h" 3 | #include "SerialOut.h" 4 | 5 | #if defined(ESP32) 6 | #include 7 | #elif defined(ESP8266) 8 | #include 9 | #endif 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | namespace Fade 16 | { 17 | 18 | namespace 19 | { 20 | 21 | FadeMode m_mode = FadeMode::NONE; 22 | uint16_t m_targetBrightness = 0; 23 | Ticker m_fadeTicker; 24 | Ticker m_debounceTicker; 25 | bool m_debounce = false; 26 | 27 | void tick() 28 | { 29 | if (FastLEDHub.getStatus() == PAUSED) 30 | return; 31 | 32 | if (m_mode == FadeMode::ALARM && FastLEDHub.getBrightness() == m_targetBrightness) 33 | { 34 | if (Config.postAlarmAnimation != Config.alarmAnimation) 35 | FastLEDHub.begin(FastLEDHub.getAnimation(Config.postAlarmAnimation)); 36 | 37 | stop(); 38 | PRINTLN("[FastLEDHub] End fade 'Alarm'"); 39 | } 40 | else if (m_mode == FadeMode::SUNSET && FastLEDHub.getBrightness() == m_targetBrightness) 41 | { 42 | stop(); 43 | PRINTLN("[FastLEDHub] End fade 'Sunset'"); 44 | } 45 | else 46 | { 47 | FastLEDHub.setBrightness(FastLEDHub.getBrightness() + 1); 48 | PRINTLN("[FastLEDHub] Fade brightness: " + String(FastLEDHub.getBrightness())); 49 | } 50 | } 51 | 52 | void getSunsetTime() 53 | { 54 | PRINT("[FastLEDHub] Getting sunset time..."); 55 | 56 | WiFiClient client; 57 | HTTPClient http; 58 | String url = "http://api.sunrise-sunset.org/json?lat=" + String(Config.latitude) + "&lng=" + String(Config.longitude) + "&date=today&formatted=0"; 59 | http.begin(client, url); 60 | String payload = ""; 61 | if (http.GET() > 0) 62 | payload = http.getString(); 63 | http.end(); 64 | 65 | StaticJsonDocument<1024> doc; 66 | deserializeJson(doc, payload); 67 | if (doc.containsKey("results") && doc["results"].containsKey("sunset")) 68 | { 69 | String sunset = doc["results"]["sunset"].as(); 70 | int16_t sunsetHour = (sunset.substring(11, 13).toInt() + Config.timeZone + Config.summerTime + 24) % 24; 71 | int16_t sunsetMinute = sunset.substring(14, 16).toInt(); 72 | int16_t minutesSinceMidnight = sunsetHour * 60 + sunsetMinute; 73 | minutesSinceMidnight = (minutesSinceMidnight + Config.sunsetOffset + 1440) % 1440; 74 | Config.sunsetHour = minutesSinceMidnight / 60; 75 | Config.sunsetMinute = minutesSinceMidnight % 60; 76 | Config.save(); 77 | PRINTLN(" " + String(Config.sunsetHour) + ":" + String(Config.sunsetMinute)); 78 | } 79 | else 80 | { 81 | PRINTLN("failed. Using last known time instead."); 82 | } 83 | } 84 | 85 | bool getCurrentTime(int8_t *hour, int8_t *minute) 86 | { 87 | time_t n = time(nullptr); 88 | 89 | if (!n) 90 | return false; 91 | 92 | tm *now = gmtime(&n); 93 | *hour = (now->tm_hour + Config.timeZone + Config.summerTime) % 24; 94 | *minute = now->tm_min; 95 | 96 | return true; 97 | } 98 | 99 | } // namespace 100 | 101 | void initialize() 102 | { 103 | configTime(0, 0, "pool.ntp.org", "time.nist.gov"); 104 | getSunsetTime(); 105 | } 106 | 107 | void handle() 108 | { 109 | if (m_mode != FadeMode::NONE || m_debounce) 110 | return; 111 | 112 | int8_t hour, minute; 113 | if (!getCurrentTime(&hour, &minute)) 114 | return; 115 | 116 | if (Config.alarmEnabled && hour == Config.alarmHour && minute == Config.alarmMinute) 117 | { 118 | Fade::begin(FadeMode::ALARM); 119 | } 120 | else if (Config.sunsetEnabled && hour == Config.sunsetHour && minute == Config.sunsetMinute && FastLEDHub.isDim()) 121 | { 122 | Fade::begin(FadeMode::SUNSET); 123 | } 124 | } 125 | 126 | void begin(FadeMode fadeMode) 127 | { 128 | m_mode = fadeMode; 129 | uint8_t currentBrightness = FastLEDHub.getBrightness(); 130 | FastLEDHub.setBrightness(0); 131 | FastLEDHub.show(); 132 | 133 | m_debounceTicker.once(61, [](){ m_debounce = false; }); 134 | m_debounce = true; 135 | 136 | if (fadeMode == FadeMode::ALARM) 137 | { 138 | m_targetBrightness = 255; 139 | FastLEDHub.begin(FastLEDHub.getAnimation(Config.alarmAnimation)); 140 | m_fadeTicker.attach_ms(Config.alarmDuration * 60 * 1000 / m_targetBrightness, tick); 141 | PRINTLN("[FastLEDHub] Start fade 'Alarm'"); 142 | } 143 | else if (fadeMode == FadeMode::SUNSET) 144 | { 145 | m_targetBrightness = currentBrightness; 146 | FastLEDHub.begin(FastLEDHub.getAnimation(Config.sunsetAnimation)); 147 | m_fadeTicker.attach_ms(Config.sunsetDuration * 60 * 1000 / m_targetBrightness, tick); 148 | PRINTLN("[FastLEDHub] Start fade 'Sunset'"); 149 | } 150 | } 151 | 152 | void stop() 153 | { 154 | m_fadeTicker.detach(); 155 | m_mode = FadeMode::NONE; 156 | } 157 | 158 | FadeMode getMode() 159 | { 160 | return m_mode; 161 | } 162 | 163 | } // namespace Fade 164 | -------------------------------------------------------------------------------- /src/Fade.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Config.h" 4 | 5 | #include 6 | 7 | namespace Fade 8 | { 9 | 10 | enum class FadeMode 11 | { 12 | NONE, 13 | ALARM, 14 | SUNSET 15 | }; 16 | 17 | void handle(); 18 | void begin(FadeMode fadeMode); 19 | void stop(); 20 | void initialize(); 21 | FadeMode getMode(); 22 | 23 | } // namespace Fade 24 | -------------------------------------------------------------------------------- /src/FastLEDHub.cpp: -------------------------------------------------------------------------------- 1 | #include "FastLEDHub.h" 2 | 3 | #include "Fade.h" 4 | #include "SerialOut.h" 5 | #include "FWebserver.h" 6 | #include "WebSocket.h" 7 | 8 | FastLEDHubClass::FastLEDHubClass() : m_cycleButtonPushed(false), 9 | m_toggleButtonPushed(false), 10 | m_autostartHandled(false), 11 | m_gammaCorrectionEnabled(false), 12 | m_filteredBrightness(128), 13 | m_status(STOPPED), 14 | m_brightness(255), 15 | m_speed(255), 16 | m_potentiometerPin(-1), 17 | m_cycleButtonPin(-1), 18 | m_toggleButtonPin(-1) 19 | { 20 | } 21 | 22 | void FastLEDHubClass::initialize(const String &projectName, bool enableGammaCorrection) 23 | { 24 | m_gammaCorrectionEnabled = enableGammaCorrection; 25 | ESPEssentials::init(projectName); 26 | Config.initialize(); 27 | if (WiFi.status() == WL_CONNECTED) 28 | { 29 | WebSocket::initialize(projectName); 30 | Webserver::initialize(); 31 | Fade::initialize(); 32 | } 33 | 34 | if (Config.sliderValues.size() >= 2) 35 | { 36 | m_speed = Config.sliderValues.get(1); 37 | m_brightness = Config.sliderValues.get(0); 38 | setBrightness(m_brightness); 39 | } 40 | 41 | registerSlider(new Slider("Brightness", 0, 255, 255, 1, "brightness-high")); 42 | registerSlider(new Slider("Speed", 0, 255, 127, 1, "speedometer")); 43 | } 44 | 45 | void FastLEDHubClass::enableCycleButton(uint8_t pin) 46 | { 47 | m_inputTicker.attach_ms(FASTLEDHUB_INPUT_TICKER_INTERVAL, +[](FastLEDHubClass* t) { t->handleInput(); }, this); 48 | pinMode(pin, INPUT); 49 | m_cycleButtonPin = pin; 50 | } 51 | 52 | void FastLEDHubClass::enableToggleButton(uint8_t pin) 53 | { 54 | m_inputTicker.attach_ms(FASTLEDHUB_INPUT_TICKER_INTERVAL, +[](FastLEDHubClass* t) { t->handleInput(); }, this); 55 | pinMode(pin, INPUT); 56 | m_toggleButtonPin = pin; 57 | } 58 | 59 | void FastLEDHubClass::enablePotentiometer(uint8_t pin) 60 | { 61 | m_inputTicker.attach_ms(FASTLEDHUB_INPUT_TICKER_INTERVAL, +[](FastLEDHubClass* t) { t->handleInput(); }, this); 62 | pinMode(pin, INPUT); 63 | m_potentiometerPin = pin; 64 | } 65 | 66 | void FastLEDHubClass::handle() 67 | { 68 | ESPEssentials::handle(); 69 | 70 | if (ESPEssentials::OTA.isBusy()) 71 | return; 72 | 73 | if (!m_autostartHandled) 74 | autostart(); 75 | 76 | if (m_status == RUNNING && m_currentAnimation) 77 | m_currentAnimation->loop(); 78 | 79 | Fade::handle(); 80 | WebSocket::handle(); 81 | } 82 | 83 | bool FastLEDHubClass::isDim() 84 | { 85 | if (getBrightness() == 0) 86 | return true; 87 | 88 | for (uint16_t i = 0; i < FastLEDHub.count(); ++i) 89 | { 90 | for (uint16_t j = 0; j < FastLEDHub.size(); ++j) 91 | { 92 | if (FastLEDHub[i].leds()[j] != CRGB(0, 0, 0)) 93 | { 94 | return false; 95 | } 96 | } 97 | } 98 | 99 | return true; 100 | } 101 | 102 | void FastLEDHubClass::setBrightness(uint8_t brightness) 103 | { 104 | m_brightness = brightness; 105 | 106 | if (m_gammaCorrectionEnabled) 107 | brightness = round((float)brightness * brightness / 255.); 108 | 109 | CFastLED::setBrightness(brightness); 110 | } 111 | 112 | uint8_t FastLEDHubClass::getBrightness() 113 | { 114 | return m_brightness; 115 | } 116 | 117 | void FastLEDHubClass::delay(uint16_t ms) 118 | { 119 | unsigned long start = micros(); 120 | while (micros() - start < 1000.0 * ms * pow((m_speed - 255) / 128.0, 2)) 121 | { 122 | ESPEssentials::handle(); 123 | Fade::handle(); 124 | WebSocket::handle(); 125 | } 126 | } 127 | 128 | void FastLEDHubClass::registerSlider(Slider *slider) 129 | { 130 | if (Config.sliderValues.size() > sliders.size()) 131 | { 132 | slider->value = Config.sliderValues.get(sliders.size()); 133 | } 134 | else 135 | { 136 | Config.sliderValues.add(slider->value); 137 | } 138 | 139 | sliders.add(slider); 140 | } 141 | 142 | void FastLEDHubClass::registerColorPicker(ColorPicker *colorPicker) 143 | { 144 | if (Config.colorPickerValues.size() > colorPickers.size()) 145 | { 146 | colorPicker->value = Config.colorPickerValues.get(colorPickers.size()); 147 | } 148 | else 149 | { 150 | Config.colorPickerValues.add(colorPicker->value); 151 | } 152 | 153 | colorPickers.add(colorPicker); 154 | } 155 | 156 | void FastLEDHubClass::registerAnimation(Animation *animation) 157 | { 158 | animations.add(animation); 159 | } 160 | 161 | Animation *FastLEDHubClass::getAnimation(String name) 162 | { 163 | for (uint8_t i = 0; i < animations.size(); i++) 164 | { 165 | Animation *a = animations.get(i); 166 | if (a->getName() == name) 167 | return a; 168 | } 169 | 170 | return NULL; 171 | } 172 | 173 | Animation *FastLEDHubClass::getAnimation(uint8_t i) 174 | { 175 | return (i < animations.size()) ? animations.get(i) : NULL; 176 | } 177 | 178 | Slider *FastLEDHubClass::getSlider(String name) 179 | { 180 | for (uint8_t i = 0; i < sliders.size(); i++) 181 | { 182 | Slider *a = sliders.get(i); 183 | if (a->name == name) 184 | return a; 185 | } 186 | 187 | return NULL; 188 | } 189 | 190 | Slider *FastLEDHubClass::getSlider(uint8_t i) 191 | { 192 | return (i < sliders.size()) ? sliders.get(i) : NULL; 193 | } 194 | 195 | ColorPicker *FastLEDHubClass::getColorPicker(String name) 196 | { 197 | for (uint8_t i = 0; i < colorPickers.size(); i++) 198 | { 199 | ColorPicker *a = colorPickers.get(i); 200 | if (a->name == name) 201 | return a; 202 | } 203 | 204 | return NULL; 205 | } 206 | 207 | ColorPicker *FastLEDHubClass::getColorPicker(uint8_t i) 208 | { 209 | return (i < colorPickers.size()) ? colorPickers.get(i) : NULL; 210 | } 211 | 212 | void FastLEDHubClass::handleInput() 213 | { 214 | if (m_potentiometerPin >= 0 && Fade::getMode() == Fade::FadeMode::NONE) 215 | { 216 | // Adjust the range slightly so low and high adc values 217 | // span the whole 10bit brightness range 218 | int16_t potiBrightness = (1023 - analogRead(m_potentiometerPin) - 29) * 1.06; 219 | potiBrightness = constrain(potiBrightness, 0, 1023); 220 | 221 | // Low pass filter the potentiometer value to smoothen it out 222 | m_filteredBrightness = m_filteredBrightness - 0.01 * (m_filteredBrightness - potiBrightness); 223 | 224 | // Only set brightness if it's not near the filtered brightness value. 225 | // This will cause the actual brightness to lock in place once the potentiometer 226 | // hasn't been adjusted to prevent it from changing randomly for low quality 227 | // potentiometers. 228 | if (!(m_filteredBrightness - 1 < potiBrightness && potiBrightness < m_filteredBrightness + 1)) 229 | { 230 | uint16_t brightness = (float)potiBrightness * potiBrightness / 1023 / 4; 231 | setBrightness(brightness); 232 | } 233 | } 234 | 235 | if (m_cycleButtonPin >= 0) 236 | { 237 | if (!digitalRead(m_cycleButtonPin) && !m_cycleButtonPushed) 238 | { 239 | Fade::stop(); 240 | cycle(); 241 | m_cycleButtonPushed = true; 242 | } 243 | else if (digitalRead(m_cycleButtonPin) && m_cycleButtonPushed) 244 | { 245 | m_cycleButtonPushed = false; 246 | } 247 | } 248 | 249 | if (m_toggleButtonPin >= 0) 250 | { 251 | if (!digitalRead(m_toggleButtonPin) && !m_toggleButtonPushed) 252 | { 253 | Fade::stop(); 254 | toggle(); 255 | m_toggleButtonPushed = true; 256 | } 257 | else if (digitalRead(m_toggleButtonPin) && m_toggleButtonPushed) 258 | { 259 | m_toggleButtonPushed = false; 260 | } 261 | } 262 | } 263 | 264 | void FastLEDHubClass::setSpeed(uint8_t speed) 265 | { 266 | m_speed = speed; 267 | } 268 | 269 | AnimationStatus FastLEDHubClass::getStatus() 270 | { 271 | return m_status; 272 | } 273 | 274 | String FastLEDHubClass::getCurrentAnimationName() 275 | { 276 | if (!m_currentAnimation) 277 | return ""; 278 | 279 | return m_currentAnimation->getName(); 280 | } 281 | 282 | void FastLEDHubClass::autostart() 283 | { 284 | if (Config.startupAnimation == "") 285 | clear(true); 286 | else 287 | begin(getAnimation(Config.startupAnimation)); 288 | 289 | m_autostartHandled = true; 290 | } 291 | 292 | void FastLEDHubClass::begin(Animation *animation) 293 | { 294 | if (animation == NULL || (m_currentAnimation && m_currentAnimation->getName() == animation->getName())) 295 | return; 296 | 297 | clear(true); 298 | 299 | m_status = RUNNING; 300 | m_currentAnimation = animation; 301 | m_currentAnimation->reset(); 302 | 303 | WebSocket::broadcastStatus(); 304 | PRINTLN("Started '" + m_currentAnimation->getName() + "'"); 305 | } 306 | 307 | void FastLEDHubClass::cycle() 308 | { 309 | for (uint8_t i = 0; i < animations.size(); i++) 310 | { 311 | if (m_currentAnimation == getAnimation(i)) 312 | { 313 | begin(getAnimation((i + 1) % animations.size())); 314 | return; 315 | } 316 | } 317 | } 318 | 319 | void FastLEDHubClass::stop() 320 | { 321 | if (m_status == STOPPED) 322 | return; 323 | 324 | m_status = STOPPED; 325 | clear(true); 326 | m_currentAnimation = NULL; 327 | 328 | WebSocket::broadcastStatus(); 329 | PRINTLN("Stopped animation"); 330 | } 331 | 332 | void FastLEDHubClass::resume() 333 | { 334 | if (m_status != PAUSED) 335 | return; 336 | 337 | m_status = RUNNING; 338 | 339 | WebSocket::broadcastStatus(); 340 | PRINTLN("Resumed '" + m_currentAnimation->getName() + "'"); 341 | } 342 | 343 | void FastLEDHubClass::restart() 344 | { 345 | stop(); 346 | begin(m_currentAnimation); 347 | 348 | PRINTLN("Restarted '" + m_currentAnimation->getName() + "'"); 349 | } 350 | 351 | void FastLEDHubClass::pause() 352 | { 353 | m_status = PAUSED; 354 | 355 | WebSocket::broadcastStatus(); 356 | PRINTLN("Paused '" + m_currentAnimation->getName() + "'"); 357 | } 358 | 359 | void FastLEDHubClass::toggle() 360 | { 361 | if (m_status == RUNNING) 362 | pause(); 363 | else if (m_status == STOPPED) 364 | begin(getAnimation(0)); 365 | else 366 | resume(); 367 | } 368 | 369 | void FastLEDHubClass::toggle(Animation *animation) 370 | { 371 | if (m_currentAnimation && m_currentAnimation == animation && m_status == RUNNING) 372 | pause(); 373 | else if (m_currentAnimation && m_currentAnimation == animation && m_status == PAUSED) 374 | resume(); 375 | else 376 | begin(animation); 377 | } 378 | 379 | FastLEDHubClass FastLEDHub; 380 | -------------------------------------------------------------------------------- /src/FastLEDHub.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Animation.h" 4 | #include "ColorUtils.h" 5 | #include "ColorPicker.h" 6 | #include "Config.h" 7 | #include "Slider.h" 8 | 9 | #include 10 | #include 11 | #define FASTLED_INTERNAL 12 | #include 13 | #include 14 | #include 15 | 16 | #define FASTLEDHUB_INPUT_TICKER_INTERVAL 10 17 | #define SPECTRUM_LENGTH 16 18 | 19 | enum AnimationStatus 20 | { 21 | STOPPED = 0, 22 | PAUSED, 23 | RUNNING 24 | }; 25 | 26 | class FastLEDHubClass : public CFastLED 27 | { 28 | public: 29 | /// Constructor 30 | FastLEDHubClass(); 31 | 32 | /// Handle every function provided by FastLEDHub. This method 33 | /// should be called in the main Arduino loop-function. 34 | void handle(); 35 | 36 | /// Initialize FastLEDHub 37 | /// @param projectName Project name 38 | /// @param enableGammaCorrection Enable brightness gamma correction (default: true) 39 | void initialize(const String &projectName, bool enableGammaCorrection = true); 40 | 41 | /// Initialize cycle button. The button will be used to cycle through animations. 42 | /// @param pin Button pin 43 | void enableCycleButton(uint8_t pin); 44 | 45 | /// Initialize toggle button. The button will be used to pause/resume animations. 46 | /// @param pin Button pin 47 | void enableToggleButton(uint8_t pin); 48 | 49 | /// Initialize potentiometer pin. The potentiometer will be used to 50 | /// control the overall brightness. 51 | /// @param pin Potentiometer pin 52 | void enablePotentiometer(uint8_t pin); 53 | 54 | /// Register a slider instance which can be used as a dynamic animation parameter 55 | /// @param slider Slider instance 56 | void registerSlider(Slider *slider); 57 | 58 | /// Register a color picker instance which can be used as a dynamic animation parameter 59 | /// @param colorPicker Color picker instance 60 | void registerColorPicker(ColorPicker *colorPicker); 61 | 62 | /// Register an animation instance to be managed by FastLEDHub 63 | /// @param animation Pointer to animation instance 64 | void registerAnimation(Animation *animation); 65 | 66 | /// Begin the next animation with respect to the currently running/paused 67 | /// animation. Use this to cycle through animations one by one. 68 | void cycle(); 69 | 70 | /// Return a pointer to an animation by name 71 | /// @param name Animation name 72 | /// @return Pointer to animation 73 | Animation *getAnimation(String name); 74 | 75 | /// Return a pointer to an animation by index 76 | /// @param i Animation index 77 | /// @return Pointer to animation 78 | Animation *getAnimation(uint8_t i); 79 | 80 | /// Return a pointer to a slider by name 81 | /// @param name Slider name 82 | /// @return Pointer to slider 83 | Slider *getSlider(String name); 84 | 85 | /// Return a pointer to a slider by index 86 | /// @param i Slider index 87 | /// @return Pointer to slider 88 | Slider *getSlider(uint8_t i); 89 | 90 | /// Return a pointer to a color picker by name 91 | /// @param name Color picker name 92 | /// @return Pointer to color picker 93 | ColorPicker *getColorPicker(String name); 94 | 95 | /// Return a pointer to a color picker by index 96 | /// @param i Color picker index 97 | /// @return Pointer to color picker 98 | ColorPicker *getColorPicker(uint8_t i); 99 | 100 | /// Check if all leds are turned off (i.e. either brightness is zero or 101 | /// all leds are black) 102 | /// @return True if all leds are dim 103 | bool isDim(); 104 | 105 | /// Wait for a given amount of milliseconds while still calling 106 | /// show() periodically. Use this instead of the regular Arduino delay. 107 | /// @param ms Milliseconds 108 | void delay(uint16_t ms); 109 | 110 | /// Begin an animation 111 | /// @param animation Animation pointer 112 | void begin(Animation *animation); 113 | 114 | /// Toggle animation playback. This method will toggle between RUNNING 115 | /// and PAUSED animation status. Calling this method will have no effect 116 | /// if the animation status is STOPPED. 117 | void toggle(); 118 | 119 | /// Toggle a specific animation. If this animation is not currently RUNNING 120 | /// or PAUSED it will begin instead. 121 | /// @param animation Animation to begin when STOPPED 122 | void toggle(Animation *animation); 123 | 124 | /// Stops the current animation. The animation status will be STOPPED. 125 | void stop(); 126 | 127 | /// Pauses the current animation. The animation status will be PAUSED. 128 | void pause(); 129 | 130 | /// Restarts the current animation. This will effectively call the animation's 131 | /// setup method again. 132 | void restart(); 133 | 134 | /// Resumes a paused animation. If the current animation status is not PAUSED 135 | /// calling this method will have no effect. 136 | void resume(); 137 | 138 | /// Get the current animation status. 139 | /// @return Current animation status 140 | AnimationStatus getStatus(); 141 | 142 | /// Set global animation speed 143 | /// @param speed Speed value (0 - 255) 144 | void setSpeed(uint8_t speed); 145 | 146 | /// Set global brightness value. This will apply gamma correction if it 147 | /// is enabled from the initialize method. 148 | /// @param brightness Brightness value 149 | void setBrightness(uint8_t brightness); 150 | 151 | /// Get current global brightness value. 152 | /// @return Brightness value 153 | uint8_t getBrightness(); 154 | 155 | /// Get the name of the currently selected animation 156 | /// @return Current animation name 157 | String getCurrentAnimationName(); 158 | 159 | /// Spectrum data byte array of length SPECTRUM_LENGTH 160 | uint8_t spectrumData[SPECTRUM_LENGTH]; 161 | 162 | /// List of all registered animation pointers 163 | LinkedList animations; 164 | 165 | /// List of all registered slider pointers 166 | LinkedList sliders; 167 | 168 | /// List of all registered color pickers 169 | LinkedList colorPickers; 170 | 171 | private: 172 | /// Handle all configured inputs. This will get called periodically. 173 | void handleInput(); 174 | 175 | /// Start the configured autostart animation 176 | void autostart(); 177 | 178 | bool m_cycleButtonPushed; 179 | bool m_toggleButtonPushed; 180 | bool m_autostartHandled; 181 | bool m_gammaCorrectionEnabled; 182 | float m_filteredBrightness; 183 | Ticker m_inputTicker; 184 | Animation *m_currentAnimation; 185 | AnimationStatus m_status = STOPPED; 186 | uint8_t m_brightness; 187 | uint8_t m_speed; 188 | int8_t m_potentiometerPin; 189 | int8_t m_cycleButtonPin; 190 | int8_t m_toggleButtonPin; 191 | }; 192 | 193 | extern FastLEDHubClass FastLEDHub; 194 | -------------------------------------------------------------------------------- /src/SerialOut.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #ifdef SERIAL_OUT_SILENT 4 | 5 | #define PRINT(s) 6 | #define PRINT_VERBOSE(s) 7 | #define PRINTLN(s) 8 | #define PRINTLN_VERBOSE(s) 9 | #define PRINTF(s, ...) 10 | #define PRINTF_VERBOSE(s, ...) 11 | 12 | #else 13 | 14 | #define PRINT(s) Serial.print(s) 15 | #define PRINTLN(s) Serial.println(s) 16 | #define PRINTF(s, ...) Serial.printf(s, ##__VA_ARGS__) 17 | 18 | #ifdef SERIAL_OUT_VERBOSE 19 | #define PRINT_VERBOSE(s) Serial.print(s) 20 | #define PRINTLN_VERBOSE(s) Serial.println(s) 21 | #define PRINTF_VERBOSE(s, ...) Serial.printf(s, ##__VA_ARGS__) 22 | #else 23 | #define PRINT_VERBOSE(s) 24 | #define PRINTLN_VERBOSE(s) 25 | #define PRINTF_VERBOSE(s, ...) 26 | #endif 27 | 28 | #endif 29 | -------------------------------------------------------------------------------- /src/Slider.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class Slider 4 | { 5 | public: 6 | String name; 7 | int16_t min; 8 | int16_t max; 9 | int16_t value; 10 | int16_t step; 11 | String icon; 12 | 13 | Slider(String _name, int16_t _min, int16_t _max, int16_t _default_value, int16_t _step, String _icon = "sliders") 14 | { 15 | name = _name; 16 | min = _min; 17 | max = _max; 18 | value = _default_value; 19 | step = _step; 20 | icon = _icon; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /src/WebSocket.cpp: -------------------------------------------------------------------------------- 1 | #include "WebSocket.h" 2 | 3 | #include 4 | #if defined(ESP32) 5 | #include 6 | #elif defined(ESP8266) 7 | #include 8 | #endif 9 | #define FASTLED_INTERNAL 10 | #include 11 | 12 | #include "Animation.h" 13 | #include "ColorUtils.h" 14 | #include "Config.h" 15 | #include "Fade.h" 16 | #include "FastLEDHub.h" 17 | #include "SerialOut.h" 18 | 19 | namespace WebSocket 20 | { 21 | 22 | namespace 23 | { 24 | 25 | WebSocketsServer m_socket = WebSocketsServer(81); 26 | 27 | /// Handle websocket events of type WStype_TEXT 28 | /// @param text Text String 29 | /// @param id Connection id that triggered event 30 | void onText(uint8_t *text, uint8_t id) 31 | { 32 | if (Config.parseJson((const char *)text)) 33 | Config.save(); 34 | } 35 | 36 | /// Handle websocket events of type WStype_BIN 37 | /// @param binary Byte array 38 | /// @param id Connection id that triggered event 39 | void onBinary(uint8_t *binary, uint8_t id) 40 | { 41 | switch (binary[0]) 42 | { 43 | case 0: // Color 44 | { 45 | CRGB color = CRGB(binary[2], binary[3], binary[4]); 46 | Config.colorPickerValues.set(binary[1], color); 47 | FastLEDHub.getColorPicker(binary[1])->value = color; 48 | break; 49 | } 50 | case 1: // Toggle animation 51 | Fade::stop(); 52 | FastLEDHub.toggle(FastLEDHub.getAnimation(binary[1])); 53 | break; 54 | case 2: // Stop 55 | FastLEDHub.stop(); 56 | break; 57 | case 10: // Led data 58 | FastLEDHub.stop(); 59 | Fade::stop(); 60 | for (uint16_t i = 0; i < FastLEDHub.size(); ++i) 61 | FastLEDHub.leds()[i] = CRGB(binary[1 + i * 3], binary[2 + i * 3], binary[3 + i * 3]); 62 | break; 63 | case 20: // Slider data 64 | { 65 | int16_t value = (binary[2] << 8) | binary[3]; 66 | if (binary[1] == 0) 67 | FastLEDHub.setBrightness(value); 68 | else if (binary[1] == 1) 69 | FastLEDHub.setSpeed(value); 70 | Config.sliderValues.set(binary[1], value); 71 | FastLEDHub.getSlider(binary[1])->value = value; 72 | break; 73 | } 74 | case 30: // Spectrum data 75 | for (uint16_t i = 0; i < SPECTRUM_LENGTH; ++i) 76 | { 77 | FastLEDHub.spectrumData[i] = binary[i + 1]; 78 | } 79 | } 80 | } 81 | 82 | /// Callback function for websocket events 83 | /// @param id Connection id that triggered event 84 | /// @param type Event type 85 | /// @param payload Payload 86 | /// @param length Payload length 87 | void onEvent(uint8_t id, WStype_t type, uint8_t *payload, size_t length) 88 | { 89 | switch (type) 90 | { 91 | case WStype_DISCONNECTED: 92 | Config.save(); 93 | PRINTF("[%u] Disconnected!\n", id); 94 | break; 95 | case WStype_CONNECTED: 96 | { 97 | IPAddress ip = m_socket.remoteIP(id); 98 | PRINTF("[%u] Connected from %d.%d.%d.%d url: %s\n", id, ip[0], ip[1], ip[2], ip[3], payload); 99 | String config = Config.asString(true); 100 | WebSocket::m_socket.sendTXT(id, config.c_str()); 101 | } 102 | break; 103 | case WStype_TEXT: 104 | PRINTF_VERBOSE("[%u] Got text: %s\n", id, payload); 105 | onText(payload, id); 106 | break; 107 | case WStype_BIN: 108 | PRINTF_VERBOSE("[%u] Got binary: %s\n", id, payload); 109 | onBinary((uint8_t *)payload, id); 110 | break; 111 | default: 112 | break; 113 | } 114 | } 115 | 116 | } // namespace 117 | 118 | void initialize(const String &hostname) 119 | { 120 | m_socket.begin(); 121 | m_socket.onEvent(onEvent); 122 | MDNS.begin(hostname); 123 | MDNS.addService("http", "tcp", 80); 124 | MDNS.addService("ws", "tcp", 81); 125 | } 126 | 127 | void handle() 128 | { 129 | m_socket.loop(); 130 | } 131 | 132 | void broadcastMessage(String msg) 133 | { 134 | WebSocket::m_socket.broadcastTXT(msg.c_str()); 135 | } 136 | 137 | void broadcastStatus() 138 | { 139 | String msg = "{\"status\": " + String((int)FastLEDHub.getStatus()) + ", \"currentAnimation\": \"" + FastLEDHub.getCurrentAnimationName() + "\"}"; 140 | broadcastMessage(msg); 141 | } 142 | 143 | } // namespace WebSocket 144 | -------------------------------------------------------------------------------- /src/WebSocket.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | namespace WebSocket 7 | { 8 | 9 | /// Initialize the websocket instance 10 | void initialize(const String &hostname = "fastledhub"); 11 | 12 | /// Handle websocket 13 | void handle(); 14 | 15 | /// Broadcast a message to all active websocket connections 16 | void broadcastMessage(String msg); 17 | 18 | /// Broadcast the current animation status to all active websocket connections 19 | void broadcastStatus(); 20 | 21 | } // namespace Websocket 22 | --------------------------------------------------------------------------------