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.

1392 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 "light.h"
  7. #include <Ticker.h>
  8. #include <Schedule.h>
  9. #include <ArduinoJson.h>
  10. #include <vector>
  11. extern "C" {
  12. #include "libs/fs_math.h"
  13. }
  14. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  15. #define PWM_CHANNEL_NUM_MAX LIGHT_CHANNELS
  16. extern "C" {
  17. #include "libs/pwm.h"
  18. }
  19. #endif
  20. // -----------------------------------------------------------------------------
  21. Ticker _light_comms_ticker;
  22. Ticker _light_save_ticker;
  23. Ticker _light_transition_ticker;
  24. struct channel_t {
  25. unsigned char pin; // real GPIO pin
  26. bool reverse; // wether we should invert the value before using it
  27. bool state; // is the channel ON
  28. unsigned char inputValue; // raw value, without the brightness
  29. unsigned char value; // normalized value, including brightness
  30. unsigned char target; // target value
  31. double current; // transition value
  32. };
  33. std::vector<channel_t> _light_channel;
  34. bool _light_has_color = false;
  35. bool _light_use_white = false;
  36. bool _light_use_cct = false;
  37. bool _light_use_gamma = false;
  38. bool _light_provider_update = false;
  39. bool _light_use_transitions = false;
  40. unsigned int _light_transition_time = LIGHT_TRANSITION_TIME;
  41. bool _light_dirty = false;
  42. bool _light_state = false;
  43. unsigned char _light_brightness = Light::BRIGHTNESS_MAX;
  44. // Default to the Philips Hue value that HA also use.
  45. // https://developers.meethue.com/documentation/core-concepts
  46. long _light_mireds_cold = LIGHT_COLDWHITE_MIRED;
  47. long _light_mireds_warm = LIGHT_WARMWHITE_MIRED;
  48. long _light_kelvin_cold = (1000000L / _light_mireds_cold);
  49. long _light_kelvin_warm = (1000000L / _light_mireds_warm);
  50. long _light_mireds = lround((_light_mireds_cold + _light_mireds_warm) / 2L);
  51. using light_brightness_func_t = void();
  52. light_brightness_func_t* _light_brightness_func = nullptr;
  53. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  54. #include <my92xx.h>
  55. my92xx * _my92xx;
  56. ARRAYINIT(unsigned char, _light_channel_map, MY92XX_MAPPING);
  57. #endif
  58. // UI hint about channel distribution
  59. const char _light_channel_desc[5][5] PROGMEM = {
  60. {'W', 0, 0, 0, 0},
  61. {'W', 'C', 0, 0, 0},
  62. {'R', 'G', 'B', 0, 0},
  63. {'R', 'G', 'B', 'W', 0},
  64. {'R', 'G', 'B', 'W', 'C'}
  65. };
  66. static_assert((LIGHT_CHANNELS * LIGHT_CHANNELS) <= (sizeof(_light_channel_desc)), "Out-of-bounds array access");
  67. // Gamma Correction lookup table (8 bit)
  68. const unsigned char _light_gamma_table[] PROGMEM = {
  69. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  70. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
  71. 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6,
  72. 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 11,
  73. 12, 12, 13, 13, 14, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19,
  74. 19, 20, 20, 21, 22, 22, 23, 23, 24, 25, 25, 26, 26, 27, 28, 28,
  75. 29, 30, 30, 31, 32, 33, 33, 34, 35, 35, 36, 37, 38, 39, 39, 40,
  76. 41, 42, 43, 43, 44, 45, 46, 47, 48, 49, 50, 50, 51, 52, 53, 54,
  77. 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 71,
  78. 72, 73, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84, 86, 87, 88, 89,
  79. 91, 92, 93, 94, 96, 97, 98, 100, 101, 102, 104, 105, 106, 108, 109, 110,
  80. 112, 113, 115, 116, 118, 119, 121, 122, 123, 125, 126, 128, 130, 131, 133, 134,
  81. 136, 137, 139, 140, 142, 144, 145, 147, 149, 150, 152, 154, 155, 157, 159, 160,
  82. 162, 164, 166, 167, 169, 171, 173, 175, 176, 178, 180, 182, 184, 186, 187, 189,
  83. 191, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 217, 219, 221,
  84. 223, 225, 227, 229, 231, 233, 235, 238, 240, 242, 244, 246, 248, 251, 253, 255
  85. };
  86. static_assert(Light::VALUE_MAX <= sizeof(_light_gamma_table), "Out-of-bounds array access");
  87. // -----------------------------------------------------------------------------
  88. // UTILS
  89. // -----------------------------------------------------------------------------
  90. void _setValue(const unsigned char id, const unsigned int value) {
  91. if (_light_channel[id].value != value) {
  92. _light_channel[id].value = value;
  93. _light_dirty = true;
  94. }
  95. }
  96. void _setInputValue(const unsigned char id, const unsigned int value) {
  97. if (_light_channel[id].inputValue != value) {
  98. _light_channel[id].inputValue = value;
  99. _light_dirty = true;
  100. }
  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_mireds_cold)/((double) _light_mireds_warm - (double) _light_mireds_cold);
  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_kelvin_warm, _light_kelvin_cold);
  269. }
  270. long _toMireds(const long kelvin) {
  271. return constrain(static_cast<long>(lround(1000000L / kelvin)), _light_mireds_cold, _light_mireds_warm);
  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_mireds_cold)/((double) _light_mireds_warm - (double) _light_mireds_cold);
  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[5];
  470. uint8_t brightness;
  471. uint16_t mired;
  472. } packed;
  473. uint64_t value;
  474. };
  475. #define LIGHT_RTCMEM_CHANNELS_MAX sizeof(light_rtcmem_t().packed.channels)
  476. void _lightSaveRtcmem() {
  477. if (lightChannels() > LIGHT_RTCMEM_CHANNELS_MAX) return;
  478. light_rtcmem_t light;
  479. for (unsigned int i=0; i < lightChannels(); i++) {
  480. light.packed.channels[i] = _light_channel[i].inputValue;
  481. }
  482. light.packed.brightness = _light_brightness;
  483. light.packed.mired = _light_mireds;
  484. Rtcmem->light = light.value;
  485. }
  486. void _lightRestoreRtcmem() {
  487. if (lightChannels() > LIGHT_RTCMEM_CHANNELS_MAX) return;
  488. light_rtcmem_t light;
  489. light.value = Rtcmem->light;
  490. for (unsigned int i=0; i < lightChannels(); i++) {
  491. _light_channel[i].inputValue = light.packed.channels[i];
  492. }
  493. _light_brightness = light.packed.brightness;
  494. _light_mireds = light.packed.mired;
  495. }
  496. void _lightSaveSettings() {
  497. for (unsigned int i=0; i < _light_channel.size(); i++) {
  498. setSetting("ch", i, _light_channel[i].inputValue);
  499. }
  500. setSetting("brightness", _light_brightness);
  501. setSetting("mireds", _light_mireds);
  502. saveSettings();
  503. }
  504. void _lightRestoreSettings() {
  505. for (unsigned int i=0; i < _light_channel.size(); i++) {
  506. _light_channel[i].inputValue = getSetting("ch", i, (i == 0) ? Light::VALUE_MAX : 0).toInt();
  507. }
  508. _light_brightness = getSetting("brightness", Light::BRIGHTNESS_MAX).toInt();
  509. _light_mireds = getSetting("mireds", _light_mireds).toInt();
  510. }
  511. // -----------------------------------------------------------------------------
  512. // MQTT
  513. // -----------------------------------------------------------------------------
  514. #if MQTT_SUPPORT
  515. void _lightMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  516. String mqtt_group_color = getSetting("mqttGroupColor");
  517. if (type == MQTT_CONNECT_EVENT) {
  518. mqttSubscribe(MQTT_TOPIC_BRIGHTNESS);
  519. if (_light_has_color) {
  520. mqttSubscribe(MQTT_TOPIC_COLOR_RGB);
  521. mqttSubscribe(MQTT_TOPIC_COLOR_HSV);
  522. mqttSubscribe(MQTT_TOPIC_TRANSITION);
  523. }
  524. if (_light_has_color || _light_use_cct) {
  525. mqttSubscribe(MQTT_TOPIC_MIRED);
  526. mqttSubscribe(MQTT_TOPIC_KELVIN);
  527. }
  528. // Group color
  529. if (mqtt_group_color.length() > 0) mqttSubscribeRaw(mqtt_group_color.c_str());
  530. // Channels
  531. char buffer[strlen(MQTT_TOPIC_CHANNEL) + 3];
  532. snprintf_P(buffer, sizeof(buffer), PSTR("%s/+"), MQTT_TOPIC_CHANNEL);
  533. mqttSubscribe(buffer);
  534. }
  535. if (type == MQTT_MESSAGE_EVENT) {
  536. // Group color
  537. if ((mqtt_group_color.length() > 0) && (mqtt_group_color.equals(topic))) {
  538. lightColor(payload, true);
  539. lightUpdate(true, mqttForward(), false);
  540. return;
  541. }
  542. // Match topic
  543. String t = mqttMagnitude((char *) topic);
  544. // Color temperature in mireds
  545. if (t.equals(MQTT_TOPIC_MIRED)) {
  546. _lightAdjustMireds(payload);
  547. lightUpdate(true, mqttForward());
  548. return;
  549. }
  550. // Color temperature in kelvins
  551. if (t.equals(MQTT_TOPIC_KELVIN)) {
  552. _lightAdjustKelvin(payload);
  553. lightUpdate(true, mqttForward());
  554. return;
  555. }
  556. // Color
  557. if (t.equals(MQTT_TOPIC_COLOR_RGB)) {
  558. lightColor(payload, true);
  559. lightUpdate(true, mqttForward());
  560. return;
  561. }
  562. if (t.equals(MQTT_TOPIC_COLOR_HSV)) {
  563. lightColor(payload, false);
  564. lightUpdate(true, mqttForward());
  565. return;
  566. }
  567. // Brightness
  568. if (t.equals(MQTT_TOPIC_BRIGHTNESS)) {
  569. _lightAdjustBrightness(payload);
  570. lightUpdate(true, mqttForward());
  571. return;
  572. }
  573. // Transitions
  574. if (t.equals(MQTT_TOPIC_TRANSITION)) {
  575. lightTransitionTime(atol(payload));
  576. return;
  577. }
  578. // Channel
  579. if (t.startsWith(MQTT_TOPIC_CHANNEL)) {
  580. unsigned int channelID = t.substring(strlen(MQTT_TOPIC_CHANNEL)+1).toInt();
  581. if (channelID >= _light_channel.size()) {
  582. DEBUG_MSG_P(PSTR("[LIGHT] Wrong channelID (%d)\n"), channelID);
  583. return;
  584. }
  585. _lightAdjustChannel(channelID, payload);
  586. lightUpdate(true, mqttForward());
  587. return;
  588. }
  589. }
  590. }
  591. void lightMQTT() {
  592. char buffer[20];
  593. if (_light_has_color) {
  594. // Color
  595. if (getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1) {
  596. _toRGB(buffer, sizeof(buffer), true);
  597. } else {
  598. _toLong(buffer, sizeof(buffer), true);
  599. }
  600. mqttSend(MQTT_TOPIC_COLOR_RGB, buffer);
  601. _toHSV(buffer, sizeof(buffer));
  602. mqttSend(MQTT_TOPIC_COLOR_HSV, buffer);
  603. }
  604. if (_light_has_color || _light_use_cct) {
  605. // Mireds
  606. snprintf_P(buffer, sizeof(buffer), PSTR("%d"), _light_mireds);
  607. mqttSend(MQTT_TOPIC_MIRED, buffer);
  608. }
  609. // Channels
  610. for (unsigned int i=0; i < _light_channel.size(); i++) {
  611. itoa(_light_channel[i].target, buffer, 10);
  612. mqttSend(MQTT_TOPIC_CHANNEL, i, buffer);
  613. }
  614. // Brightness
  615. snprintf_P(buffer, sizeof(buffer), PSTR("%d"), _light_brightness);
  616. mqttSend(MQTT_TOPIC_BRIGHTNESS, buffer);
  617. }
  618. void lightMQTTGroup() {
  619. const String mqtt_group_color = getSetting("mqttGroupColor");
  620. if (mqtt_group_color.length()) {
  621. mqttSendRaw(mqtt_group_color.c_str(), _toCSV(false).c_str());
  622. }
  623. }
  624. #endif
  625. // -----------------------------------------------------------------------------
  626. // Broker
  627. // -----------------------------------------------------------------------------
  628. #if BROKER_SUPPORT
  629. void lightBroker() {
  630. char buffer[10];
  631. for (unsigned int i=0; i < _light_channel.size(); i++) {
  632. itoa(_light_channel[i].inputValue, buffer, 10);
  633. brokerPublish(BROKER_MSG_TYPE_STATUS, MQTT_TOPIC_CHANNEL, i, buffer);
  634. }
  635. }
  636. #endif
  637. // -----------------------------------------------------------------------------
  638. // API
  639. // -----------------------------------------------------------------------------
  640. size_t lightChannels() {
  641. return _light_channel.size();
  642. }
  643. bool lightHasColor() {
  644. return _light_has_color;
  645. }
  646. bool lightUseCCT() {
  647. return _light_use_cct;
  648. }
  649. void _lightComms(const unsigned char mask) {
  650. // Report color and brightness to MQTT broker
  651. #if MQTT_SUPPORT
  652. if (mask & Light::COMMS_NORMAL) lightMQTT();
  653. if (mask & Light::COMMS_GROUP) lightMQTTGroup();
  654. #endif
  655. // Report color to WS clients (using current brightness setting)
  656. #if WEB_SUPPORT
  657. wsPost(_lightWebSocketStatus);
  658. #endif
  659. // Report channels to local broker
  660. #if BROKER_SUPPORT
  661. lightBroker();
  662. #endif
  663. }
  664. void lightUpdate(bool save, bool forward, bool group_forward) {
  665. // Calculate values based on inputs and brightness
  666. _light_brightness_func();
  667. // Only update if a channel has changed
  668. if (!_light_dirty) return;
  669. _light_dirty = false;
  670. // Update channels
  671. for (unsigned int i=0; i < _light_channel.size(); i++) {
  672. _light_channel[i].target = _light_state && _light_channel[i].state ? _light_channel[i].value : 0;
  673. //DEBUG_MSG_P("[LIGHT] Channel #%u target value: %u\n", i, _light_channel[i].target);
  674. }
  675. // Channel transition will be handled by the provider function
  676. // User can configure total transition time, step time is a fixed value
  677. const unsigned long steps = _light_use_transitions ? _light_transition_time / LIGHT_TRANSITION_STEP : 1;
  678. _light_transition_ticker.once_ms(LIGHT_TRANSITION_STEP, _lightProviderScheduleUpdate, steps);
  679. // Delay every communication 100ms to avoid jamming
  680. const unsigned char mask =
  681. ((forward) ? Light::COMMS_NORMAL : Light::COMMS_NONE) |
  682. ((group_forward) ? Light::COMMS_GROUP : Light::COMMS_NONE);
  683. _light_comms_ticker.once_ms(LIGHT_COMMS_DELAY, _lightComms, mask);
  684. _lightSaveRtcmem();
  685. #if LIGHT_SAVE_ENABLED
  686. // Delay saving to EEPROM 5 seconds to avoid wearing it out unnecessarily
  687. if (save) _light_save_ticker.once(LIGHT_SAVE_DELAY, _lightSaveSettings);
  688. #endif
  689. };
  690. void lightUpdate(bool save, bool forward) {
  691. lightUpdate(save, forward, true);
  692. }
  693. #if LIGHT_SAVE_ENABLED == 0
  694. void lightSave() {
  695. _lightSaveSettings();
  696. }
  697. #endif
  698. void lightState(unsigned char i, bool state) {
  699. if (_light_channel[i].state != state) {
  700. _light_channel[i].state = state;
  701. _light_dirty = true;
  702. }
  703. }
  704. bool lightState(unsigned char i) {
  705. return _light_channel[i].state;
  706. }
  707. void lightState(bool state) {
  708. if (_light_state != state) {
  709. _light_state = state;
  710. _light_dirty = true;
  711. }
  712. }
  713. bool lightState() {
  714. return _light_state;
  715. }
  716. void lightColor(const char * color, bool rgb) {
  717. DEBUG_MSG_P(PSTR("[LIGHT] %s: %s\n"), rgb ? "RGB" : "HSV", color);
  718. if (rgb) {
  719. _fromRGB(color);
  720. } else {
  721. _fromHSV(color);
  722. }
  723. }
  724. void lightColor(const char * color) {
  725. lightColor(color, true);
  726. }
  727. void lightColor(unsigned long color) {
  728. _fromLong(color, false);
  729. }
  730. String lightColor(bool rgb) {
  731. char str[12];
  732. if (rgb) {
  733. _toRGB(str, sizeof(str));
  734. } else {
  735. _toHSV(str, sizeof(str));
  736. }
  737. return String(str);
  738. }
  739. String lightColor() {
  740. return lightColor(true);
  741. }
  742. long lightChannel(unsigned char id) {
  743. if (id <= _light_channel.size()) {
  744. return _light_channel[id].inputValue;
  745. }
  746. return 0;
  747. }
  748. void lightChannel(unsigned char id, long value) {
  749. if (id > _light_channel.size()) return;
  750. _setInputValue(id, constrain(value, Light::VALUE_MIN, Light::VALUE_MAX));
  751. }
  752. void lightChannelStep(unsigned char id, long steps, long multiplier) {
  753. lightChannel(id, static_cast<int>(lightChannel(id)) + (steps * multiplier));
  754. }
  755. long lightBrightness() {
  756. return _light_brightness;
  757. }
  758. void lightBrightness(long brightness) {
  759. _light_brightness = constrain(brightness, Light::BRIGHTNESS_MIN, Light::BRIGHTNESS_MAX);
  760. }
  761. void lightBrightnessStep(long steps, long multiplier) {
  762. lightBrightness(static_cast<int>(_light_brightness) + (steps * multiplier));
  763. }
  764. unsigned int lightTransitionTime() {
  765. if (_light_use_transitions) {
  766. return _light_transition_time;
  767. } else {
  768. return 0;
  769. }
  770. }
  771. void lightTransitionTime(unsigned long m) {
  772. if (0 == m) {
  773. _light_use_transitions = false;
  774. } else {
  775. _light_use_transitions = true;
  776. _light_transition_time = m;
  777. }
  778. setSetting("useTransitions", _light_use_transitions);
  779. setSetting("lightTime", _light_transition_time);
  780. saveSettings();
  781. }
  782. // -----------------------------------------------------------------------------
  783. // SETUP
  784. // -----------------------------------------------------------------------------
  785. #if WEB_SUPPORT
  786. bool _lightWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  787. if (strncmp(key, "light", 5) == 0) return true;
  788. if (strncmp(key, "use", 3) == 0) return true;
  789. return false;
  790. }
  791. void _lightWebSocketStatus(JsonObject& root) {
  792. if (_light_has_color) {
  793. if (getSetting("useRGB", LIGHT_USE_RGB).toInt() == 1) {
  794. root["rgb"] = lightColor(true);
  795. } else {
  796. root["hsv"] = lightColor(false);
  797. }
  798. }
  799. if (_light_use_cct) {
  800. root["useCCT"] = _light_use_cct;
  801. root["mireds"] = _light_mireds;
  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 _lightInitCommands() {
  930. terminalRegisterCommand(F("BRIGHTNESS"), [](Embedis* e) {
  931. if (e->argc > 1) {
  932. _lightAdjustBrightness(e->argv[1]);
  933. lightUpdate(true, true);
  934. }
  935. DEBUG_MSG_P(PSTR("Brightness: %u\n"), lightBrightness());
  936. terminalOK();
  937. });
  938. terminalRegisterCommand(F("CHANNEL"), [](Embedis* e) {
  939. if (e->argc < 2) {
  940. terminalError(F("CHANNEL <ID> [<VALUE>]"));
  941. return;
  942. }
  943. const int id = String(e->argv[1]).toInt();
  944. if (id < 0 || id >= lightChannels()) {
  945. terminalError(F("Channel value out of range"));
  946. return;
  947. }
  948. if (e->argc > 2) {
  949. _lightAdjustChannel(id, e->argv[2]);
  950. lightUpdate(true, true);
  951. }
  952. DEBUG_MSG_P(PSTR("Channel #%u (%s): %d\n"), id, lightDesc(id).c_str(), lightChannel(id));
  953. terminalOK();
  954. });
  955. terminalRegisterCommand(F("COLOR"), [](Embedis* e) {
  956. if (e->argc > 1) {
  957. lightColor(e->argv[1]);
  958. lightUpdate(true, true);
  959. }
  960. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  961. terminalOK();
  962. });
  963. terminalRegisterCommand(F("KELVIN"), [](Embedis* e) {
  964. if (e->argc > 1) {
  965. _lightAdjustKelvin(e->argv[1]);
  966. lightUpdate(true, true);
  967. }
  968. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  969. terminalOK();
  970. });
  971. terminalRegisterCommand(F("MIRED"), [](Embedis* e) {
  972. if (e->argc > 1) {
  973. _lightAdjustMireds(e->argv[1]);
  974. lightUpdate(true, true);
  975. }
  976. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  977. terminalOK();
  978. });
  979. }
  980. #endif // TERMINAL_SUPPORT
  981. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  982. const unsigned long _light_iomux[16] PROGMEM = {
  983. PERIPHS_IO_MUX_GPIO0_U, PERIPHS_IO_MUX_U0TXD_U, PERIPHS_IO_MUX_GPIO2_U, PERIPHS_IO_MUX_U0RXD_U,
  984. PERIPHS_IO_MUX_GPIO4_U, PERIPHS_IO_MUX_GPIO5_U, PERIPHS_IO_MUX_SD_CLK_U, PERIPHS_IO_MUX_SD_DATA0_U,
  985. PERIPHS_IO_MUX_SD_DATA1_U, PERIPHS_IO_MUX_SD_DATA2_U, PERIPHS_IO_MUX_SD_DATA3_U, PERIPHS_IO_MUX_SD_CMD_U,
  986. PERIPHS_IO_MUX_MTDI_U, PERIPHS_IO_MUX_MTCK_U, PERIPHS_IO_MUX_MTMS_U, PERIPHS_IO_MUX_MTDO_U
  987. };
  988. const unsigned long _light_iofunc[16] PROGMEM = {
  989. FUNC_GPIO0, FUNC_GPIO1, FUNC_GPIO2, FUNC_GPIO3,
  990. FUNC_GPIO4, FUNC_GPIO5, FUNC_GPIO6, FUNC_GPIO7,
  991. FUNC_GPIO8, FUNC_GPIO9, FUNC_GPIO10, FUNC_GPIO11,
  992. FUNC_GPIO12, FUNC_GPIO13, FUNC_GPIO14, FUNC_GPIO15
  993. };
  994. #endif
  995. void _lightConfigure() {
  996. _light_has_color = getSetting("useColor", LIGHT_USE_COLOR).toInt() == 1;
  997. if (_light_has_color && (_light_channel.size() < 3)) {
  998. _light_has_color = false;
  999. setSetting("useColor", _light_has_color);
  1000. }
  1001. _light_use_white = getSetting("useWhite", LIGHT_USE_WHITE).toInt() == 1;
  1002. if (_light_use_white && (_light_channel.size() < 4) && (_light_channel.size() != 2)) {
  1003. _light_use_white = false;
  1004. setSetting("useWhite", _light_use_white);
  1005. }
  1006. if (_light_has_color) {
  1007. if (_light_use_white) {
  1008. _light_brightness_func = _lightApplyBrightnessColor;
  1009. } else {
  1010. _light_brightness_func = []() { _lightApplyBrightness(3); };
  1011. }
  1012. } else {
  1013. _light_brightness_func = []() { _lightApplyBrightness(); };
  1014. }
  1015. _light_use_cct = getSetting("useCCT", LIGHT_USE_CCT).toInt() == 1;
  1016. if (_light_use_cct && (((_light_channel.size() < 5) && (_light_channel.size() != 2)) || !_light_use_white)) {
  1017. _light_use_cct = false;
  1018. setSetting("useCCT", _light_use_cct);
  1019. }
  1020. if (_light_use_cct) {
  1021. _light_mireds_cold = getSetting("lightColdMired", LIGHT_COLDWHITE_MIRED).toInt();
  1022. _light_mireds_warm = getSetting("lightWarmMired", LIGHT_WARMWHITE_MIRED).toInt();
  1023. _light_kelvin_cold = (1000000L / _light_mireds_cold);
  1024. _light_kelvin_warm = (1000000L / _light_mireds_warm);
  1025. }
  1026. _light_use_gamma = getSetting("useGamma", LIGHT_USE_GAMMA).toInt() == 1;
  1027. _light_use_transitions = getSetting("useTransitions", LIGHT_USE_TRANSITIONS).toInt() == 1;
  1028. _light_transition_time = getSetting("lightTime", LIGHT_TRANSITION_TIME).toInt();
  1029. }
  1030. void lightSetup() {
  1031. #ifdef LIGHT_ENABLE_PIN
  1032. pinMode(LIGHT_ENABLE_PIN, OUTPUT);
  1033. digitalWrite(LIGHT_ENABLE_PIN, HIGH);
  1034. #endif
  1035. _light_channel.reserve(LIGHT_CHANNELS);
  1036. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  1037. _my92xx = new my92xx(MY92XX_MODEL, MY92XX_CHIPS, MY92XX_DI_PIN, MY92XX_DCKI_PIN, MY92XX_COMMAND);
  1038. for (unsigned char i=0; i<LIGHT_CHANNELS; i++) {
  1039. _light_channel.push_back((channel_t) {0, false, true, 0, 0, 0});
  1040. }
  1041. #endif
  1042. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  1043. #ifdef LIGHT_CH1_PIN
  1044. _light_channel.push_back((channel_t) {LIGHT_CH1_PIN, LIGHT_CH1_INVERSE, true, 0, 0, 0});
  1045. #endif
  1046. #ifdef LIGHT_CH2_PIN
  1047. _light_channel.push_back((channel_t) {LIGHT_CH2_PIN, LIGHT_CH2_INVERSE, true, 0, 0, 0});
  1048. #endif
  1049. #ifdef LIGHT_CH3_PIN
  1050. _light_channel.push_back((channel_t) {LIGHT_CH3_PIN, LIGHT_CH3_INVERSE, true, 0, 0, 0});
  1051. #endif
  1052. #ifdef LIGHT_CH4_PIN
  1053. _light_channel.push_back((channel_t) {LIGHT_CH4_PIN, LIGHT_CH4_INVERSE, true, 0, 0, 0});
  1054. #endif
  1055. #ifdef LIGHT_CH5_PIN
  1056. _light_channel.push_back((channel_t) {LIGHT_CH5_PIN, LIGHT_CH5_INVERSE, true, 0, 0, 0});
  1057. #endif
  1058. uint32 pwm_duty_init[PWM_CHANNEL_NUM_MAX];
  1059. uint32 io_info[PWM_CHANNEL_NUM_MAX][3];
  1060. for (unsigned int i=0; i < _light_channel.size(); i++) {
  1061. const auto pin = _light_channel.at(i).pin;
  1062. pwm_duty_init[i] = 0;
  1063. io_info[i][0] = pgm_read_dword(&_light_iomux[pin]);
  1064. io_info[i][1] = pgm_read_dword(&_light_iofunc[pin]);
  1065. io_info[i][2] = pin;
  1066. pinMode(pin, OUTPUT);
  1067. }
  1068. pwm_init(LIGHT_MAX_PWM, pwm_duty_init, PWM_CHANNEL_NUM_MAX, io_info);
  1069. pwm_start();
  1070. #endif
  1071. DEBUG_MSG_P(PSTR("[LIGHT] LIGHT_PROVIDER = %d\n"), LIGHT_PROVIDER);
  1072. DEBUG_MSG_P(PSTR("[LIGHT] Number of channels: %d\n"), _light_channel.size());
  1073. _lightConfigure();
  1074. if (rtcmemStatus()) {
  1075. _lightRestoreRtcmem();
  1076. } else {
  1077. _lightRestoreSettings();
  1078. }
  1079. lightUpdate(false, false);
  1080. #if WEB_SUPPORT
  1081. wsRegister()
  1082. .onVisible(_lightWebSocketOnVisible)
  1083. .onConnected(_lightWebSocketOnConnected)
  1084. .onAction(_lightWebSocketOnAction)
  1085. .onKeyCheck(_lightWebSocketOnKeyCheck);
  1086. #endif
  1087. #if API_SUPPORT
  1088. _lightAPISetup();
  1089. #endif
  1090. #if MQTT_SUPPORT
  1091. mqttRegister(_lightMQTTCallback);
  1092. #endif
  1093. #if TERMINAL_SUPPORT
  1094. _lightInitCommands();
  1095. #endif
  1096. // Main callbacks
  1097. espurnaRegisterReload([]() {
  1098. #if LIGHT_SAVE_ENABLED == 0
  1099. lightSave();
  1100. #endif
  1101. _lightConfigure();
  1102. });
  1103. }
  1104. #endif // LIGHT_PROVIDER != LIGHT_PROVIDER_NONE