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.

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