From 7129a1b974d76d3cf0a17cb0d8f715f653d5e72a Mon Sep 17 00:00:00 2001 From: Mathieu Carbou Date: Fri, 2 Aug 2024 16:58:53 +0200 Subject: [PATCH] New Dimmer library based on MycilaPulseAnalyzer --- lib/DimmableLight/LICENSE | 504 -------------- lib/DimmableLight/library.json | 29 - lib/DimmableLight/library.properties | 9 - lib/DimmableLight/src/hw_timer_esp32.cpp | 75 -- lib/DimmableLight/src/hw_timer_esp32.h | 33 - lib/DimmableLight/src/thyristor.cpp | 852 ----------------------- lib/DimmableLight/src/thyristor.h | 295 -------- lib/MycilaDimmer/MycilaDimmer.cpp | 30 +- lib/MycilaDimmer/MycilaDimmer.h | 18 +- src/init/Config.cpp | 4 +- src/tasks/ZCD.cpp | 12 +- 11 files changed, 40 insertions(+), 1821 deletions(-) delete mode 100644 lib/DimmableLight/LICENSE delete mode 100644 lib/DimmableLight/library.json delete mode 100644 lib/DimmableLight/library.properties delete mode 100644 lib/DimmableLight/src/hw_timer_esp32.cpp delete mode 100644 lib/DimmableLight/src/hw_timer_esp32.h delete mode 100644 lib/DimmableLight/src/thyristor.cpp delete mode 100644 lib/DimmableLight/src/thyristor.h diff --git a/lib/DimmableLight/LICENSE b/lib/DimmableLight/LICENSE deleted file mode 100644 index 8000a6fa..00000000 --- a/lib/DimmableLight/LICENSE +++ /dev/null @@ -1,504 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms of the -ordinary General Public License). - - To apply these terms, attach the following notices to the library. It is -safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least the -"copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 - USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the library, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James Random - Hacker. - - , 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! diff --git a/lib/DimmableLight/library.json b/lib/DimmableLight/library.json deleted file mode 100644 index cbb4677a..00000000 --- a/lib/DimmableLight/library.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "Dimmable Light for Arduino", - "version": "1.6.0", - "authors": { - "name": "Fabiano Riccardi", - "email": "fabiano.riccardi@outlook.com" - }, - "description": "This library allows to easily control dimmers (also known as thyristors).", - "keywords": [ - "dimmer", - "triac", - "thyristor", - "timer", - "light", - "arduino-library", - "phase-fired control" - ], - "repository": { - "type": "git", - "url": "https://github.com/fabianoriccardi/dimmable-light" - }, - "licence": "LGPL-2.1-or-later", - "frameworks": [ - "arduino" - ], - "platforms": [ - "espressif32" - ] -} \ No newline at end of file diff --git a/lib/DimmableLight/library.properties b/lib/DimmableLight/library.properties deleted file mode 100644 index 48852b49..00000000 --- a/lib/DimmableLight/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=Dimmable Light for Arduino -version=1.6.0 -author=Fabiano Riccardi -maintainer=Fabiano Riccardi -sentence=This library allows to easily control dimmers (also known as thyristors). -paragraph=This library was born to control dimmable light bulbs, but actually dimmers are fully compatible with other AC loads like electrical heaters and motors (be aware of what you are doing!). Actually it works on ESP8266, ESP32, AVR and SAMD. -category=Device Control -url=https://github.com/fabianoriccardi/dimmable-light -architectures=esp32 diff --git a/lib/DimmableLight/src/hw_timer_esp32.cpp b/lib/DimmableLight/src/hw_timer_esp32.cpp deleted file mode 100644 index 25dad235..00000000 --- a/lib/DimmableLight/src/hw_timer_esp32.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/****************************************************************************** - * This file is part of Dimmable Light for Arduino, a library to control * - * dimmers. * - * * - * Copyright (C) 2018-2023 Fabiano Riccardi * - * * - * Dimmable Light for Arduino is free software; you can redistribute * - * it and/or modify it under the terms of the GNU Lesser General Public * - * License as published by the Free Software Foundation; either * - * version 2.1 of the License, or (at your option) any later version. * - * * - * This library is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * - * Lesser General Public License for more details. * - * * - * You should have received a copy of the GNU Lesser General Public License * - * along with this library; if not, see . * - ******************************************************************************/ -#ifdef ESP32 - -#include "hw_timer_esp32.h" - -const static int TIMER_ID = 0; - -static hw_timer_t* timer = nullptr; - -void timerInit(void (*callback)()) { -#if ESP_IDF_VERSION_MAJOR >= 5 - timer = timerBegin(1000000); - timerWrite(timer, 0); - timerAttachInterrupt(timer, callback); -#else - // Use 1st timer of 4 (counted from zero). - // Set 80 divider for prescaler (see ESP32 Technical Reference Manual for more - // info), count up. The counter starts to increase its value. - timer = timerBegin(TIMER_ID, 80, true); - timerStop(timer); - timerWrite(timer, 0); - - timerAttachInterrupt(timer, callback, false); -#endif -} - -void ARDUINO_ISR_ATTR startTimerAndTrigger(uint32_t delay) { -#if ESP_IDF_VERSION_MAJOR >= 5 - timerRestart(timer); - timerAlarm(timer, delay, false, 0); -#else - timerWrite(timer, 0); - timerAlarmWrite(timer, delay, false); - timerAlarmEnable(timer); - timerStart(timer); -#endif -} - -void ARDUINO_ISR_ATTR setAlarm(uint32_t delay) { -#if ESP_IDF_VERSION_MAJOR >= 5 - timerAlarm(timer, delay, false, 0); -#else - timerAlarmWrite(timer, delay, false); - - // On core v2.0.0-2.0.1, the timer alarm is automatically disabled after triggering, - // so re-enable the alarm - timerAlarmEnable(timer); -#endif -} - -void ARDUINO_ISR_ATTR stopTimer() { -#if ESP_IDF_VERSION_MAJOR < 5 - timerStop(timer); -#endif -} - -#endif // END ESP32 diff --git a/lib/DimmableLight/src/hw_timer_esp32.h b/lib/DimmableLight/src/hw_timer_esp32.h deleted file mode 100644 index 247e9caa..00000000 --- a/lib/DimmableLight/src/hw_timer_esp32.h +++ /dev/null @@ -1,33 +0,0 @@ -/****************************************************************************** - * This file is part of Dimmable Light for Arduino, a library to control * - * dimmers. * - * * - * Copyright (C) 2018-2023 Fabiano Riccardi * - * * - * Dimmable Light for Arduino is free software; you can redistribute * - * it and/or modify it under the terms of the GNU Lesser General Public * - * License as published by the Free Software Foundation; either * - * version 2.1 of the License, or (at your option) any later version. * - * * - * This library is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * - * Lesser General Public License for more details. * - * * - * You should have received a copy of the GNU Lesser General Public License * - * along with this library; if not, see . * - ******************************************************************************/ -#ifndef HW_TIMER_ESP32_H -#define HW_TIMER_ESP32_H - -#include - -void timerInit(void (*callback)()); - -void startTimerAndTrigger(uint32_t delay); - -void setAlarm(uint32_t delay); - -void stopTimer(); - -#endif // END HW_TIMER_ESP32_H \ No newline at end of file diff --git a/lib/DimmableLight/src/thyristor.cpp b/lib/DimmableLight/src/thyristor.cpp deleted file mode 100644 index bc7b6a7f..00000000 --- a/lib/DimmableLight/src/thyristor.cpp +++ /dev/null @@ -1,852 +0,0 @@ -/****************************************************************************** - * This file is part of Dimmable Light for Arduino, a library to control * - * dimmers. * - * * - * Copyright (C) 2018-2023 Fabiano Riccardi * - * * - * Dimmable Light for Arduino is free software; you can redistribute * - * it and/or modify it under the terms of the GNU Lesser General Public * - * License as published by the Free Software Foundation; either * - * version 2.1 of the License, or (at your option) any later version. * - * * - * This library is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * - * Lesser General Public License for more details. * - * * - * You should have received a copy of the GNU Lesser General Public License * - * along with this library; if not, see . * - ******************************************************************************/ -#include "thyristor.h" - -#include -#include - -#if defined(ARDUINO_ARCH_ESP8266) - #include "hw_timer_esp8266.h" -#elif defined(ARDUINO_ARCH_ESP32) - #include "hw_timer_esp32.h" -#elif defined(ARDUINO_ARCH_AVR) - #include "hw_timer_avr.h" -#elif defined(ARDUINO_ARCH_SAMD) - #include "hw_timer_samd.h" -#elif defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_ARCH_MBED) - #include "hw_timer_pico.h" -#else - #error "only ESP8266, ESP32, AVR, SAMD & RP2040 (non-mbed) architectures are supported" -#endif - -// Ignore zero-cross interrupts when they occurs too early w.r.t semi-period ideal length. -// The constant *semiPeriodShrinkMargin* defines the "too early" margin. -// This filter affects the MONITOR_FREQUENCY measurement. -// #define FILTER_INT_PERIOD - -// FOR DEBUG PURPOSE ONLY. This option requires FILTER_INT_PERIOD enabled. -// Print on serial port the time passed from the previous zero cross interrupt when the semi-period -// length is exceed the interval defined by *semiPeriodShrinkMargin* and *semiPeriodExpandMargin*. -// #define PRINT_INT_PERIOD - -// FOR DEBUG PURPOSE ONLY. -// Prints a char on the serial port if not all thyristors are managed in a semi-period. -// #define CHECK_MANAGED_THYR - -// Force the signal length of thyristor's gate. If not enabled, the signal to gate -// is turned off through an interrupt just before the end of the period. -// Look at gateTurnOffTime constant for more info. -// #define PREDEFINED_PULSE_LENGTH - -// In microseconds -#ifdef NETWORK_FREQ_FIXED_50HZ -static const uint16_t semiPeriodLength = 10000; -#endif -#ifdef NETWORK_FREQ_FIXED_60HZ -static const uint16_t semiPeriodLength = 8333; -#endif -#ifdef NETWORK_FREQ_RUNTIME -static uint16_t semiPeriodLength = 0; -#endif - -// These margins are precautions against noise, electrical spikes and frequency skew errors. -// Activation delays lower than *startMargin* turn the thyristor fully ON. -// Activation delays higher than *endMargin* turn the thyristor fully OFF. -// Tune this parameters accordingly to your setup (electrical network, MCU, and ZC circuitry). -// Values are expressed in microseconds. -static const uint16_t startMargin = 200; -static const uint16_t endMargin = 200; - -// Merge Period represents the time span in which 2 (or more) very near delays are merged (the -// higher ones are merged in the smaller one). This could be necessary for 2 main reasons: -// 1) Efficiency, in fact in some applications you will never seem differences between -// near delays, hence raising many interrupts is useless. -// 2) MCU inability to satisfy very tight "timer start". -// After some experiments on incandescence light bulbs, I noted that even 50 microseconds -// are not negligible, so I decided to set threshold lower than 20microsecond. Before lowering this -// value, check the documentation of the specific MCU since some have limitations. For example, -// ESP8266 API documentation suggests to set timer dealy higher than >10us. If you use 8-bit timers -// on AVR, you should set a bigger Merge Period (e.g. 100us). Moreover, you should also consider the -// number of instantiated dimmers: ISRs will take more time as the dimmer count increases, so you -// may need to increase Merge Period. The default value is intended to handle up to 8 dimmers. -#if defined(ARDUINO_ARCH_AVR) -// This longer Merge Period is due to the implementation of digitalWrite(..) on AVR core, which is -// slower than others. In particular, on Arduino Uno R3 and Arduino Mega it takes, -// respectively, about 5us and 6us to execute. -static const uint16_t mergePeriod = 20 + Thyristor::N * 6; -#else -static const uint16_t mergePeriod = 20; -#endif - -// Period in microseconds before the end of the semiperiod when an interrupt is triggered to -// turn off all gate signals. This parameter doesn't have any effect if you enable -// PREDEFINED_PULSE_LENGTH. -static const uint16_t gateTurnOffTime = 100; - -static_assert(endMargin - gateTurnOffTime > mergePeriod, "endMargin must be greater than " - "(gateTurnOffTime + mergePeriod)"); - -#ifdef PREDEFINED_PULSE_LENGTH -// Length of pulse on thyristor's gate pin. This parameter is not applied if thyristor is fully on -// or off. This option is suitable only for very short pulses, since it blocks the ISR for the -// specified amount of time. -static uint8_t pulseWidth = 15; -#endif - -struct PinDelay { - uint8_t pin; - uint16_t delay; -}; - -enum class INT_TYPE { ACTIVATE_THYRISTORS, - TURN_OFF_GATES }; - -static INT_TYPE nextISR = INT_TYPE::ACTIVATE_THYRISTORS; - -/** - * Temporary struct manipulated by the ISR storing the timing information about each dimmer. - */ -static struct PinDelay pinDelay[Thyristor::N]; - -/** - * Summary of thyristors' state used by ISR (concurrent-safe). - */ -static bool _allThyristorsOnOff = true; - -/** - * Tell if zero-cross interrupt is enabled. - */ -static bool interruptEnabled = false; - -/** - * Number of thyristors already managed in the current semi-period. - */ -static uint8_t thyristorManaged = 0; - -/** - * Number of thyristors FULLY on. The remaining ones must be turned - * off by turn_off_gates_int at the end of the semi-period. - */ -static uint8_t alwaysOnCounter = 0; -static uint8_t alwaysOffCounter = 0; - -#if defined(ARDUINO_ARCH_ESP8266) -void HW_TIMER_IRAM_ATTR turn_off_gates_int() { -#elif defined(ARDUINO_ARCH_ESP32) -void ARDUINO_ISR_ATTR turn_off_gates_int() { -#else -void turn_off_gates_int() { -#endif - for (int i = alwaysOnCounter; i < Thyristor::nThyristors; i++) { - if (pinDelay[i].pin != 0xff) { - digitalWrite(pinDelay[i].pin, LOW); - } - } - -#if defined(ARDUINO_ARCH_AVR) - timerStop(); -#endif -} - -/** - * Timer routine to turn on one or more thyristors. This function may be be called multiple times - * per semi-period depending on the current thyristors configuration. - */ -#if defined(ARDUINO_ARCH_ESP8266) -void HW_TIMER_IRAM_ATTR activate_thyristors() { -#elif defined(ARDUINO_ARCH_ESP32) -void ARDUINO_ISR_ATTR activate_thyristors() { -#else -void activate_thyristors() { -#endif - - const uint8_t firstToBeUpdated = thyristorManaged; - - for (; - // The last thyristor is managed outside the loop - thyristorManaged < Thyristor::nThyristors - 1 && - // Consider the "near" thyristors - pinDelay[thyristorManaged + 1].delay - pinDelay[firstToBeUpdated].delay < mergePeriod && - // Exclude the one who must remain totally off - pinDelay[thyristorManaged].delay <= semiPeriodLength - endMargin; - thyristorManaged++) { - if (pinDelay[thyristorManaged].pin != 0xff) { - digitalWrite(pinDelay[thyristorManaged].pin, HIGH); - } - } - if (pinDelay[thyristorManaged].pin != 0xff) { - digitalWrite(pinDelay[thyristorManaged].pin, HIGH); - } - thyristorManaged++; - - // This while is dedicated to all those thyristors with delay == semiPeriodLength-margin; those - // are the ones who shouldn't turn on, hence they can be skipped - while (thyristorManaged < Thyristor::nThyristors && pinDelay[thyristorManaged].delay == semiPeriodLength) { - thyristorManaged++; - } - -#ifdef PREDEFINED_PULSE_LENGTH - delayMicroseconds(pulseWidth); - - for (int i = firstToBeUpdated; i < thyristorManaged; i++) { - digitalWrite(pinDelay[i].pin, LOW); - } -#endif - - if (thyristorManaged < Thyristor::nThyristors) { - int delayAbsolute = pinDelay[thyristorManaged].delay; - -#if defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_SAMD) || (defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_ARCH_MBED)) - int delayRelative = delayAbsolute - pinDelay[firstToBeUpdated].delay; -#endif - -#if defined(ARDUINO_ARCH_ESP8266) - timer1_write(US_TO_RTC_TIMER_TICKS(delayRelative)); -#elif defined(ARDUINO_ARCH_ESP32) - setAlarm(delayAbsolute); -#elif defined(ARDUINO_ARCH_AVR) - timerSetAlarm(microsecond2Tick(delayRelative)); -#elif defined(ARDUINO_ARCH_SAMD) - timerStart(microsecond2Tick(delayRelative)); -#elif defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_ARCH_MBED) - timerStart(delayRelative); -#else - #error "Not implemented" -#endif - } else { - -#ifdef PREDEFINED_PULSE_LENGTH - // If there are not more thyristor to serve, I can stop timer. Energy saving? - #if defined(ARDUINO_ARCH_ESP8266) - // Given the Arduino HAL and esp8266 technical reference manual, - // when timer triggers, the counter stops because it has reach zero - // and no-autorealod was set (this timer can only down-count). - #elif defined(ARDUINO_ARCH_ESP32) - stopTimer(); - #elif defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_SAMD) - // Given actual HAL, AVR and SAMD counter automatically stops on interrupt - #elif defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_ARCH_MBED) - // Timer callback is not rescheduled - #endif -#else - // If there are not more thyristors to serve, set timer to turn off gates' signal - uint16_t delayAbsolute = semiPeriodLength - gateTurnOffTime; - - #if defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_SAMD) || (defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_ARCH_MBED)) - uint16_t delayRelative = delayAbsolute - pinDelay[firstToBeUpdated].delay; - #endif - - #if defined(ARDUINO_ARCH_ESP8266) - timer1_attachInterrupt(turn_off_gates_int); - timer1_write(US_TO_RTC_TIMER_TICKS(delayRelative)); - #elif defined(ARDUINO_ARCH_ESP32) - nextISR = INT_TYPE::TURN_OFF_GATES; - setAlarm(delayAbsolute); - #elif defined(ARDUINO_ARCH_AVR) - timerSetCallback(turn_off_gates_int); - timerSetAlarm(microsecond2Tick(delayRelative)); - #elif defined(ARDUINO_ARCH_SAMD) - timerSetCallback(turn_off_gates_int); - timerStart(microsecond2Tick(delayRelative)); - #elif defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_ARCH_MBED) - timerSetCallback(turn_off_gates_int); - timerStart(delayRelative); - #else - #error "Not implemented" - #endif -#endif - } -} - -#ifdef FILTER_INT_PERIOD -// In microsecond -int Thyristor::semiPeriodShrinkMargin = 500; -int Thyristor::semiPeriodExpandMargin = 50; -#endif - -#if defined(FILTER_INT_PERIOD) || defined(MONITOR_FREQUENCY) -static uint32_t lastTime = 0; -#endif - -#ifdef MONITOR_FREQUENCY -// Circular queue to compute the moving average -static Mycila::CircularBuffer queue; -#endif - -#if defined(ARDUINO_ARCH_ESP8266) -void HW_TIMER_IRAM_ATTR Thyristor::zero_cross_int(void* arg) { -#elif defined(ARDUINO_ARCH_ESP32) -void ARDUINO_ISR_ATTR Thyristor::zero_cross_int(void* arg) { -#else -void Thyristor::zero_cross_int(void* arg) { -#endif - -#if defined(FILTER_INT_PERIOD) || defined(MONITOR_FREQUENCY) - if (!lastTime) { - lastTime = micros(); - } else { - uint32_t now = micros(); - - // "diff" is correct even when timer rolls back, because these values are unsigned - uint32_t diff = now - lastTime; - - #ifdef PRINT_INT_PERIOD - if (diff < semiPeriodLength - Thyristor::semiPeriodShrinkMargin) { - #ifdef ARDUINO_ARCH_ESP32 - ets_printf("B%d\n", diff); - #else - Serial.println(String('B') + diff); - #endif - } - if (diff > semiPeriodLength + Thyristor::semiPeriodExpandMargin) { - #ifdef ARDUINO_ARCH_ESP32 - ets_printf("A%d\n", diff); - #else - Serial.println(String('A') + diff); - #endif - } - #endif - - #ifdef FILTER_INT_PERIOD - // Filters out spurious interrupts. The effectiveness of this simple - // filter could vary depending on noise on electrical networ. - if (diff < semiPeriodLength - Thyristor::semiPeriodShrinkMargin) { - return; - } - #endif - -#endif - -#if defined(ARDUINO_ARCH_AVR) - // Early timer start, only for avr. This is necessary since the instructions executed in this - // ISR take much time (more than 30us with only 4 dimmers). Before the end of this ISR, either - // the timer is stop or the alarm time is properly set. - timerStartAndTrigger(microsecond2Tick(15000)); -#endif - -#if defined(FILTER_INT_PERIOD) || defined(MONITOR_FREQUENCY) - #ifdef MONITOR_FREQUENCY - // if diff is very very greater than the theoretical value, the electrical signal - // can be considered as lost for a while and I must reset my moving average. - // I decided to use "16" because is a power of 2, very fast to be computed. - if (semiPeriodLength && diff > semiPeriodLength * 16) { - queue.reset(); - } else { - // If filtering has passed, I can update the moving average - queue.add(diff); - } - #endif - - lastTime = now; - } -#endif - - // Turn OFF all the thyristors, even if always ON. - // This is to speed up transitions between ON to OFF state: - // If I don't turn OFF all those thyristors, I must wait - // a semiperiod to turn off those one. - for (int i = 0; i < Thyristor::nThyristors; i++) { - if (pinDelay[i].pin != 0xff) { - digitalWrite(pinDelay[i].pin, LOW); - } - } - -#ifdef CHECK_MANAGED_THYR - if (thyristorManaged != Thyristor::nThyristors) { - #ifdef ARDUINO_ARCH_ESP32 - ets_printf("E%d\n", thyristorManaged); - #else - Serial.print("E"); - Serial.println(thyristorManaged); - #endif - } -#endif - - // Update the structures and set thresholds, if needed - if (Thyristor::newDelayValues && !Thyristor::updatingStruct) { - Thyristor::newDelayValues = false; - alwaysOffCounter = 0; - alwaysOnCounter = 0; - for (int i = 0; i < Thyristor::nThyristors; i++) { - pinDelay[i].pin = Thyristor::thyristors[i]->pin; - // Rounding delays to avoid error and unexpected behavior due to - // non-ideal thyristors and not perfect sine wave - if (Thyristor::thyristors[i]->delay == 0) { - alwaysOnCounter++; - pinDelay[i].delay = 0; - } else if (Thyristor::thyristors[i]->delay < startMargin) { - alwaysOnCounter++; - pinDelay[i].delay = 0; - } else if (Thyristor::thyristors[i]->delay == semiPeriodLength) { - alwaysOffCounter++; - pinDelay[i].delay = semiPeriodLength; - } else if (Thyristor::thyristors[i]->delay > semiPeriodLength - endMargin) { - alwaysOffCounter++; - pinDelay[i].delay = semiPeriodLength; - } else { - pinDelay[i].delay = Thyristor::thyristors[i]->delay; - } - } - _allThyristorsOnOff = Thyristor::allThyristorsOnOff; - } - - thyristorManaged = 0; - - // if all are on and off, I can disable the zero cross interrupt - if (_allThyristorsOnOff) { - for (int i = 0; i < Thyristor::nThyristors; i++) { - if (pinDelay[i].pin != 0xff) { - if (pinDelay[i].delay == semiPeriodLength) { - digitalWrite(pinDelay[i].pin, LOW); - } else { - digitalWrite(pinDelay[i].pin, HIGH); - } - } - thyristorManaged++; - } - -#if defined(MONITOR_FREQUENCY) - if (!Thyristor::frequencyMonitorAlwaysEnabled) { - interruptEnabled = false; - #ifdef THYRISTOR_ZCD - detachInterrupt(digitalPinToInterrupt(Thyristor::syncPin)); - #endif - queue.reset(); - - lastTime = 0; - } -#elif defined(FILTER_INT_MONITOR) - lastTime = 0; - interruptEnabled = false; - #ifdef THYRISTOR_ZCD - detachInterrupt(digitalPinToInterrupt(Thyristor::syncPin)); - #endif -#else - interruptEnabled = false; - #ifdef THYRISTOR_ZCD - detachInterrupt(digitalPinToInterrupt(Thyristor::syncPin)); - #endif -#endif - - return; - } - - // Turn on thyristors with 0 delay (always on) - while (thyristorManaged < Thyristor::nThyristors && pinDelay[thyristorManaged].delay == 0) { - if(pinDelay[thyristorManaged].pin != 0xff) { - digitalWrite(pinDelay[thyristorManaged].pin, HIGH); - } - thyristorManaged++; - } - - // This block of code is inteded to manage the case near to the next semi-period: - // In this case we should avoid to trigger the timer, because the effective semiperiod - // perceived by the esp8266 could be less than 10000microsecond. This could be due to - // the relative time (there is no possibily to set the timer to an absolute time) - // Moreover, it is impossible to disable an interrupt once it is armed, neither - // change the callback function. - // NOTE: don't know why, but the timer seem trigger even when it is not set... - // so a provvisory solution if to set the relative callback to NULL! - // NOTE 2: this improvement should be think even for multiple lamp! - if (thyristorManaged < Thyristor::nThyristors && pinDelay[thyristorManaged].delay < semiPeriodLength) { - uint16_t delayAbsolute = pinDelay[thyristorManaged].delay; -#if defined(ARDUINO_ARCH_ESP8266) - timer1_attachInterrupt(activate_thyristors); - timer1_write(US_TO_RTC_TIMER_TICKS(delayAbsolute)); -#elif defined(ARDUINO_ARCH_ESP32) - // setCallback(activate_thyristors); - nextISR = INT_TYPE::ACTIVATE_THYRISTORS; - startTimerAndTrigger(delayAbsolute); -#elif defined(ARDUINO_ARCH_AVR) - timerSetCallback(activate_thyristors); - timerSetAlarm(microsecond2Tick(delayAbsolute)); -#elif defined(ARDUINO_ARCH_SAMD) - timerSetCallback(activate_thyristors); - timerStart(microsecond2Tick(delayAbsolute)); -#elif defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_ARCH_MBED) - timerSetCallback(activate_thyristors); - timerStart(pinDelay[thyristorManaged].delay); -#else - #error "Not implemented" -#endif - } else { - - // This while is dedicated to all those thyristor wih delay == semiPeriodLength-margin; those - // are the ones who shouldn't turn on, hence they can be skipped - while (thyristorManaged < Thyristor::nThyristors && pinDelay[thyristorManaged].delay == semiPeriodLength) { - thyristorManaged++; - } - -#if defined(ARDUINO_ARCH_ESP8266) - // Given the Arduino HAL and esp8266 technical reference manual, - // when timer triggers, the counter stops because it has reached zero - // and no-autorealod was set (this timer can only down-count). -#elif defined(ARDUINO_ARCH_ESP32) - stopTimer(); -#elif defined(ARDUINO_ARCH_AVR) - timerStop(); -#elif defined(ARDUINO_ARCH_SAMD) - // Given actual HAL, and SAMD counter automatically stops on interrupt -#elif defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_ARCH_MBED) - // Timer callback is not rescheduled -#endif - } -} - -#if defined(ARDUINO_ARCH_ESP8266) -void HW_TIMER_IRAM_ATTR isr_selector() { -#elif defined(ARDUINO_ARCH_ESP32) -void ARDUINO_ISR_ATTR isr_selector() { -#else -void isr_selector() { -#endif - if (nextISR == INT_TYPE::ACTIVATE_THYRISTORS) { - activate_thyristors(); - } else if (nextISR == INT_TYPE::TURN_OFF_GATES) { - turn_off_gates_int(); - } -} - -void Thyristor::setDelay(uint16_t newDelay) { - if (verbosity > 2) { - for (int i = 0; i < Thyristor::nThyristors; i++) { - Serial.print(String("setB: ") + "posIntoArray:" + thyristors[i]->posIntoArray + " pin:" + thyristors[i]->pin); - Serial.print(" "); - Serial.println(thyristors[i]->delay); - } - } - - if (newDelay > semiPeriodLength) { - newDelay = semiPeriodLength; - } - - // Reorder the array to speed up the interrupt. - // This mini-algorithm works on a different memory area w.r.t. the ISR, - // so it is concurrent-safe - - updatingStruct = true; - // Array example, it is always ordered, higher values means lower brightness levels - // [45,678,5000,7500,9000] - if (newDelay > delay) { - if (verbosity > 2) - Serial.println("\tlowering the light.."); - bool done = false; - ///////////////////////////////////////////////////////////////// - // Let's find the new position - int i = posIntoArray + 1; - while (i < nThyristors && !done) { - if (newDelay <= thyristors[i]->delay) { - done = true; - } else { - i++; - } - } - // This could be due to 2 reasons: - // 1) the light is already the lowest delay (i.e. turned off) - // 2) the delay is not changed to overpass the neightbour - if (posIntoArray + 1 == i) { - if (verbosity > 2) - Serial.println("No need to shift.."); - } else { - int target; - // Means that we have reached the end, the target i the last element - if (i == nThyristors) { - target = nThyristors - 1; - } else { - target = i - 1; - } - - // Let's shift - for (int i = posIntoArray; i < target; i++) { - thyristors[i] = thyristors[i + 1]; - thyristors[i]->posIntoArray = i; - } - thyristors[target] = this; - this->posIntoArray = target; - } - } else if (newDelay < delay) { - if (verbosity > 2) - Serial.println("\traising the light.."); - bool done = false; - int i = posIntoArray - 1; - while (i >= 0 && !done) { - if (newDelay >= thyristors[i]->delay) { - done = true; - } else { - i--; - } - } - if (posIntoArray - 1 == i) { - if (verbosity > 2) - Serial.println("No need to shift.."); - } else { - int target; - // Means that we have reached the start, the target is the first element - if (!done) { - target = 0; - } else { - target = i + 1; - } - - // Let's shift - for (int i = posIntoArray; i > target; i--) { - thyristors[i] = thyristors[i - 1]; - thyristors[i]->posIntoArray = i; - } - thyristors[target] = this; - this->posIntoArray = target; - } - } else { - if (verbosity > 2) - Serial.println("Warning: you are setting the same delay as the previous one!"); - updatingStruct = false; - return; - } - - delay = newDelay; - bool enableInt = mustInterruptBeReEnabled(newDelay); - newDelayValues = true; - updatingStruct = false; - if (enableInt) { - if (verbosity > 2) - Serial.println("Re-enabling interrupt"); - interruptEnabled = true; -#ifdef THYRISTOR_ZCD - attachInterrupt(digitalPinToInterrupt(syncPin), zero_cross_int, syncDir); -#endif - } - - if (verbosity > 2) { - for (int i = 0; i < Thyristor::nThyristors; i++) { - Serial.print(String("\tsetB: ") + "posIntoArray:" + thyristors[i]->posIntoArray + " pin:" + thyristors[i]->pin); - Serial.print(" "); - Serial.println(thyristors[i]->delay); - } - } -} - -void Thyristor::begin() { -#ifdef THYRISTOR_ZCD - pinMode(syncPin, syncPullup ? INPUT_PULLUP : INPUT); -#endif - -#if defined(ARDUINO_ARCH_ESP8266) - timer1_attachInterrupt(activate_thyristors); - // These 2 registers assignments are the "unrolling" of: - // timer1_enable(TIM_DIV16, TIM_EDGE, TIM_SINGLE); - T1C = (1 << TCTE) | ((TIM_DIV16 & 3) << TCPD) | ((TIM_EDGE & 1) << TCIT) | ((TIM_SINGLE & 1) << TCAR); - T1I = 0; -#elif defined(ARDUINO_ARCH_ESP32) - timerInit(isr_selector); -#elif defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_SAMD) || (defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_ARCH_MBED)) - timerSetCallback(activate_thyristors); - timerBegin(); -#else - #error "Not implemented" -#endif - -#ifdef MONITOR_FREQUENCY - // Starts immediately to sense the eletricity grid - - interruptEnabled = true; - #ifdef THYRISTOR_ZCD - attachInterrupt(digitalPinToInterrupt(syncPin), zero_cross_int, syncDir); - #endif -#endif -} - -void Thyristor::end() { - #ifdef THYRISTOR_ZCD - detachInterrupt(digitalPinToInterrupt(syncPin)); - #endif -#ifdef MONITOR_FREQUENCY - queue.reset(); -#endif -} - -float Thyristor::getFrequency() { - if (semiPeriodLength == 0) { - return 0; - } - return 1000000 / 2 / (float)(semiPeriodLength); -} - -uint16_t Thyristor::getSemiPeriod() { - return semiPeriodLength; -} - -#ifdef NETWORK_FREQ_RUNTIME -void Thyristor::setFrequency(float frequency) { - if (frequency < 0) { - return; - } - - if (frequency == 0) { - semiPeriodLength = 0; - return; - } - - semiPeriodLength = 1000000 / 2 / frequency; -} -void Thyristor::setSemiPeriod(uint16_t semiPeriod) { - semiPeriodLength = semiPeriod; -} -#endif - -#ifdef MONITOR_FREQUENCY -uint32_t Thyristor::getPulsePeriod() { - uint32_t avgPulsePeriod; - { - // Stop interrupt to freeze variables modified or accessed in the interrupt - noInterrupts(); - - // "diff" is correct even when rolling back, because all of them are unsigned - uint32_t diff = micros() - lastTime; - - // if diff is very very greater than the theoretical value, the electrical signal - // can be considered as lost for a while. - // I decided to use "16" because is a power of 2, very fast to be computed. - if (semiPeriodLength && diff > semiPeriodLength * 16) { - queue.reset(); - } - - avgPulsePeriod = queue.avg(); - interrupts(); - } - - return avgPulsePeriod; -} - -void Thyristor::frequencyMonitorAlwaysOn(bool enable) { - { - // Stop interrupt to freeze variables modified or accessed in the interrupt - noInterrupts(); - - if (enable && !interruptEnabled) { - interruptEnabled = true; -#ifdef THYRISTOR_ZCDptEnabled = true; - attachInterrupt(digitalPinToInterrupt(syncPin), zero_cross_int, syncDir); -#endif - } - frequencyMonitorAlwaysEnabled = enable; - - interrupts(); - } -} -#endif - -Thyristor::Thyristor(int pin) : pin(pin), delay(semiPeriodLength) { - if (nThyristors < N) { - pinMode(pin, OUTPUT); - - updatingStruct = true; - - posIntoArray = nThyristors; - nThyristors++; - thyristors[posIntoArray] = this; - - // Full reorder of the array - for (int i = 0; i < nThyristors; i++) { - for (int j = i + 1; j < nThyristors - 1; j++) { - if (thyristors[i]->delay > thyristors[j]->delay) { - Thyristor* temp = thyristors[i]; - thyristors[i] = thyristors[j]; - thyristors[j] = temp; - } - } - } - // Set the posIntoArray with a "brutal" assignement to each Thyristor - for (int i = 0; i < nThyristors; i++) { - thyristors[i]->posIntoArray = i; - } - - newDelayValues = true; - updatingStruct = false; - } else { - // TODO return error or exception - } -} - -Thyristor::~Thyristor() { - // Recompact the array - updatingStruct = true; - - if (nThyristors == 1) { - thyristors[0] = nullptr; - pinDelay[0].pin = 0xff; - } else if (nThyristors == 2) { - if (thyristors[0] == this) { - thyristors[0] = thyristors[1]; - } - if (pinDelay[0].pin == pin) { - pinDelay[0] = pinDelay[1]; - } - } - thyristors[1] = nullptr; - pinDelay[1].pin = 0xff; - - nThyristors--; - - updatingStruct = false; -} - -bool Thyristor::areThyristorsOnOff() { - bool allOnOff = true; - int i = 0; - while (i < nThyristors && allOnOff) { - if (thyristors[i]->getDelay() != 0 && thyristors[i]->getDelay() != semiPeriodLength) { - allOnOff = false; - } else { - i++; - } - } - return allOnOff; -} - -bool Thyristor::mustInterruptBeReEnabled(uint16_t newDelay) { - bool interruptMustBeEnabled = true; - - // Temp values those are "commited" at the end of this method - bool newAllThyristorsOnOff = allThyristorsOnOff; - - if (newDelay == semiPeriodLength || newDelay == 0) { - newAllThyristorsOnOff = areThyristorsOnOff(); - } else { - // if newDelay is not optimizable i.e. a value between (0; semiPeriodLength) - newAllThyristorsOnOff = false; - } - - allThyristorsOnOff = newAllThyristorsOnOff; - if (verbosity > 1) - Serial.println(String("allThyristorsOnOff: ") + allThyristorsOnOff); - return !interruptEnabled && interruptMustBeEnabled; -} - -uint8_t Thyristor::nThyristors = 0; -Thyristor* Thyristor::thyristors[Thyristor::N] = {nullptr}; -bool Thyristor::newDelayValues = false; -bool Thyristor::updatingStruct = false; -bool Thyristor::allThyristorsOnOff = true; -#ifdef THYRISTOR_ZCD -uint8_t Thyristor::syncPin = 255; -decltype(RISING) Thyristor::syncDir = RISING; -bool Thyristor::syncPullup = false; -#endif -bool Thyristor::frequencyMonitorAlwaysEnabled = true; diff --git a/lib/DimmableLight/src/thyristor.h b/lib/DimmableLight/src/thyristor.h deleted file mode 100644 index a131d59e..00000000 --- a/lib/DimmableLight/src/thyristor.h +++ /dev/null @@ -1,295 +0,0 @@ -/****************************************************************************** - * This file is part of Dimmable Light for Arduino, a library to control * - * dimmers. * - * * - * Copyright (C) 2018-2023 Fabiano Riccardi * - * * - * Dimmable Light for Arduino is free software; you can redistribute * - * it and/or modify it under the terms of the GNU Lesser General Public * - * License as published by the Free Software Foundation; either * - * version 2.1 of the License, or (at your option) any later version. * - * * - * This library is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * - * Lesser General Public License for more details. * - * * - * You should have received a copy of the GNU Lesser General Public License * - * along with this library; if not, see . * - ******************************************************************************/ -#ifndef THYRISTOR_H -#define THYRISTOR_H - -#include - -/** - * These defines affect the declaration of this class and the relative wrappers. - */ - -// Set the network frequency. -// The first 2 options fix the frequency to the common values (respectively to 50 and 60Hz) at -// compile time. The third option allows you change network frequency at runtime. This option -// automatically enables the setFrequency() method. The main drawback is that it requires a few more -// resources w.r.t. the "fixed frequency" alternatives. -// Select one and ONLY one among the following alternatives: -// #define NETWORK_FREQ_FIXED_50HZ -// #define NETWORK_FREQ_FIXED_60HZ -#define NETWORK_FREQ_RUNTIME - -// Set the default value if no option is selected -#if !defined(NETWORK_FREQ_FIXED_50HZ) && !defined(NETWORK_FREQ_FIXED_60HZ) && !defined(NETWORK_FREQ_RUNTIME) - #define NETWORK_FREQ_FIXED_50HZ -#endif - -// If enabled, you can monitor the actual frequency of the electrical network. -// #define MONITOR_FREQUENCY - -#define FILTER_INT_PERIOD -// #define THYRISTOR_ZCD - -/** - * This is the core class of this library, that provides the finest control on thyristors. - * - * NOTE: Design Principle for this library: There are 2 main abstraction levels: the first one, - * represented by Thyristor class, is agnostic about the controlled load (it doesn't assume a lamp, - * a heater or a motor). The second one provides a simpler and more concrete interface, presenting - * simplified APIs to the user as expected by an Arduino library, and it is exemplified by - * DimmableLight class. - * Now, I'm aware that this is positive because it allows to write very - * readable code IF the appliance is a light, but it is limiting and weird if the user is going to - * use another appliance. - * - * About this class, the "core" of the library, the name of the method to control a dimmer is - * setDelay(..) and not, for example, setPower(..), setBrightness(..), ... This gives a precise idea - * of what's happening at electrical level, that is controlling the activation time of the - * thyristor. Secondly, the measurement unit is expressed in microseconds, allowing the finest and - * feasible control reachable with almost any MCU avaialble on the market (including Arduino UNO - * based on ATmega328p). - */ -class Thyristor { - public: - Thyristor(int pin); - Thyristor(Thyristor const&) = delete; - void operator=(Thyristor const& t) = delete; - - /** - * Set the delay, 10000 (ms, with 50Hz voltage) to turn off the thyristor - */ - void setDelay(uint16_t delay); - - /** - * Return the current delay. - */ - uint16_t getDelay() const { - return delay; - } - - /** - * Turn on the thyristor at full power. - */ - void turnOn() { - setDelay(0); - } - - /** - * Turn off the thyristor. - */ - void turnOff() { - setDelay(getSemiPeriod()); - } - - ~Thyristor(); - - /** - * Setup timer and interrupt routine. - */ - static void begin(); - static void end(); - - /** - * Return the number of instantiated thyristors. - */ - static uint8_t getThyristorNumber() { - return nThyristors; - }; - -#ifdef THYRISTOR_ZCD - /** - * Set the pin dedicated to receive the AC zero cross signal. - */ - static void setSyncPin(uint8_t pin) { - syncPin = pin; - } - - /** - * Set the pin direction (RISING (default), FALLING, CHANGE). - */ - static void setSyncDir(decltype(RISING) dir) { - syncDir = dir; - } - - /** - * Set the pin pullup (true = INPUT_PULLUP, false = INPUT). The internal pullup resistor is not - * available for each platform and each pin. - */ - static void setSyncPullup(bool pullup) { - syncPullup = pullup; - } -#endif - - /** - * Get frequency. - */ - static float getFrequency(); - - /** - * Get the semiperiod. - */ - static uint16_t getSemiPeriod(); - -#ifdef NETWORK_FREQ_RUNTIME - /** - * Set target frequency. Negative values are ignored; - * zero set the semi-period to 0. - */ - static void setFrequency(float frequency); - static void setSemiPeriod(uint16_t semiPeriod); -#endif - -#ifdef MONITOR_FREQUENCY - /** - * Get the detected frequency on the electrical network, constantly updated. - * Return 0 if there is no signal or while sampling the first periods. - * - * NOTE: when (re)starting, it will take a while before returning a value different from 0. - */ - static uint32_t getPulsePeriod(); - - /** - * Check if frequency monitor is always enabled. - */ - static bool isFrequencyMonitorAlwaysOn() { - return frequencyMonitorAlwaysEnabled; - } - - /** - * Control if the monitoring can be automatically stopped when - * all lights are on and off. True to force the constant monitoring, - * false to allow automatic stop. By default the monitoring is always active. - * - */ - static void frequencyMonitorAlwaysOn(bool enable); -#endif - - static const uint8_t N = 8; - - private: - /** - * Tell if interrupt must be re-enabled. This metohd affect allMixedOnOff variable. - * This methods must be called every time a thyristor's delay is updated. - * - * NewDelay the new delay just set of this thyristor. - * Return true if interrupt for zero cross detection should be re-enabled, - * false do nothing. - */ - bool mustInterruptBeReEnabled(uint16_t newDelay); - - /** - * Search if all the values are only on and off. - * Return true if all are on/off, false otherwise. - */ - bool areThyristorsOnOff(); - - /** - * Number of instantiated thyristors. - */ - static uint8_t nThyristors; - - /** - * Vector of instatiated thyristors. - */ - static Thyristor* thyristors[]; - - /** - * Variable to tell to interrupt routine to update its internal structures - */ - static bool newDelayValues; - - /** - * Variable to avoid concurrency problem between interrupt and threads. - * In particular, this variable is used to prevent the copy of the memory used by - * the array of struct during reordering (interrupt can continue because it - * keeps its own copy of the array). - * A condition variable does not make sense because interrupt routine cannot be - * stopped. - */ - static bool updatingStruct; - - /** - * This variable tells if the thyristors are completely ON and OFF, - * mixed configuration are included. If one thyristor has a value between - * (0; semiPeriodLength), this variable is false. If true, this implies that - * zero cross interrupt must be enabled to manage the thyristor activation. - */ - static bool allThyristorsOnOff; - -#ifdef THYRISTOR_ZCD - /** - * Pin receiving the external Zero Cross signal. - */ - static uint8_t syncPin; - - /** - * Pin direction (FALLING, RISING, CHANGE). - */ - static decltype(RISING) syncDir; - - /** - * Pin pullup active. - */ - static bool syncPullup; -#endif - - /** - * 0) no messages - * 1) error messages - * 2) debug messages - * 3) info messages - */ - static const uint8_t verbosity = 1; - - /** - * True means the is always listeing, false means - * auto-stop when all lights are on/off. - */ - static bool frequencyMonitorAlwaysEnabled; - - /** - * Pin used to control thyristor's gate. - */ - uint8_t pin; - - /** - * Position into the static array, this is used to speed up the research - * operation while setting the new brightness value. - */ - uint8_t posIntoArray; - - /** - * Time to wait before turning on the thryristor. - */ - uint16_t delay; - - friend void activate_thyristors(); - friend void turn_off_gates_int(); - - public: - static void zero_cross_int(void* arg); - -#ifdef FILTER_INT_PERIOD - static int semiPeriodShrinkMargin; - static int semiPeriodExpandMargin; -#endif -}; - -#endif // END THYRISTOR_H diff --git a/lib/MycilaDimmer/MycilaDimmer.cpp b/lib/MycilaDimmer/MycilaDimmer.cpp index 982ad005..2f8f48cc 100644 --- a/lib/MycilaDimmer/MycilaDimmer.cpp +++ b/lib/MycilaDimmer/MycilaDimmer.cpp @@ -4,6 +4,14 @@ */ #include +#include +#include +#include + +#ifdef MYCILA_PULSE_DEBUG + #include +#endif + #ifdef MYCILA_LOGGER_SUPPORT #include extern Mycila::Logger logger; @@ -70,11 +78,12 @@ void Mycila::Dimmer::begin(int8_t pin, uint32_t semiPeriod) { LOGI(TAG, "Enable Dimmer on pin %" PRId8 " with semi-period %" PRIu32 " us", pin, semiPeriod); _semiPeriod = semiPeriod; - _dimmer = new Thyristor(_pin); pinMode(_pin, OUTPUT); digitalWrite(_pin, LOW); _enabled = true; + _registerDimmer(this); + // restart with last saved value setDutyCycle(_dutyCycle); } @@ -82,15 +91,13 @@ void Mycila::Dimmer::begin(int8_t pin, uint32_t semiPeriod) { void Mycila::Dimmer::end() { if (!_enabled) return; + _unregisterDimmer(this); _enabled = false; LOGI(TAG, "Disable Dimmer on pin %" PRId8, _pin); // keep last saved value, // _dutyCycle = 0; _delay = UINT32_MAX; _semiPeriod = 0; - _dimmer->setDelay(_delay); - delete _dimmer; - _dimmer = nullptr; digitalWrite(_pin, LOW); _pin = GPIO_NUM_NC; } @@ -112,8 +119,6 @@ void Mycila::Dimmer::setDutyCycle(float newDutyCycle) { } else { _delay = _lookupPhaseDelay(mappedDutyCycle * DIMMER_MAX, _semiPeriod); } - - _dimmer->setDelay(_delay); } void Mycila::Dimmer::setDutyCycleLimit(float limit) { @@ -134,3 +139,16 @@ void Mycila::Dimmer::setDutyCycleMax(float max) { LOGD(TAG, "Set dimmer %" PRId8 " duty cycle max to %f", _pin, _dutyCycleMax); setDutyCycle(_dutyCycle); } + +void Mycila::Dimmer::_registerDimmer(Dimmer* dimmer) { +} + +void Mycila::Dimmer::_unregisterDimmer(Dimmer* dimmer) { +} + +void IRAM_ATTR Mycila::Dimmer::onZeroCross(void* arg) { +} + +bool IRAM_ATTR Mycila::Dimmer::_fireTimerISR(gptimer_handle_t timer, const gptimer_alarm_event_data_t* event, void* arg) { + return false; +} diff --git a/lib/MycilaDimmer/MycilaDimmer.h b/lib/MycilaDimmer/MycilaDimmer.h index 48d7b59c..0c9a6f3b 100644 --- a/lib/MycilaDimmer/MycilaDimmer.h +++ b/lib/MycilaDimmer/MycilaDimmer.h @@ -4,13 +4,16 @@ */ #pragma once -#include -#include - #ifdef MYCILA_JSON_SUPPORT #include #endif +#include +#include +#include + +#include + /** * Optional resolution, 15bits max */ @@ -167,6 +170,8 @@ namespace Mycila { */ float getPhaseAngle() const { return _delay >= _semiPeriod ? PI : PI * _delay / _semiPeriod; } + static void onZeroCross(void* args); + private: bool _enabled = false; gpio_num_t _pin = GPIO_NUM_NC; @@ -176,6 +181,11 @@ namespace Mycila { float _dutyCycleMin = 0; float _dutyCycleMax = 1; uint32_t _delay = UINT32_MAX; - Thyristor* _dimmer = nullptr; + + static gptimer_handle_t _fireTimer; + static volatile std::list _dimmers; + static void _registerDimmer(Dimmer* dimmer); + static void _unregisterDimmer(Dimmer* dimmer); + static bool _fireTimerISR(gptimer_handle_t timer, const gptimer_alarm_event_data_t* event, void* arg); }; } // namespace Mycila diff --git a/src/init/Config.cpp b/src/init/Config.cpp index 256a211e..55b87811 100644 --- a/src/init/Config.cpp +++ b/src/init/Config.cpp @@ -4,8 +4,6 @@ */ #include -#include - Mycila::Task initConfigTask("Init Config", [](void* params) { logger.warn(TAG, "Configuring %s", Mycila::AppInfo.nameModelVersion.c_str()); @@ -189,7 +187,7 @@ Mycila::Task initConfigTask("Init Config", [](void* params) { espConnect.begin(Mycila::AppInfo.defaultHostname.c_str(), Mycila::AppInfo.defaultSSID.c_str(), config.get(KEY_ADMIN_PASSWORD).c_str(), {config.get(KEY_WIFI_SSID).c_str(), config.get(KEY_WIFI_PASSWORD).c_str(), config.getBool(KEY_ENABLE_AP_MODE)}); // ZCD + Dimmers - pulseAnalyzer.onZeroCross(Thyristor::zero_cross_int); + pulseAnalyzer.onZeroCross(Mycila::Dimmer::onZeroCross); dimmerO1.setDutyCycleMin(config.get(KEY_OUTPUT1_DIMMER_MIN).toFloat() / 100); dimmerO1.setDutyCycleMax(config.get(KEY_OUTPUT1_DIMMER_MAX).toFloat() / 100); dimmerO1.setDutyCycleLimit(config.get(KEY_OUTPUT1_DIMMER_LIMIT).toFloat() / 100); diff --git a/src/tasks/ZCD.cpp b/src/tasks/ZCD.cpp index ebcdb83b..15d92d01 100644 --- a/src/tasks/ZCD.cpp +++ b/src/tasks/ZCD.cpp @@ -4,8 +4,6 @@ */ #include -#include - Mycila::Task zcdTask("ZCD", [](void* params) { const bool zcdSwitched = config.getBool(KEY_ENABLE_ZCD); const bool dimmer1Switched = config.getBool(KEY_ENABLE_OUTPUT1_DIMMER); @@ -28,8 +26,6 @@ Mycila::Task zcdTask("ZCD", [](void* params) { pulseAnalyzer.end(); dimmerO1.end(); dimmerO2.end(); - Thyristor::end(); - Thyristor::setSemiPeriod(0); return; } @@ -53,16 +49,10 @@ Mycila::Task zcdTask("ZCD", [](void* params) { // => ZCD switch turned on + Pulse Analyzer online - if (!Thyristor::getSemiPeriod() || (dimmer1Switched && !dimmerO1.isEnabled()) || (dimmer2Switched && !dimmerO2.isEnabled())) { + if ((dimmer1Switched && !dimmerO1.isEnabled()) || (dimmer2Switched && !dimmerO2.isEnabled())) { float frequency = detectGridFrequency(); uint32_t semiPeriod = 1000000 / 2 / frequency; - if (!Thyristor::getSemiPeriod()) { - logger.info(TAG, "Starting Thyristor with semi-period: %" PRIu32 " us", semiPeriod); - Thyristor::setSemiPeriod(semiPeriod); - Thyristor::begin(); - } - if (dimmer1Switched && !dimmerO1.isEnabled()) { dimmerO1.begin(config.get(KEY_PIN_OUTPUT1_DIMMER).toInt(), semiPeriod); }