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.

1113 lines
32 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
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-2018 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  6. #include <Ticker.h>
  7. #include <ArduinoJson.h>
  8. #include <vector>
  9. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  10. #define PWM_CHANNEL_NUM_MAX LIGHT_CHANNELS
  11. extern "C" {
  12. #include "libs/pwm.h"
  13. }
  14. #endif
  15. // -----------------------------------------------------------------------------
  16. Ticker _light_save_ticker;
  17. Ticker _light_transition_ticker;
  18. typedef struct {
  19. unsigned char pin;
  20. bool reverse;
  21. bool state;
  22. unsigned char value; // target or nominal value
  23. unsigned char original; // original value before RGBW calculation
  24. bool useOriginal; // determine if it should use the original or value variable
  25. unsigned char shadow; // represented value
  26. double current; // transition value
  27. } channel_t;
  28. std::vector<channel_t> _light_channel;
  29. bool _light_state = false;
  30. bool _light_use_transitions = false;
  31. bool _light_has_color = false;
  32. bool _light_use_white = false;
  33. bool _light_use_gamma = false;
  34. unsigned long _light_steps_left = 1;
  35. unsigned int _light_brightness = LIGHT_MAX_BRIGHTNESS;
  36. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  37. #include <my92xx.h>
  38. my92xx * _my92xx;
  39. ARRAYINIT(unsigned char, _light_channel_map, MY92XX_MAPPING);
  40. #endif
  41. // Gamma Correction lookup table (8 bit)
  42. // TODO: move to PROGMEM
  43. const unsigned char _light_gamma_table[] = {
  44. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  45. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
  46. 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6,
  47. 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 11,
  48. 12, 12, 13, 13, 14, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19,
  49. 19, 20, 20, 21, 22, 22, 23, 23, 24, 25, 25, 26, 26, 27, 28, 28,
  50. 29, 30, 30, 31, 32, 33, 33, 34, 35, 35, 36, 37, 38, 39, 39, 40,
  51. 41, 42, 43, 43, 44, 45, 46, 47, 48, 49, 50, 50, 51, 52, 53, 54,
  52. 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 71,
  53. 72, 73, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84, 86, 87, 88, 89,
  54. 91, 92, 93, 94, 96, 97, 98, 100, 101, 102, 104, 105, 106, 108, 109, 110,
  55. 112, 113, 115, 116, 118, 119, 121, 122, 123, 125, 126, 128, 130, 131, 133, 134,
  56. 136, 137, 139, 140, 142, 144, 145, 147, 149, 150, 152, 154, 155, 157, 159, 160,
  57. 162, 164, 166, 167, 169, 171, 173, 175, 176, 178, 180, 182, 184, 186, 187, 189,
  58. 191, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 217, 219, 221,
  59. 223, 225, 227, 229, 231, 233, 235, 238, 240, 242, 244, 246, 248, 251, 253, 255
  60. };
  61. // -----------------------------------------------------------------------------
  62. // UTILS
  63. // -----------------------------------------------------------------------------
  64. // Returns the "correct" value for each channel
  65. unsigned char _getChannel(char i) {
  66. if (_light_channel[i].useOriginal) {
  67. // Reset value when user disable the white channel without rebooting:
  68. if (!_light_use_white) {
  69. _light_channel[i].value = _light_channel[i].original;
  70. _light_channel[i].useOriginal = false;
  71. _light_channel[i].original = 0;
  72. return _light_channel[i].value;
  73. }
  74. return _light_channel[i].original;
  75. }
  76. return _light_channel[i].value;
  77. }
  78. void _setWhite() {
  79. if (!_light_use_white) return;
  80. unsigned int white, max_in, max_out;
  81. double factor = 0;
  82. white = std::min(_light_channel[0].value, std::min(_light_channel[1].value, _light_channel[2].value));
  83. max_in = std::max(_light_channel[0].value, std::max(_light_channel[1].value, _light_channel[2].value));
  84. for (unsigned int i=0; i < 3; i++) {
  85. _light_channel[i].useOriginal = true;
  86. _light_channel[i].original = _light_channel[i].value;
  87. _light_channel[i].value -= white;
  88. }
  89. _light_channel[3].value = white;
  90. max_out = std::max(std::max(_light_channel[0].value, _light_channel[1].value), std::max(_light_channel[2].value, _light_channel[3].value));
  91. if (max_out > 0) {
  92. factor = (double) (max_in / max_out);
  93. }
  94. for (unsigned int i=0; i < 4; i++) {
  95. _light_channel[i].value = round(_light_channel[i].value * factor);;
  96. }
  97. }
  98. //Return 4 (RGBW) or 3 (RGB)
  99. unsigned char _getRGBChannelWidth() {
  100. return _light_use_white ? 4 : 3;
  101. }
  102. void _fromLong(unsigned long value, bool brightness) {
  103. if (brightness) {
  104. _light_channel[0].value = (value >> 24) & 0xFF;
  105. _light_channel[1].value = (value >> 16) & 0xFF;
  106. _light_channel[2].value = (value >> 8) & 0xFF;
  107. _light_brightness = (value & 0xFF) * LIGHT_MAX_BRIGHTNESS / 255;
  108. } else {
  109. _light_channel[0].value = (value >> 16) & 0xFF;
  110. _light_channel[1].value = (value >> 8) & 0xFF;
  111. _light_channel[2].value = (value) & 0xFF;
  112. }
  113. }
  114. void _fromRGB(const char * rgb) {
  115. char * p = (char *) rgb;
  116. if (strlen(p) == 0) return;
  117. switch (p[0]) {
  118. case '#': // HEX Value
  119. if (_light_has_color) {
  120. ++p;
  121. unsigned long value = strtoul(p, NULL, 16);
  122. // RGBA values are interpreted like RGB + brightness
  123. _fromLong(value, strlen(p) > 7);
  124. _setWhite();
  125. }
  126. break;
  127. case 'M': // Mired Value
  128. if (_light_has_color) {
  129. unsigned long mireds = atol(p + 1);
  130. _fromMireds(mireds);
  131. //_setWhite();
  132. }
  133. break;
  134. case 'K': // Kelvin Value
  135. if (_light_has_color) {
  136. unsigned long kelvin = atol(p + 1);
  137. _fromKelvin(kelvin);
  138. //_setWhite();
  139. }
  140. break;
  141. default: // assume decimal values separated by commas
  142. char * tok;
  143. unsigned char count = 0;
  144. unsigned char channels = _light_channel.size();
  145. tok = strtok(p, ",");
  146. while (tok != NULL) {
  147. _light_channel[count].value = atoi(tok);
  148. if (++count == channels) break;
  149. tok = strtok(NULL, ",");
  150. }
  151. // RGB but less than 3 values received
  152. if (_light_has_color && (count < 3)) {
  153. _light_channel[1].value = _light_channel[0].value;
  154. _light_channel[2].value = _light_channel[0].value;
  155. }
  156. _setWhite();
  157. break;
  158. }
  159. }
  160. void _toRGB(char * rgb, size_t len, bool applyBrightness) {
  161. if (!_light_has_color) return;
  162. float b = applyBrightness ? (float) _light_brightness / LIGHT_MAX_BRIGHTNESS : 1;
  163. unsigned long value = 0;
  164. value += _getChannel(0) * b;
  165. value <<= 8;
  166. value += _getChannel(1) * b;
  167. value <<= 8;
  168. value += _getChannel(2) * b;
  169. snprintf_P(rgb, len, PSTR("#%06X"), value);
  170. }
  171. void _toRGB(char * rgb, size_t len) {
  172. _toRGB(rgb, len, false);
  173. }
  174. // HSV string is expected to be "H,S,V", where:
  175. // 0 <= H <= 360
  176. // 0 <= S <= 100
  177. // 0 <= V <= 100
  178. void _fromHSV(const char * hsv) {
  179. char * ptr = (char *) hsv;
  180. if (strlen(ptr) == 0) return;
  181. if (!_light_has_color) return;
  182. char * tok;
  183. unsigned char count = 0;
  184. unsigned int value[3] = {0};
  185. tok = strtok(ptr, ",");
  186. while (tok != NULL) {
  187. value[count] = atoi(tok);
  188. if (++count == 3) break;
  189. tok = strtok(NULL, ",");
  190. }
  191. if (count != 3) return;
  192. // HSV to RGB transformation -----------------------------------------------
  193. double h = (value[0] == 360) ? 0 : (double) value[0] / 60.0;
  194. double f = (h - floor(h));
  195. double s = (double) value[1] / 100.0;
  196. unsigned char v = round((double) value[2] * 255.0 / 100.0);
  197. unsigned char p = round(v * (1.0 - s));
  198. unsigned char q = round(v * (1.0 - s * f));
  199. unsigned char t = round(v * (1.0 - s * (1.0 - f)));
  200. switch (int(h)) {
  201. case 0:
  202. _light_channel[0].value = v;
  203. _light_channel[1].value = t;
  204. _light_channel[2].value = p;
  205. break;
  206. case 1:
  207. _light_channel[0].value = q;
  208. _light_channel[1].value = v;
  209. _light_channel[2].value = p;
  210. break;
  211. case 2:
  212. _light_channel[0].value = p;
  213. _light_channel[1].value = v;
  214. _light_channel[2].value = t;
  215. break;
  216. case 3:
  217. _light_channel[0].value = p;
  218. _light_channel[1].value = q;
  219. _light_channel[2].value = v;
  220. break;
  221. case 4:
  222. _light_channel[0].value = t;
  223. _light_channel[1].value = p;
  224. _light_channel[2].value = v;
  225. break;
  226. case 5:
  227. _light_channel[0].value = v;
  228. _light_channel[1].value = p;
  229. _light_channel[2].value = q;
  230. break;
  231. default:
  232. _light_channel[0].value = 0;
  233. _light_channel[1].value = 0;
  234. _light_channel[2].value = 0;
  235. break;
  236. }
  237. _setWhite();
  238. _light_brightness = LIGHT_MAX_BRIGHTNESS;
  239. }
  240. void _toHSV(char * hsv, size_t len) {
  241. if (!_light_has_color) return;
  242. double min, max;
  243. double h, s, v;
  244. double r = (double) _getChannel(0) / 255.0;
  245. double g = (double) _getChannel(1) / 255.0;
  246. double b = (double) _getChannel(2) / 255.0;
  247. min = (r < g) ? r : g;
  248. min = (min < b) ? min : b;
  249. max = (r > g) ? r : g;
  250. max = (max > b) ? max : b;
  251. v = 100.0 * max;
  252. if (v == 0) {
  253. h = s = 0;
  254. } else {
  255. s = 100.0 * (max - min) / max;
  256. if (s == 0) {
  257. h = 0;
  258. } else {
  259. if (max == r) {
  260. if (g >= b) {
  261. h = 0.0 + 60.0 * (g - b) / (max - min);
  262. } else {
  263. h = 360.0 + 60.0 * (g - b) / (max - min);
  264. }
  265. } else if (max == g) {
  266. h = 120.0 + 60.0 * (b - r) / (max - min);
  267. } else {
  268. h = 240.0 + 60.0 * (r - g) / (max - min);
  269. }
  270. }
  271. }
  272. // String
  273. snprintf_P(hsv, len, PSTR("%d,%d,%d"), round(h), round(s), round(v));
  274. }
  275. void _toLong(char * color, size_t len, bool applyBrightness) {
  276. if (!_light_has_color) return;
  277. float b = applyBrightness ? (float) _light_brightness / LIGHT_MAX_BRIGHTNESS : 1;
  278. snprintf_P(color, len, PSTR("%d,%d,%d"),
  279. (int) (_getChannel(0) * b),
  280. (int) (_getChannel(1) * b),
  281. (int) (_getChannel(2) * b)
  282. );
  283. }
  284. void _toLong(char * color, size_t len) {
  285. _toLong(color, len, false);
  286. }
  287. void _toCSV(char * buffer, size_t len, bool applyBrightness) {
  288. char num[10];
  289. float b = applyBrightness ? (float) _light_brightness / LIGHT_MAX_BRIGHTNESS : 1;
  290. for (unsigned char i=0; i<_light_channel.size(); i++) {
  291. itoa(_light_channel[i].value * b, num, 10);
  292. if (i>0) strncat(buffer, ",", len--);
  293. strncat(buffer, num, len);
  294. len = len - strlen(num);
  295. }
  296. }
  297. // Thanks to Sacha Telgenhof for sharing this code in his AiLight library
  298. // https://github.com/stelgenhof/AiLight
  299. void _fromKelvin(unsigned long kelvin) {
  300. // Check we have RGB channels
  301. if (!_light_has_color) return;
  302. // Calculate colors
  303. unsigned int red = (kelvin <= 66)
  304. ? LIGHT_MAX_VALUE
  305. : 329.698727446 * pow((kelvin - 60), -0.1332047592);
  306. unsigned int green = (kelvin <= 66)
  307. ? 99.4708025861 * log(kelvin) - 161.1195681661
  308. : 288.1221695283 * pow(kelvin, -0.0755148492);
  309. unsigned int blue = (kelvin >= 66)
  310. ? LIGHT_MAX_VALUE
  311. : ((kelvin <= 19)
  312. ? 0
  313. : 138.5177312231 * log(kelvin - 10) - 305.0447927307);
  314. // Save values
  315. _light_channel[0].value = constrain(red, 0, LIGHT_MAX_VALUE);
  316. _light_channel[1].value = constrain(green, 0, LIGHT_MAX_VALUE);
  317. _light_channel[2].value = constrain(blue, 0, LIGHT_MAX_VALUE);
  318. }
  319. // Color temperature is measured in mireds (kelvin = 1e6/mired)
  320. void _fromMireds(unsigned long mireds) {
  321. if (mireds == 0) mireds = 1;
  322. unsigned long kelvin = constrain(1000000UL / mireds, 1000, 40000) / 100;
  323. _fromKelvin(kelvin);
  324. }
  325. // -----------------------------------------------------------------------------
  326. // PROVIDER
  327. // -----------------------------------------------------------------------------
  328. unsigned int _toPWM(unsigned long value, bool gamma, bool reverse) {
  329. value = constrain(value, 0, LIGHT_MAX_VALUE);
  330. if (gamma) value = _light_gamma_table[value];
  331. if (LIGHT_MAX_VALUE != LIGHT_LIMIT_PWM) value = map(value, 0, LIGHT_MAX_VALUE, 0, LIGHT_LIMIT_PWM);
  332. if (reverse) value = LIGHT_LIMIT_PWM - value;
  333. return value;
  334. }
  335. // Returns a PWM value for the given channel ID
  336. unsigned int _toPWM(unsigned char id) {
  337. bool useGamma = _light_use_gamma && _light_has_color && (id < _getRGBChannelWidth());
  338. return _toPWM(_light_channel[id].shadow, useGamma, _light_channel[id].reverse);
  339. }
  340. void _shadow() {
  341. // Update transition ticker
  342. _light_steps_left--;
  343. if (_light_steps_left == 0) _light_transition_ticker.detach();
  344. // Update 4 Channels if RGBW else 3
  345. unsigned char channels = _getRGBChannelWidth();
  346. // Transitions
  347. unsigned char target;
  348. for (unsigned int i=0; i < _light_channel.size(); i++) {
  349. if (_light_state && _light_channel[i].state) {
  350. target = _light_channel[i].value;
  351. if ((_light_brightness < LIGHT_MAX_BRIGHTNESS) && _light_has_color && (i < channels)) {
  352. target *= ((float) _light_brightness / LIGHT_MAX_BRIGHTNESS);
  353. }
  354. } else {
  355. target = 0;
  356. }
  357. if (_light_steps_left == 0) {
  358. _light_channel[i].current = target;
  359. } else {
  360. double difference = (double) (target - _light_channel[i].current) / (_light_steps_left + 1);
  361. _light_channel[i].current = _light_channel[i].current + difference;
  362. }
  363. _light_channel[i].shadow = _light_channel[i].current;
  364. }
  365. }
  366. void _lightProviderUpdate() {
  367. _shadow();
  368. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  369. for (unsigned char i=0; i<_light_channel.size(); i++) {
  370. _my92xx->setChannel(_light_channel_map[i], _toPWM(i));
  371. }
  372. _my92xx->setState(true);
  373. _my92xx->update();
  374. #endif
  375. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  376. for (unsigned int i=0; i < _light_channel.size(); i++) {
  377. pwm_set_duty(_toPWM(i), i);
  378. }
  379. pwm_start();
  380. #endif
  381. }
  382. // -----------------------------------------------------------------------------
  383. // PERSISTANCE
  384. // -----------------------------------------------------------------------------
  385. void _lightColorSave() {
  386. // TODO: Remove this once this code was in a stable release
  387. // This force set ch3 to 0 which could be not zero when you update from a old version
  388. if (_light_use_white) {
  389. setSetting("ch", 3, 0);
  390. }
  391. for (unsigned int i=0; i < _light_channel.size(); i++) {
  392. if (_light_use_white && (i == 3)) continue; //Don't save white channel.
  393. setSetting("ch", i, _getChannel(i));
  394. }
  395. setSetting("brightness", _light_brightness);
  396. saveSettings();
  397. }
  398. void _lightColorRestore() {
  399. for (unsigned int i=0; i < _light_channel.size(); i++) {
  400. _light_channel[i].value = getSetting("ch", i, i==0 ? 255 : 0).toInt();
  401. }
  402. _setWhite();
  403. _light_brightness = getSetting("brightness", LIGHT_MAX_BRIGHTNESS).toInt();
  404. lightUpdate(false, false);
  405. }
  406. // -----------------------------------------------------------------------------
  407. // MQTT
  408. // -----------------------------------------------------------------------------
  409. #if MQTT_SUPPORT
  410. void _lightMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  411. String mqtt_group_color = getSetting("mqttGroupColor");
  412. if (type == MQTT_CONNECT_EVENT) {
  413. if (_light_has_color) {
  414. mqttSubscribe(MQTT_TOPIC_BRIGHTNESS);
  415. mqttSubscribe(MQTT_TOPIC_MIRED);
  416. mqttSubscribe(MQTT_TOPIC_KELVIN);
  417. mqttSubscribe(MQTT_TOPIC_COLOR); // DEPRECATE
  418. mqttSubscribe(MQTT_TOPIC_COLOR_RGB);
  419. mqttSubscribe(MQTT_TOPIC_COLOR_HSV);
  420. }
  421. // Group color
  422. if (mqtt_group_color.length() > 0) mqttSubscribeRaw(mqtt_group_color.c_str());
  423. // Channels
  424. char buffer[strlen(MQTT_TOPIC_CHANNEL) + 3];
  425. snprintf_P(buffer, sizeof(buffer), PSTR("%s/+"), MQTT_TOPIC_CHANNEL);
  426. mqttSubscribe(buffer);
  427. }
  428. if (type == MQTT_MESSAGE_EVENT) {
  429. // Group color
  430. if ((mqtt_group_color.length() > 0) & (mqtt_group_color.equals(topic))) {
  431. lightColor(payload, true);
  432. lightUpdate(true, mqttForward(), false);
  433. return;
  434. }
  435. // Match topic
  436. String t = mqttMagnitude((char *) topic);
  437. // Color temperature in mireds
  438. if (t.equals(MQTT_TOPIC_MIRED)) {
  439. _fromMireds(atol(payload));
  440. lightUpdate(true, mqttForward());
  441. return;
  442. }
  443. // Color temperature in kelvins
  444. if (t.equals(MQTT_TOPIC_KELVIN)) {
  445. _fromKelvin(atol(payload));
  446. lightUpdate(true, mqttForward());
  447. return;
  448. }
  449. // Color
  450. if (t.equals(MQTT_TOPIC_COLOR) || t.equals(MQTT_TOPIC_COLOR_RGB)) { // DEPRECATE MQTT_TOPIC_COLOR
  451. lightColor(payload, true);
  452. lightUpdate(true, mqttForward());
  453. return;
  454. }
  455. if (t.equals(MQTT_TOPIC_COLOR_HSV)) {
  456. lightColor(payload, false);
  457. lightUpdate(true, mqttForward());
  458. return;
  459. }
  460. // Brightness
  461. if (t.equals(MQTT_TOPIC_BRIGHTNESS)) {
  462. _light_brightness = constrain(atoi(payload), 0, LIGHT_MAX_BRIGHTNESS);
  463. lightUpdate(true, mqttForward());
  464. return;
  465. }
  466. // Channel
  467. if (t.startsWith(MQTT_TOPIC_CHANNEL)) {
  468. unsigned int channelID = t.substring(strlen(MQTT_TOPIC_CHANNEL)+1).toInt();
  469. if (channelID >= _light_channel.size()) {
  470. DEBUG_MSG_P(PSTR("[LIGHT] Wrong channelID (%d)\n"), channelID);
  471. return;
  472. }
  473. lightChannel(channelID, atoi(payload));
  474. lightUpdate(true, mqttForward());
  475. return;
  476. }
  477. }
  478. }
  479. void lightMQTT() {
  480. char buffer[20];
  481. if (_light_has_color) {
  482. // Color
  483. if (getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1) {
  484. _toRGB(buffer, sizeof(buffer), false);
  485. } else {
  486. _toLong(buffer, sizeof(buffer), false);
  487. }
  488. mqttSend(MQTT_TOPIC_COLOR, buffer); // DEPRECATE
  489. mqttSend(MQTT_TOPIC_COLOR_RGB, buffer);
  490. _toHSV(buffer, sizeof(buffer));
  491. mqttSend(MQTT_TOPIC_COLOR_HSV, buffer);
  492. // Brightness
  493. snprintf_P(buffer, sizeof(buffer), PSTR("%d"), _light_brightness);
  494. mqttSend(MQTT_TOPIC_BRIGHTNESS, buffer);
  495. }
  496. // Channels
  497. for (unsigned int i=0; i < _light_channel.size(); i++) {
  498. itoa(_light_channel[i].value, buffer, 10);
  499. mqttSend(MQTT_TOPIC_CHANNEL, i, buffer);
  500. }
  501. }
  502. void lightMQTTGroup() {
  503. String mqtt_group_color = getSetting("mqttGroupColor");
  504. if (mqtt_group_color.length()>0) {
  505. char buffer[20];
  506. _toCSV(buffer, sizeof(buffer), true);
  507. mqttSendRaw(mqtt_group_color.c_str(), buffer);
  508. }
  509. }
  510. #endif
  511. // -----------------------------------------------------------------------------
  512. // Broker
  513. // -----------------------------------------------------------------------------
  514. #if BROKER_SUPPORT
  515. void lightBroker() {
  516. char buffer[10];
  517. for (unsigned int i=0; i < _light_channel.size(); i++) {
  518. itoa(_light_channel[i].value, buffer, 10);
  519. brokerPublish(MQTT_TOPIC_CHANNEL, i, buffer);
  520. }
  521. }
  522. #endif
  523. // -----------------------------------------------------------------------------
  524. // API
  525. // -----------------------------------------------------------------------------
  526. unsigned char lightChannels() {
  527. return _light_channel.size();
  528. }
  529. bool lightHasColor() {
  530. return _light_has_color;
  531. }
  532. unsigned char lightWhiteChannels() {
  533. return _light_channel.size() % 3;
  534. }
  535. void lightUpdate(bool save, bool forward, bool group_forward) {
  536. // Configure color transition
  537. _light_steps_left = _light_use_transitions ? LIGHT_TRANSITION_STEPS : 1;
  538. _light_transition_ticker.attach_ms(LIGHT_TRANSITION_STEP, _lightProviderUpdate);
  539. // Report channels to local broker
  540. #if BROKER_SUPPORT
  541. lightBroker();
  542. #endif
  543. // Report color & brightness to MQTT broker
  544. #if MQTT_SUPPORT
  545. if (forward) lightMQTT();
  546. if (group_forward) lightMQTTGroup();
  547. #endif
  548. // Report color to WS clients (using current brightness setting)
  549. #if WEB_SUPPORT
  550. wsSend(_lightWebSocketOnSend);
  551. #endif
  552. #if LIGHT_SAVE_ENABLED
  553. // Delay saving to EEPROM 5 seconds to avoid wearing it out unnecessarily
  554. if (save) _light_save_ticker.once(LIGHT_SAVE_DELAY, _lightColorSave);
  555. #endif
  556. };
  557. void lightUpdate(bool save, bool forward) {
  558. lightUpdate(save, forward, true);
  559. }
  560. #if LIGHT_SAVE_ENABLED == 0
  561. void lightSave() {
  562. _lightColorSave();
  563. }
  564. #endif
  565. void lightState(unsigned char i, bool state) {
  566. _light_channel[i].state = state;
  567. }
  568. bool lightState(unsigned char i) {
  569. return _light_channel[i].state;
  570. }
  571. void lightState(bool state) {
  572. _light_state = state;
  573. }
  574. bool lightState() {
  575. return _light_state;
  576. }
  577. void lightColor(const char * color, bool rgb) {
  578. DEBUG_MSG_P(PSTR("[LIGHT] %s: %s\n"), rgb ? "RGB" : "HSV", color);
  579. if (rgb) {
  580. _fromRGB(color);
  581. } else {
  582. _fromHSV(color);
  583. }
  584. }
  585. void lightColor(const char * color) {
  586. lightColor(color, true);
  587. }
  588. void lightColor(unsigned long color) {
  589. _fromLong(color, false);
  590. }
  591. String lightColor(bool rgb) {
  592. char str[12];
  593. if (rgb) {
  594. _toRGB(str, sizeof(str), false);
  595. } else {
  596. _toHSV(str, sizeof(str));
  597. }
  598. return String(str);
  599. }
  600. String lightColor() {
  601. return lightColor(true);
  602. }
  603. unsigned int lightChannel(unsigned char id) {
  604. if (id <= _light_channel.size()) {
  605. return _light_channel[id].value;
  606. }
  607. return 0;
  608. }
  609. void lightChannel(unsigned char id, unsigned int value) {
  610. if (id <= _light_channel.size()) {
  611. _light_channel[id].value = constrain(value, 0, LIGHT_MAX_VALUE);
  612. }
  613. }
  614. unsigned int lightBrightness() {
  615. return _light_brightness;
  616. }
  617. void lightBrightness(int b) {
  618. _light_brightness = constrain(b, 0, LIGHT_MAX_BRIGHTNESS);
  619. }
  620. void lightBrightnessStep(int steps) {
  621. lightBrightness(_light_brightness + steps * LIGHT_STEP);
  622. }
  623. // -----------------------------------------------------------------------------
  624. // SETUP
  625. // -----------------------------------------------------------------------------
  626. #if WEB_SUPPORT
  627. void _lightWebSocketOnSend(JsonObject& root) {
  628. root["colorVisible"] = 1;
  629. root["mqttGroupColor"] = getSetting("mqttGroupColor");
  630. root["useColor"] = _light_has_color;
  631. root["useWhite"] = _light_use_white;
  632. root["useGamma"] = _light_use_gamma;
  633. root["useTransitions"] = _light_use_transitions;
  634. root["useCSS"] = getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1;
  635. bool useRGB = getSetting("useRGB", LIGHT_USE_RGB).toInt() == 1;
  636. root["useRGB"] = useRGB;
  637. if (_light_has_color) {
  638. if (useRGB) {
  639. root["rgb"] = lightColor(true);
  640. root["brightness"] = lightBrightness();
  641. } else {
  642. root["hsv"] = lightColor(false);
  643. }
  644. }
  645. JsonArray& channels = root.createNestedArray("channels");
  646. for (unsigned char id=0; id < lightChannels(); id++) {
  647. channels.add(lightChannel(id));
  648. }
  649. }
  650. void _lightWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  651. if (_light_has_color) {
  652. if (strcmp(action, "color") == 0) {
  653. if (data.containsKey("rgb")) {
  654. lightColor(data["rgb"], true);
  655. lightUpdate(true, true);
  656. }
  657. if (data.containsKey("hsv")) {
  658. lightColor(data["hsv"], false);
  659. lightUpdate(true, true);
  660. }
  661. if (data.containsKey("brightness")) {
  662. lightBrightness(data["brightness"]);
  663. lightUpdate(true, true);
  664. }
  665. }
  666. }
  667. if (strcmp(action, "channel") == 0) {
  668. if (data.containsKey("id") && data.containsKey("value")) {
  669. lightChannel(data["id"], data["value"]);
  670. lightUpdate(true, true);
  671. }
  672. }
  673. }
  674. void _lightAPISetup() {
  675. // API entry points (protected with apikey)
  676. if (_light_has_color) {
  677. // DEPRECATE
  678. apiRegister(MQTT_TOPIC_COLOR,
  679. [](char * buffer, size_t len) {
  680. if (getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1) {
  681. _toRGB(buffer, len, false);
  682. } else {
  683. _toLong(buffer, len, false);
  684. }
  685. },
  686. [](const char * payload) {
  687. lightColor(payload, true);
  688. lightUpdate(true, true);
  689. }
  690. );
  691. apiRegister(MQTT_TOPIC_COLOR_RGB,
  692. [](char * buffer, size_t len) {
  693. if (getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1) {
  694. _toRGB(buffer, len, false);
  695. } else {
  696. _toLong(buffer, len, false);
  697. }
  698. },
  699. [](const char * payload) {
  700. lightColor(payload, true);
  701. lightUpdate(true, true);
  702. }
  703. );
  704. apiRegister(MQTT_TOPIC_COLOR_HSV,
  705. [](char * buffer, size_t len) {
  706. _toHSV(buffer, len);
  707. },
  708. [](const char * payload) {
  709. lightColor(payload, false);
  710. lightUpdate(true, true);
  711. }
  712. );
  713. apiRegister(MQTT_TOPIC_BRIGHTNESS,
  714. [](char * buffer, size_t len) {
  715. snprintf_P(buffer, len, PSTR("%d"), _light_brightness);
  716. },
  717. [](const char * payload) {
  718. lightBrightness(atoi(payload));
  719. lightUpdate(true, true);
  720. }
  721. );
  722. apiRegister(MQTT_TOPIC_KELVIN,
  723. [](char * buffer, size_t len) {},
  724. [](const char * payload) {
  725. _fromKelvin(atol(payload));
  726. lightUpdate(true, true);
  727. }
  728. );
  729. apiRegister(MQTT_TOPIC_MIRED,
  730. [](char * buffer, size_t len) {},
  731. [](const char * payload) {
  732. _fromMireds(atol(payload));
  733. lightUpdate(true, true);
  734. }
  735. );
  736. }
  737. for (unsigned int id=0; id<lightChannels(); id++) {
  738. char key[15];
  739. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_CHANNEL, id);
  740. apiRegister(key,
  741. [id](char * buffer, size_t len) {
  742. snprintf_P(buffer, len, PSTR("%d"), lightChannel(id));
  743. },
  744. [id](const char * payload) {
  745. lightChannel(id, atoi(payload));
  746. lightUpdate(true, true);
  747. }
  748. );
  749. }
  750. }
  751. #endif // WEB_SUPPORT
  752. #if TERMINAL_SUPPORT
  753. void _lightInitCommands() {
  754. settingsRegisterCommand(F("BRIGHTNESS"), [](Embedis* e) {
  755. if (e->argc > 1) {
  756. lightBrightness(String(e->argv[1]).toInt());
  757. lightUpdate(true, true);
  758. }
  759. DEBUG_MSG_P(PSTR("Brightness: %d\n"), lightBrightness());
  760. DEBUG_MSG_P(PSTR("+OK\n"));
  761. });
  762. settingsRegisterCommand(F("CHANNEL"), [](Embedis* e) {
  763. if (e->argc < 2) {
  764. DEBUG_MSG_P(PSTR("-ERROR: Wrong arguments\n"));
  765. }
  766. int id = String(e->argv[1]).toInt();
  767. if (e->argc > 2) {
  768. int value = String(e->argv[2]).toInt();
  769. lightChannel(id, value);
  770. lightUpdate(true, true);
  771. }
  772. DEBUG_MSG_P(PSTR("Channel #%d: %d\n"), id, lightChannel(id));
  773. DEBUG_MSG_P(PSTR("+OK\n"));
  774. });
  775. settingsRegisterCommand(F("COLOR"), [](Embedis* e) {
  776. if (e->argc > 1) {
  777. String color = String(e->argv[1]);
  778. lightColor(color.c_str());
  779. lightUpdate(true, true);
  780. }
  781. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  782. DEBUG_MSG_P(PSTR("+OK\n"));
  783. });
  784. settingsRegisterCommand(F("KELVIN"), [](Embedis* e) {
  785. if (e->argc > 1) {
  786. String color = String("K") + String(e->argv[1]);
  787. lightColor(color.c_str());
  788. lightUpdate(true, true);
  789. }
  790. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  791. DEBUG_MSG_P(PSTR("+OK\n"));
  792. });
  793. settingsRegisterCommand(F("MIRED"), [](Embedis* e) {
  794. if (e->argc > 1) {
  795. String color = String("M") + String(e->argv[1]);
  796. lightColor(color.c_str());
  797. lightUpdate(true, true);
  798. }
  799. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  800. DEBUG_MSG_P(PSTR("+OK\n"));
  801. });
  802. }
  803. #endif // TERMINAL_SUPPORT
  804. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  805. unsigned long getIOMux(unsigned long gpio) {
  806. unsigned long muxes[16] = {
  807. PERIPHS_IO_MUX_GPIO0_U, PERIPHS_IO_MUX_U0TXD_U, PERIPHS_IO_MUX_GPIO2_U, PERIPHS_IO_MUX_U0RXD_U,
  808. PERIPHS_IO_MUX_GPIO4_U, PERIPHS_IO_MUX_GPIO5_U, PERIPHS_IO_MUX_SD_CLK_U, PERIPHS_IO_MUX_SD_DATA0_U,
  809. PERIPHS_IO_MUX_SD_DATA1_U, PERIPHS_IO_MUX_SD_DATA2_U, PERIPHS_IO_MUX_SD_DATA3_U, PERIPHS_IO_MUX_SD_CMD_U,
  810. PERIPHS_IO_MUX_MTDI_U, PERIPHS_IO_MUX_MTCK_U, PERIPHS_IO_MUX_MTMS_U, PERIPHS_IO_MUX_MTDO_U
  811. };
  812. return muxes[gpio];
  813. }
  814. unsigned long getIOFunc(unsigned long gpio) {
  815. unsigned long funcs[16] = {
  816. FUNC_GPIO0, FUNC_GPIO1, FUNC_GPIO2, FUNC_GPIO3,
  817. FUNC_GPIO4, FUNC_GPIO5, FUNC_GPIO6, FUNC_GPIO7,
  818. FUNC_GPIO8, FUNC_GPIO9, FUNC_GPIO10, FUNC_GPIO11,
  819. FUNC_GPIO12, FUNC_GPIO13, FUNC_GPIO14, FUNC_GPIO15
  820. };
  821. return funcs[gpio];
  822. }
  823. #endif
  824. void _lightConfigure() {
  825. _light_has_color = getSetting("useColor", LIGHT_USE_COLOR).toInt() == 1;
  826. if (_light_has_color && (_light_channel.size() < 3)) {
  827. _light_has_color = false;
  828. setSetting("useColor", _light_has_color);
  829. }
  830. _light_use_white = getSetting("useWhite", LIGHT_USE_WHITE).toInt() == 1;
  831. if (_light_use_white && (_light_channel.size() < 4)) {
  832. _light_use_white = false;
  833. setSetting("useWhite", _light_use_white);
  834. }
  835. _light_use_gamma = getSetting("useGamma", LIGHT_USE_GAMMA).toInt() == 1;
  836. _light_use_transitions = getSetting("useTransitions", LIGHT_USE_TRANSITIONS).toInt() == 1;
  837. }
  838. void lightSetup() {
  839. #ifdef LIGHT_ENABLE_PIN
  840. pinMode(LIGHT_ENABLE_PIN, OUTPUT);
  841. digitalWrite(LIGHT_ENABLE_PIN, HIGH);
  842. #endif
  843. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  844. _my92xx = new my92xx(MY92XX_MODEL, MY92XX_CHIPS, MY92XX_DI_PIN, MY92XX_DCKI_PIN, MY92XX_COMMAND);
  845. for (unsigned char i=0; i<LIGHT_CHANNELS; i++) {
  846. _light_channel.push_back((channel_t) {0, false, true, 0, 0, 0});
  847. }
  848. #endif
  849. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  850. #ifdef LIGHT_CH1_PIN
  851. _light_channel.push_back((channel_t) {LIGHT_CH1_PIN, LIGHT_CH1_INVERSE, true, 0, 0, 0});
  852. #endif
  853. #ifdef LIGHT_CH2_PIN
  854. _light_channel.push_back((channel_t) {LIGHT_CH2_PIN, LIGHT_CH2_INVERSE, true, 0, 0, 0});
  855. #endif
  856. #ifdef LIGHT_CH3_PIN
  857. _light_channel.push_back((channel_t) {LIGHT_CH3_PIN, LIGHT_CH3_INVERSE, true, 0, 0, 0});
  858. #endif
  859. #ifdef LIGHT_CH4_PIN
  860. _light_channel.push_back((channel_t) {LIGHT_CH4_PIN, LIGHT_CH4_INVERSE, true, 0, 0, 0});
  861. #endif
  862. #ifdef LIGHT_CH5_PIN
  863. _light_channel.push_back((channel_t) {LIGHT_CH5_PIN, LIGHT_CH5_INVERSE, true, 0, 0, 0});
  864. #endif
  865. uint32 pwm_duty_init[PWM_CHANNEL_NUM_MAX];
  866. uint32 io_info[PWM_CHANNEL_NUM_MAX][3];
  867. for (unsigned int i=0; i < _light_channel.size(); i++) {
  868. pwm_duty_init[i] = 0;
  869. io_info[i][0] = getIOMux(_light_channel[i].pin);
  870. io_info[i][1] = getIOFunc(_light_channel[i].pin);
  871. io_info[i][2] = _light_channel[i].pin;
  872. pinMode(_light_channel[i].pin, OUTPUT);
  873. }
  874. pwm_init(LIGHT_MAX_PWM, pwm_duty_init, PWM_CHANNEL_NUM_MAX, io_info);
  875. pwm_start();
  876. #endif
  877. DEBUG_MSG_P(PSTR("[LIGHT] LIGHT_PROVIDER = %d\n"), LIGHT_PROVIDER);
  878. DEBUG_MSG_P(PSTR("[LIGHT] Number of channels: %d\n"), _light_channel.size());
  879. _lightConfigure();
  880. _lightColorRestore();
  881. #if WEB_SUPPORT
  882. _lightAPISetup();
  883. wsOnSendRegister(_lightWebSocketOnSend);
  884. wsOnActionRegister(_lightWebSocketOnAction);
  885. wsOnAfterParseRegister([]() {
  886. #if LIGHT_SAVE_ENABLED == 0
  887. lightSave();
  888. #endif
  889. _lightConfigure();
  890. });
  891. #endif
  892. #if MQTT_SUPPORT
  893. mqttRegister(_lightMQTTCallback);
  894. #endif
  895. #if TERMINAL_SUPPORT
  896. _lightInitCommands();
  897. #endif
  898. }
  899. #endif // LIGHT_PROVIDER != LIGHT_PROVIDER_NONE