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.

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