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.

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