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.

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