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.

1415 lines
43 KiB

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