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.

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