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.

1376 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(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 FPSTR(pstr_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 FPSTR(pstr_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. String _toCSV(bool target) {
  369. const auto channels = lightChannels();
  370. String result;
  371. result.reserve(4 * channels);
  372. for (auto& channel : _light_channel) {
  373. if (result.length()) result += ',';
  374. result += String(target ? channel.target : channel.inputValue);
  375. }
  376. return result;
  377. }
  378. // See cores/esp8266/WMath.cpp::map
  379. // Redefining as local method here to avoid breaking in unexpected ways in inputs like (0, 0, 0, 0, 1)
  380. template <typename T, typename Tin, typename Tout> T _lightMap(T x, Tin in_min, Tin in_max, Tout out_min, Tout out_max) {
  381. auto divisor = (in_max - in_min);
  382. if (divisor == 0){
  383. return -1; //AVR returns -1, SAM returns 0
  384. }
  385. return (x - in_min) * (out_max - out_min) / divisor + out_min;
  386. }
  387. int _lightAdjustValue(const int& value, const String& operation) {
  388. if (!operation.length()) return value;
  389. // if prefixed with a sign, treat expression as numerical operation
  390. // otherwise, use as the new value
  391. int updated = operation.toInt();
  392. if (operation[0] == '+' || operation[0] == '-') {
  393. updated = value + updated;
  394. }
  395. return updated;
  396. }
  397. void _lightAdjustBrightness(const char *payload) {
  398. lightBrightness(_lightAdjustValue(lightBrightness(), payload));
  399. }
  400. void _lightAdjustChannel(unsigned char id, const char *payload) {
  401. lightChannel(id, _lightAdjustValue(lightChannel(id), payload));
  402. }
  403. void _lightAdjustKelvin(const char *payload) {
  404. _fromKelvin(_lightAdjustValue(_toKelvin(_light_mireds), payload));
  405. }
  406. void _lightAdjustMireds(const char *payload) {
  407. _fromMireds(_lightAdjustValue(_light_mireds, payload));
  408. }
  409. // -----------------------------------------------------------------------------
  410. // PROVIDER
  411. // -----------------------------------------------------------------------------
  412. unsigned int _toPWM(unsigned int value, bool gamma, bool reverse) {
  413. value = constrain(value, Light::VALUE_MIN, Light::VALUE_MAX);
  414. if (gamma) value = pgm_read_byte(_light_gamma_table + value);
  415. if (Light::VALUE_MAX != Light::PWM_LIMIT) value = _lightMap(value, Light::VALUE_MIN, Light::VALUE_MAX, Light::PWM_MIN, Light::PWM_LIMIT);
  416. if (reverse) value = LIGHT_LIMIT_PWM - value;
  417. return value;
  418. }
  419. // Returns a PWM value for the given channel ID
  420. unsigned int _toPWM(unsigned char id) {
  421. bool useGamma = _light_use_gamma && _light_has_color && (id < 3);
  422. return _toPWM(_light_channel[id].current, useGamma, _light_channel[id].reverse);
  423. }
  424. void _lightTransition(unsigned long step) {
  425. // Transitions based on current step. If step == 0, then it is the last transition
  426. for (auto& channel : _light_channel) {
  427. if (!step) {
  428. channel.current = channel.target;
  429. } else {
  430. channel.current += (double) (channel.target - channel.current) / (step + 1);
  431. }
  432. }
  433. }
  434. void _lightProviderUpdate(unsigned long steps) {
  435. if (_light_provider_update) return;
  436. _light_provider_update = true;
  437. _lightTransition(--steps);
  438. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  439. for (unsigned char i=0; i<_light_channel.size(); i++) {
  440. _my92xx->setChannel(_light_channel_map[i], _toPWM(i));
  441. }
  442. _my92xx->setState(true);
  443. _my92xx->update();
  444. #endif
  445. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  446. for (unsigned int i=0; i < _light_channel.size(); i++) {
  447. pwm_set_duty(_toPWM(i), i);
  448. }
  449. pwm_start();
  450. #endif
  451. // This is not the final value, update again
  452. if (steps) _light_transition_ticker.once_ms(LIGHT_TRANSITION_STEP, _lightProviderScheduleUpdate, steps);
  453. _light_provider_update = false;
  454. }
  455. void _lightProviderScheduleUpdate(unsigned long steps) {
  456. schedule_function(std::bind(_lightProviderUpdate, steps));
  457. }
  458. // -----------------------------------------------------------------------------
  459. // PERSISTANCE
  460. // -----------------------------------------------------------------------------
  461. union light_rtcmem_t {
  462. struct {
  463. uint8_t channels[5];
  464. uint8_t brightness;
  465. uint16_t mired;
  466. } packed;
  467. uint64_t value;
  468. };
  469. #define LIGHT_RTCMEM_CHANNELS_MAX sizeof(light_rtcmem_t().packed.channels)
  470. void _lightSaveRtcmem() {
  471. if (lightChannels() > LIGHT_RTCMEM_CHANNELS_MAX) return;
  472. light_rtcmem_t light;
  473. for (unsigned int i=0; i < lightChannels(); i++) {
  474. light.packed.channels[i] = _light_channel[i].inputValue;
  475. }
  476. light.packed.brightness = _light_brightness;
  477. light.packed.mired = _light_mireds;
  478. Rtcmem->light = light.value;
  479. }
  480. void _lightRestoreRtcmem() {
  481. if (lightChannels() > LIGHT_RTCMEM_CHANNELS_MAX) return;
  482. light_rtcmem_t light;
  483. light.value = Rtcmem->light;
  484. for (unsigned int i=0; i < lightChannels(); i++) {
  485. _light_channel[i].inputValue = light.packed.channels[i];
  486. }
  487. _light_brightness = light.packed.brightness;
  488. _light_mireds = light.packed.mired;
  489. }
  490. void _lightSaveSettings() {
  491. for (unsigned int i=0; i < _light_channel.size(); i++) {
  492. setSetting("ch", i, _light_channel[i].inputValue);
  493. }
  494. setSetting("brightness", _light_brightness);
  495. setSetting("mireds", _light_mireds);
  496. saveSettings();
  497. }
  498. void _lightRestoreSettings() {
  499. for (unsigned int i=0; i < _light_channel.size(); i++) {
  500. _light_channel[i].inputValue = getSetting("ch", i, (i == 0) ? Light::VALUE_MAX : 0).toInt();
  501. }
  502. _light_brightness = getSetting("brightness", Light::BRIGHTNESS_MAX).toInt();
  503. _light_mireds = getSetting("mireds", _light_mireds).toInt();
  504. }
  505. // -----------------------------------------------------------------------------
  506. // MQTT
  507. // -----------------------------------------------------------------------------
  508. #if MQTT_SUPPORT
  509. void _lightMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  510. String mqtt_group_color = getSetting("mqttGroupColor");
  511. if (type == MQTT_CONNECT_EVENT) {
  512. mqttSubscribe(MQTT_TOPIC_BRIGHTNESS);
  513. if (_light_has_color) {
  514. mqttSubscribe(MQTT_TOPIC_COLOR_RGB);
  515. mqttSubscribe(MQTT_TOPIC_COLOR_HSV);
  516. mqttSubscribe(MQTT_TOPIC_TRANSITION);
  517. }
  518. if (_light_has_color || _light_use_cct) {
  519. mqttSubscribe(MQTT_TOPIC_MIRED);
  520. mqttSubscribe(MQTT_TOPIC_KELVIN);
  521. }
  522. // Group color
  523. if (mqtt_group_color.length() > 0) mqttSubscribeRaw(mqtt_group_color.c_str());
  524. // Channels
  525. char buffer[strlen(MQTT_TOPIC_CHANNEL) + 3];
  526. snprintf_P(buffer, sizeof(buffer), PSTR("%s/+"), MQTT_TOPIC_CHANNEL);
  527. mqttSubscribe(buffer);
  528. }
  529. if (type == MQTT_MESSAGE_EVENT) {
  530. // Group color
  531. if ((mqtt_group_color.length() > 0) && (mqtt_group_color.equals(topic))) {
  532. lightColor(payload, true);
  533. lightUpdate(true, mqttForward(), false);
  534. return;
  535. }
  536. // Match topic
  537. String t = mqttMagnitude((char *) topic);
  538. // Color temperature in mireds
  539. if (t.equals(MQTT_TOPIC_MIRED)) {
  540. _lightAdjustMireds(payload);
  541. lightUpdate(true, mqttForward());
  542. return;
  543. }
  544. // Color temperature in kelvins
  545. if (t.equals(MQTT_TOPIC_KELVIN)) {
  546. _lightAdjustKelvin(payload);
  547. lightUpdate(true, mqttForward());
  548. return;
  549. }
  550. // Color
  551. if (t.equals(MQTT_TOPIC_COLOR_RGB)) {
  552. lightColor(payload, true);
  553. lightUpdate(true, mqttForward());
  554. return;
  555. }
  556. if (t.equals(MQTT_TOPIC_COLOR_HSV)) {
  557. lightColor(payload, false);
  558. lightUpdate(true, mqttForward());
  559. return;
  560. }
  561. // Brightness
  562. if (t.equals(MQTT_TOPIC_BRIGHTNESS)) {
  563. _lightAdjustBrightness(payload);
  564. lightUpdate(true, mqttForward());
  565. return;
  566. }
  567. // Transitions
  568. if (t.equals(MQTT_TOPIC_TRANSITION)) {
  569. lightTransitionTime(atol(payload));
  570. return;
  571. }
  572. // Channel
  573. if (t.startsWith(MQTT_TOPIC_CHANNEL)) {
  574. unsigned int channelID = t.substring(strlen(MQTT_TOPIC_CHANNEL)+1).toInt();
  575. if (channelID >= _light_channel.size()) {
  576. DEBUG_MSG_P(PSTR("[LIGHT] Wrong channelID (%d)\n"), channelID);
  577. return;
  578. }
  579. _lightAdjustChannel(channelID, payload);
  580. lightUpdate(true, mqttForward());
  581. return;
  582. }
  583. }
  584. }
  585. void lightMQTT() {
  586. char buffer[20];
  587. if (_light_has_color) {
  588. // Color
  589. if (getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1) {
  590. _toRGB(buffer, sizeof(buffer), true);
  591. } else {
  592. _toLong(buffer, sizeof(buffer), true);
  593. }
  594. mqttSend(MQTT_TOPIC_COLOR_RGB, buffer);
  595. _toHSV(buffer, sizeof(buffer));
  596. mqttSend(MQTT_TOPIC_COLOR_HSV, buffer);
  597. }
  598. if (_light_has_color || _light_use_cct) {
  599. // Mireds
  600. snprintf_P(buffer, sizeof(buffer), PSTR("%d"), _light_mireds);
  601. mqttSend(MQTT_TOPIC_MIRED, buffer);
  602. }
  603. // Channels
  604. for (unsigned int i=0; i < _light_channel.size(); i++) {
  605. itoa(_light_channel[i].target, buffer, 10);
  606. mqttSend(MQTT_TOPIC_CHANNEL, i, buffer);
  607. }
  608. // Brightness
  609. snprintf_P(buffer, sizeof(buffer), PSTR("%d"), _light_brightness);
  610. mqttSend(MQTT_TOPIC_BRIGHTNESS, buffer);
  611. }
  612. void lightMQTTGroup() {
  613. const String mqtt_group_color = getSetting("mqttGroupColor");
  614. if (mqtt_group_color.length()) {
  615. mqttSendRaw(mqtt_group_color.c_str(), _toCSV(false).c_str());
  616. }
  617. }
  618. #endif
  619. // -----------------------------------------------------------------------------
  620. // Broker
  621. // -----------------------------------------------------------------------------
  622. #if BROKER_SUPPORT
  623. void lightBroker() {
  624. char buffer[10];
  625. for (unsigned int i=0; i < _light_channel.size(); i++) {
  626. itoa(_light_channel[i].inputValue, buffer, 10);
  627. brokerPublish(BROKER_MSG_TYPE_STATUS, MQTT_TOPIC_CHANNEL, i, buffer);
  628. }
  629. }
  630. #endif
  631. // -----------------------------------------------------------------------------
  632. // API
  633. // -----------------------------------------------------------------------------
  634. size_t lightChannels() {
  635. return _light_channel.size();
  636. }
  637. bool lightHasColor() {
  638. return _light_has_color;
  639. }
  640. bool lightUseCCT() {
  641. return _light_use_cct;
  642. }
  643. void _lightComms(const unsigned char mask) {
  644. // Report color and brightness to MQTT broker
  645. #if MQTT_SUPPORT
  646. if (mask & Light::COMMS_NORMAL) lightMQTT();
  647. if (mask & Light::COMMS_GROUP) lightMQTTGroup();
  648. #endif
  649. // Report color to WS clients (using current brightness setting)
  650. #if WEB_SUPPORT
  651. wsPost(_lightWebSocketStatus);
  652. #endif
  653. // Report channels to local broker
  654. #if BROKER_SUPPORT
  655. lightBroker();
  656. #endif
  657. }
  658. void lightUpdate(bool save, bool forward, bool group_forward) {
  659. // Calculate values based on inputs and brightness
  660. _light_brightness_func();
  661. // Only update if a channel has changed
  662. if (!_light_dirty) return;
  663. _light_dirty = false;
  664. // Update channels
  665. for (unsigned int i=0; i < _light_channel.size(); i++) {
  666. _light_channel[i].target = _light_state && _light_channel[i].state ? _light_channel[i].value : 0;
  667. //DEBUG_MSG_P("[LIGHT] Channel #%u target value: %u\n", i, _light_channel[i].target);
  668. }
  669. // Channel transition will be handled by the provider function
  670. // User can configure total transition time, step time is a fixed value
  671. const unsigned long steps = _light_use_transitions ? _light_transition_time / LIGHT_TRANSITION_STEP : 1;
  672. _light_transition_ticker.once_ms(LIGHT_TRANSITION_STEP, _lightProviderScheduleUpdate, steps);
  673. // Delay every communication 100ms to avoid jamming
  674. const unsigned char mask =
  675. ((forward) ? Light::COMMS_NORMAL : Light::COMMS_NONE) |
  676. ((group_forward) ? Light::COMMS_GROUP : Light::COMMS_NONE);
  677. _light_comms_ticker.once_ms(LIGHT_COMMS_DELAY, _lightComms, mask);
  678. _lightSaveRtcmem();
  679. #if LIGHT_SAVE_ENABLED
  680. // Delay saving to EEPROM 5 seconds to avoid wearing it out unnecessarily
  681. if (save) _light_save_ticker.once(LIGHT_SAVE_DELAY, _lightSaveSettings);
  682. #endif
  683. };
  684. void lightUpdate(bool save, bool forward) {
  685. lightUpdate(save, forward, true);
  686. }
  687. #if LIGHT_SAVE_ENABLED == 0
  688. void lightSave() {
  689. _lightSaveSettings();
  690. }
  691. #endif
  692. void lightState(unsigned char i, bool state) {
  693. if (_light_channel[i].state != state) {
  694. _light_channel[i].state = state;
  695. _light_dirty = true;
  696. }
  697. }
  698. bool lightState(unsigned char i) {
  699. return _light_channel[i].state;
  700. }
  701. void lightState(bool state) {
  702. if (_light_state != state) {
  703. _light_state = state;
  704. _light_dirty = true;
  705. }
  706. }
  707. bool lightState() {
  708. return _light_state;
  709. }
  710. void lightColor(const char * color, bool rgb) {
  711. DEBUG_MSG_P(PSTR("[LIGHT] %s: %s\n"), rgb ? "RGB" : "HSV", color);
  712. if (rgb) {
  713. _fromRGB(color);
  714. } else {
  715. _fromHSV(color);
  716. }
  717. }
  718. void lightColor(const char * color) {
  719. lightColor(color, true);
  720. }
  721. void lightColor(unsigned long color) {
  722. _fromLong(color, false);
  723. }
  724. String lightColor(bool rgb) {
  725. char str[12];
  726. if (rgb) {
  727. _toRGB(str, sizeof(str));
  728. } else {
  729. _toHSV(str, sizeof(str));
  730. }
  731. return String(str);
  732. }
  733. String lightColor() {
  734. return lightColor(true);
  735. }
  736. long lightChannel(unsigned char id) {
  737. if (id <= _light_channel.size()) {
  738. return _light_channel[id].inputValue;
  739. }
  740. return 0;
  741. }
  742. void lightChannel(unsigned char id, long value) {
  743. if (id > _light_channel.size()) return;
  744. _setInputValue(id, constrain(value, Light::VALUE_MIN, Light::VALUE_MAX));
  745. }
  746. void lightChannelStep(unsigned char id, long steps, long multiplier) {
  747. lightChannel(id, static_cast<int>(lightChannel(id)) + (steps * multiplier));
  748. }
  749. long lightBrightness() {
  750. return _light_brightness;
  751. }
  752. void lightBrightness(long brightness) {
  753. _light_brightness = constrain(brightness, Light::BRIGHTNESS_MIN, Light::BRIGHTNESS_MAX);
  754. }
  755. void lightBrightnessStep(long steps, long multiplier) {
  756. lightBrightness(static_cast<int>(_light_brightness) + (steps * multiplier));
  757. }
  758. unsigned int lightTransitionTime() {
  759. if (_light_use_transitions) {
  760. return _light_transition_time;
  761. } else {
  762. return 0;
  763. }
  764. }
  765. void lightTransitionTime(unsigned long m) {
  766. if (0 == m) {
  767. _light_use_transitions = false;
  768. } else {
  769. _light_use_transitions = true;
  770. _light_transition_time = m;
  771. }
  772. setSetting("useTransitions", _light_use_transitions);
  773. setSetting("lightTime", _light_transition_time);
  774. saveSettings();
  775. }
  776. // -----------------------------------------------------------------------------
  777. // SETUP
  778. // -----------------------------------------------------------------------------
  779. #if WEB_SUPPORT
  780. bool _lightWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  781. if (strncmp(key, "light", 5) == 0) return true;
  782. if (strncmp(key, "use", 3) == 0) return true;
  783. return false;
  784. }
  785. void _lightWebSocketStatus(JsonObject& root) {
  786. if (_light_has_color) {
  787. if (getSetting("useRGB", LIGHT_USE_RGB).toInt() == 1) {
  788. root["rgb"] = lightColor(true);
  789. } else {
  790. root["hsv"] = lightColor(false);
  791. }
  792. }
  793. if (_light_use_cct) {
  794. root["useCCT"] = _light_use_cct;
  795. root["mireds"] = _light_mireds;
  796. }
  797. JsonArray& channels = root.createNestedArray("channels");
  798. for (unsigned char id=0; id < _light_channel.size(); id++) {
  799. channels.add(lightChannel(id));
  800. }
  801. root["brightness"] = lightBrightness();
  802. }
  803. void _lightWebSocketOnVisible(JsonObject& root) {
  804. root["colorVisible"] = 1;
  805. }
  806. void _lightWebSocketOnConnected(JsonObject& root) {
  807. root["mqttGroupColor"] = getSetting("mqttGroupColor");
  808. root["useColor"] = _light_has_color;
  809. root["useWhite"] = _light_use_white;
  810. root["useGamma"] = _light_use_gamma;
  811. root["useTransitions"] = _light_use_transitions;
  812. root["useCSS"] = getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1;
  813. root["useRGB"] = getSetting("useRGB", LIGHT_USE_RGB).toInt() == 1;
  814. root["lightTime"] = _light_transition_time;
  815. _lightWebSocketStatus(root);
  816. }
  817. void _lightWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  818. if (_light_has_color) {
  819. if (strcmp(action, "color") == 0) {
  820. if (data.containsKey("rgb")) {
  821. lightColor(data["rgb"], true);
  822. lightUpdate(true, true);
  823. }
  824. if (data.containsKey("hsv")) {
  825. lightColor(data["hsv"], false);
  826. lightUpdate(true, true);
  827. }
  828. }
  829. }
  830. if (_light_use_cct) {
  831. if (strcmp(action, "mireds") == 0) {
  832. _fromMireds(data["mireds"]);
  833. lightUpdate(true, true);
  834. }
  835. }
  836. if (strcmp(action, "channel") == 0) {
  837. if (data.containsKey("id") && data.containsKey("value")) {
  838. lightChannel(data["id"].as<unsigned char>(), data["value"].as<int>());
  839. lightUpdate(true, true);
  840. }
  841. }
  842. if (strcmp(action, "brightness") == 0) {
  843. if (data.containsKey("value")) {
  844. lightBrightness(data["value"].as<int>());
  845. lightUpdate(true, true);
  846. }
  847. }
  848. }
  849. #endif
  850. #if API_SUPPORT
  851. void _lightAPISetup() {
  852. if (_light_has_color) {
  853. apiRegister(MQTT_TOPIC_COLOR_RGB,
  854. [](char * buffer, size_t len) {
  855. if (getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1) {
  856. _toRGB(buffer, len, true);
  857. } else {
  858. _toLong(buffer, len, true);
  859. }
  860. },
  861. [](const char * payload) {
  862. lightColor(payload, true);
  863. lightUpdate(true, true);
  864. }
  865. );
  866. apiRegister(MQTT_TOPIC_COLOR_HSV,
  867. [](char * buffer, size_t len) {
  868. _toHSV(buffer, len);
  869. },
  870. [](const char * payload) {
  871. lightColor(payload, false);
  872. lightUpdate(true, true);
  873. }
  874. );
  875. apiRegister(MQTT_TOPIC_KELVIN,
  876. [](char * buffer, size_t len) {},
  877. [](const char * payload) {
  878. _lightAdjustKelvin(payload);
  879. lightUpdate(true, true);
  880. }
  881. );
  882. apiRegister(MQTT_TOPIC_MIRED,
  883. [](char * buffer, size_t len) {},
  884. [](const char * payload) {
  885. _lightAdjustMireds(payload);
  886. lightUpdate(true, true);
  887. }
  888. );
  889. }
  890. for (unsigned int id=0; id<_light_channel.size(); id++) {
  891. char key[15];
  892. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_CHANNEL, id);
  893. apiRegister(key,
  894. [id](char * buffer, size_t len) {
  895. snprintf_P(buffer, len, PSTR("%d"), _light_channel[id].target);
  896. },
  897. [id](const char * payload) {
  898. _lightAdjustChannel(id, payload);
  899. lightUpdate(true, true);
  900. }
  901. );
  902. }
  903. apiRegister(MQTT_TOPIC_TRANSITION,
  904. [](char * buffer, size_t len) {
  905. snprintf_P(buffer, len, PSTR("%d"), lightTransitionTime());
  906. },
  907. [](const char * payload) {
  908. lightTransitionTime(atol(payload));
  909. }
  910. );
  911. apiRegister(MQTT_TOPIC_BRIGHTNESS,
  912. [](char * buffer, size_t len) {
  913. snprintf_P(buffer, len, PSTR("%d"), _light_brightness);
  914. },
  915. [](const char * payload) {
  916. _lightAdjustBrightness(payload);
  917. lightUpdate(true, true);
  918. }
  919. );
  920. }
  921. #endif // API_SUPPORT
  922. #if TERMINAL_SUPPORT
  923. void _lightInitCommands() {
  924. terminalRegisterCommand(F("BRIGHTNESS"), [](Embedis* e) {
  925. if (e->argc > 1) {
  926. _lightAdjustBrightness(e->argv[1]);
  927. lightUpdate(true, true);
  928. }
  929. DEBUG_MSG_P(PSTR("Brightness: %u\n"), lightBrightness());
  930. terminalOK();
  931. });
  932. terminalRegisterCommand(F("CHANNEL"), [](Embedis* e) {
  933. if (e->argc < 2) {
  934. terminalError(F("CHANNEL <ID> [<VALUE>]"));
  935. return;
  936. }
  937. const int id = String(e->argv[1]).toInt();
  938. if (id < 0 || id >= lightChannels()) {
  939. terminalError(F("Channel value out of range"));
  940. return;
  941. }
  942. if (e->argc > 2) {
  943. _lightAdjustChannel(id, e->argv[2]);
  944. lightUpdate(true, true);
  945. }
  946. DEBUG_MSG_P(PSTR("Channel #%u (%s): %d\n"), id, lightDesc(id).c_str(), lightChannel(id));
  947. terminalOK();
  948. });
  949. terminalRegisterCommand(F("COLOR"), [](Embedis* e) {
  950. if (e->argc > 1) {
  951. lightColor(e->argv[1]);
  952. lightUpdate(true, true);
  953. }
  954. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  955. terminalOK();
  956. });
  957. terminalRegisterCommand(F("KELVIN"), [](Embedis* e) {
  958. if (e->argc > 1) {
  959. _lightAdjustKelvin(e->argv[1]);
  960. lightUpdate(true, true);
  961. }
  962. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  963. terminalOK();
  964. });
  965. terminalRegisterCommand(F("MIRED"), [](Embedis* e) {
  966. if (e->argc > 1) {
  967. _lightAdjustMireds(e->argv[1]);
  968. lightUpdate(true, true);
  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