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.

1107 lines
32 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. /*
  2. LIGHT MODULE
  3. Copyright (C) 2016-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. for (unsigned int i=0; i < _light_channel.size(); i++) {
  383. setSetting("ch", i, _light_channel[i].value);
  384. }
  385. setSetting("brightness", _light_brightness);
  386. saveSettings();
  387. }
  388. void _lightColorRestore() {
  389. for (unsigned int i=0; i < _light_channel.size(); i++) {
  390. _light_channel[i].value = getSetting("ch", i, i==0 ? 255 : 0).toInt();
  391. }
  392. _light_brightness = getSetting("brightness", LIGHT_MAX_BRIGHTNESS).toInt();
  393. lightUpdate(false, false);
  394. }
  395. // -----------------------------------------------------------------------------
  396. // MQTT
  397. // -----------------------------------------------------------------------------
  398. #if MQTT_SUPPORT
  399. void _lightMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  400. String mqtt_group_color = getSetting("mqttGroupColor");
  401. if (type == MQTT_CONNECT_EVENT) {
  402. if (_light_has_color) {
  403. mqttSubscribe(MQTT_TOPIC_BRIGHTNESS);
  404. mqttSubscribe(MQTT_TOPIC_MIRED);
  405. mqttSubscribe(MQTT_TOPIC_KELVIN);
  406. mqttSubscribe(MQTT_TOPIC_COLOR); // DEPRECATE
  407. mqttSubscribe(MQTT_TOPIC_COLOR_RGB);
  408. mqttSubscribe(MQTT_TOPIC_COLOR_HSV);
  409. }
  410. // Group color
  411. if (mqtt_group_color.length() > 0) mqttSubscribeRaw(mqtt_group_color.c_str());
  412. // Channels
  413. char buffer[strlen(MQTT_TOPIC_CHANNEL) + 3];
  414. snprintf_P(buffer, sizeof(buffer), PSTR("%s/+"), MQTT_TOPIC_CHANNEL);
  415. mqttSubscribe(buffer);
  416. }
  417. if (type == MQTT_MESSAGE_EVENT) {
  418. // Group color
  419. if ((mqtt_group_color.length() > 0) & (mqtt_group_color.equals(topic))) {
  420. lightColor(payload, true);
  421. lightUpdate(true, mqttForward(), false);
  422. return;
  423. }
  424. // Match topic
  425. String t = mqttMagnitude((char *) topic);
  426. // Color temperature in mireds
  427. if (t.equals(MQTT_TOPIC_MIRED)) {
  428. _fromMireds(atol(payload));
  429. lightUpdate(true, mqttForward());
  430. return;
  431. }
  432. // Color temperature in kelvins
  433. if (t.equals(MQTT_TOPIC_KELVIN)) {
  434. _fromKelvin(atol(payload));
  435. lightUpdate(true, mqttForward());
  436. return;
  437. }
  438. // Color
  439. if (t.equals(MQTT_TOPIC_COLOR) || t.equals(MQTT_TOPIC_COLOR_RGB)) { // DEPRECATE MQTT_TOPIC_COLOR
  440. lightColor(payload, true);
  441. lightUpdate(true, mqttForward());
  442. return;
  443. }
  444. if (t.equals(MQTT_TOPIC_COLOR_HSV)) {
  445. lightColor(payload, false);
  446. lightUpdate(true, mqttForward());
  447. return;
  448. }
  449. // Brightness
  450. if (t.equals(MQTT_TOPIC_BRIGHTNESS)) {
  451. _light_brightness = constrain(atoi(payload), 0, LIGHT_MAX_BRIGHTNESS);
  452. lightUpdate(true, mqttForward());
  453. return;
  454. }
  455. // Channel
  456. if (t.startsWith(MQTT_TOPIC_CHANNEL)) {
  457. unsigned int channelID = t.substring(strlen(MQTT_TOPIC_CHANNEL)+1).toInt();
  458. if (channelID >= _light_channel.size()) {
  459. DEBUG_MSG_P(PSTR("[LIGHT] Wrong channelID (%d)\n"), channelID);
  460. return;
  461. }
  462. lightChannel(channelID, atoi(payload));
  463. lightUpdate(true, mqttForward());
  464. return;
  465. }
  466. }
  467. }
  468. void lightMQTT() {
  469. char buffer[20];
  470. if (_light_has_color) {
  471. // Color
  472. if (getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1) {
  473. _toRGB(buffer, sizeof(buffer), false);
  474. } else {
  475. _toLong(buffer, sizeof(buffer), false);
  476. }
  477. mqttSend(MQTT_TOPIC_COLOR, buffer); // DEPRECATE
  478. mqttSend(MQTT_TOPIC_COLOR_RGB, buffer);
  479. _toHSV(buffer, sizeof(buffer));
  480. mqttSend(MQTT_TOPIC_COLOR_HSV, buffer);
  481. // Brightness
  482. snprintf_P(buffer, sizeof(buffer), PSTR("%d"), _light_brightness);
  483. mqttSend(MQTT_TOPIC_BRIGHTNESS, buffer);
  484. }
  485. // Channels
  486. for (unsigned int i=0; i < _light_channel.size(); i++) {
  487. itoa(_light_channel[i].value, buffer, 10);
  488. mqttSend(MQTT_TOPIC_CHANNEL, i, buffer);
  489. }
  490. }
  491. void lightMQTTGroup() {
  492. String mqtt_group_color = getSetting("mqttGroupColor");
  493. if (mqtt_group_color.length()>0) {
  494. char buffer[20];
  495. _toCSV(buffer, sizeof(buffer), true);
  496. mqttSendRaw(mqtt_group_color.c_str(), buffer);
  497. }
  498. }
  499. #endif
  500. // -----------------------------------------------------------------------------
  501. // Broker
  502. // -----------------------------------------------------------------------------
  503. #if BROKER_SUPPORT
  504. void lightBroker() {
  505. char buffer[10];
  506. for (unsigned int i=0; i < _light_channel.size(); i++) {
  507. itoa(_light_channel[i].value, buffer, 10);
  508. brokerPublish(MQTT_TOPIC_CHANNEL, i, buffer);
  509. }
  510. }
  511. #endif
  512. // -----------------------------------------------------------------------------
  513. // API
  514. // -----------------------------------------------------------------------------
  515. unsigned char lightChannels() {
  516. return _light_channel.size();
  517. }
  518. bool lightHasColor() {
  519. return _light_has_color;
  520. }
  521. unsigned char lightWhiteChannels() {
  522. return _light_channel.size() % 3;
  523. }
  524. void lightUpdate(bool save, bool forward, bool group_forward) {
  525. // Configure color transition
  526. _light_steps_left = _light_use_transitions ? LIGHT_TRANSITION_STEPS : 1;
  527. _light_transition_ticker.attach_ms(LIGHT_TRANSITION_STEP, _lightProviderUpdate);
  528. // Report channels to local broker
  529. #if BROKER_SUPPORT
  530. lightBroker();
  531. #endif
  532. // Report color & brightness to MQTT broker
  533. #if MQTT_SUPPORT
  534. if (forward) lightMQTT();
  535. if (group_forward) lightMQTTGroup();
  536. #endif
  537. // Report color to WS clients (using current brightness setting)
  538. #if WEB_SUPPORT
  539. wsSend(_lightWebSocketOnSend);
  540. #endif
  541. #if LIGHT_SAVE_ENABLED
  542. // Delay saving to EEPROM 5 seconds to avoid wearing it out unnecessarily
  543. if (save) _light_save_ticker.once(LIGHT_SAVE_DELAY, _lightColorSave);
  544. #endif
  545. };
  546. void lightUpdate(bool save, bool forward) {
  547. lightUpdate(save, forward, true);
  548. }
  549. #if LIGHT_SAVE_ENABLED == 0
  550. void lightSave() {
  551. _lightColorSave();
  552. }
  553. #endif
  554. void lightState(unsigned char i, bool state) {
  555. _light_channel[i].state = state;
  556. }
  557. bool lightState(unsigned char i) {
  558. return _light_channel[i].state;
  559. }
  560. void lightState(bool state) {
  561. _light_state = state;
  562. }
  563. bool lightState() {
  564. return _light_state;
  565. }
  566. void lightColor(const char * color, bool rgb) {
  567. DEBUG_MSG_P(PSTR("[LIGHT] %s: %s\n"), rgb ? "RGB" : "HSV", color);
  568. if (rgb) {
  569. _fromRGB(color);
  570. } else {
  571. _fromHSV(color);
  572. }
  573. }
  574. void lightColor(const char * color) {
  575. lightColor(color, true);
  576. }
  577. void lightColor(unsigned long color) {
  578. _fromLong(color, false);
  579. }
  580. String lightColor(bool rgb) {
  581. char str[12];
  582. if (rgb) {
  583. _toRGB(str, sizeof(str), false);
  584. } else {
  585. _toHSV(str, sizeof(str));
  586. }
  587. return String(str);
  588. }
  589. String lightColor() {
  590. return lightColor(true);
  591. }
  592. unsigned int lightChannel(unsigned char id) {
  593. if (id <= _light_channel.size()) {
  594. return _light_channel[id].value;
  595. }
  596. return 0;
  597. }
  598. void lightChannel(unsigned char id, unsigned int value) {
  599. if (id <= _light_channel.size()) {
  600. _light_channel[id].value = constrain(value, 0, LIGHT_MAX_VALUE);
  601. }
  602. }
  603. unsigned int lightBrightness() {
  604. return _light_brightness;
  605. }
  606. void lightBrightness(int b) {
  607. _light_brightness = constrain(b, 0, LIGHT_MAX_BRIGHTNESS);
  608. }
  609. void lightBrightnessStep(int steps) {
  610. lightBrightness(_light_brightness + steps * LIGHT_STEP);
  611. }
  612. // -----------------------------------------------------------------------------
  613. // SETUP
  614. // -----------------------------------------------------------------------------
  615. #if WEB_SUPPORT
  616. void _lightWebSocketOnSend(JsonObject& root) {
  617. root["colorVisible"] = 1;
  618. root["mqttGroupColor"] = getSetting("mqttGroupColor");
  619. root["useColor"] = _light_has_color;
  620. root["useWhite"] = _light_use_white;
  621. root["useGamma"] = _light_use_gamma;
  622. root["useTransitions"] = _light_use_transitions;
  623. root["useCSS"] = getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1;
  624. bool useRGB = getSetting("useRGB", LIGHT_USE_RGB).toInt() == 1;
  625. root["useRGB"] = useRGB;
  626. if (_light_has_color) {
  627. if (useRGB) {
  628. root["rgb"] = lightColor(true);
  629. root["brightness"] = lightBrightness();
  630. } else {
  631. root["hsv"] = lightColor(false);
  632. }
  633. }
  634. JsonArray& channels = root.createNestedArray("channels");
  635. for (unsigned char id=0; id < lightChannels(); id++) {
  636. channels.add(lightChannel(id));
  637. }
  638. }
  639. void _lightWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  640. if (_light_has_color) {
  641. if (strcmp(action, "color") == 0) {
  642. if (data.containsKey("rgb")) {
  643. lightColor(data["rgb"], true);
  644. lightUpdate(true, true);
  645. }
  646. if (data.containsKey("hsv")) {
  647. lightColor(data["hsv"], false);
  648. lightUpdate(true, true);
  649. }
  650. if (data.containsKey("brightness")) {
  651. lightBrightness(data["brightness"]);
  652. lightUpdate(true, true);
  653. }
  654. }
  655. }
  656. if (strcmp(action, "channel") == 0) {
  657. if (data.containsKey("id") && data.containsKey("value")) {
  658. lightChannel(data["id"], data["value"]);
  659. lightUpdate(true, true);
  660. }
  661. }
  662. }
  663. void _lightAPISetup() {
  664. // API entry points (protected with apikey)
  665. if (_light_has_color) {
  666. // DEPRECATE
  667. apiRegister(MQTT_TOPIC_COLOR,
  668. [](char * buffer, size_t len) {
  669. if (getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1) {
  670. _toRGB(buffer, len, false);
  671. } else {
  672. _toLong(buffer, len, false);
  673. }
  674. },
  675. [](const char * payload) {
  676. lightColor(payload, true);
  677. lightUpdate(true, true);
  678. }
  679. );
  680. apiRegister(MQTT_TOPIC_COLOR_RGB,
  681. [](char * buffer, size_t len) {
  682. if (getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1) {
  683. _toRGB(buffer, len, false);
  684. } else {
  685. _toLong(buffer, len, false);
  686. }
  687. },
  688. [](const char * payload) {
  689. lightColor(payload, true);
  690. lightUpdate(true, true);
  691. }
  692. );
  693. apiRegister(MQTT_TOPIC_COLOR_HSV,
  694. [](char * buffer, size_t len) {
  695. _toHSV(buffer, len);
  696. },
  697. [](const char * payload) {
  698. lightColor(payload, false);
  699. lightUpdate(true, true);
  700. }
  701. );
  702. apiRegister(MQTT_TOPIC_BRIGHTNESS,
  703. [](char * buffer, size_t len) {
  704. snprintf_P(buffer, len, PSTR("%d"), _light_brightness);
  705. },
  706. [](const char * payload) {
  707. lightBrightness(atoi(payload));
  708. lightUpdate(true, true);
  709. }
  710. );
  711. apiRegister(MQTT_TOPIC_KELVIN,
  712. [](char * buffer, size_t len) {},
  713. [](const char * payload) {
  714. _fromKelvin(atol(payload));
  715. lightUpdate(true, true);
  716. }
  717. );
  718. apiRegister(MQTT_TOPIC_MIRED,
  719. [](char * buffer, size_t len) {},
  720. [](const char * payload) {
  721. _fromMireds(atol(payload));
  722. lightUpdate(true, true);
  723. }
  724. );
  725. }
  726. for (unsigned int id=0; id<lightChannels(); id++) {
  727. char key[15];
  728. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_CHANNEL, id);
  729. apiRegister(key,
  730. [id](char * buffer, size_t len) {
  731. snprintf_P(buffer, len, PSTR("%d"), lightChannel(id));
  732. },
  733. [id](const char * payload) {
  734. lightChannel(id, atoi(payload));
  735. lightUpdate(true, true);
  736. }
  737. );
  738. }
  739. }
  740. #endif // WEB_SUPPORT
  741. #if TERMINAL_SUPPORT
  742. void _lightInitCommands() {
  743. settingsRegisterCommand(F("BRIGHTNESS"), [](Embedis* e) {
  744. if (e->argc > 1) {
  745. lightBrightness(String(e->argv[1]).toInt());
  746. lightUpdate(true, true);
  747. }
  748. DEBUG_MSG_P(PSTR("Brightness: %d\n"), lightBrightness());
  749. DEBUG_MSG_P(PSTR("+OK\n"));
  750. });
  751. settingsRegisterCommand(F("CHANNEL"), [](Embedis* e) {
  752. if (e->argc < 2) {
  753. DEBUG_MSG_P(PSTR("-ERROR: Wrong arguments\n"));
  754. }
  755. int id = String(e->argv[1]).toInt();
  756. if (e->argc > 2) {
  757. int value = String(e->argv[2]).toInt();
  758. lightChannel(id, value);
  759. lightUpdate(true, true);
  760. }
  761. DEBUG_MSG_P(PSTR("Channel #%d: %d\n"), id, lightChannel(id));
  762. DEBUG_MSG_P(PSTR("+OK\n"));
  763. });
  764. settingsRegisterCommand(F("COLOR"), [](Embedis* e) {
  765. if (e->argc > 1) {
  766. String color = String(e->argv[1]);
  767. lightColor(color.c_str());
  768. lightUpdate(true, true);
  769. }
  770. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  771. DEBUG_MSG_P(PSTR("+OK\n"));
  772. });
  773. settingsRegisterCommand(F("KELVIN"), [](Embedis* e) {
  774. if (e->argc > 1) {
  775. String color = String("K") + String(e->argv[1]);
  776. lightColor(color.c_str());
  777. lightUpdate(true, true);
  778. }
  779. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  780. DEBUG_MSG_P(PSTR("+OK\n"));
  781. });
  782. settingsRegisterCommand(F("MIRED"), [](Embedis* e) {
  783. if (e->argc > 1) {
  784. String color = String("M") + String(e->argv[1]);
  785. lightColor(color.c_str());
  786. lightUpdate(true, true);
  787. }
  788. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  789. DEBUG_MSG_P(PSTR("+OK\n"));
  790. });
  791. }
  792. #endif // TERMINAL_SUPPORT
  793. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  794. unsigned long getIOMux(unsigned long gpio) {
  795. unsigned long muxes[16] = {
  796. PERIPHS_IO_MUX_GPIO0_U, PERIPHS_IO_MUX_U0TXD_U, PERIPHS_IO_MUX_GPIO2_U, PERIPHS_IO_MUX_U0RXD_U,
  797. PERIPHS_IO_MUX_GPIO4_U, PERIPHS_IO_MUX_GPIO5_U, PERIPHS_IO_MUX_SD_CLK_U, PERIPHS_IO_MUX_SD_DATA0_U,
  798. PERIPHS_IO_MUX_SD_DATA1_U, PERIPHS_IO_MUX_SD_DATA2_U, PERIPHS_IO_MUX_SD_DATA3_U, PERIPHS_IO_MUX_SD_CMD_U,
  799. PERIPHS_IO_MUX_MTDI_U, PERIPHS_IO_MUX_MTCK_U, PERIPHS_IO_MUX_MTMS_U, PERIPHS_IO_MUX_MTDO_U
  800. };
  801. return muxes[gpio];
  802. }
  803. unsigned long getIOFunc(unsigned long gpio) {
  804. unsigned long funcs[16] = {
  805. FUNC_GPIO0, FUNC_GPIO1, FUNC_GPIO2, FUNC_GPIO3,
  806. FUNC_GPIO4, FUNC_GPIO5, FUNC_GPIO6, FUNC_GPIO7,
  807. FUNC_GPIO8, FUNC_GPIO9, FUNC_GPIO10, FUNC_GPIO11,
  808. FUNC_GPIO12, FUNC_GPIO13, FUNC_GPIO14, FUNC_GPIO15
  809. };
  810. return funcs[gpio];
  811. }
  812. #endif
  813. void _lightConfigure() {
  814. _light_has_color = getSetting("useColor", LIGHT_USE_COLOR).toInt() == 1;
  815. if (_light_has_color && (_light_channel.size() < 3)) {
  816. _light_has_color = false;
  817. setSetting("useColor", _light_has_color);
  818. }
  819. _light_use_white = getSetting("useWhite", LIGHT_USE_WHITE).toInt() == 1;
  820. if (_light_use_white && (_light_channel.size() < 4)) {
  821. _light_use_white = false;
  822. setSetting("useWhite", _light_use_white);
  823. }
  824. _light_use_gamma = getSetting("useGamma", LIGHT_USE_GAMMA).toInt() == 1;
  825. _light_use_transitions = getSetting("useTransitions", LIGHT_USE_TRANSITIONS).toInt() == 1;
  826. }
  827. void lightSetup() {
  828. #ifdef LIGHT_ENABLE_PIN
  829. pinMode(LIGHT_ENABLE_PIN, OUTPUT);
  830. digitalWrite(LIGHT_ENABLE_PIN, HIGH);
  831. #endif
  832. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  833. _my92xx = new my92xx(MY92XX_MODEL, MY92XX_CHIPS, MY92XX_DI_PIN, MY92XX_DCKI_PIN, MY92XX_COMMAND);
  834. for (unsigned char i=0; i<LIGHT_CHANNELS; i++) {
  835. _light_channel.push_back((channel_t) {0, false, true, 0, 0, 0});
  836. }
  837. #endif
  838. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  839. #ifdef LIGHT_CH1_PIN
  840. _light_channel.push_back((channel_t) {LIGHT_CH1_PIN, LIGHT_CH1_INVERSE, true, 0, 0, 0});
  841. #endif
  842. #ifdef LIGHT_CH2_PIN
  843. _light_channel.push_back((channel_t) {LIGHT_CH2_PIN, LIGHT_CH2_INVERSE, true, 0, 0, 0});
  844. #endif
  845. #ifdef LIGHT_CH3_PIN
  846. _light_channel.push_back((channel_t) {LIGHT_CH3_PIN, LIGHT_CH3_INVERSE, true, 0, 0, 0});
  847. #endif
  848. #ifdef LIGHT_CH4_PIN
  849. _light_channel.push_back((channel_t) {LIGHT_CH4_PIN, LIGHT_CH4_INVERSE, true, 0, 0, 0});
  850. #endif
  851. #ifdef LIGHT_CH5_PIN
  852. _light_channel.push_back((channel_t) {LIGHT_CH5_PIN, LIGHT_CH5_INVERSE, true, 0, 0, 0});
  853. #endif
  854. uint32 pwm_duty_init[PWM_CHANNEL_NUM_MAX];
  855. uint32 io_info[PWM_CHANNEL_NUM_MAX][3];
  856. for (unsigned int i=0; i < _light_channel.size(); i++) {
  857. pwm_duty_init[i] = 0;
  858. io_info[i][0] = getIOMux(_light_channel[i].pin);
  859. io_info[i][1] = getIOFunc(_light_channel[i].pin);
  860. io_info[i][2] = _light_channel[i].pin;
  861. pinMode(_light_channel[i].pin, OUTPUT);
  862. }
  863. pwm_init(LIGHT_MAX_PWM, pwm_duty_init, PWM_CHANNEL_NUM_MAX, io_info);
  864. pwm_start();
  865. #endif
  866. DEBUG_MSG_P(PSTR("[LIGHT] LIGHT_PROVIDER = %d\n"), LIGHT_PROVIDER);
  867. DEBUG_MSG_P(PSTR("[LIGHT] Number of channels: %d\n"), _light_channel.size());
  868. _lightColorRestore();
  869. _lightConfigure();
  870. #if WEB_SUPPORT
  871. _lightAPISetup();
  872. wsOnSendRegister(_lightWebSocketOnSend);
  873. wsOnActionRegister(_lightWebSocketOnAction);
  874. wsOnAfterParseRegister([]() {
  875. #if LIGHT_SAVE_ENABLED == 0
  876. lightSave();
  877. #endif
  878. _lightConfigure();
  879. });
  880. #endif
  881. #if MQTT_SUPPORT
  882. mqttRegister(_lightMQTTCallback);
  883. #endif
  884. #if TERMINAL_SUPPORT
  885. _lightInitCommands();
  886. #endif
  887. }
  888. #endif // LIGHT_PROVIDER != LIGHT_PROVIDER_NONE