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.

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