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.

1340 lines
40 KiB

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