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.

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