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.

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