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.

1400 lines
42 KiB

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