MycilaJSY 13.0.0
Arduino / ESP32 library for the JSY1031, JSY-MK-163, JSY-MK-193, JSY-MK-194, JSY-MK-227, JSY-MK-229, JSY-MK-333 families single-phase and three-phase AC bidirectional meters from Shenzhen Jiansiyan Technologies Co, Ltd.
Loading...
Searching...
No Matches
MycilaDimmerBurstFire.cpp
1// SPDX-License-Identifier: MIT
2/*
3 * Copyright (C) 2023-2025 Mathieu Carbou
4 */
5#include <MycilaDimmerBurstFire.h>
6
7// lock
8#include <freertos/FreeRTOS.h>
9
10// gpio
11#include <driver/gpio.h>
12#include <driver/gptimer_types.h>
13#include <esp32-hal-gpio.h>
14#include <hal/gpio_ll.h>
15#include <soc/gpio_struct.h>
16
17// logging
18#include <esp32-hal-log.h>
19
20// timers
21#include "priv/inlined_gptimer.h"
22
23#ifdef MYCILA_LOGGER_SUPPORT
24 #include <MycilaLogger.h>
25extern Mycila::Logger logger;
26 #define LOGD(tag, format, ...) logger.debug(tag, format, ##__VA_ARGS__)
27 #define LOGI(tag, format, ...) logger.info(tag, format, ##__VA_ARGS__)
28 #define LOGW(tag, format, ...) logger.warn(tag, format, ##__VA_ARGS__)
29 #define LOGE(tag, format, ...) logger.error(tag, format, ##__VA_ARGS__)
30#else
31 #define LOGD(tag, format, ...) ESP_LOGD(tag, format, ##__VA_ARGS__)
32 #define LOGI(tag, format, ...) ESP_LOGI(tag, format, ##__VA_ARGS__)
33 #define LOGW(tag, format, ...) ESP_LOGW(tag, format, ##__VA_ARGS__)
34 #define LOGE(tag, format, ...) ESP_LOGE(tag, format, ##__VA_ARGS__)
35#endif
36
37#ifndef GPIO_IS_VALID_OUTPUT_GPIO
38 #define GPIO_IS_VALID_OUTPUT_GPIO(gpio_num) ((gpio_num >= 0) && \
39 (((1ULL << (gpio_num)) & SOC_GPIO_VALID_OUTPUT_GPIO_MASK) != 0))
40#endif
41
42#ifndef GPIO_IS_VALID_GPIO
43 #define GPIO_IS_VALID_GPIO(gpio_num) ((gpio_num >= 0) && \
44 (((1ULL << (gpio_num)) & SOC_GPIO_VALID_GPIO_MASK) != 0))
45#endif
46
47#define TAG "BF_DIMMER"
48
49struct EnabledDimmer;
51 Mycila::BurstFireDimmer* dimmer = nullptr;
52 EnabledDimmer* prev = nullptr;
53 EnabledDimmer* next = nullptr;
54 uint16_t alarm_count = UINT16_MAX; // when to fire the dimmer
55};
56
57static struct EnabledDimmer* dimmers = nullptr;
58static gptimer_handle_t fire_timer = nullptr;
59
60#define USE_DIMMER_LOCK 1
61#if USE_DIMMER_LOCK
62static portMUX_TYPE dimmers_spinlock = portMUX_INITIALIZER_UNLOCKED;
63#endif
64
66 if (_enabled)
67 return;
68
69 if (!GPIO_IS_VALID_OUTPUT_GPIO(_pin)) {
70 LOGE(TAG, "Disable ZC Dimmer: Invalid pin: %" PRId8, _pin);
71 return;
72 }
73
74 LOGI(TAG, "Enable Thyristor Dimmer on pin %" PRId8, _pin);
75
76 pinMode(_pin, OUTPUT);
77 digitalWrite(_pin, LOW);
78 _registerDimmer(this);
79 _enabled = true;
80
81 // restart with last saved value
82 setDutyCycle(_dutyCycle);
83}
84
86 if (!_enabled)
87 return;
88 _enabled = false;
89 _online = false;
90 LOGI(TAG, "Disable ZC Dimmer on pin %" PRId8, _pin);
91 _apply();
92 _unregisterDimmer(this);
93 digitalWrite(_pin, LOW);
94}
95
96void ARDUINO_ISR_ATTR Mycila::BurstFireDimmer::onZeroCross(int16_t delayUntilZero, void* arg) {
97 // prepare our next alarm for the next dimmer to be fired
98 gptimer_alarm_config_t fire_timer_alarm_cfg = {.alarm_count = UINT16_MAX, .reload_count = 0, .flags = {.auto_reload_on_alarm = false}};
99
100 // immediately reset the firing timer to start counting from this ZC event and avoid it to trigger other alarms
101 if (inlined_gptimer_set_raw_count(fire_timer, 0) != ESP_OK) {
102 // failed to reset the timer: probably not initialized yet: just ignore this ZC event
103 return;
104 }
105
106#if USE_DIMMER_LOCK
107 // lock since we need to iterate over the list of dimmers
108 portENTER_CRITICAL_SAFE(&dimmers_spinlock);
109#endif
110
111 // go through all registered dimmers to prepare the next firing
112 struct EnabledDimmer* current = dimmers;
113 while (current != nullptr) {
114 // if a delay is applied (dimmer is off - UINT16_MAX - or on with a delay > 0), turn off the triac and it will be turned on again later
115 if (current->dimmer->_delay)
116 gpio_ll_set_level(&GPIO, current->dimmer->_pin, LOW);
117 // calculate the next firing time:
118 // - Dimmer is off (UINT16_MAX) => remainingDelay = UINT16_MAX (will not be fired)
119 // - Dimmer is on at full power (0) => remainingDelay = PHASE_DELAY (and we did not turned off the triac and it will be turned on again at the next ZC event + PHASE_DELAY
120 // - Dimmer is on with a delay > 0 => remainingDelay = delay or PHASE_DELAY_MIN_US if delay is too low
121 current->alarm_count = current->dimmer->_delay < PHASE_DELAY_MIN_US ? PHASE_DELAY_MIN_US : current->dimmer->_delay;
122 // keep the minimum time at which we have to fire a dimmer
123 if (current->alarm_count < fire_timer_alarm_cfg.alarm_count)
124 fire_timer_alarm_cfg.alarm_count = current->alarm_count;
125 current = current->next;
126 }
127
128#if USE_DIMMER_LOCK
129 // unlock the list of dimmers
130 portEXIT_CRITICAL_SAFE(&dimmers_spinlock);
131#endif
132
133 // get the time we spent looping and eventually waiting for the lock
134 uint64_t fire_timer_count_value;
135 if (inlined_gptimer_get_raw_count(fire_timer, &fire_timer_count_value) != ESP_OK) {
136 // failed to get the timer count: just ignore this ZC event
137 return;
138 }
139
140 // check if we had to wait too much time for the lock and we missed the 0V crossing point
141 if (fire_timer_count_value >= delayUntilZero) {
142 fire_timer_count_value -= delayUntilZero;
143
144 // check if we missed the minimum time at which we have to turn the first dimmer on (next alarm)
145 if (fire_timer_count_value <= fire_timer_alarm_cfg.alarm_count) {
146 // directly call the firing ISR to turn on the first dimmer without waiting for an alarm
147 if (inlined_gptimer_set_raw_count(fire_timer, fire_timer_count_value) == ESP_OK) {
148 _fireTimerISR(fire_timer, nullptr, nullptr);
149 }
150 } else {
151 // we are too late: do nothing: this is better to wait for the next ZC event than trying to turn on dimmers too late, which would create flickering
152 }
153
154 } else {
155 // 0V crossing point not yet reached: set the counter to be at the right current position (very large number) before 0: the timer count will then overflow
156 if (inlined_gptimer_set_raw_count(fire_timer, -static_cast<uint64_t>(delayUntilZero) + fire_timer_count_value) == ESP_OK) {
157 // and set an alarm to be woken up at the right time: minimumCount
158 inlined_gptimer_set_alarm_action(fire_timer, &fire_timer_alarm_cfg);
159 }
160 }
161}
162
163// Timer ISR to be called as soon as a dimmer needs to be fired
164bool ARDUINO_ISR_ATTR Mycila::BurstFireDimmer::_fireTimerISR(gptimer_handle_t timer, const gptimer_alarm_event_data_t* event, void* arg) {
165 // prepare our next alarm for the first dimmer to be fired
166 gptimer_alarm_config_t fire_timer_alarm_cfg = {.alarm_count = UINT16_MAX, .reload_count = 0, .flags = {.auto_reload_on_alarm = false}};
167
168 // get the time we spent looping and eventually waiting for the lock
169 uint64_t fire_timer_count_value;
170 if (inlined_gptimer_get_raw_count(fire_timer, &fire_timer_count_value) != ESP_OK) {
171 // failed to get the timer count: just ignore this event
172 return false;
173 }
174
175 do {
176 fire_timer_alarm_cfg.alarm_count = UINT16_MAX;
177
178#if USE_DIMMER_LOCK
179 // lock since we need to iterate over the list of dimmers
180 portENTER_CRITICAL_SAFE(&dimmers_spinlock);
181#endif
182
183 // go through all registered dimmers and check the ones to fire
184 struct EnabledDimmer* current = dimmers;
185 while (current != nullptr) {
186 if (current->alarm_count != UINT16_MAX) {
187 // this dimmer has not yet been fired (< UINT16_MAX)
188 if (current->alarm_count <= fire_timer_count_value) {
189 // timer alarm has reached this dimmer alarm => time to fire this dimmer
190 gpio_ll_set_level(&GPIO, current->dimmer->_pin, HIGH);
191 // reset the alarm count to indicate that this dimmer has been fired
192 current->alarm_count = UINT16_MAX;
193 } else {
194 // dimmer has to be fired later => keep the minimum time at which we have to fire a dimmer
195 if (current->alarm_count < fire_timer_alarm_cfg.alarm_count)
196 fire_timer_alarm_cfg.alarm_count = current->alarm_count;
197 }
198 }
199 current = current->next;
200 }
201
202#if USE_DIMMER_LOCK
203 // unlock the list of dimmers
204 portEXIT_CRITICAL_SAFE(&dimmers_spinlock);
205#endif
206
207 // refresh the current timer count value to check if we have to fire other dimmers
208 inlined_gptimer_get_raw_count(fire_timer, &fire_timer_count_value);
209 } while (fire_timer_alarm_cfg.alarm_count != UINT16_MAX && fire_timer_alarm_cfg.alarm_count <= fire_timer_count_value);
210
211 // if there are some remaining dimmers to be fired, set an alarm for the next ones
212 if (fire_timer_alarm_cfg.alarm_count != UINT16_MAX)
213 inlined_gptimer_set_alarm_action(fire_timer, &fire_timer_alarm_cfg);
214
215 return false;
216}
217
218// add a dimmer to the list of managed dimmers
219void Mycila::BurstFireDimmer::_registerDimmer(Mycila::BurstFireDimmer* dimmer) {
220 if (dimmers == nullptr) {
221 LOGI(TAG, "Starting dimmer firing ISR");
222
223 gptimer_config_t timer_config;
224 timer_config.clk_src = GPTIMER_CLK_SRC_DEFAULT;
225 timer_config.direction = GPTIMER_COUNT_UP;
226 timer_config.resolution_hz = 1000000; // 1MHz resolution
227 timer_config.flags.intr_shared = true;
228 timer_config.intr_priority = 0;
229#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 0)
230 timer_config.flags.backup_before_sleep = false;
231#endif
232#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 0)
233 timer_config.flags.allow_pd = false;
234#endif
235
236 ESP_ERROR_CHECK(gptimer_new_timer(&timer_config, &fire_timer));
237 gptimer_event_callbacks_t callbacks_config;
238 callbacks_config.on_alarm = _fireTimerISR;
239 ESP_ERROR_CHECK(gptimer_register_event_callbacks(fire_timer, &callbacks_config, nullptr));
240 ESP_ERROR_CHECK(gptimer_enable(fire_timer));
241 ESP_ERROR_CHECK(gptimer_start(fire_timer));
242 }
243
244 LOGD(TAG, "Register new dimmer %p on pin %d", dimmer, dimmer->getPin());
245
246#if USE_DIMMER_LOCK
247 portENTER_CRITICAL_SAFE(&dimmers_spinlock);
248#endif
249
250 if (dimmers == nullptr) {
251 dimmers = new EnabledDimmer();
252 dimmers->dimmer = dimmer;
253 } else {
254 struct EnabledDimmer* first = new EnabledDimmer();
255 first->next = dimmers;
256 dimmers->prev = first;
257 dimmers = first;
258 }
259
260#if USE_DIMMER_LOCK
261 portEXIT_CRITICAL_SAFE(&dimmers_spinlock);
262#endif
263}
264
265// remove a dimmer from the list of managed dimmers
266void Mycila::BurstFireDimmer::_unregisterDimmer(Mycila::BurstFireDimmer* dimmer) {
267 LOGD(TAG, "Unregister dimmer %p on pin %d", dimmer, dimmer->getPin());
268
269#if USE_DIMMER_LOCK
270 portENTER_CRITICAL_SAFE(&dimmers_spinlock);
271#endif
272
273 struct EnabledDimmer* current = dimmers;
274 while (current != nullptr) {
275 if (current->dimmer == dimmer) {
276 if (current->prev != nullptr) {
277 current->prev->next = current->next;
278 } else {
279 dimmers = current->next;
280 }
281 if (current->next != nullptr) {
282 current->next->prev = current->prev;
283 }
284 delete current;
285 break;
286 }
287 current = current->next;
288 }
289
290#if USE_DIMMER_LOCK
291 portEXIT_CRITICAL_SAFE(&dimmers_spinlock);
292#endif
293
294 if (dimmers == nullptr) {
295 LOGI(TAG, "Stopping dimmer firing ISR");
296 gptimer_stop(fire_timer); // might be already stopped
297 ESP_ERROR_CHECK(gptimer_disable(fire_timer));
298 ESP_ERROR_CHECK(gptimer_del_timer(fire_timer));
299 fire_timer = nullptr;
300 }
301}
virtual void begin()
Enable a dimmer on a specific GPIO pin.
static void onZeroCross(int16_t delayUntilZero, void *args)
virtual void end()
Disable the dimmer.
gpio_num_t getPin() const
Get the GPIO pin used for the dimmer.
bool setDutyCycle(float dutyCycle)
Set the power duty.