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.

1422 lines
42 KiB

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