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.

1421 lines
42 KiB

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