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.

1338 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 <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] * (static_cast<double>(Light::BRIGHTNESS_MAX) / 100.0)); // (255/100)
  231. unsigned char p = lround(Light::VALUE_MAX * (1.0 - s));
  232. unsigned char q = lround(Light::VALUE_MAX * (1.0 - s * f));
  233. 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. 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) {
  312. double h {0.}, s {0.}, v {0.};
  313. double r {0.}, g {0.}, b {0.};
  314. double min {0.}, max {0.};
  315. r = static_cast<double>(_light_channel[0].target) / Light::VALUE_MAX;
  316. g = static_cast<double>(_light_channel[1].target) / Light::VALUE_MAX;
  317. b = static_cast<double>(_light_channel[2].target) / Light::VALUE_MAX;
  318. min = std::min(r, std::min(g, b));
  319. 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. // Convert to string. Using lround, since we can't (yet) printf floats
  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 _toLong(char * color, size_t len, bool target) {
  349. if (!_light_has_color) return;
  350. snprintf_P(color, len, PSTR("%u,%u,%u"),
  351. (target ? _light_channel[0].target : _light_channel[0].inputValue),
  352. (target ? _light_channel[1].target : _light_channel[1].inputValue),
  353. (target ? _light_channel[2].target : _light_channel[2].inputValue)
  354. );
  355. }
  356. void _toLong(char * color, size_t len) {
  357. _toLong(color, len, false);
  358. }
  359. void _toCSV(char * buffer, size_t len, bool applyBrightness, bool target) {
  360. char num[10];
  361. float b = applyBrightness ? (float) _light_brightness / Light::BRIGHTNESS_MAX : 1;
  362. for (unsigned char i=0; i<_light_channel.size(); i++) {
  363. itoa((target ? _light_channel[i].target : _light_channel[i].inputValue) * b, num, 10);
  364. if (i>0) strncat(buffer, ",", len--);
  365. strncat(buffer, num, len);
  366. len = len - strlen(num);
  367. }
  368. }
  369. void _toCSV(char * buffer, size_t len, bool applyBrightness) {
  370. _toCSV(buffer, len, applyBrightness, false);
  371. }
  372. // See cores/esp8266/WMath.cpp::map
  373. // Redefining as local method here to avoid breaking in unexpected ways in inputs like (0, 0, 0, 0, 1)
  374. template <typename T, typename T2> T _lightMap(T x, T in_min, T in_max, T2 out_min, T2 out_max) {
  375. T divisor = (in_max - in_min);
  376. if (divisor == 0){
  377. return -1; //AVR returns -1, SAM returns 0
  378. }
  379. return (x - in_min) * (out_max - out_min) / divisor + out_min;
  380. }
  381. // -----------------------------------------------------------------------------
  382. // PROVIDER
  383. // -----------------------------------------------------------------------------
  384. unsigned int _toPWM(unsigned char value, bool gamma, bool reverse) {
  385. value = constrain(value, Light::VALUE_MIN, Light::VALUE_MAX);
  386. if (gamma) value = pgm_read_byte(_light_gamma_table + value);
  387. if (Light::VALUE_MAX != Light::PWM_LIMIT) value = _lightMap(value, Light::VALUE_MIN, Light::VALUE_MAX, Light::PWM_MIN, Light::PWM_LIMIT);
  388. if (reverse) value = LIGHT_LIMIT_PWM - value;
  389. return value;
  390. }
  391. // Returns a PWM value for the given channel ID
  392. unsigned int _toPWM(unsigned char id) {
  393. bool useGamma = _light_use_gamma && _light_has_color && (id < 3);
  394. return _toPWM(_light_channel[id].current, useGamma, _light_channel[id].reverse);
  395. }
  396. void _transition() {
  397. // Update transition ticker
  398. _light_steps_left--;
  399. if (_light_steps_left == 0) _light_transition_ticker.detach();
  400. // Transitions
  401. for (unsigned int i=0; i < _light_channel.size(); i++) {
  402. if (_light_steps_left == 0) {
  403. _light_channel[i].current = _light_channel[i].target;
  404. } else {
  405. double difference = (double) (_light_channel[i].target - _light_channel[i].current) / (_light_steps_left + 1);
  406. _light_channel[i].current = _light_channel[i].current + difference;
  407. }
  408. }
  409. }
  410. void _lightProviderUpdate() {
  411. _transition();
  412. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  413. for (unsigned char i=0; i<_light_channel.size(); i++) {
  414. _my92xx->setChannel(_light_channel_map[i], _toPWM(i));
  415. }
  416. _my92xx->setState(true);
  417. _my92xx->update();
  418. #endif
  419. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  420. for (unsigned int i=0; i < _light_channel.size(); i++) {
  421. pwm_set_duty(_toPWM(i), i);
  422. }
  423. pwm_start();
  424. #endif
  425. }
  426. // -----------------------------------------------------------------------------
  427. // PERSISTANCE
  428. // -----------------------------------------------------------------------------
  429. union light_rtcmem_t {
  430. struct {
  431. uint8_t channels[5];
  432. uint8_t brightness;
  433. uint16_t mired;
  434. } packed;
  435. uint64_t value;
  436. };
  437. #define LIGHT_RTCMEM_CHANNELS_MAX sizeof(light_rtcmem_t().packed.channels)
  438. void _lightSaveRtcmem() {
  439. if (lightChannels() > LIGHT_RTCMEM_CHANNELS_MAX) return;
  440. light_rtcmem_t light;
  441. for (unsigned int i=0; i < lightChannels(); i++) {
  442. light.packed.channels[i] = _light_channel[i].inputValue;
  443. }
  444. light.packed.brightness = _light_brightness;
  445. light.packed.mired = _light_mireds;
  446. Rtcmem->light = light.value;
  447. }
  448. void _lightRestoreRtcmem() {
  449. if (lightChannels() > LIGHT_RTCMEM_CHANNELS_MAX) return;
  450. light_rtcmem_t light;
  451. light.value = Rtcmem->light;
  452. for (unsigned int i=0; i < lightChannels(); i++) {
  453. _light_channel[i].inputValue = light.packed.channels[i];
  454. }
  455. _light_brightness = light.packed.brightness;
  456. _light_mireds = light.packed.mired;
  457. }
  458. void _lightSaveSettings() {
  459. for (unsigned int i=0; i < _light_channel.size(); i++) {
  460. setSetting("ch", i, _light_channel[i].inputValue);
  461. }
  462. setSetting("brightness", _light_brightness);
  463. setSetting("mireds", _light_mireds);
  464. saveSettings();
  465. }
  466. void _lightRestoreSettings() {
  467. for (unsigned int i=0; i < _light_channel.size(); i++) {
  468. _light_channel[i].inputValue = getSetting("ch", i, (i == 0) ? Light::VALUE_MAX : 0).toInt();
  469. }
  470. _light_brightness = getSetting("brightness", Light::BRIGHTNESS_MAX).toInt();
  471. _light_mireds = getSetting("mireds", _light_mireds).toInt();
  472. lightUpdate(false, false);
  473. }
  474. // -----------------------------------------------------------------------------
  475. // MQTT
  476. // -----------------------------------------------------------------------------
  477. #if MQTT_SUPPORT
  478. void _lightMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  479. String mqtt_group_color = getSetting("mqttGroupColor");
  480. if (type == MQTT_CONNECT_EVENT) {
  481. mqttSubscribe(MQTT_TOPIC_BRIGHTNESS);
  482. if (_light_has_color) {
  483. mqttSubscribe(MQTT_TOPIC_COLOR_RGB);
  484. mqttSubscribe(MQTT_TOPIC_COLOR_HSV);
  485. mqttSubscribe(MQTT_TOPIC_TRANSITION);
  486. }
  487. if (_light_has_color || _light_use_cct) {
  488. mqttSubscribe(MQTT_TOPIC_MIRED);
  489. mqttSubscribe(MQTT_TOPIC_KELVIN);
  490. }
  491. // Group color
  492. if (mqtt_group_color.length() > 0) mqttSubscribeRaw(mqtt_group_color.c_str());
  493. // Channels
  494. char buffer[strlen(MQTT_TOPIC_CHANNEL) + 3];
  495. snprintf_P(buffer, sizeof(buffer), PSTR("%s/+"), MQTT_TOPIC_CHANNEL);
  496. mqttSubscribe(buffer);
  497. }
  498. if (type == MQTT_MESSAGE_EVENT) {
  499. // Group color
  500. if ((mqtt_group_color.length() > 0) & (mqtt_group_color.equals(topic))) {
  501. lightColor(payload, true);
  502. lightUpdate(true, mqttForward(), false);
  503. return;
  504. }
  505. // Match topic
  506. String t = mqttMagnitude((char *) topic);
  507. // Color temperature in mireds
  508. if (t.equals(MQTT_TOPIC_MIRED)) {
  509. _fromMireds(atol(payload));
  510. lightUpdate(true, mqttForward());
  511. return;
  512. }
  513. // Color temperature in kelvins
  514. if (t.equals(MQTT_TOPIC_KELVIN)) {
  515. _fromKelvin(atol(payload));
  516. lightUpdate(true, mqttForward());
  517. return;
  518. }
  519. // Color
  520. if (t.equals(MQTT_TOPIC_COLOR_RGB)) {
  521. lightColor(payload, true);
  522. lightUpdate(true, mqttForward());
  523. return;
  524. }
  525. if (t.equals(MQTT_TOPIC_COLOR_HSV)) {
  526. lightColor(payload, false);
  527. lightUpdate(true, mqttForward());
  528. return;
  529. }
  530. // Brightness
  531. if (t.equals(MQTT_TOPIC_BRIGHTNESS)) {
  532. lightBrightness(atoi(payload));
  533. lightUpdate(true, mqttForward());
  534. return;
  535. }
  536. // Transitions
  537. if (t.equals(MQTT_TOPIC_TRANSITION)) {
  538. lightTransitionTime(atol(payload));
  539. return;
  540. }
  541. // Channel
  542. if (t.startsWith(MQTT_TOPIC_CHANNEL)) {
  543. unsigned int channelID = t.substring(strlen(MQTT_TOPIC_CHANNEL)+1).toInt();
  544. if (channelID >= _light_channel.size()) {
  545. DEBUG_MSG_P(PSTR("[LIGHT] Wrong channelID (%d)\n"), channelID);
  546. return;
  547. }
  548. lightChannel(channelID, atoi(payload));
  549. lightUpdate(true, mqttForward());
  550. return;
  551. }
  552. }
  553. }
  554. void lightMQTT() {
  555. char buffer[20];
  556. if (_light_has_color) {
  557. // Color
  558. if (getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1) {
  559. _toRGB(buffer, sizeof(buffer), true);
  560. } else {
  561. _toLong(buffer, sizeof(buffer), true);
  562. }
  563. mqttSend(MQTT_TOPIC_COLOR_RGB, buffer);
  564. _toHSV(buffer, sizeof(buffer));
  565. mqttSend(MQTT_TOPIC_COLOR_HSV, buffer);
  566. }
  567. if (_light_has_color || _light_use_cct) {
  568. // Mireds
  569. snprintf_P(buffer, sizeof(buffer), PSTR("%d"), _light_mireds);
  570. mqttSend(MQTT_TOPIC_MIRED, buffer);
  571. }
  572. // Channels
  573. for (unsigned int i=0; i < _light_channel.size(); i++) {
  574. itoa(_light_channel[i].target, buffer, 10);
  575. mqttSend(MQTT_TOPIC_CHANNEL, i, buffer);
  576. }
  577. // Brightness
  578. snprintf_P(buffer, sizeof(buffer), PSTR("%d"), _light_brightness);
  579. mqttSend(MQTT_TOPIC_BRIGHTNESS, buffer);
  580. }
  581. void lightMQTTGroup() {
  582. String mqtt_group_color = getSetting("mqttGroupColor");
  583. if (mqtt_group_color.length()>0) {
  584. char buffer[20];
  585. _toCSV(buffer, sizeof(buffer), true);
  586. mqttSendRaw(mqtt_group_color.c_str(), buffer);
  587. }
  588. }
  589. #endif
  590. // -----------------------------------------------------------------------------
  591. // Broker
  592. // -----------------------------------------------------------------------------
  593. #if BROKER_SUPPORT
  594. void lightBroker() {
  595. char buffer[10];
  596. for (unsigned int i=0; i < _light_channel.size(); i++) {
  597. itoa(_light_channel[i].inputValue, buffer, 10);
  598. brokerPublish(BROKER_MSG_TYPE_STATUS, MQTT_TOPIC_CHANNEL, i, buffer);
  599. }
  600. }
  601. #endif
  602. // -----------------------------------------------------------------------------
  603. // API
  604. // -----------------------------------------------------------------------------
  605. unsigned char lightChannels() {
  606. return _light_channel.size();
  607. }
  608. bool lightHasColor() {
  609. return _light_has_color;
  610. }
  611. bool lightUseCCT() {
  612. return _light_use_cct;
  613. }
  614. void _lightComms(unsigned char mask) {
  615. // Report color & brightness to MQTT broker
  616. #if MQTT_SUPPORT
  617. if (mask & 0x01) lightMQTT();
  618. if (mask & 0x02) lightMQTTGroup();
  619. #endif
  620. // Report color to WS clients (using current brightness setting)
  621. #if WEB_SUPPORT
  622. wsPost(_lightWebSocketStatus);
  623. #endif
  624. // Report channels to local broker
  625. #if BROKER_SUPPORT
  626. lightBroker();
  627. #endif
  628. }
  629. void lightUpdate(bool save, bool forward, bool group_forward) {
  630. _light_brightness_func();
  631. // Update channels
  632. for (unsigned int i=0; i < _light_channel.size(); i++) {
  633. _light_channel[i].target = _light_state && _light_channel[i].state ? _light_channel[i].value : 0;
  634. //DEBUG_MSG_P("[LIGHT] Channel #%u target value: %u\n", i, _light_channel[i].target);
  635. }
  636. // Configure color transition
  637. _light_steps_left = _light_use_transitions ? _light_transition_time / LIGHT_TRANSITION_STEP : 1;
  638. _light_transition_ticker.attach_ms(LIGHT_TRANSITION_STEP, _lightProviderUpdate);
  639. // Delay every communication 100ms to avoid jamming
  640. unsigned char mask = 0;
  641. if (forward) mask += 1;
  642. if (group_forward) mask += 2;
  643. _light_comms_ticker.once_ms(LIGHT_COMMS_DELAY, _lightComms, mask);
  644. _lightSaveRtcmem();
  645. #if LIGHT_SAVE_ENABLED
  646. // Delay saving to EEPROM 5 seconds to avoid wearing it out unnecessarily
  647. if (save) _light_save_ticker.once(LIGHT_SAVE_DELAY, _lightSaveSettings);
  648. #endif
  649. };
  650. void lightUpdate(bool save, bool forward) {
  651. lightUpdate(save, forward, true);
  652. }
  653. #if LIGHT_SAVE_ENABLED == 0
  654. void lightSave() {
  655. _lightSaveSettings();
  656. }
  657. #endif
  658. void lightState(unsigned char i, bool state) {
  659. _light_channel[i].state = state;
  660. }
  661. bool lightState(unsigned char i) {
  662. return _light_channel[i].state;
  663. }
  664. void lightState(bool state) {
  665. _light_state = state;
  666. }
  667. bool lightState() {
  668. return _light_state;
  669. }
  670. void lightColor(const char * color, bool rgb) {
  671. DEBUG_MSG_P(PSTR("[LIGHT] %s: %s\n"), rgb ? "RGB" : "HSV", color);
  672. if (rgb) {
  673. _fromRGB(color);
  674. } else {
  675. _fromHSV(color);
  676. }
  677. }
  678. void lightColor(const char * color) {
  679. lightColor(color, true);
  680. }
  681. void lightColor(unsigned long color) {
  682. _fromLong(color, false);
  683. }
  684. String lightColor(bool rgb) {
  685. char str[12];
  686. if (rgb) {
  687. _toRGB(str, sizeof(str));
  688. } else {
  689. _toHSV(str, sizeof(str));
  690. }
  691. return String(str);
  692. }
  693. String lightColor() {
  694. return lightColor(true);
  695. }
  696. unsigned int lightChannel(unsigned char id) {
  697. if (id <= _light_channel.size()) {
  698. return _light_channel[id].inputValue;
  699. }
  700. return 0;
  701. }
  702. void lightChannel(unsigned char id, unsigned char value) {
  703. if (id <= _light_channel.size()) {
  704. _light_channel[id].inputValue = constrain(value, Light::VALUE_MIN, Light::VALUE_MAX);
  705. }
  706. }
  707. void lightChannelStep(unsigned char id, int steps) {
  708. lightChannel(id, lightChannel(id) + steps * LIGHT_STEP);
  709. }
  710. unsigned int lightBrightness() {
  711. return _light_brightness;
  712. }
  713. void lightBrightness(unsigned int brightness) {
  714. _light_brightness = constrain(brightness, Light::BRIGHTNESS_MIN, Light::BRIGHTNESS_MAX);
  715. }
  716. void lightBrightnessStep(int steps) {
  717. lightBrightness(_light_brightness + steps * LIGHT_STEP);
  718. }
  719. unsigned int lightTransitionTime() {
  720. if (_light_use_transitions) {
  721. return _light_transition_time;
  722. } else {
  723. return 0;
  724. }
  725. }
  726. void lightTransitionTime(unsigned long m) {
  727. if (0 == m) {
  728. _light_use_transitions = false;
  729. } else {
  730. _light_use_transitions = true;
  731. _light_transition_time = m;
  732. }
  733. setSetting("useTransitions", _light_use_transitions);
  734. setSetting("lightTime", _light_transition_time);
  735. saveSettings();
  736. }
  737. // -----------------------------------------------------------------------------
  738. // SETUP
  739. // -----------------------------------------------------------------------------
  740. #if WEB_SUPPORT
  741. bool _lightWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  742. if (strncmp(key, "light", 5) == 0) return true;
  743. if (strncmp(key, "use", 3) == 0) return true;
  744. return false;
  745. }
  746. void _lightWebSocketStatus(JsonObject& root) {
  747. if (_light_has_color) {
  748. if (getSetting("useRGB", LIGHT_USE_RGB).toInt() == 1) {
  749. root["rgb"] = lightColor(true);
  750. } else {
  751. root["hsv"] = lightColor(false);
  752. }
  753. }
  754. if (_light_use_cct) {
  755. root["useCCT"] = _light_use_cct;
  756. root["mireds"] = _light_mireds;
  757. }
  758. JsonArray& channels = root.createNestedArray("channels");
  759. for (unsigned char id=0; id < _light_channel.size(); id++) {
  760. channels.add(lightChannel(id));
  761. }
  762. root["brightness"] = lightBrightness();
  763. }
  764. void _lightWebSocketOnVisible(JsonObject& root) {
  765. root["colorVisible"] = 1;
  766. }
  767. void _lightWebSocketOnConnected(JsonObject& root) {
  768. root["mqttGroupColor"] = getSetting("mqttGroupColor");
  769. root["useColor"] = _light_has_color;
  770. root["useWhite"] = _light_use_white;
  771. root["useGamma"] = _light_use_gamma;
  772. root["useTransitions"] = _light_use_transitions;
  773. root["useCSS"] = getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1;
  774. root["useRGB"] = getSetting("useRGB", LIGHT_USE_RGB).toInt() == 1;
  775. root["lightTime"] = _light_transition_time;
  776. _lightWebSocketStatus(root);
  777. }
  778. void _lightWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  779. if (_light_has_color) {
  780. if (strcmp(action, "color") == 0) {
  781. if (data.containsKey("rgb")) {
  782. lightColor(data["rgb"], true);
  783. lightUpdate(true, true);
  784. }
  785. if (data.containsKey("hsv")) {
  786. lightColor(data["hsv"], false);
  787. lightUpdate(true, true);
  788. }
  789. }
  790. }
  791. if (_light_use_cct) {
  792. if (strcmp(action, "mireds") == 0) {
  793. _fromMireds(data["mireds"]);
  794. lightUpdate(true, true);
  795. }
  796. }
  797. if (strcmp(action, "channel") == 0) {
  798. if (data.containsKey("id") && data.containsKey("value")) {
  799. lightChannel(data["id"], data["value"]);
  800. lightUpdate(true, true);
  801. }
  802. }
  803. if (strcmp(action, "brightness") == 0) {
  804. if (data.containsKey("value")) {
  805. lightBrightness(data["value"]);
  806. lightUpdate(true, true);
  807. }
  808. }
  809. }
  810. #endif
  811. #if API_SUPPORT
  812. void _lightAPISetup() {
  813. if (_light_has_color) {
  814. apiRegister(MQTT_TOPIC_COLOR_RGB,
  815. [](char * buffer, size_t len) {
  816. if (getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1) {
  817. _toRGB(buffer, len, true);
  818. } else {
  819. _toLong(buffer, len, true);
  820. }
  821. },
  822. [](const char * payload) {
  823. lightColor(payload, true);
  824. lightUpdate(true, true);
  825. }
  826. );
  827. apiRegister(MQTT_TOPIC_COLOR_HSV,
  828. [](char * buffer, size_t len) {
  829. _toHSV(buffer, len);
  830. },
  831. [](const char * payload) {
  832. lightColor(payload, false);
  833. lightUpdate(true, true);
  834. }
  835. );
  836. apiRegister(MQTT_TOPIC_KELVIN,
  837. [](char * buffer, size_t len) {},
  838. [](const char * payload) {
  839. _fromKelvin(atol(payload));
  840. lightUpdate(true, true);
  841. }
  842. );
  843. apiRegister(MQTT_TOPIC_MIRED,
  844. [](char * buffer, size_t len) {},
  845. [](const char * payload) {
  846. _fromMireds(atol(payload));
  847. lightUpdate(true, true);
  848. }
  849. );
  850. }
  851. for (unsigned int id=0; id<_light_channel.size(); id++) {
  852. char key[15];
  853. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_CHANNEL, id);
  854. apiRegister(key,
  855. [id](char * buffer, size_t len) {
  856. snprintf_P(buffer, len, PSTR("%d"), _light_channel[id].target);
  857. },
  858. [id](const char * payload) {
  859. lightChannel(id, atoi(payload));
  860. lightUpdate(true, true);
  861. }
  862. );
  863. }
  864. apiRegister(MQTT_TOPIC_TRANSITION,
  865. [](char * buffer, size_t len) {
  866. snprintf_P(buffer, len, PSTR("%d"), lightTransitionTime());
  867. },
  868. [](const char * payload) {
  869. lightTransitionTime(atol(payload));
  870. }
  871. );
  872. apiRegister(MQTT_TOPIC_BRIGHTNESS,
  873. [](char * buffer, size_t len) {
  874. snprintf_P(buffer, len, PSTR("%d"), _light_brightness);
  875. },
  876. [](const char * payload) {
  877. lightBrightness(atoi(payload));
  878. lightUpdate(true, true);
  879. }
  880. );
  881. }
  882. #endif // API_SUPPORT
  883. #if TERMINAL_SUPPORT
  884. void _lightInitCommands() {
  885. terminalRegisterCommand(F("BRIGHTNESS"), [](Embedis* e) {
  886. if (e->argc > 1) {
  887. const String value(e->argv[1]);
  888. if( value.length() > 0 ) {
  889. if( value[0] == '+' || value[0] == '-' ) {
  890. lightBrightness(lightBrightness()+String(e->argv[1]).toInt());
  891. } else {
  892. lightBrightness(String(e->argv[1]).toInt());
  893. }
  894. lightUpdate(true, true);
  895. }
  896. }
  897. DEBUG_MSG_P(PSTR("Brightness: %d\n"), lightBrightness());
  898. terminalOK();
  899. });
  900. terminalRegisterCommand(F("CHANNEL"), [](Embedis* e) {
  901. if (e->argc < 2) {
  902. terminalError(F("Wrong arguments"));
  903. }
  904. int id = String(e->argv[1]).toInt();
  905. if (e->argc > 2) {
  906. int value = String(e->argv[2]).toInt();
  907. lightChannel(id, value);
  908. lightUpdate(true, true);
  909. }
  910. DEBUG_MSG_P(PSTR("Channel #%d (%s): %d\n"), id, lightDesc(id).c_str(), lightChannel(id));
  911. terminalOK();
  912. });
  913. terminalRegisterCommand(F("COLOR"), [](Embedis* e) {
  914. if (e->argc > 1) {
  915. String color = String(e->argv[1]);
  916. lightColor(color.c_str());
  917. lightUpdate(true, true);
  918. }
  919. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  920. terminalOK();
  921. });
  922. terminalRegisterCommand(F("KELVIN"), [](Embedis* e) {
  923. if (e->argc > 1) {
  924. String color = String("K") + String(e->argv[1]);
  925. lightColor(color.c_str());
  926. lightUpdate(true, true);
  927. }
  928. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  929. terminalOK();
  930. });
  931. terminalRegisterCommand(F("MIRED"), [](Embedis* e) {
  932. if (e->argc > 1) {
  933. const String value(e->argv[1]);
  934. String color = String("M");
  935. if( value.length() > 0 ) {
  936. if( value[0] == '+' || value[0] == '-' ) {
  937. color += String(_light_mireds + String(e->argv[1]).toInt());
  938. } else {
  939. color += String(e->argv[1]);
  940. }
  941. lightColor(color.c_str());
  942. lightUpdate(true, true);
  943. }
  944. }
  945. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  946. terminalOK();
  947. });
  948. }
  949. #endif // TERMINAL_SUPPORT
  950. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  951. unsigned long getIOMux(unsigned long gpio) {
  952. unsigned long muxes[16] = {
  953. PERIPHS_IO_MUX_GPIO0_U, PERIPHS_IO_MUX_U0TXD_U, PERIPHS_IO_MUX_GPIO2_U, PERIPHS_IO_MUX_U0RXD_U,
  954. PERIPHS_IO_MUX_GPIO4_U, PERIPHS_IO_MUX_GPIO5_U, PERIPHS_IO_MUX_SD_CLK_U, PERIPHS_IO_MUX_SD_DATA0_U,
  955. PERIPHS_IO_MUX_SD_DATA1_U, PERIPHS_IO_MUX_SD_DATA2_U, PERIPHS_IO_MUX_SD_DATA3_U, PERIPHS_IO_MUX_SD_CMD_U,
  956. PERIPHS_IO_MUX_MTDI_U, PERIPHS_IO_MUX_MTCK_U, PERIPHS_IO_MUX_MTMS_U, PERIPHS_IO_MUX_MTDO_U
  957. };
  958. return muxes[gpio];
  959. }
  960. unsigned long getIOFunc(unsigned long gpio) {
  961. unsigned long funcs[16] = {
  962. FUNC_GPIO0, FUNC_GPIO1, FUNC_GPIO2, FUNC_GPIO3,
  963. FUNC_GPIO4, FUNC_GPIO5, FUNC_GPIO6, FUNC_GPIO7,
  964. FUNC_GPIO8, FUNC_GPIO9, FUNC_GPIO10, FUNC_GPIO11,
  965. FUNC_GPIO12, FUNC_GPIO13, FUNC_GPIO14, FUNC_GPIO15
  966. };
  967. return funcs[gpio];
  968. }
  969. #endif
  970. void _lightConfigure() {
  971. _light_has_color = getSetting("useColor", LIGHT_USE_COLOR).toInt() == 1;
  972. if (_light_has_color && (_light_channel.size() < 3)) {
  973. _light_has_color = false;
  974. setSetting("useColor", _light_has_color);
  975. }
  976. _light_use_white = getSetting("useWhite", LIGHT_USE_WHITE).toInt() == 1;
  977. if (_light_use_white && (_light_channel.size() < 4) && (_light_channel.size() != 2)) {
  978. _light_use_white = false;
  979. setSetting("useWhite", _light_use_white);
  980. }
  981. if (_light_has_color) {
  982. if (_light_use_white) {
  983. _light_brightness_func = _lightApplyBrightnessColor;
  984. } else {
  985. _light_brightness_func = []() { _lightApplyBrightness(3); };
  986. }
  987. } else {
  988. _light_brightness_func = []() { _lightApplyBrightness(); };
  989. }
  990. _light_use_cct = getSetting("useCCT", LIGHT_USE_CCT).toInt() == 1;
  991. if (_light_use_cct && (((_light_channel.size() < 5) && (_light_channel.size() != 2)) || !_light_use_white)) {
  992. _light_use_cct = false;
  993. setSetting("useCCT", _light_use_cct);
  994. }
  995. _light_use_gamma = getSetting("useGamma", LIGHT_USE_GAMMA).toInt() == 1;
  996. _light_use_transitions = getSetting("useTransitions", LIGHT_USE_TRANSITIONS).toInt() == 1;
  997. _light_transition_time = getSetting("lightTime", LIGHT_TRANSITION_TIME).toInt();
  998. }
  999. void lightSetup() {
  1000. #ifdef LIGHT_ENABLE_PIN
  1001. pinMode(LIGHT_ENABLE_PIN, OUTPUT);
  1002. digitalWrite(LIGHT_ENABLE_PIN, HIGH);
  1003. #endif
  1004. _light_channel.reserve(LIGHT_CHANNELS);
  1005. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  1006. _my92xx = new my92xx(MY92XX_MODEL, MY92XX_CHIPS, MY92XX_DI_PIN, MY92XX_DCKI_PIN, MY92XX_COMMAND);
  1007. for (unsigned char i=0; i<LIGHT_CHANNELS; i++) {
  1008. _light_channel.push_back((channel_t) {0, false, true, 0, 0, 0});
  1009. }
  1010. #endif
  1011. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  1012. #ifdef LIGHT_CH1_PIN
  1013. _light_channel.push_back((channel_t) {LIGHT_CH1_PIN, LIGHT_CH1_INVERSE, true, 0, 0, 0});
  1014. #endif
  1015. #ifdef LIGHT_CH2_PIN
  1016. _light_channel.push_back((channel_t) {LIGHT_CH2_PIN, LIGHT_CH2_INVERSE, true, 0, 0, 0});
  1017. #endif
  1018. #ifdef LIGHT_CH3_PIN
  1019. _light_channel.push_back((channel_t) {LIGHT_CH3_PIN, LIGHT_CH3_INVERSE, true, 0, 0, 0});
  1020. #endif
  1021. #ifdef LIGHT_CH4_PIN
  1022. _light_channel.push_back((channel_t) {LIGHT_CH4_PIN, LIGHT_CH4_INVERSE, true, 0, 0, 0});
  1023. #endif
  1024. #ifdef LIGHT_CH5_PIN
  1025. _light_channel.push_back((channel_t) {LIGHT_CH5_PIN, LIGHT_CH5_INVERSE, true, 0, 0, 0});
  1026. #endif
  1027. uint32 pwm_duty_init[PWM_CHANNEL_NUM_MAX];
  1028. uint32 io_info[PWM_CHANNEL_NUM_MAX][3];
  1029. for (unsigned int i=0; i < _light_channel.size(); i++) {
  1030. pwm_duty_init[i] = 0;
  1031. io_info[i][0] = getIOMux(_light_channel[i].pin);
  1032. io_info[i][1] = getIOFunc(_light_channel[i].pin);
  1033. io_info[i][2] = _light_channel[i].pin;
  1034. pinMode(_light_channel[i].pin, OUTPUT);
  1035. }
  1036. pwm_init(LIGHT_MAX_PWM, pwm_duty_init, PWM_CHANNEL_NUM_MAX, io_info);
  1037. pwm_start();
  1038. #endif
  1039. DEBUG_MSG_P(PSTR("[LIGHT] LIGHT_PROVIDER = %d\n"), LIGHT_PROVIDER);
  1040. DEBUG_MSG_P(PSTR("[LIGHT] Number of channels: %d\n"), _light_channel.size());
  1041. _lightConfigure();
  1042. if (rtcmemStatus()) {
  1043. _lightRestoreRtcmem();
  1044. } else {
  1045. _lightRestoreSettings();
  1046. }
  1047. #if WEB_SUPPORT
  1048. wsRegister()
  1049. .onVisible(_lightWebSocketOnVisible)
  1050. .onConnected(_lightWebSocketOnConnected)
  1051. .onAction(_lightWebSocketOnAction)
  1052. .onKeyCheck(_lightWebSocketOnKeyCheck);
  1053. #endif
  1054. #if API_SUPPORT
  1055. _lightAPISetup();
  1056. #endif
  1057. #if MQTT_SUPPORT
  1058. mqttRegister(_lightMQTTCallback);
  1059. #endif
  1060. #if TERMINAL_SUPPORT
  1061. _lightInitCommands();
  1062. #endif
  1063. // Main callbacks
  1064. espurnaRegisterReload([]() {
  1065. #if LIGHT_SAVE_ENABLED == 0
  1066. lightSave();
  1067. #endif
  1068. _lightConfigure();
  1069. });
  1070. }
  1071. #endif // LIGHT_PROVIDER != LIGHT_PROVIDER_NONE