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.

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