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.

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