Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1364 lines
41 KiB

6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. /*
  2. LIGHT MODULE
  3. Copyright (C) 2016-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  6. #include "light.h"
  7. #include <Ticker.h>
  8. #include <Schedule.h>
  9. #include <ArduinoJson.h>
  10. #include <vector>
  11. extern "C" {
  12. #include "libs/fs_math.h"
  13. }
  14. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  15. #define PWM_CHANNEL_NUM_MAX LIGHT_CHANNELS
  16. extern "C" {
  17. #include "libs/pwm.h"
  18. }
  19. #endif
  20. // -----------------------------------------------------------------------------
  21. Ticker _light_comms_ticker;
  22. Ticker _light_save_ticker;
  23. Ticker _light_transition_ticker;
  24. struct channel_t {
  25. unsigned char pin; // real GPIO pin
  26. bool reverse; // wether we should invert the value before using it
  27. bool state; // is the channel ON
  28. unsigned char inputValue; // raw value, without the brightness
  29. unsigned char value; // normalized value, including brightness
  30. unsigned char target; // target value
  31. double current; // transition value
  32. };
  33. std::vector<channel_t> _light_channel;
  34. bool _light_has_color = false;
  35. bool _light_use_white = false;
  36. bool _light_use_cct = false;
  37. bool _light_use_gamma = false;
  38. bool _light_provider_update = false;
  39. bool _light_use_transitions = false;
  40. unsigned int _light_transition_time = LIGHT_TRANSITION_TIME;
  41. bool _light_dirty = false;
  42. bool _light_state = false;
  43. unsigned char _light_brightness = Light::BRIGHTNESS_MAX;
  44. unsigned int _light_mireds = lround((Light::MIREDS_COLDWHITE + Light::MIREDS_WARMWHITE) / 2);
  45. using light_brightness_func_t = void();
  46. light_brightness_func_t* _light_brightness_func = nullptr;
  47. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  48. #include <my92xx.h>
  49. my92xx * _my92xx;
  50. ARRAYINIT(unsigned char, _light_channel_map, MY92XX_MAPPING);
  51. #endif
  52. // UI hint about channel distribution
  53. const char _light_channel_desc[5][5] PROGMEM = {
  54. {'W', 0, 0, 0, 0},
  55. {'W', 'C', 0, 0, 0},
  56. {'R', 'G', 'B', 0, 0},
  57. {'R', 'G', 'B', 'W', 0},
  58. {'R', 'G', 'B', 'W', 'C'}
  59. };
  60. static_assert((LIGHT_CHANNELS * LIGHT_CHANNELS) <= (sizeof(_light_channel_desc)), "Out-of-bounds array access");
  61. // Gamma Correction lookup table (8 bit)
  62. const unsigned char _light_gamma_table[] PROGMEM = {
  63. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  64. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
  65. 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6,
  66. 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 11,
  67. 12, 12, 13, 13, 14, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19,
  68. 19, 20, 20, 21, 22, 22, 23, 23, 24, 25, 25, 26, 26, 27, 28, 28,
  69. 29, 30, 30, 31, 32, 33, 33, 34, 35, 35, 36, 37, 38, 39, 39, 40,
  70. 41, 42, 43, 43, 44, 45, 46, 47, 48, 49, 50, 50, 51, 52, 53, 54,
  71. 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 71,
  72. 72, 73, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84, 86, 87, 88, 89,
  73. 91, 92, 93, 94, 96, 97, 98, 100, 101, 102, 104, 105, 106, 108, 109, 110,
  74. 112, 113, 115, 116, 118, 119, 121, 122, 123, 125, 126, 128, 130, 131, 133, 134,
  75. 136, 137, 139, 140, 142, 144, 145, 147, 149, 150, 152, 154, 155, 157, 159, 160,
  76. 162, 164, 166, 167, 169, 171, 173, 175, 176, 178, 180, 182, 184, 186, 187, 189,
  77. 191, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 217, 219, 221,
  78. 223, 225, 227, 229, 231, 233, 235, 238, 240, 242, 244, 246, 248, 251, 253, 255
  79. };
  80. static_assert(Light::VALUE_MAX <= sizeof(_light_gamma_table), "Out-of-bounds array access");
  81. // -----------------------------------------------------------------------------
  82. // UTILS
  83. // -----------------------------------------------------------------------------
  84. void _setValue(const unsigned char id, const unsigned int value) {
  85. if (_light_channel[id].value != value) {
  86. _light_channel[id].value = value;
  87. _light_dirty = true;
  88. }
  89. }
  90. void _setInputValue(const unsigned char id, const unsigned int value) {
  91. if (_light_channel[id].inputValue != value) {
  92. _light_channel[id].inputValue = value;
  93. _light_dirty = true;
  94. }
  95. }
  96. void _setRGBInputValue(unsigned char red, unsigned char green, unsigned char blue) {
  97. _setInputValue(0, constrain(red, Light::VALUE_MIN, Light::VALUE_MAX));
  98. _setInputValue(1, constrain(green, Light::VALUE_MIN, Light::VALUE_MAX));
  99. _setInputValue(2, constrain(blue, Light::VALUE_MIN, Light::VALUE_MAX));
  100. }
  101. void _setCCTInputValue(unsigned char warm, unsigned char cold) {
  102. _setInputValue(0, constrain(warm, Light::VALUE_MIN, Light::VALUE_MAX));
  103. _setInputValue(1, constrain(cold, Light::VALUE_MIN, Light::VALUE_MAX));
  104. }
  105. void _lightApplyBrightness(unsigned char channels = lightChannels()) {
  106. double brightness = static_cast<double>(_light_brightness) / static_cast<double>(Light::BRIGHTNESS_MAX);
  107. channels = std::min(channels, lightChannels());
  108. for (unsigned char i=0; i < lightChannels(); i++) {
  109. if (i >= channels) brightness = 1;
  110. _setValue(i, _light_channel[i].inputValue * brightness);
  111. }
  112. }
  113. void _lightApplyBrightnessColor() {
  114. double brightness = static_cast<double>(_light_brightness) / static_cast<double>(Light::BRIGHTNESS_MAX);
  115. // Substract the common part from RGB channels and add it to white channel. So [250,150,50] -> [200,100,0,50]
  116. unsigned char white = std::min(_light_channel[0].inputValue, std::min(_light_channel[1].inputValue, _light_channel[2].inputValue));
  117. for (unsigned int i=0; i < 3; i++) {
  118. _setValue(i, _light_channel[i].inputValue - white);
  119. }
  120. // Split the White Value across 2 White LED Strips.
  121. if (_light_use_cct) {
  122. // This change the range from 153-500 to 0-347 so we get a value between 0 and 1 in the end.
  123. double miredFactor = ((double) _light_mireds - (double) Light::MIREDS_COLDWHITE)/((double) Light::MIREDS_WARMWHITE - (double) Light::MIREDS_COLDWHITE);
  124. // set cold white
  125. _light_channel[3].inputValue = 0;
  126. _setValue(3, lround(((double) 1.0 - miredFactor) * white));
  127. // set warm white
  128. _light_channel[4].inputValue = 0;
  129. _setValue(4, lround(miredFactor * white));
  130. } else {
  131. _light_channel[3].inputValue = 0;
  132. _setValue(3, white);
  133. }
  134. // Scale up to equal input values. So [250,150,50] -> [200,100,0,50] -> [250, 125, 0, 63]
  135. unsigned char max_in = std::max(_light_channel[0].inputValue, std::max(_light_channel[1].inputValue, _light_channel[2].inputValue));
  136. unsigned char max_out = std::max(std::max(_light_channel[0].value, _light_channel[1].value), std::max(_light_channel[2].value, _light_channel[3].value));
  137. unsigned char channelSize = _light_use_cct ? 5 : 4;
  138. if (_light_use_cct) {
  139. max_out = std::max(max_out, _light_channel[4].value);
  140. }
  141. double factor = (max_out > 0) ? (double) (max_in / max_out) : 0;
  142. for (unsigned char i=0; i < channelSize; i++) {
  143. _setValue(i, lround((double) _light_channel[i].value * factor * brightness));
  144. }
  145. // Scale white channel to match brightness
  146. for (unsigned char i=3; i < channelSize; i++) {
  147. _setValue(i, constrain(static_cast<unsigned int>(_light_channel[i].value * LIGHT_WHITE_FACTOR), Light::BRIGHTNESS_MIN, Light::BRIGHTNESS_MAX));
  148. }
  149. // For the rest of channels, don't apply brightness, it is already in the inputValue
  150. // i should be 4 when RGBW and 5 when RGBWW
  151. for (unsigned char i=channelSize; i < _light_channel.size(); i++) {
  152. _setValue(i, _light_channel[i].inputValue);
  153. }
  154. }
  155. String lightDesc(unsigned char id) {
  156. if (id >= _light_channel.size()) return F("UNKNOWN");
  157. const char tag = pgm_read_byte(&_light_channel_desc[_light_channel.size() - 1][id]);
  158. switch (tag) {
  159. case 'W': return F("WARM WHITE");
  160. case 'C': return F("COLD WHITE");
  161. case 'R': return F("RED");
  162. case 'G': return F("GREEN");
  163. case 'B': return F("BLUE");
  164. default: break;
  165. }
  166. return F("UNKNOWN");
  167. }
  168. // -----------------------------------------------------------------------------
  169. // Input Values
  170. // -----------------------------------------------------------------------------
  171. void _fromLong(unsigned long value, bool brightness) {
  172. if (brightness) {
  173. _setRGBInputValue((value >> 24) & 0xFF, (value >> 16) & 0xFF, (value >> 8) & 0xFF);
  174. _light_brightness = (value & 0xFF) * Light::BRIGHTNESS_MAX / 255;
  175. } else {
  176. _setRGBInputValue((value >> 16) & 0xFF, (value >> 8) & 0xFF, (value) & 0xFF);
  177. }
  178. }
  179. void _fromRGB(const char * rgb) {
  180. char * p = (char *) rgb;
  181. if (strlen(p) == 0) return;
  182. switch (p[0]) {
  183. case '#': // HEX Value
  184. if (_light_has_color) {
  185. ++p;
  186. unsigned long value = strtoul(p, NULL, 16);
  187. // RGBA values are interpreted like RGB + brightness
  188. _fromLong(value, strlen(p) > 7);
  189. }
  190. break;
  191. case 'M': // Mired Value
  192. _fromMireds(atol(p + 1));
  193. break;
  194. case 'K': // Kelvin Value
  195. _fromKelvin(atol(p + 1));
  196. break;
  197. default: // assume decimal values separated by commas
  198. char * tok;
  199. unsigned char count = 0;
  200. unsigned char channels = _light_channel.size();
  201. tok = strtok(p, ",");
  202. while (tok != NULL) {
  203. _setInputValue(count, atoi(tok));
  204. if (++count == channels) break;
  205. tok = strtok(NULL, ",");
  206. }
  207. // RGB but less than 3 values received, assume it is 0
  208. if (_light_has_color && (count < 3)) {
  209. // check channel 1 and 2:
  210. for (int i = 1; i <= 2; i++) {
  211. if (count < (i+1)) {
  212. _setInputValue(i, 0);
  213. }
  214. }
  215. }
  216. break;
  217. }
  218. }
  219. // HSV string is expected to be "H,S,V", where:
  220. // 0 <= H <= 360
  221. // 0 <= S <= 100
  222. // 0 <= V <= 100
  223. void _fromHSV(const char * hsv) {
  224. char * ptr = (char *) hsv;
  225. if (strlen(ptr) == 0) return;
  226. if (!_light_has_color) return;
  227. char * tok;
  228. unsigned char count = 0;
  229. unsigned int value[3] = {0};
  230. tok = strtok(ptr, ",");
  231. while (tok != NULL) {
  232. value[count] = atoi(tok);
  233. if (++count == 3) break;
  234. tok = strtok(NULL, ",");
  235. }
  236. if (count != 3) return;
  237. // HSV to RGB transformation -----------------------------------------------
  238. //INPUT: [0,100,57]
  239. //IS: [145,0,0]
  240. //SHOULD: [255,0,0]
  241. double h = (value[0] == 360) ? 0 : (double) value[0] / 60.0;
  242. double f = (h - floor(h));
  243. double s = (double) value[1] / 100.0;
  244. _light_brightness = lround((double) value[2] * (static_cast<double>(Light::BRIGHTNESS_MAX) / 100.0)); // (default 255/100)
  245. unsigned char p = lround(Light::VALUE_MAX * (1.0 - s));
  246. unsigned char q = lround(Light::VALUE_MAX * (1.0 - s * f));
  247. unsigned char t = lround(Light::VALUE_MAX * (1.0 - s * (1.0 - f)));
  248. switch (int(h)) {
  249. case 0:
  250. _setRGBInputValue(Light::VALUE_MAX, t, p);
  251. break;
  252. case 1:
  253. _setRGBInputValue(q, Light::VALUE_MAX, p);
  254. break;
  255. case 2:
  256. _setRGBInputValue(p, Light::VALUE_MAX, t);
  257. break;
  258. case 3:
  259. _setRGBInputValue(p, q, Light::VALUE_MAX);
  260. break;
  261. case 4:
  262. _setRGBInputValue(t, p, Light::VALUE_MAX);
  263. break;
  264. case 5:
  265. _setRGBInputValue(Light::VALUE_MAX, p, q);
  266. break;
  267. default:
  268. _setRGBInputValue(Light::VALUE_MIN, Light::VALUE_MIN, Light::VALUE_MIN);
  269. break;
  270. }
  271. }
  272. // Thanks to Sacha Telgenhof for sharing this code in his AiLight library
  273. // https://github.com/stelgenhof/AiLight
  274. void _fromKelvin(unsigned long kelvin) {
  275. if (!_light_has_color) {
  276. if(!_light_use_cct) return;
  277. _light_mireds = constrain(static_cast<unsigned int>(lround(1000000UL / kelvin)), Light::MIREDS_COLDWHITE, Light::MIREDS_WARMWHITE);
  278. // This change the range from 153-500 to 0-347 so we get a value between 0 and 1 in the end.
  279. double factor = ((double) _light_mireds - (double) Light::MIREDS_COLDWHITE)/((double) Light::MIREDS_WARMWHITE - (double) Light::MIREDS_COLDWHITE);
  280. unsigned char warm = lround(factor * Light::VALUE_MAX);
  281. unsigned char cold = lround(((double) 1.0 - factor) * Light::VALUE_MAX);
  282. _setCCTInputValue(warm, cold);
  283. return;
  284. }
  285. _light_mireds = constrain(static_cast<unsigned int>(lround(1000000UL / kelvin)), Light::MIREDS_COLDWHITE, Light::MIREDS_WARMWHITE);
  286. if (_light_use_cct) {
  287. _setRGBInputValue(Light::VALUE_MAX, Light::VALUE_MAX, Light::VALUE_MAX);
  288. return;
  289. }
  290. // Calculate colors
  291. kelvin /= 100;
  292. unsigned int red = (kelvin <= 66)
  293. ? Light::VALUE_MAX
  294. : 329.698727446 * fs_pow((double) (kelvin - 60), -0.1332047592);
  295. unsigned int green = (kelvin <= 66)
  296. ? 99.4708025861 * fs_log(kelvin) - 161.1195681661
  297. : 288.1221695283 * fs_pow((double) kelvin, -0.0755148492);
  298. unsigned int blue = (kelvin >= 66)
  299. ? Light::VALUE_MAX
  300. : ((kelvin <= 19)
  301. ? 0
  302. : 138.5177312231 * fs_log(kelvin - 10) - 305.0447927307);
  303. _setRGBInputValue(red, green, blue);
  304. }
  305. // Color temperature is measured in mireds (kelvin = 1e6/mired)
  306. void _fromMireds(unsigned long mireds) {
  307. unsigned long kelvin = constrain(static_cast<unsigned int>(1000000UL / mireds), Light::KELVIN_WARMWHITE, Light::KELVIN_COLDWHITE);
  308. _fromKelvin(kelvin);
  309. }
  310. // -----------------------------------------------------------------------------
  311. // Output Values
  312. // -----------------------------------------------------------------------------
  313. void _toRGB(char * rgb, size_t len, bool target = false) {
  314. unsigned long value = 0;
  315. value += target ? _light_channel[0].target : _light_channel[0].inputValue;
  316. value <<= 8;
  317. value += target ? _light_channel[1].target : _light_channel[1].inputValue;
  318. value <<= 8;
  319. value += target ? _light_channel[2].target : _light_channel[2].inputValue;
  320. snprintf_P(rgb, len, PSTR("#%06X"), value);
  321. }
  322. void _toHSV(char * hsv, size_t len) {
  323. double h {0.}, s {0.}, v {0.};
  324. double r {0.}, g {0.}, b {0.};
  325. double min {0.}, max {0.};
  326. r = static_cast<double>(_light_channel[0].target) / Light::VALUE_MAX;
  327. g = static_cast<double>(_light_channel[1].target) / Light::VALUE_MAX;
  328. b = static_cast<double>(_light_channel[2].target) / Light::VALUE_MAX;
  329. min = std::min(r, std::min(g, b));
  330. max = std::max(r, std::max(g, b));
  331. v = 100.0 * max;
  332. if (v == 0) {
  333. h = s = 0;
  334. } else {
  335. s = 100.0 * (max - min) / max;
  336. if (s == 0) {
  337. h = 0;
  338. } else {
  339. if (max == r) {
  340. if (g >= b) {
  341. h = 0.0 + 60.0 * (g - b) / (max - min);
  342. } else {
  343. h = 360.0 + 60.0 * (g - b) / (max - min);
  344. }
  345. } else if (max == g) {
  346. h = 120.0 + 60.0 * (b - r) / (max - min);
  347. } else {
  348. h = 240.0 + 60.0 * (r - g) / (max - min);
  349. }
  350. }
  351. }
  352. // Convert to string. Using lround, since we can't (yet) printf floats
  353. snprintf(hsv, len, "%d,%d,%d",
  354. static_cast<int>(lround(h)),
  355. static_cast<int>(lround(s)),
  356. static_cast<int>(lround(v))
  357. );
  358. }
  359. void _toLong(char * color, size_t len, bool target) {
  360. if (!_light_has_color) return;
  361. snprintf_P(color, len, PSTR("%u,%u,%u"),
  362. (target ? _light_channel[0].target : _light_channel[0].inputValue),
  363. (target ? _light_channel[1].target : _light_channel[1].inputValue),
  364. (target ? _light_channel[2].target : _light_channel[2].inputValue)
  365. );
  366. }
  367. void _toLong(char * color, size_t len) {
  368. _toLong(color, len, false);
  369. }
  370. void _toCSV(char * buffer, size_t len, bool applyBrightness, bool target) {
  371. char num[10];
  372. float b = applyBrightness ? (float) _light_brightness / Light::BRIGHTNESS_MAX : 1;
  373. for (unsigned char i=0; i<_light_channel.size(); i++) {
  374. itoa((target ? _light_channel[i].target : _light_channel[i].inputValue) * b, num, 10);
  375. if (i>0) strncat(buffer, ",", len--);
  376. strncat(buffer, num, len);
  377. len = len - strlen(num);
  378. }
  379. }
  380. void _toCSV(char * buffer, size_t len, bool applyBrightness) {
  381. _toCSV(buffer, len, applyBrightness, false);
  382. }
  383. // See cores/esp8266/WMath.cpp::map
  384. // Redefining as local method here to avoid breaking in unexpected ways in inputs like (0, 0, 0, 0, 1)
  385. template <typename T, typename Tin, typename Tout> T _lightMap(T x, Tin in_min, Tin in_max, Tout out_min, Tout out_max) {
  386. auto divisor = (in_max - in_min);
  387. if (divisor == 0){
  388. return -1; //AVR returns -1, SAM returns 0
  389. }
  390. return (x - in_min) * (out_max - out_min) / divisor + out_min;
  391. }
  392. // -----------------------------------------------------------------------------
  393. // PROVIDER
  394. // -----------------------------------------------------------------------------
  395. unsigned int _toPWM(unsigned int value, bool gamma, bool reverse) {
  396. value = constrain(value, Light::VALUE_MIN, Light::VALUE_MAX);
  397. if (gamma) value = pgm_read_byte(_light_gamma_table + value);
  398. if (Light::VALUE_MAX != Light::PWM_LIMIT) value = _lightMap(value, Light::VALUE_MIN, Light::VALUE_MAX, Light::PWM_MIN, Light::PWM_LIMIT);
  399. if (reverse) value = LIGHT_LIMIT_PWM - value;
  400. return value;
  401. }
  402. // Returns a PWM value for the given channel ID
  403. unsigned int _toPWM(unsigned char id) {
  404. bool useGamma = _light_use_gamma && _light_has_color && (id < 3);
  405. return _toPWM(_light_channel[id].current, useGamma, _light_channel[id].reverse);
  406. }
  407. void _lightTransition(unsigned long step) {
  408. // Transitions based on current step. If step == 0, then it is the last transition
  409. for (auto& channel : _light_channel) {
  410. if (!step) {
  411. channel.current = channel.target;
  412. } else {
  413. channel.current += (double) (channel.target - channel.current) / (step + 1);
  414. }
  415. }
  416. }
  417. void _lightProviderUpdate(unsigned long steps) {
  418. if (_light_provider_update) return;
  419. _light_provider_update = true;
  420. _lightTransition(--steps);
  421. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  422. for (unsigned char i=0; i<_light_channel.size(); i++) {
  423. _my92xx->setChannel(_light_channel_map[i], _toPWM(i));
  424. }
  425. _my92xx->setState(true);
  426. _my92xx->update();
  427. #endif
  428. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  429. for (unsigned int i=0; i < _light_channel.size(); i++) {
  430. pwm_set_duty(_toPWM(i), i);
  431. }
  432. pwm_start();
  433. #endif
  434. // This is not the final value, update again
  435. if (steps) _light_transition_ticker.once_ms(LIGHT_TRANSITION_STEP, _lightProviderScheduleUpdate, steps);
  436. _light_provider_update = false;
  437. }
  438. void _lightProviderScheduleUpdate(unsigned long steps) {
  439. schedule_function(std::bind(_lightProviderUpdate, steps));
  440. }
  441. // -----------------------------------------------------------------------------
  442. // PERSISTANCE
  443. // -----------------------------------------------------------------------------
  444. union light_rtcmem_t {
  445. struct {
  446. uint8_t channels[5];
  447. uint8_t brightness;
  448. uint16_t mired;
  449. } packed;
  450. uint64_t value;
  451. };
  452. #define LIGHT_RTCMEM_CHANNELS_MAX sizeof(light_rtcmem_t().packed.channels)
  453. void _lightSaveRtcmem() {
  454. if (lightChannels() > LIGHT_RTCMEM_CHANNELS_MAX) return;
  455. light_rtcmem_t light;
  456. for (unsigned int i=0; i < lightChannels(); i++) {
  457. light.packed.channels[i] = _light_channel[i].inputValue;
  458. }
  459. light.packed.brightness = _light_brightness;
  460. light.packed.mired = _light_mireds;
  461. Rtcmem->light = light.value;
  462. }
  463. void _lightRestoreRtcmem() {
  464. if (lightChannels() > LIGHT_RTCMEM_CHANNELS_MAX) return;
  465. light_rtcmem_t light;
  466. light.value = Rtcmem->light;
  467. for (unsigned int i=0; i < lightChannels(); i++) {
  468. _light_channel[i].inputValue = light.packed.channels[i];
  469. }
  470. _light_brightness = light.packed.brightness;
  471. _light_mireds = light.packed.mired;
  472. }
  473. void _lightSaveSettings() {
  474. for (unsigned int i=0; i < _light_channel.size(); i++) {
  475. setSetting("ch", i, _light_channel[i].inputValue);
  476. }
  477. setSetting("brightness", _light_brightness);
  478. setSetting("mireds", _light_mireds);
  479. saveSettings();
  480. }
  481. void _lightRestoreSettings() {
  482. for (unsigned int i=0; i < _light_channel.size(); i++) {
  483. _light_channel[i].inputValue = getSetting("ch", i, (i == 0) ? Light::VALUE_MAX : 0).toInt();
  484. }
  485. _light_brightness = getSetting("brightness", Light::BRIGHTNESS_MAX).toInt();
  486. _light_mireds = getSetting("mireds", _light_mireds).toInt();
  487. }
  488. // -----------------------------------------------------------------------------
  489. // MQTT
  490. // -----------------------------------------------------------------------------
  491. #if MQTT_SUPPORT
  492. void _lightMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  493. String mqtt_group_color = getSetting("mqttGroupColor");
  494. if (type == MQTT_CONNECT_EVENT) {
  495. mqttSubscribe(MQTT_TOPIC_BRIGHTNESS);
  496. if (_light_has_color) {
  497. mqttSubscribe(MQTT_TOPIC_COLOR_RGB);
  498. mqttSubscribe(MQTT_TOPIC_COLOR_HSV);
  499. mqttSubscribe(MQTT_TOPIC_TRANSITION);
  500. }
  501. if (_light_has_color || _light_use_cct) {
  502. mqttSubscribe(MQTT_TOPIC_MIRED);
  503. mqttSubscribe(MQTT_TOPIC_KELVIN);
  504. }
  505. // Group color
  506. if (mqtt_group_color.length() > 0) mqttSubscribeRaw(mqtt_group_color.c_str());
  507. // Channels
  508. char buffer[strlen(MQTT_TOPIC_CHANNEL) + 3];
  509. snprintf_P(buffer, sizeof(buffer), PSTR("%s/+"), MQTT_TOPIC_CHANNEL);
  510. mqttSubscribe(buffer);
  511. }
  512. if (type == MQTT_MESSAGE_EVENT) {
  513. // Group color
  514. if ((mqtt_group_color.length() > 0) & (mqtt_group_color.equals(topic))) {
  515. lightColor(payload, true);
  516. lightUpdate(true, mqttForward(), false);
  517. return;
  518. }
  519. // Match topic
  520. String t = mqttMagnitude((char *) topic);
  521. // Color temperature in mireds
  522. if (t.equals(MQTT_TOPIC_MIRED)) {
  523. _fromMireds(atol(payload));
  524. lightUpdate(true, mqttForward());
  525. return;
  526. }
  527. // Color temperature in kelvins
  528. if (t.equals(MQTT_TOPIC_KELVIN)) {
  529. _fromKelvin(atol(payload));
  530. lightUpdate(true, mqttForward());
  531. return;
  532. }
  533. // Color
  534. if (t.equals(MQTT_TOPIC_COLOR_RGB)) {
  535. lightColor(payload, true);
  536. lightUpdate(true, mqttForward());
  537. return;
  538. }
  539. if (t.equals(MQTT_TOPIC_COLOR_HSV)) {
  540. lightColor(payload, false);
  541. lightUpdate(true, mqttForward());
  542. return;
  543. }
  544. // Brightness
  545. if (t.equals(MQTT_TOPIC_BRIGHTNESS)) {
  546. lightBrightness(atoi(payload));
  547. lightUpdate(true, mqttForward());
  548. return;
  549. }
  550. // Transitions
  551. if (t.equals(MQTT_TOPIC_TRANSITION)) {
  552. lightTransitionTime(atol(payload));
  553. return;
  554. }
  555. // Channel
  556. if (t.startsWith(MQTT_TOPIC_CHANNEL)) {
  557. unsigned int channelID = t.substring(strlen(MQTT_TOPIC_CHANNEL)+1).toInt();
  558. if (channelID >= _light_channel.size()) {
  559. DEBUG_MSG_P(PSTR("[LIGHT] Wrong channelID (%d)\n"), channelID);
  560. return;
  561. }
  562. lightChannel(channelID, atoi(payload));
  563. lightUpdate(true, mqttForward());
  564. return;
  565. }
  566. }
  567. }
  568. void lightMQTT() {
  569. char buffer[20];
  570. if (_light_has_color) {
  571. // Color
  572. if (getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1) {
  573. _toRGB(buffer, sizeof(buffer), true);
  574. } else {
  575. _toLong(buffer, sizeof(buffer), true);
  576. }
  577. mqttSend(MQTT_TOPIC_COLOR_RGB, buffer);
  578. _toHSV(buffer, sizeof(buffer));
  579. mqttSend(MQTT_TOPIC_COLOR_HSV, buffer);
  580. }
  581. if (_light_has_color || _light_use_cct) {
  582. // Mireds
  583. snprintf_P(buffer, sizeof(buffer), PSTR("%d"), _light_mireds);
  584. mqttSend(MQTT_TOPIC_MIRED, buffer);
  585. }
  586. // Channels
  587. for (unsigned int i=0; i < _light_channel.size(); i++) {
  588. itoa(_light_channel[i].target, buffer, 10);
  589. mqttSend(MQTT_TOPIC_CHANNEL, i, buffer);
  590. }
  591. // Brightness
  592. snprintf_P(buffer, sizeof(buffer), PSTR("%d"), _light_brightness);
  593. mqttSend(MQTT_TOPIC_BRIGHTNESS, buffer);
  594. }
  595. void lightMQTTGroup() {
  596. String mqtt_group_color = getSetting("mqttGroupColor");
  597. if (mqtt_group_color.length()>0) {
  598. char buffer[20];
  599. _toCSV(buffer, sizeof(buffer), true);
  600. mqttSendRaw(mqtt_group_color.c_str(), buffer);
  601. }
  602. }
  603. #endif
  604. // -----------------------------------------------------------------------------
  605. // Broker
  606. // -----------------------------------------------------------------------------
  607. #if BROKER_SUPPORT
  608. void lightBroker() {
  609. char buffer[10];
  610. for (unsigned int i=0; i < _light_channel.size(); i++) {
  611. itoa(_light_channel[i].inputValue, buffer, 10);
  612. brokerPublish(BROKER_MSG_TYPE_STATUS, MQTT_TOPIC_CHANNEL, i, buffer);
  613. }
  614. }
  615. #endif
  616. // -----------------------------------------------------------------------------
  617. // API
  618. // -----------------------------------------------------------------------------
  619. unsigned char lightChannels() {
  620. return _light_channel.size();
  621. }
  622. bool lightHasColor() {
  623. return _light_has_color;
  624. }
  625. bool lightUseCCT() {
  626. return _light_use_cct;
  627. }
  628. void _lightComms(unsigned char mask) {
  629. // Report color & brightness to MQTT broker
  630. #if MQTT_SUPPORT
  631. if (mask & 0x01) lightMQTT();
  632. if (mask & 0x02) lightMQTTGroup();
  633. #endif
  634. // Report color to WS clients (using current brightness setting)
  635. #if WEB_SUPPORT
  636. wsPost(_lightWebSocketStatus);
  637. #endif
  638. // Report channels to local broker
  639. #if BROKER_SUPPORT
  640. lightBroker();
  641. #endif
  642. }
  643. void lightUpdate(bool save, bool forward, bool group_forward) {
  644. // Calculate values based on inputs and brightness
  645. _light_brightness_func();
  646. // Only update if a channel has changed
  647. if (!_light_dirty) return;
  648. _light_dirty = false;
  649. // Update channels
  650. for (unsigned int i=0; i < _light_channel.size(); i++) {
  651. _light_channel[i].target = _light_state && _light_channel[i].state ? _light_channel[i].value : 0;
  652. //DEBUG_MSG_P("[LIGHT] Channel #%u target value: %u\n", i, _light_channel[i].target);
  653. }
  654. // Channel transition will be handled by the provider function
  655. // User can configure total transition time, step time is a fixed value
  656. unsigned long steps = _light_use_transitions ? _light_transition_time / LIGHT_TRANSITION_STEP : 1;
  657. _light_transition_ticker.once_ms(LIGHT_TRANSITION_STEP, _lightProviderScheduleUpdate, steps);
  658. // Delay every communication 100ms to avoid jamming
  659. unsigned char mask = 0;
  660. if (forward) mask += 1;
  661. if (group_forward) mask += 2;
  662. _light_comms_ticker.once_ms(LIGHT_COMMS_DELAY, _lightComms, mask);
  663. _lightSaveRtcmem();
  664. #if LIGHT_SAVE_ENABLED
  665. // Delay saving to EEPROM 5 seconds to avoid wearing it out unnecessarily
  666. if (save) _light_save_ticker.once(LIGHT_SAVE_DELAY, _lightSaveSettings);
  667. #endif
  668. };
  669. void lightUpdate(bool save, bool forward) {
  670. lightUpdate(save, forward, true);
  671. }
  672. #if LIGHT_SAVE_ENABLED == 0
  673. void lightSave() {
  674. _lightSaveSettings();
  675. }
  676. #endif
  677. void lightState(unsigned char i, bool state) {
  678. if (_light_channel[i].state != state) {
  679. _light_channel[i].state = state;
  680. _light_dirty = true;
  681. }
  682. }
  683. bool lightState(unsigned char i) {
  684. return _light_channel[i].state;
  685. }
  686. void lightState(bool state) {
  687. if (_light_state != state) {
  688. _light_state = state;
  689. _light_dirty = true;
  690. }
  691. }
  692. bool lightState() {
  693. return _light_state;
  694. }
  695. void lightColor(const char * color, bool rgb) {
  696. DEBUG_MSG_P(PSTR("[LIGHT] %s: %s\n"), rgb ? "RGB" : "HSV", color);
  697. if (rgb) {
  698. _fromRGB(color);
  699. } else {
  700. _fromHSV(color);
  701. }
  702. }
  703. void lightColor(const char * color) {
  704. lightColor(color, true);
  705. }
  706. void lightColor(unsigned long color) {
  707. _fromLong(color, false);
  708. }
  709. String lightColor(bool rgb) {
  710. char str[12];
  711. if (rgb) {
  712. _toRGB(str, sizeof(str));
  713. } else {
  714. _toHSV(str, sizeof(str));
  715. }
  716. return String(str);
  717. }
  718. String lightColor() {
  719. return lightColor(true);
  720. }
  721. unsigned int lightChannel(unsigned char id) {
  722. if (id <= _light_channel.size()) {
  723. return _light_channel[id].inputValue;
  724. }
  725. return 0;
  726. }
  727. void lightChannel(unsigned char id, unsigned char value) {
  728. if (id <= _light_channel.size()) {
  729. _setInputValue(id, constrain(value, Light::VALUE_MIN, Light::VALUE_MAX));
  730. }
  731. }
  732. void lightChannelStep(unsigned char id, int steps) {
  733. lightChannel(id, lightChannel(id) + steps * LIGHT_STEP);
  734. }
  735. unsigned int lightBrightness() {
  736. return _light_brightness;
  737. }
  738. void lightBrightness(unsigned int brightness) {
  739. _light_brightness = constrain(brightness, Light::BRIGHTNESS_MIN, Light::BRIGHTNESS_MAX);
  740. }
  741. void lightBrightnessStep(int steps) {
  742. lightBrightness(_light_brightness + steps * LIGHT_STEP);
  743. }
  744. unsigned int lightTransitionTime() {
  745. if (_light_use_transitions) {
  746. return _light_transition_time;
  747. } else {
  748. return 0;
  749. }
  750. }
  751. void lightTransitionTime(unsigned long m) {
  752. if (0 == m) {
  753. _light_use_transitions = false;
  754. } else {
  755. _light_use_transitions = true;
  756. _light_transition_time = m;
  757. }
  758. setSetting("useTransitions", _light_use_transitions);
  759. setSetting("lightTime", _light_transition_time);
  760. saveSettings();
  761. }
  762. // -----------------------------------------------------------------------------
  763. // SETUP
  764. // -----------------------------------------------------------------------------
  765. #if WEB_SUPPORT
  766. bool _lightWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  767. if (strncmp(key, "light", 5) == 0) return true;
  768. if (strncmp(key, "use", 3) == 0) return true;
  769. return false;
  770. }
  771. void _lightWebSocketStatus(JsonObject& root) {
  772. if (_light_has_color) {
  773. if (getSetting("useRGB", LIGHT_USE_RGB).toInt() == 1) {
  774. root["rgb"] = lightColor(true);
  775. } else {
  776. root["hsv"] = lightColor(false);
  777. }
  778. }
  779. if (_light_use_cct) {
  780. root["useCCT"] = _light_use_cct;
  781. root["mireds"] = _light_mireds;
  782. }
  783. JsonArray& channels = root.createNestedArray("channels");
  784. for (unsigned char id=0; id < _light_channel.size(); id++) {
  785. channels.add(lightChannel(id));
  786. }
  787. root["brightness"] = lightBrightness();
  788. }
  789. void _lightWebSocketOnVisible(JsonObject& root) {
  790. root["colorVisible"] = 1;
  791. }
  792. void _lightWebSocketOnConnected(JsonObject& root) {
  793. root["mqttGroupColor"] = getSetting("mqttGroupColor");
  794. root["useColor"] = _light_has_color;
  795. root["useWhite"] = _light_use_white;
  796. root["useGamma"] = _light_use_gamma;
  797. root["useTransitions"] = _light_use_transitions;
  798. root["useCSS"] = getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1;
  799. root["useRGB"] = getSetting("useRGB", LIGHT_USE_RGB).toInt() == 1;
  800. root["lightTime"] = _light_transition_time;
  801. _lightWebSocketStatus(root);
  802. }
  803. void _lightWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  804. if (_light_has_color) {
  805. if (strcmp(action, "color") == 0) {
  806. if (data.containsKey("rgb")) {
  807. lightColor(data["rgb"], true);
  808. lightUpdate(true, true);
  809. }
  810. if (data.containsKey("hsv")) {
  811. lightColor(data["hsv"], false);
  812. lightUpdate(true, true);
  813. }
  814. }
  815. }
  816. if (_light_use_cct) {
  817. if (strcmp(action, "mireds") == 0) {
  818. _fromMireds(data["mireds"]);
  819. lightUpdate(true, true);
  820. }
  821. }
  822. if (strcmp(action, "channel") == 0) {
  823. if (data.containsKey("id") && data.containsKey("value")) {
  824. lightChannel(data["id"], data["value"]);
  825. lightUpdate(true, true);
  826. }
  827. }
  828. if (strcmp(action, "brightness") == 0) {
  829. if (data.containsKey("value")) {
  830. lightBrightness(data["value"]);
  831. lightUpdate(true, true);
  832. }
  833. }
  834. }
  835. #endif
  836. #if API_SUPPORT
  837. void _lightAPISetup() {
  838. if (_light_has_color) {
  839. apiRegister(MQTT_TOPIC_COLOR_RGB,
  840. [](char * buffer, size_t len) {
  841. if (getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1) {
  842. _toRGB(buffer, len, true);
  843. } else {
  844. _toLong(buffer, len, true);
  845. }
  846. },
  847. [](const char * payload) {
  848. lightColor(payload, true);
  849. lightUpdate(true, true);
  850. }
  851. );
  852. apiRegister(MQTT_TOPIC_COLOR_HSV,
  853. [](char * buffer, size_t len) {
  854. _toHSV(buffer, len);
  855. },
  856. [](const char * payload) {
  857. lightColor(payload, false);
  858. lightUpdate(true, true);
  859. }
  860. );
  861. apiRegister(MQTT_TOPIC_KELVIN,
  862. [](char * buffer, size_t len) {},
  863. [](const char * payload) {
  864. _fromKelvin(atol(payload));
  865. lightUpdate(true, true);
  866. }
  867. );
  868. apiRegister(MQTT_TOPIC_MIRED,
  869. [](char * buffer, size_t len) {},
  870. [](const char * payload) {
  871. _fromMireds(atol(payload));
  872. lightUpdate(true, true);
  873. }
  874. );
  875. }
  876. for (unsigned int id=0; id<_light_channel.size(); id++) {
  877. char key[15];
  878. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_CHANNEL, id);
  879. apiRegister(key,
  880. [id](char * buffer, size_t len) {
  881. snprintf_P(buffer, len, PSTR("%d"), _light_channel[id].target);
  882. },
  883. [id](const char * payload) {
  884. lightChannel(id, atoi(payload));
  885. lightUpdate(true, true);
  886. }
  887. );
  888. }
  889. apiRegister(MQTT_TOPIC_TRANSITION,
  890. [](char * buffer, size_t len) {
  891. snprintf_P(buffer, len, PSTR("%d"), lightTransitionTime());
  892. },
  893. [](const char * payload) {
  894. lightTransitionTime(atol(payload));
  895. }
  896. );
  897. apiRegister(MQTT_TOPIC_BRIGHTNESS,
  898. [](char * buffer, size_t len) {
  899. snprintf_P(buffer, len, PSTR("%d"), _light_brightness);
  900. },
  901. [](const char * payload) {
  902. lightBrightness(atoi(payload));
  903. lightUpdate(true, true);
  904. }
  905. );
  906. }
  907. #endif // API_SUPPORT
  908. #if TERMINAL_SUPPORT
  909. void _lightInitCommands() {
  910. terminalRegisterCommand(F("BRIGHTNESS"), [](Embedis* e) {
  911. if (e->argc > 1) {
  912. const String value(e->argv[1]);
  913. if( value.length() > 0 ) {
  914. if( value[0] == '+' || value[0] == '-' ) {
  915. lightBrightness(lightBrightness()+String(e->argv[1]).toInt());
  916. } else {
  917. lightBrightness(String(e->argv[1]).toInt());
  918. }
  919. lightUpdate(true, true);
  920. }
  921. }
  922. DEBUG_MSG_P(PSTR("Brightness: %d\n"), lightBrightness());
  923. terminalOK();
  924. });
  925. terminalRegisterCommand(F("CHANNEL"), [](Embedis* e) {
  926. if (e->argc < 2) {
  927. terminalError(F("Wrong arguments"));
  928. }
  929. int id = String(e->argv[1]).toInt();
  930. if (e->argc > 2) {
  931. int value = String(e->argv[2]).toInt();
  932. lightChannel(id, value);
  933. lightUpdate(true, true);
  934. }
  935. DEBUG_MSG_P(PSTR("Channel #%d (%s): %d\n"), id, lightDesc(id).c_str(), lightChannel(id));
  936. terminalOK();
  937. });
  938. terminalRegisterCommand(F("COLOR"), [](Embedis* e) {
  939. if (e->argc > 1) {
  940. String color = String(e->argv[1]);
  941. lightColor(color.c_str());
  942. lightUpdate(true, true);
  943. }
  944. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  945. terminalOK();
  946. });
  947. terminalRegisterCommand(F("KELVIN"), [](Embedis* e) {
  948. if (e->argc > 1) {
  949. String color = String("K") + String(e->argv[1]);
  950. lightColor(color.c_str());
  951. lightUpdate(true, true);
  952. }
  953. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  954. terminalOK();
  955. });
  956. terminalRegisterCommand(F("MIRED"), [](Embedis* e) {
  957. if (e->argc > 1) {
  958. const String value(e->argv[1]);
  959. String color = String("M");
  960. if( value.length() > 0 ) {
  961. if( value[0] == '+' || value[0] == '-' ) {
  962. color += String(_light_mireds + String(e->argv[1]).toInt());
  963. } else {
  964. color += String(e->argv[1]);
  965. }
  966. lightColor(color.c_str());
  967. lightUpdate(true, true);
  968. }
  969. }
  970. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  971. terminalOK();
  972. });
  973. }
  974. #endif // TERMINAL_SUPPORT
  975. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  976. const unsigned long _light_iomux[16] PROGMEM = {
  977. PERIPHS_IO_MUX_GPIO0_U, PERIPHS_IO_MUX_U0TXD_U, PERIPHS_IO_MUX_GPIO2_U, PERIPHS_IO_MUX_U0RXD_U,
  978. PERIPHS_IO_MUX_GPIO4_U, PERIPHS_IO_MUX_GPIO5_U, PERIPHS_IO_MUX_SD_CLK_U, PERIPHS_IO_MUX_SD_DATA0_U,
  979. PERIPHS_IO_MUX_SD_DATA1_U, PERIPHS_IO_MUX_SD_DATA2_U, PERIPHS_IO_MUX_SD_DATA3_U, PERIPHS_IO_MUX_SD_CMD_U,
  980. PERIPHS_IO_MUX_MTDI_U, PERIPHS_IO_MUX_MTCK_U, PERIPHS_IO_MUX_MTMS_U, PERIPHS_IO_MUX_MTDO_U
  981. };
  982. const unsigned long _light_iofunc[16] PROGMEM = {
  983. FUNC_GPIO0, FUNC_GPIO1, FUNC_GPIO2, FUNC_GPIO3,
  984. FUNC_GPIO4, FUNC_GPIO5, FUNC_GPIO6, FUNC_GPIO7,
  985. FUNC_GPIO8, FUNC_GPIO9, FUNC_GPIO10, FUNC_GPIO11,
  986. FUNC_GPIO12, FUNC_GPIO13, FUNC_GPIO14, FUNC_GPIO15
  987. };
  988. #endif
  989. void _lightConfigure() {
  990. _light_has_color = getSetting("useColor", LIGHT_USE_COLOR).toInt() == 1;
  991. if (_light_has_color && (_light_channel.size() < 3)) {
  992. _light_has_color = false;
  993. setSetting("useColor", _light_has_color);
  994. }
  995. _light_use_white = getSetting("useWhite", LIGHT_USE_WHITE).toInt() == 1;
  996. if (_light_use_white && (_light_channel.size() < 4) && (_light_channel.size() != 2)) {
  997. _light_use_white = false;
  998. setSetting("useWhite", _light_use_white);
  999. }
  1000. if (_light_has_color) {
  1001. if (_light_use_white) {
  1002. _light_brightness_func = _lightApplyBrightnessColor;
  1003. } else {
  1004. _light_brightness_func = []() { _lightApplyBrightness(3); };
  1005. }
  1006. } else {
  1007. _light_brightness_func = []() { _lightApplyBrightness(); };
  1008. }
  1009. _light_use_cct = getSetting("useCCT", LIGHT_USE_CCT).toInt() == 1;
  1010. if (_light_use_cct && (((_light_channel.size() < 5) && (_light_channel.size() != 2)) || !_light_use_white)) {
  1011. _light_use_cct = false;
  1012. setSetting("useCCT", _light_use_cct);
  1013. }
  1014. _light_use_gamma = getSetting("useGamma", LIGHT_USE_GAMMA).toInt() == 1;
  1015. _light_use_transitions = getSetting("useTransitions", LIGHT_USE_TRANSITIONS).toInt() == 1;
  1016. _light_transition_time = getSetting("lightTime", LIGHT_TRANSITION_TIME).toInt();
  1017. }
  1018. void lightSetup() {
  1019. #ifdef LIGHT_ENABLE_PIN
  1020. pinMode(LIGHT_ENABLE_PIN, OUTPUT);
  1021. digitalWrite(LIGHT_ENABLE_PIN, HIGH);
  1022. #endif
  1023. _light_channel.reserve(LIGHT_CHANNELS);
  1024. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  1025. _my92xx = new my92xx(MY92XX_MODEL, MY92XX_CHIPS, MY92XX_DI_PIN, MY92XX_DCKI_PIN, MY92XX_COMMAND);
  1026. for (unsigned char i=0; i<LIGHT_CHANNELS; i++) {
  1027. _light_channel.push_back((channel_t) {0, false, true, 0, 0, 0});
  1028. }
  1029. #endif
  1030. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  1031. #ifdef LIGHT_CH1_PIN
  1032. _light_channel.push_back((channel_t) {LIGHT_CH1_PIN, LIGHT_CH1_INVERSE, true, 0, 0, 0});
  1033. #endif
  1034. #ifdef LIGHT_CH2_PIN
  1035. _light_channel.push_back((channel_t) {LIGHT_CH2_PIN, LIGHT_CH2_INVERSE, true, 0, 0, 0});
  1036. #endif
  1037. #ifdef LIGHT_CH3_PIN
  1038. _light_channel.push_back((channel_t) {LIGHT_CH3_PIN, LIGHT_CH3_INVERSE, true, 0, 0, 0});
  1039. #endif
  1040. #ifdef LIGHT_CH4_PIN
  1041. _light_channel.push_back((channel_t) {LIGHT_CH4_PIN, LIGHT_CH4_INVERSE, true, 0, 0, 0});
  1042. #endif
  1043. #ifdef LIGHT_CH5_PIN
  1044. _light_channel.push_back((channel_t) {LIGHT_CH5_PIN, LIGHT_CH5_INVERSE, true, 0, 0, 0});
  1045. #endif
  1046. uint32 pwm_duty_init[PWM_CHANNEL_NUM_MAX];
  1047. uint32 io_info[PWM_CHANNEL_NUM_MAX][3];
  1048. for (unsigned int i=0; i < _light_channel.size(); i++) {
  1049. const auto pin = _light_channel.at(i).pin;
  1050. pwm_duty_init[i] = 0;
  1051. io_info[i][0] = pgm_read_dword(&_light_iomux[pin]);
  1052. io_info[i][1] = pgm_read_dword(&_light_iofunc[pin]);
  1053. io_info[i][2] = pin;
  1054. pinMode(pin, OUTPUT);
  1055. }
  1056. pwm_init(LIGHT_MAX_PWM, pwm_duty_init, PWM_CHANNEL_NUM_MAX, io_info);
  1057. pwm_start();
  1058. #endif
  1059. DEBUG_MSG_P(PSTR("[LIGHT] LIGHT_PROVIDER = %d\n"), LIGHT_PROVIDER);
  1060. DEBUG_MSG_P(PSTR("[LIGHT] Number of channels: %d\n"), _light_channel.size());
  1061. _lightConfigure();
  1062. if (rtcmemStatus()) {
  1063. _lightRestoreRtcmem();
  1064. } else {
  1065. _lightRestoreSettings();
  1066. }
  1067. lightUpdate(false, false);
  1068. #if WEB_SUPPORT
  1069. wsRegister()
  1070. .onVisible(_lightWebSocketOnVisible)
  1071. .onConnected(_lightWebSocketOnConnected)
  1072. .onAction(_lightWebSocketOnAction)
  1073. .onKeyCheck(_lightWebSocketOnKeyCheck);
  1074. #endif
  1075. #if API_SUPPORT
  1076. _lightAPISetup();
  1077. #endif
  1078. #if MQTT_SUPPORT
  1079. mqttRegister(_lightMQTTCallback);
  1080. #endif
  1081. #if TERMINAL_SUPPORT
  1082. _lightInitCommands();
  1083. #endif
  1084. // Main callbacks
  1085. espurnaRegisterReload([]() {
  1086. #if LIGHT_SAVE_ENABLED == 0
  1087. lightSave();
  1088. #endif
  1089. _lightConfigure();
  1090. });
  1091. }
  1092. #endif // LIGHT_PROVIDER != LIGHT_PROVIDER_NONE