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.

1349 lines
41 KiB

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