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.

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