Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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