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.

1416 lines
43 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 "tuya.h"
  7. #include "light.h"
  8. #include "broker.h"
  9. #include "ws.h"
  10. #include <Ticker.h>
  11. #include <Schedule.h>
  12. #include <ArduinoJson.h>
  13. #include <vector>
  14. extern "C" {
  15. #include "libs/fs_math.h"
  16. }
  17. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  18. #define PWM_CHANNEL_NUM_MAX LIGHT_CHANNELS
  19. extern "C" {
  20. #include "libs/pwm.h"
  21. }
  22. #endif
  23. // -----------------------------------------------------------------------------
  24. Ticker _light_comms_ticker;
  25. Ticker _light_save_ticker;
  26. Ticker _light_transition_ticker;
  27. struct channel_t {
  28. unsigned char pin; // real GPIO pin
  29. bool reverse; // whether we should invert the value before using it
  30. bool state; // is the channel ON
  31. unsigned char inputValue; // raw value, without the brightness
  32. unsigned char value; // normalized value, including brightness
  33. unsigned char target; // target value
  34. double current; // transition value
  35. };
  36. std::vector<channel_t> _light_channel;
  37. unsigned char _light_channels = LIGHT_CHANNELS;
  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. bool _light_dirty = false;
  46. bool _light_state = false;
  47. unsigned char _light_brightness = Light::BRIGHTNESS_MAX;
  48. // Default to the Philips Hue value that HA also use.
  49. // https://developers.meethue.com/documentation/core-concepts
  50. long _light_cold_mireds = LIGHT_COLDWHITE_MIRED;
  51. long _light_warm_mireds = LIGHT_WARMWHITE_MIRED;
  52. long _light_cold_kelvin = (1000000L / _light_cold_mireds);
  53. long _light_warm_kelvin = (1000000L / _light_warm_mireds);
  54. long _light_mireds = lround((_light_cold_mireds + _light_warm_mireds) / 2L);
  55. using light_brightness_func_t = void();
  56. light_brightness_func_t* _light_brightness_func = nullptr;
  57. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  58. #include <my92xx.h>
  59. my92xx * _my92xx;
  60. ARRAYINIT(unsigned char, _light_channel_map, MY92XX_MAPPING);
  61. #endif
  62. // UI hint about channel distribution
  63. const char _light_channel_desc[5][5] PROGMEM = {
  64. {'W', 0, 0, 0, 0},
  65. {'W', 'C', 0, 0, 0},
  66. {'R', 'G', 'B', 0, 0},
  67. {'R', 'G', 'B', 'W', 0},
  68. {'R', 'G', 'B', 'W', 'C'}
  69. };
  70. static_assert((LIGHT_CHANNELS * LIGHT_CHANNELS) <= (sizeof(_light_channel_desc)), "Out-of-bounds array access");
  71. // Gamma Correction lookup table (8 bit)
  72. const unsigned char _light_gamma_table[] PROGMEM = {
  73. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  74. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
  75. 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6,
  76. 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 11,
  77. 12, 12, 13, 13, 14, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19,
  78. 19, 20, 20, 21, 22, 22, 23, 23, 24, 25, 25, 26, 26, 27, 28, 28,
  79. 29, 30, 30, 31, 32, 33, 33, 34, 35, 35, 36, 37, 38, 39, 39, 40,
  80. 41, 42, 43, 43, 44, 45, 46, 47, 48, 49, 50, 50, 51, 52, 53, 54,
  81. 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 71,
  82. 72, 73, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84, 86, 87, 88, 89,
  83. 91, 92, 93, 94, 96, 97, 98, 100, 101, 102, 104, 105, 106, 108, 109, 110,
  84. 112, 113, 115, 116, 118, 119, 121, 122, 123, 125, 126, 128, 130, 131, 133, 134,
  85. 136, 137, 139, 140, 142, 144, 145, 147, 149, 150, 152, 154, 155, 157, 159, 160,
  86. 162, 164, 166, 167, 169, 171, 173, 175, 176, 178, 180, 182, 184, 186, 187, 189,
  87. 191, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 217, 219, 221,
  88. 223, 225, 227, 229, 231, 233, 235, 238, 240, 242, 244, 246, 248, 251, 253, 255
  89. };
  90. static_assert(Light::VALUE_MAX <= sizeof(_light_gamma_table), "Out-of-bounds array access");
  91. // -----------------------------------------------------------------------------
  92. // UTILS
  93. // -----------------------------------------------------------------------------
  94. void _setValue(const unsigned char id, const unsigned int value) {
  95. if (_light_channel[id].value != value) {
  96. _light_channel[id].value = value;
  97. _light_dirty = true;
  98. }
  99. }
  100. void _setInputValue(const unsigned char id, const unsigned int value) {
  101. _light_channel[id].inputValue = value;
  102. }
  103. void _setRGBInputValue(unsigned char red, unsigned char green, unsigned char blue) {
  104. _setInputValue(0, constrain(red, Light::VALUE_MIN, Light::VALUE_MAX));
  105. _setInputValue(1, constrain(green, Light::VALUE_MIN, Light::VALUE_MAX));
  106. _setInputValue(2, constrain(blue, Light::VALUE_MIN, Light::VALUE_MAX));
  107. }
  108. void _setCCTInputValue(unsigned char warm, unsigned char cold) {
  109. _setInputValue(0, constrain(warm, Light::VALUE_MIN, Light::VALUE_MAX));
  110. _setInputValue(1, constrain(cold, Light::VALUE_MIN, Light::VALUE_MAX));
  111. }
  112. void _lightApplyBrightness(size_t channels = lightChannels()) {
  113. double brightness = static_cast<double>(_light_brightness) / static_cast<double>(Light::BRIGHTNESS_MAX);
  114. channels = std::min(channels, lightChannels());
  115. for (unsigned char i=0; i < lightChannels(); i++) {
  116. if (i >= channels) brightness = 1;
  117. _setValue(i, _light_channel[i].inputValue * brightness);
  118. }
  119. }
  120. void _lightApplyBrightnessColor() {
  121. double brightness = static_cast<double>(_light_brightness) / static_cast<double>(Light::BRIGHTNESS_MAX);
  122. // Substract the common part from RGB channels and add it to white channel. So [250,150,50] -> [200,100,0,50]
  123. unsigned char white = std::min(_light_channel[0].inputValue, std::min(_light_channel[1].inputValue, _light_channel[2].inputValue));
  124. for (unsigned int i=0; i < 3; i++) {
  125. _setValue(i, _light_channel[i].inputValue - white);
  126. }
  127. // Split the White Value across 2 White LED Strips.
  128. if (_light_use_cct) {
  129. // This change the range from 153-500 to 0-347 so we get a value between 0 and 1 in the end.
  130. double miredFactor = ((double) _light_mireds - (double) _light_cold_mireds)/((double) _light_warm_mireds - (double) _light_cold_mireds);
  131. // set cold white
  132. _light_channel[3].inputValue = 0;
  133. _setValue(3, lround(((double) 1.0 - miredFactor) * white));
  134. // set warm white
  135. _light_channel[4].inputValue = 0;
  136. _setValue(4, lround(miredFactor * white));
  137. } else {
  138. _light_channel[3].inputValue = 0;
  139. _setValue(3, white);
  140. }
  141. // Scale up to equal input values. So [250,150,50] -> [200,100,0,50] -> [250, 125, 0, 63]
  142. unsigned char max_in = std::max(_light_channel[0].inputValue, std::max(_light_channel[1].inputValue, _light_channel[2].inputValue));
  143. 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));
  144. unsigned char channelSize = _light_use_cct ? 5 : 4;
  145. if (_light_use_cct) {
  146. max_out = std::max(max_out, _light_channel[4].value);
  147. }
  148. double factor = (max_out > 0) ? (double) (max_in / max_out) : 0;
  149. for (unsigned char i=0; i < channelSize; i++) {
  150. _setValue(i, lround((double) _light_channel[i].value * factor * brightness));
  151. }
  152. // Scale white channel to match brightness
  153. for (unsigned char i=3; i < channelSize; i++) {
  154. _setValue(i, constrain(static_cast<unsigned int>(_light_channel[i].value * LIGHT_WHITE_FACTOR), Light::BRIGHTNESS_MIN, Light::BRIGHTNESS_MAX));
  155. }
  156. // For the rest of channels, don't apply brightness, it is already in the inputValue
  157. // i should be 4 when RGBW and 5 when RGBWW
  158. for (unsigned char i=channelSize; i < _light_channel.size(); i++) {
  159. _setValue(i, _light_channel[i].inputValue);
  160. }
  161. }
  162. String lightDesc(unsigned char id) {
  163. if (id >= _light_channel.size()) return FPSTR(pstr_unknown);
  164. const char tag = pgm_read_byte(&_light_channel_desc[_light_channel.size() - 1][id]);
  165. switch (tag) {
  166. case 'W': return F("WARM WHITE");
  167. case 'C': return F("COLD WHITE");
  168. case 'R': return F("RED");
  169. case 'G': return F("GREEN");
  170. case 'B': return F("BLUE");
  171. default: break;
  172. }
  173. return FPSTR(pstr_unknown);
  174. }
  175. // -----------------------------------------------------------------------------
  176. // Input Values
  177. // -----------------------------------------------------------------------------
  178. void _fromLong(unsigned long value, bool brightness) {
  179. if (brightness) {
  180. _setRGBInputValue((value >> 24) & 0xFF, (value >> 16) & 0xFF, (value >> 8) & 0xFF);
  181. lightBrightness((value & 0xFF) * Light::BRIGHTNESS_MAX / 255);
  182. } else {
  183. _setRGBInputValue((value >> 16) & 0xFF, (value >> 8) & 0xFF, (value) & 0xFF);
  184. }
  185. }
  186. void _fromRGB(const char * rgb) {
  187. // 9 char #........ , 11 char ...,...,...
  188. if (!_light_has_color) return;
  189. if (!rgb || (strlen(rgb) == 0)) return;
  190. // HEX value is always prefixed, like CSS
  191. // values are interpreted like RGB + optional brightness
  192. if (rgb[0] == '#') {
  193. _fromLong(strtoul(rgb + 1, nullptr, 16), strlen(rgb + 1) > 7);
  194. // With comma separated string, assume decimal values
  195. } else {
  196. const auto channels = _light_channel.size();
  197. unsigned char count = 0;
  198. char buf[16] = {0};
  199. strncpy(buf, rgb, sizeof(buf) - 1);
  200. char *tok = strtok(buf, ",");
  201. while (tok != NULL) {
  202. _setInputValue(count, atoi(tok));
  203. if (++count == channels) break;
  204. tok = strtok(NULL, ",");
  205. }
  206. // If less than 3 values received, set the rest to 0
  207. if (count < 2) _setInputValue(1, 0);
  208. if (count < 3) _setInputValue(2, 0);
  209. return;
  210. }
  211. }
  212. // HSV string is expected to be "H,S,V", where:
  213. // 0 <= H <= 360
  214. // 0 <= S <= 100
  215. // 0 <= V <= 100
  216. void _fromHSV(const char * hsv) {
  217. if (!_light_has_color) return;
  218. if (strlen(hsv) == 0) return;
  219. char buf[16] = {0};
  220. strncpy(buf, hsv, sizeof(buf) - 1);
  221. unsigned char count = 0;
  222. unsigned int value[3] = {0};
  223. char * tok = strtok(buf, ",");
  224. while (tok != NULL) {
  225. value[count] = atoi(tok);
  226. if (++count == 3) break;
  227. tok = strtok(NULL, ",");
  228. }
  229. if (count != 3) return;
  230. // HSV to RGB transformation -----------------------------------------------
  231. //INPUT: [0,100,57]
  232. //IS: [145,0,0]
  233. //SHOULD: [255,0,0]
  234. const double h = (value[0] == 360) ? 0 : (double) value[0] / 60.0;
  235. const double f = (h - floor(h));
  236. const double s = (double) value[1] / 100.0;
  237. _light_brightness = lround((double) value[2] * (static_cast<double>(Light::BRIGHTNESS_MAX) / 100.0)); // (default 255/100)
  238. const unsigned char p = lround(Light::VALUE_MAX * (1.0 - s));
  239. const unsigned char q = lround(Light::VALUE_MAX * (1.0 - s * f));
  240. const unsigned char t = lround(Light::VALUE_MAX * (1.0 - s * (1.0 - f)));
  241. switch (int(h)) {
  242. case 0:
  243. _setRGBInputValue(Light::VALUE_MAX, t, p);
  244. break;
  245. case 1:
  246. _setRGBInputValue(q, Light::VALUE_MAX, p);
  247. break;
  248. case 2:
  249. _setRGBInputValue(p, Light::VALUE_MAX, t);
  250. break;
  251. case 3:
  252. _setRGBInputValue(p, q, Light::VALUE_MAX);
  253. break;
  254. case 4:
  255. _setRGBInputValue(t, p, Light::VALUE_MAX);
  256. break;
  257. case 5:
  258. _setRGBInputValue(Light::VALUE_MAX, p, q);
  259. break;
  260. default:
  261. _setRGBInputValue(Light::VALUE_MIN, Light::VALUE_MIN, Light::VALUE_MIN);
  262. break;
  263. }
  264. }
  265. // Thanks to Sacha Telgenhof for sharing this code in his AiLight library
  266. // https://github.com/stelgenhof/AiLight
  267. // Color temperature is measured in mireds (kelvin = 1e6/mired)
  268. long _toKelvin(const long mireds) {
  269. return constrain(static_cast<long>(1000000L / mireds), _light_warm_kelvin, _light_cold_kelvin);
  270. }
  271. long _toMireds(const long kelvin) {
  272. return constrain(static_cast<long>(lround(1000000L / kelvin)), _light_cold_mireds, _light_warm_mireds);
  273. }
  274. void _lightMireds(const long kelvin) {
  275. _light_mireds = _toMireds(kelvin);
  276. }
  277. void _lightMiredsCCT(const long kelvin) {
  278. _lightMireds(kelvin);
  279. // This change the range from 153-500 to 0-347 so we get a value between 0 and 1 in the end.
  280. const double factor = ((double) _light_mireds - (double) _light_cold_mireds)/((double) _light_warm_mireds - (double) _light_cold_mireds);
  281. _setCCTInputValue(
  282. lround(factor * Light::VALUE_MAX),
  283. lround(((double) 1.0 - factor) * Light::VALUE_MAX)
  284. );
  285. }
  286. void _fromKelvin(long kelvin) {
  287. if (!_light_has_color) {
  288. if (!_light_use_cct) return;
  289. _lightMiredsCCT(kelvin);
  290. return;
  291. }
  292. _lightMireds(kelvin);
  293. if (_light_use_cct) {
  294. _setRGBInputValue(Light::VALUE_MAX, Light::VALUE_MAX, Light::VALUE_MAX);
  295. return;
  296. }
  297. // Calculate colors
  298. kelvin /= 100;
  299. const unsigned int red = (kelvin <= 66)
  300. ? Light::VALUE_MAX
  301. : 329.698727446 * fs_pow((double) (kelvin - 60), -0.1332047592);
  302. const unsigned int green = (kelvin <= 66)
  303. ? 99.4708025861 * fs_log(kelvin) - 161.1195681661
  304. : 288.1221695283 * fs_pow((double) kelvin, -0.0755148492);
  305. const unsigned int blue = (kelvin >= 66)
  306. ? Light::VALUE_MAX
  307. : ((kelvin <= 19)
  308. ? 0
  309. : 138.5177312231 * fs_log(kelvin - 10) - 305.0447927307);
  310. _setRGBInputValue(red, green, blue);
  311. }
  312. void _fromMireds(const long mireds) {
  313. _fromKelvin(_toKelvin(mireds));
  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. String _toCSV(bool target) {
  376. const auto channels = lightChannels();
  377. String result;
  378. result.reserve(4 * channels);
  379. for (auto& channel : _light_channel) {
  380. if (result.length()) result += ',';
  381. result += String(target ? channel.target : channel.inputValue);
  382. }
  383. return result;
  384. }
  385. // See cores/esp8266/WMath.cpp::map
  386. // Redefining as local method here to avoid breaking in unexpected ways in inputs like (0, 0, 0, 0, 1)
  387. template <typename T, typename Tin, typename Tout> T _lightMap(T x, Tin in_min, Tin in_max, Tout out_min, Tout out_max) {
  388. auto divisor = (in_max - in_min);
  389. if (divisor == 0){
  390. return -1; //AVR returns -1, SAM returns 0
  391. }
  392. return (x - in_min) * (out_max - out_min) / divisor + out_min;
  393. }
  394. int _lightAdjustValue(const int& value, const String& operation) {
  395. if (!operation.length()) return value;
  396. // if prefixed with a sign, treat expression as numerical operation
  397. // otherwise, use as the new value
  398. int updated = operation.toInt();
  399. if (operation[0] == '+' || operation[0] == '-') {
  400. updated = value + updated;
  401. }
  402. return updated;
  403. }
  404. void _lightAdjustBrightness(const char *payload) {
  405. lightBrightness(_lightAdjustValue(lightBrightness(), payload));
  406. }
  407. void _lightAdjustChannel(unsigned char id, const char *payload) {
  408. lightChannel(id, _lightAdjustValue(lightChannel(id), payload));
  409. }
  410. void _lightAdjustKelvin(const char *payload) {
  411. _fromKelvin(_lightAdjustValue(_toKelvin(_light_mireds), payload));
  412. }
  413. void _lightAdjustMireds(const char *payload) {
  414. _fromMireds(_lightAdjustValue(_light_mireds, payload));
  415. }
  416. // -----------------------------------------------------------------------------
  417. // PROVIDER
  418. // -----------------------------------------------------------------------------
  419. unsigned int _toPWM(unsigned int value, bool gamma, bool reverse) {
  420. value = constrain(value, Light::VALUE_MIN, Light::VALUE_MAX);
  421. if (gamma) value = pgm_read_byte(_light_gamma_table + value);
  422. if (Light::VALUE_MAX != Light::PWM_LIMIT) value = _lightMap(value, Light::VALUE_MIN, Light::VALUE_MAX, Light::PWM_MIN, Light::PWM_LIMIT);
  423. if (reverse) value = LIGHT_LIMIT_PWM - value;
  424. return value;
  425. }
  426. // Returns a PWM value for the given channel ID
  427. unsigned int _toPWM(unsigned char id) {
  428. bool useGamma = _light_use_gamma && _light_has_color && (id < 3);
  429. return _toPWM(_light_channel[id].current, useGamma, _light_channel[id].reverse);
  430. }
  431. void _lightTransition(unsigned long step) {
  432. // Transitions based on current step. If step == 0, then it is the last transition
  433. for (auto& channel : _light_channel) {
  434. if (!step) {
  435. channel.current = channel.target;
  436. } else {
  437. channel.current += (double) (channel.target - channel.current) / (step + 1);
  438. }
  439. }
  440. }
  441. void _lightProviderUpdate(unsigned long steps) {
  442. if (_light_provider_update) return;
  443. _light_provider_update = true;
  444. _lightTransition(--steps);
  445. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  446. for (unsigned char i=0; i<_light_channel.size(); i++) {
  447. _my92xx->setChannel(_light_channel_map[i], _toPWM(i));
  448. }
  449. _my92xx->setState(true);
  450. _my92xx->update();
  451. #endif
  452. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  453. for (unsigned int i=0; i < _light_channel.size(); i++) {
  454. pwm_set_duty(_toPWM(i), i);
  455. }
  456. pwm_start();
  457. #endif
  458. // This is not the final value, update again
  459. if (steps) _light_transition_ticker.once_ms(LIGHT_TRANSITION_STEP, _lightProviderScheduleUpdate, steps);
  460. _light_provider_update = false;
  461. }
  462. void _lightProviderScheduleUpdate(unsigned long steps) {
  463. schedule_function(std::bind(_lightProviderUpdate, steps));
  464. }
  465. // -----------------------------------------------------------------------------
  466. // PERSISTANCE
  467. // -----------------------------------------------------------------------------
  468. union light_rtcmem_t {
  469. struct {
  470. uint8_t channels[Light::CHANNELS_MAX];
  471. uint8_t brightness;
  472. uint16_t mired;
  473. } __attribute__((packed)) packed;
  474. uint64_t value;
  475. };
  476. void _lightSaveRtcmem() {
  477. if (lightChannels() > Light::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::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. for (unsigned int id = 0; id < _light_channel.size(); ++id) {
  631. StatusBroker::Publish(MQTT_TOPIC_CHANNEL, id, _light_channel[id].value);
  632. }
  633. }
  634. #endif
  635. // -----------------------------------------------------------------------------
  636. // API
  637. // -----------------------------------------------------------------------------
  638. size_t lightChannels() {
  639. return _light_channel.size();
  640. }
  641. bool lightHasColor() {
  642. return _light_has_color;
  643. }
  644. bool lightUseCCT() {
  645. return _light_use_cct;
  646. }
  647. void _lightComms(const unsigned char mask) {
  648. // Report color and brightness to MQTT broker
  649. #if MQTT_SUPPORT
  650. if (mask & Light::COMMS_NORMAL) lightMQTT();
  651. if (mask & Light::COMMS_GROUP) lightMQTTGroup();
  652. #endif
  653. // Report color to WS clients (using current brightness setting)
  654. #if WEB_SUPPORT
  655. wsPost(_lightWebSocketStatus);
  656. #endif
  657. // Report channels to local broker
  658. #if BROKER_SUPPORT
  659. lightBroker();
  660. #endif
  661. }
  662. void lightUpdate(bool save, bool forward, bool group_forward) {
  663. // Calculate values based on inputs and brightness
  664. _light_brightness_func();
  665. // Only update if a channel has changed
  666. if (!_light_dirty) return;
  667. _light_dirty = false;
  668. // Update channels
  669. for (unsigned int i=0; i < _light_channel.size(); i++) {
  670. _light_channel[i].target = _light_state && _light_channel[i].state ? _light_channel[i].value : 0;
  671. //DEBUG_MSG_P("[LIGHT] Channel #%u target value: %u\n", i, _light_channel[i].target);
  672. }
  673. // Channel transition will be handled by the provider function
  674. // User can configure total transition time, step time is a fixed value
  675. const unsigned long steps = _light_use_transitions ? _light_transition_time / LIGHT_TRANSITION_STEP : 1;
  676. _light_transition_ticker.once_ms(LIGHT_TRANSITION_STEP, _lightProviderScheduleUpdate, steps);
  677. // Delay every communication 100ms to avoid jamming
  678. const unsigned char mask =
  679. ((forward) ? Light::COMMS_NORMAL : Light::COMMS_NONE) |
  680. ((group_forward) ? Light::COMMS_GROUP : Light::COMMS_NONE);
  681. _light_comms_ticker.once_ms(LIGHT_COMMS_DELAY, _lightComms, mask);
  682. _lightSaveRtcmem();
  683. #if LIGHT_SAVE_ENABLED
  684. // Delay saving to EEPROM 5 seconds to avoid wearing it out unnecessarily
  685. if (save) _light_save_ticker.once(LIGHT_SAVE_DELAY, _lightSaveSettings);
  686. #endif
  687. };
  688. void lightUpdate(bool save, bool forward) {
  689. lightUpdate(save, forward, true);
  690. }
  691. #if LIGHT_SAVE_ENABLED == 0
  692. void lightSave() {
  693. _lightSaveSettings();
  694. }
  695. #endif
  696. void lightState(unsigned char id, bool state) {
  697. if (id >= _light_channel.size()) return;
  698. if (_light_channel[id].state != state) {
  699. _light_channel[id].state = state;
  700. _light_dirty = true;
  701. }
  702. }
  703. bool lightState(unsigned char id) {
  704. if (id >= _light_channel.size()) return false;
  705. return _light_channel[id].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()) return 0;
  744. return _light_channel[id].inputValue;
  745. }
  746. void lightChannel(unsigned char id, long value) {
  747. if (id >= _light_channel.size()) return;
  748. _setInputValue(id, constrain(value, Light::VALUE_MIN, Light::VALUE_MAX));
  749. }
  750. void lightChannelStep(unsigned char id, long steps, long multiplier) {
  751. lightChannel(id, static_cast<int>(lightChannel(id)) + (steps * multiplier));
  752. }
  753. long lightBrightness() {
  754. return _light_brightness;
  755. }
  756. void lightBrightness(long brightness) {
  757. _light_brightness = constrain(brightness, Light::BRIGHTNESS_MIN, Light::BRIGHTNESS_MAX);
  758. }
  759. void lightBrightnessStep(long steps, long multiplier) {
  760. lightBrightness(static_cast<int>(_light_brightness) + (steps * multiplier));
  761. }
  762. unsigned int lightTransitionTime() {
  763. if (_light_use_transitions) {
  764. return _light_transition_time;
  765. } else {
  766. return 0;
  767. }
  768. }
  769. void lightTransitionTime(unsigned long m) {
  770. if (0 == m) {
  771. _light_use_transitions = false;
  772. } else {
  773. _light_use_transitions = true;
  774. _light_transition_time = m;
  775. }
  776. setSetting("useTransitions", _light_use_transitions);
  777. setSetting("lightTime", _light_transition_time);
  778. saveSettings();
  779. }
  780. // -----------------------------------------------------------------------------
  781. // SETUP
  782. // -----------------------------------------------------------------------------
  783. #if WEB_SUPPORT
  784. bool _lightWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  785. if (strncmp(key, "light", 5) == 0) return true;
  786. if (strncmp(key, "use", 3) == 0) return true;
  787. return false;
  788. }
  789. void _lightWebSocketStatus(JsonObject& root) {
  790. if (_light_has_color) {
  791. if (getSetting("useRGB", LIGHT_USE_RGB).toInt() == 1) {
  792. root["rgb"] = lightColor(true);
  793. } else {
  794. root["hsv"] = lightColor(false);
  795. }
  796. }
  797. if (_light_use_cct) {
  798. JsonObject& mireds = root.createNestedObject("mireds");
  799. mireds["value"] = _light_mireds;
  800. mireds["cold"] = _light_cold_mireds;
  801. mireds["warm"] = _light_warm_mireds;
  802. root["useCCT"] = _light_use_cct;
  803. }
  804. JsonArray& channels = root.createNestedArray("channels");
  805. for (unsigned char id=0; id < _light_channel.size(); id++) {
  806. channels.add(lightChannel(id));
  807. }
  808. root["brightness"] = lightBrightness();
  809. }
  810. void _lightWebSocketOnVisible(JsonObject& root) {
  811. root["colorVisible"] = 1;
  812. }
  813. void _lightWebSocketOnConnected(JsonObject& root) {
  814. root["mqttGroupColor"] = getSetting("mqttGroupColor");
  815. root["useColor"] = _light_has_color;
  816. root["useWhite"] = _light_use_white;
  817. root["useGamma"] = _light_use_gamma;
  818. root["useTransitions"] = _light_use_transitions;
  819. root["useCSS"] = getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1;
  820. root["useRGB"] = getSetting("useRGB", LIGHT_USE_RGB).toInt() == 1;
  821. root["lightTime"] = _light_transition_time;
  822. _lightWebSocketStatus(root);
  823. }
  824. void _lightWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  825. if (_light_has_color) {
  826. if (strcmp(action, "color") == 0) {
  827. if (data.containsKey("rgb")) {
  828. lightColor(data["rgb"], true);
  829. lightUpdate(true, true);
  830. }
  831. if (data.containsKey("hsv")) {
  832. lightColor(data["hsv"], false);
  833. lightUpdate(true, true);
  834. }
  835. }
  836. }
  837. if (_light_use_cct) {
  838. if (strcmp(action, "mireds") == 0) {
  839. _fromMireds(data["mireds"]);
  840. lightUpdate(true, true);
  841. }
  842. }
  843. if (strcmp(action, "channel") == 0) {
  844. if (data.containsKey("id") && data.containsKey("value")) {
  845. lightChannel(data["id"].as<unsigned char>(), data["value"].as<int>());
  846. lightUpdate(true, true);
  847. }
  848. }
  849. if (strcmp(action, "brightness") == 0) {
  850. if (data.containsKey("value")) {
  851. lightBrightness(data["value"].as<int>());
  852. lightUpdate(true, true);
  853. }
  854. }
  855. }
  856. #endif
  857. #if API_SUPPORT
  858. void _lightAPISetup() {
  859. if (_light_has_color) {
  860. apiRegister(MQTT_TOPIC_COLOR_RGB,
  861. [](char * buffer, size_t len) {
  862. if (getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1) {
  863. _toRGB(buffer, len, true);
  864. } else {
  865. _toLong(buffer, len, true);
  866. }
  867. },
  868. [](const char * payload) {
  869. lightColor(payload, true);
  870. lightUpdate(true, true);
  871. }
  872. );
  873. apiRegister(MQTT_TOPIC_COLOR_HSV,
  874. [](char * buffer, size_t len) {
  875. _toHSV(buffer, len);
  876. },
  877. [](const char * payload) {
  878. lightColor(payload, false);
  879. lightUpdate(true, true);
  880. }
  881. );
  882. apiRegister(MQTT_TOPIC_KELVIN,
  883. [](char * buffer, size_t len) {},
  884. [](const char * payload) {
  885. _lightAdjustKelvin(payload);
  886. lightUpdate(true, true);
  887. }
  888. );
  889. apiRegister(MQTT_TOPIC_MIRED,
  890. [](char * buffer, size_t len) {},
  891. [](const char * payload) {
  892. _lightAdjustMireds(payload);
  893. lightUpdate(true, true);
  894. }
  895. );
  896. }
  897. for (unsigned int id=0; id<_light_channel.size(); id++) {
  898. char key[15];
  899. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_CHANNEL, id);
  900. apiRegister(key,
  901. [id](char * buffer, size_t len) {
  902. snprintf_P(buffer, len, PSTR("%d"), _light_channel[id].target);
  903. },
  904. [id](const char * payload) {
  905. _lightAdjustChannel(id, payload);
  906. lightUpdate(true, true);
  907. }
  908. );
  909. }
  910. apiRegister(MQTT_TOPIC_TRANSITION,
  911. [](char * buffer, size_t len) {
  912. snprintf_P(buffer, len, PSTR("%d"), lightTransitionTime());
  913. },
  914. [](const char * payload) {
  915. lightTransitionTime(atol(payload));
  916. }
  917. );
  918. apiRegister(MQTT_TOPIC_BRIGHTNESS,
  919. [](char * buffer, size_t len) {
  920. snprintf_P(buffer, len, PSTR("%d"), _light_brightness);
  921. },
  922. [](const char * payload) {
  923. _lightAdjustBrightness(payload);
  924. lightUpdate(true, true);
  925. }
  926. );
  927. }
  928. #endif // API_SUPPORT
  929. #if TERMINAL_SUPPORT
  930. void _lightChannelDebug(unsigned char id) {
  931. DEBUG_MSG_P(PSTR("Channel #%u (%s): %d\n"), id, lightDesc(id).c_str(), lightChannel(id));
  932. }
  933. void _lightInitCommands() {
  934. terminalRegisterCommand(F("BRIGHTNESS"), [](Embedis* e) {
  935. if (e->argc > 1) {
  936. _lightAdjustBrightness(e->argv[1]);
  937. lightUpdate(true, true);
  938. }
  939. DEBUG_MSG_P(PSTR("Brightness: %u\n"), lightBrightness());
  940. terminalOK();
  941. });
  942. terminalRegisterCommand(F("CHANNEL"), [](Embedis* e) {
  943. if (!lightChannels()) return;
  944. auto id = -1;
  945. if (e->argc > 1) {
  946. id = String(e->argv[1]).toInt();
  947. }
  948. if (id < 0 || id >= static_cast<decltype(id)>(lightChannels())) {
  949. for (unsigned char index = 0; index < lightChannels(); ++index) {
  950. _lightChannelDebug(index);
  951. }
  952. return;
  953. }
  954. if (e->argc > 2) {
  955. _lightAdjustChannel(id, e->argv[2]);
  956. lightUpdate(true, true);
  957. }
  958. _lightChannelDebug(id);
  959. terminalOK();
  960. });
  961. terminalRegisterCommand(F("COLOR"), [](Embedis* e) {
  962. if (e->argc > 1) {
  963. lightColor(e->argv[1]);
  964. lightUpdate(true, true);
  965. }
  966. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  967. terminalOK();
  968. });
  969. terminalRegisterCommand(F("KELVIN"), [](Embedis* e) {
  970. if (e->argc > 1) {
  971. _lightAdjustKelvin(e->argv[1]);
  972. lightUpdate(true, true);
  973. }
  974. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  975. terminalOK();
  976. });
  977. terminalRegisterCommand(F("MIRED"), [](Embedis* e) {
  978. if (e->argc > 1) {
  979. _lightAdjustMireds(e->argv[1]);
  980. lightUpdate(true, true);
  981. }
  982. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  983. terminalOK();
  984. });
  985. }
  986. #endif // TERMINAL_SUPPORT
  987. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  988. const unsigned long _light_iomux[16] PROGMEM = {
  989. PERIPHS_IO_MUX_GPIO0_U, PERIPHS_IO_MUX_U0TXD_U, PERIPHS_IO_MUX_GPIO2_U, PERIPHS_IO_MUX_U0RXD_U,
  990. PERIPHS_IO_MUX_GPIO4_U, PERIPHS_IO_MUX_GPIO5_U, PERIPHS_IO_MUX_SD_CLK_U, PERIPHS_IO_MUX_SD_DATA0_U,
  991. PERIPHS_IO_MUX_SD_DATA1_U, PERIPHS_IO_MUX_SD_DATA2_U, PERIPHS_IO_MUX_SD_DATA3_U, PERIPHS_IO_MUX_SD_CMD_U,
  992. PERIPHS_IO_MUX_MTDI_U, PERIPHS_IO_MUX_MTCK_U, PERIPHS_IO_MUX_MTMS_U, PERIPHS_IO_MUX_MTDO_U
  993. };
  994. const unsigned long _light_iofunc[16] PROGMEM = {
  995. FUNC_GPIO0, FUNC_GPIO1, FUNC_GPIO2, FUNC_GPIO3,
  996. FUNC_GPIO4, FUNC_GPIO5, FUNC_GPIO6, FUNC_GPIO7,
  997. FUNC_GPIO8, FUNC_GPIO9, FUNC_GPIO10, FUNC_GPIO11,
  998. FUNC_GPIO12, FUNC_GPIO13, FUNC_GPIO14, FUNC_GPIO15
  999. };
  1000. #endif
  1001. void _lightConfigure() {
  1002. _light_has_color = getSetting("useColor", LIGHT_USE_COLOR).toInt() == 1;
  1003. if (_light_has_color && (_light_channel.size() < 3)) {
  1004. _light_has_color = false;
  1005. setSetting("useColor", _light_has_color);
  1006. }
  1007. _light_use_white = getSetting("useWhite", LIGHT_USE_WHITE).toInt() == 1;
  1008. if (_light_use_white && (_light_channel.size() < 4) && (_light_channel.size() != 2)) {
  1009. _light_use_white = false;
  1010. setSetting("useWhite", _light_use_white);
  1011. }
  1012. if (_light_has_color) {
  1013. if (_light_use_white) {
  1014. _light_brightness_func = _lightApplyBrightnessColor;
  1015. } else {
  1016. _light_brightness_func = []() { _lightApplyBrightness(3); };
  1017. }
  1018. } else {
  1019. _light_brightness_func = []() { _lightApplyBrightness(); };
  1020. }
  1021. _light_use_cct = getSetting("useCCT", LIGHT_USE_CCT).toInt() == 1;
  1022. if (_light_use_cct && (((_light_channel.size() < 5) && (_light_channel.size() != 2)) || !_light_use_white)) {
  1023. _light_use_cct = false;
  1024. setSetting("useCCT", _light_use_cct);
  1025. }
  1026. if (_light_use_cct) {
  1027. _light_cold_mireds = getSetting("lightColdMired", LIGHT_COLDWHITE_MIRED).toInt();
  1028. _light_warm_mireds = getSetting("lightWarmMired", LIGHT_WARMWHITE_MIRED).toInt();
  1029. _light_cold_kelvin = (1000000L / _light_cold_mireds);
  1030. _light_warm_kelvin = (1000000L / _light_warm_mireds);
  1031. }
  1032. _light_use_gamma = getSetting("useGamma", LIGHT_USE_GAMMA).toInt() == 1;
  1033. _light_use_transitions = getSetting("useTransitions", LIGHT_USE_TRANSITIONS).toInt() == 1;
  1034. _light_transition_time = getSetting("lightTime", LIGHT_TRANSITION_TIME).toInt();
  1035. }
  1036. // Dummy channel setup for light providers without real GPIO
  1037. void lightSetupChannels(unsigned char size) {
  1038. size = constrain(size, 0, Light::CHANNELS_MAX);
  1039. if (size == _light_channel.size()) return;
  1040. _light_channels = size;
  1041. _light_channel.assign(size, {
  1042. GPIO_NONE, false, true,
  1043. 0, 0, 0
  1044. });
  1045. }
  1046. void lightSetup() {
  1047. #ifdef LIGHT_ENABLE_PIN
  1048. pinMode(LIGHT_ENABLE_PIN, OUTPUT);
  1049. digitalWrite(LIGHT_ENABLE_PIN, HIGH);
  1050. #endif
  1051. _light_channel.reserve(LIGHT_CHANNELS);
  1052. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  1053. _my92xx = new my92xx(MY92XX_MODEL, MY92XX_CHIPS, MY92XX_DI_PIN, MY92XX_DCKI_PIN, MY92XX_COMMAND);
  1054. lightSetupChannels(LIGHT_CHANNELS);
  1055. #endif
  1056. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  1057. #ifdef LIGHT_CH1_PIN
  1058. _light_channel.push_back((channel_t) {LIGHT_CH1_PIN, LIGHT_CH1_INVERSE, true, 0, 0, 0});
  1059. #endif
  1060. #ifdef LIGHT_CH2_PIN
  1061. _light_channel.push_back((channel_t) {LIGHT_CH2_PIN, LIGHT_CH2_INVERSE, true, 0, 0, 0});
  1062. #endif
  1063. #ifdef LIGHT_CH3_PIN
  1064. _light_channel.push_back((channel_t) {LIGHT_CH3_PIN, LIGHT_CH3_INVERSE, true, 0, 0, 0});
  1065. #endif
  1066. #ifdef LIGHT_CH4_PIN
  1067. _light_channel.push_back((channel_t) {LIGHT_CH4_PIN, LIGHT_CH4_INVERSE, true, 0, 0, 0});
  1068. #endif
  1069. #ifdef LIGHT_CH5_PIN
  1070. _light_channel.push_back((channel_t) {LIGHT_CH5_PIN, LIGHT_CH5_INVERSE, true, 0, 0, 0});
  1071. #endif
  1072. uint32 pwm_duty_init[PWM_CHANNEL_NUM_MAX];
  1073. uint32 io_info[PWM_CHANNEL_NUM_MAX][3];
  1074. for (unsigned int i=0; i < _light_channel.size(); i++) {
  1075. const auto pin = _light_channel.at(i).pin;
  1076. pwm_duty_init[i] = 0;
  1077. io_info[i][0] = pgm_read_dword(&_light_iomux[pin]);
  1078. io_info[i][1] = pgm_read_dword(&_light_iofunc[pin]);
  1079. io_info[i][2] = pin;
  1080. pinMode(pin, OUTPUT);
  1081. }
  1082. pwm_init(LIGHT_MAX_PWM, pwm_duty_init, PWM_CHANNEL_NUM_MAX, io_info);
  1083. pwm_start();
  1084. #endif
  1085. #if LIGHT_PROVIDER == LIGHT_PROVIDER_TUYA
  1086. tuyaSetupLight();
  1087. #endif
  1088. DEBUG_MSG_P(PSTR("[LIGHT] LIGHT_PROVIDER = %d\n"), LIGHT_PROVIDER);
  1089. DEBUG_MSG_P(PSTR("[LIGHT] Number of channels: %d\n"), _light_channel.size());
  1090. _lightConfigure();
  1091. if (rtcmemStatus()) {
  1092. _lightRestoreRtcmem();
  1093. } else {
  1094. _lightRestoreSettings();
  1095. }
  1096. lightUpdate(false, false);
  1097. #if WEB_SUPPORT
  1098. wsRegister()
  1099. .onVisible(_lightWebSocketOnVisible)
  1100. .onConnected(_lightWebSocketOnConnected)
  1101. .onAction(_lightWebSocketOnAction)
  1102. .onKeyCheck(_lightWebSocketOnKeyCheck);
  1103. #endif
  1104. #if API_SUPPORT
  1105. _lightAPISetup();
  1106. #endif
  1107. #if MQTT_SUPPORT
  1108. mqttRegister(_lightMQTTCallback);
  1109. #endif
  1110. #if TERMINAL_SUPPORT
  1111. _lightInitCommands();
  1112. #endif
  1113. // Main callbacks
  1114. espurnaRegisterReload([]() {
  1115. #if LIGHT_SAVE_ENABLED == 0
  1116. lightSave();
  1117. #endif
  1118. _lightConfigure();
  1119. });
  1120. }
  1121. #endif // LIGHT_PROVIDER != LIGHT_PROVIDER_NONE