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.

1104 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_cold_white = 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 = (LIGHT_MIRED_W1+LIGHT_MIRED_W2)/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_cold_white) {
  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_MIRED_W2)/((double) LIGHT_MIRED_W1 - (double) LIGHT_MIRED_W2);
  96. _light_channel[3].inputValue = 0;
  97. _light_channel[3].value = round(miredFactor * white);
  98. _light_channel[4].inputValue = 0;
  99. _light_channel[4].value = round(((double) 1.0 - (double) miredFactor) * white);
  100. } else {
  101. _light_channel[3].inputValue = 0;
  102. _light_channel[3].value = white;
  103. }
  104. // Scale up to equal input values. So [250,150,50] -> [200,100,0,50] -> [250, 125, 0, 63]
  105. unsigned char max_in = getMax(_light_channel[0].inputValue, _light_channel[1].inputValue, _light_channel[2].inputValue);
  106. unsigned char max_out = getMax(_light_channel[0].value, _light_channel[1].value, _light_channel[2].value, _light_channel[3].value, (_light_use_cold_white ? _light_channel[4].value : 0));
  107. unsigned char channelSize = _light_use_cold_white ? 5 : 4;
  108. double factor = (max_out > 0) ? (double) (max_in / max_out) : 0;
  109. for (unsigned char i=0; i < channelSize; i++) {
  110. _light_channel[i].value = round((double) _light_channel[i].value * factor * brightness);
  111. }
  112. // Scale white channel to match brightness
  113. for (unsigned char i=3; i < channelSize; i++) {
  114. _light_channel[i].value = constrain(_light_channel[i].value * LIGHT_WHITE_FACTOR, 0, LIGHT_MAX_BRIGHTNESS);
  115. }
  116. // For the rest of channels, don't apply brightness, it is already in the inputValue
  117. // i should be 4 when RGBW and 5 when RGBWW
  118. for (unsigned char i=channelSize; i < _light_channel.size(); i++) {
  119. _light_channel[i].value = _light_channel[i].inputValue;
  120. }
  121. } else {
  122. // Don't apply brightness, it is already in the inputValue:
  123. for (unsigned char i=0; i < _light_channel.size(); i++) {
  124. if (_light_has_color & (i<3)) {
  125. _light_channel[i].value = _light_channel[i].inputValue * brightness;
  126. } else {
  127. _light_channel[i].value = _light_channel[i].inputValue;
  128. }
  129. }
  130. }
  131. }
  132. // -----------------------------------------------------------------------------
  133. // Input Values
  134. // -----------------------------------------------------------------------------
  135. void _fromLong(unsigned long value, bool brightness) {
  136. if (brightness) {
  137. _setRGBInputValue((value >> 24) & 0xFF, (value >> 16) & 0xFF, (value >> 8) & 0xFF);
  138. _light_brightness = (value & 0xFF) * LIGHT_MAX_BRIGHTNESS / 255;
  139. } else {
  140. _setRGBInputValue((value >> 16) & 0xFF, (value >> 8) & 0xFF, (value) & 0xFF);
  141. }
  142. }
  143. void _fromRGB(const char * rgb) {
  144. char * p = (char *) rgb;
  145. if (strlen(p) == 0) return;
  146. switch (p[0]) {
  147. case '#': // HEX Value
  148. if (_light_has_color) {
  149. ++p;
  150. unsigned long value = strtoul(p, NULL, 16);
  151. // RGBA values are interpreted like RGB + brightness
  152. _fromLong(value, strlen(p) > 7);
  153. }
  154. break;
  155. case 'M': // Mired Value
  156. if (_light_has_color) {
  157. unsigned long mireds = atol(p + 1);
  158. _fromMireds(mireds);
  159. }
  160. break;
  161. case 'K': // Kelvin Value
  162. if (_light_has_color) {
  163. unsigned long kelvin = atol(p + 1);
  164. _fromKelvin(kelvin);
  165. }
  166. break;
  167. default: // assume decimal values separated by commas
  168. char * tok;
  169. unsigned char count = 0;
  170. unsigned char channels = _light_channel.size();
  171. tok = strtok(p, ",");
  172. while (tok != NULL) {
  173. _light_channel[count].inputValue = atoi(tok);
  174. if (++count == channels) break;
  175. tok = strtok(NULL, ",");
  176. }
  177. // RGB but less than 3 values received, assume it is 0
  178. if (_light_has_color && (count < 3)) {
  179. // check channel 1 and 2:
  180. for (int i = 1; i <= 2; i++) {
  181. if (count < (i+1)) {
  182. _light_channel[i].inputValue = 0;
  183. }
  184. }
  185. }
  186. break;
  187. }
  188. }
  189. // HSV string is expected to be "H,S,V", where:
  190. // 0 <= H <= 360
  191. // 0 <= S <= 100
  192. // 0 <= V <= 100
  193. void _fromHSV(const char * hsv) {
  194. char * ptr = (char *) hsv;
  195. if (strlen(ptr) == 0) return;
  196. if (!_light_has_color) return;
  197. char * tok;
  198. unsigned char count = 0;
  199. unsigned int value[3] = {0};
  200. tok = strtok(ptr, ",");
  201. while (tok != NULL) {
  202. value[count] = atoi(tok);
  203. if (++count == 3) break;
  204. tok = strtok(NULL, ",");
  205. }
  206. if (count != 3) return;
  207. // HSV to RGB transformation -----------------------------------------------
  208. //INPUT: [0,100,57]
  209. //IS: [145,0,0]
  210. //SHOULD: [255,0,0]
  211. double h = (value[0] == 360) ? 0 : (double) value[0] / 60.0;
  212. double f = (h - floor(h));
  213. double s = (double) value[1] / 100.0;
  214. _light_brightness = round((double) value[2] * 2.55); // (255/100)
  215. unsigned char p = round(255 * (1.0 - s));
  216. unsigned char q = round(255 * (1.0 - s * f));
  217. unsigned char t = round(255 * (1.0 - s * (1.0 - f)));
  218. switch (int(h)) {
  219. case 0:
  220. _setRGBInputValue(255, t, p);
  221. break;
  222. case 1:
  223. _setRGBInputValue(q, 255, p);
  224. break;
  225. case 2:
  226. _setRGBInputValue(p, 255, t);
  227. break;
  228. case 3:
  229. _setRGBInputValue(p, q, 255);
  230. break;
  231. case 4:
  232. _setRGBInputValue(t, p, 255);
  233. break;
  234. case 5:
  235. _setRGBInputValue(255, p, q);
  236. break;
  237. default:
  238. _setRGBInputValue(0, 0, 0);
  239. break;
  240. }
  241. }
  242. // Thanks to Sacha Telgenhof for sharing this code in his AiLight library
  243. // https://github.com/stelgenhof/AiLight
  244. void _fromKelvin(unsigned long kelvin, bool setMireds) {
  245. // Check we have RGB channels
  246. if (!_light_has_color) return;
  247. if (setMireds) {
  248. _light_mireds = constrain(round(1000000UL / kelvin), LIGHT_MIN_MIREDS, LIGHT_MAX_MIREDS);
  249. }
  250. if (_light_has_color && _light_use_cold_white) {
  251. // _setRGBInputValue(LIGHT_MAX_VALUE, LIGHT_MAX_VALUE, LIGHT_MAX_VALUE);
  252. return;
  253. }
  254. // Calculate colors
  255. unsigned int red = (kelvin <= 66)
  256. ? LIGHT_MAX_VALUE
  257. : 329.698727446 * pow((kelvin - 60), -0.1332047592);
  258. unsigned int green = (kelvin <= 66)
  259. ? 99.4708025861 * log(kelvin) - 161.1195681661
  260. : 288.1221695283 * pow(kelvin, -0.0755148492);
  261. unsigned int blue = (kelvin >= 66)
  262. ? LIGHT_MAX_VALUE
  263. : ((kelvin <= 19)
  264. ? 0
  265. : 138.5177312231 * log(kelvin - 10) - 305.0447927307);
  266. _setRGBInputValue(red, green, blue);
  267. }
  268. void _fromKelvin(unsigned long kelvin) {
  269. _fromKelvin(kelvin, true);
  270. }
  271. // Color temperature is measured in mireds (kelvin = 1e6/mired)
  272. void _fromMireds(unsigned long mireds) {
  273. _light_mireds = mireds = constrain(mireds, LIGHT_MIN_MIREDS, LIGHT_MAX_MIREDS);
  274. if (_light_has_color && _light_use_cold_white) {
  275. // _setRGBInputValue(LIGHT_MAX_VALUE, LIGHT_MAX_VALUE, LIGHT_MAX_VALUE);
  276. return;
  277. }
  278. unsigned long kelvin = constrain(1000000UL / mireds, 1000, 40000) / 100;
  279. _fromKelvin(kelvin, false);
  280. }
  281. // -----------------------------------------------------------------------------
  282. // Output Values
  283. // -----------------------------------------------------------------------------
  284. void _toRGB(char * rgb, size_t len) {
  285. unsigned long value = 0;
  286. value += _light_channel[0].inputValue;
  287. value <<= 8;
  288. value += _light_channel[1].inputValue;
  289. value <<= 8;
  290. value += _light_channel[2].inputValue;
  291. snprintf_P(rgb, len, PSTR("#%06X"), value);
  292. }
  293. void _toHSV(char * hsv, size_t len) {
  294. double min, max, h, s, v;
  295. double brightness = (double) _light_brightness / LIGHT_MAX_BRIGHTNESS;
  296. double r = (double) (_light_channel[0].inputValue * brightness) / 255.0;
  297. double g = (double) (_light_channel[1].inputValue * brightness) / 255.0;
  298. double b = (double) (_light_channel[2].inputValue * brightness) / 255.0;
  299. min = getMin(r, g, b);
  300. max = getMax(r, g, b);
  301. v = 100.0 * max;
  302. if (v == 0) {
  303. h = s = 0;
  304. } else {
  305. s = 100.0 * (max - min) / max;
  306. if (s == 0) {
  307. h = 0;
  308. } else {
  309. if (max == r) {
  310. if (g >= b) {
  311. h = 0.0 + 60.0 * (g - b) / (max - min);
  312. } else {
  313. h = 360.0 + 60.0 * (g - b) / (max - min);
  314. }
  315. } else if (max == g) {
  316. h = 120.0 + 60.0 * (b - r) / (max - min);
  317. } else {
  318. h = 240.0 + 60.0 * (r - g) / (max - min);
  319. }
  320. }
  321. }
  322. // String
  323. snprintf_P(hsv, len, PSTR("%d,%d,%d"), round(h), round(s), round(v));
  324. }
  325. void _toLong(char * color, size_t len) {
  326. if (!_light_has_color) return;
  327. snprintf_P(color, len, PSTR("%d,%d,%d"),
  328. (int) _light_channel[0].inputValue,
  329. (int) _light_channel[1].inputValue,
  330. (int) _light_channel[2].inputValue
  331. );
  332. }
  333. void _toCSV(char * buffer, size_t len, bool applyBrightness) {
  334. char num[10];
  335. float b = applyBrightness ? (float) _light_brightness / LIGHT_MAX_BRIGHTNESS : 1;
  336. for (unsigned char i=0; i<_light_channel.size(); i++) {
  337. itoa(_light_channel[i].inputValue * b, num, 10);
  338. if (i>0) strncat(buffer, ",", len--);
  339. strncat(buffer, num, len);
  340. len = len - strlen(num);
  341. }
  342. }
  343. // -----------------------------------------------------------------------------
  344. // PROVIDER
  345. // -----------------------------------------------------------------------------
  346. unsigned int _toPWM(unsigned long value, bool gamma, bool reverse) {
  347. value = constrain(value, 0, LIGHT_MAX_VALUE);
  348. if (gamma) value = _light_gamma_table[value];
  349. if (LIGHT_MAX_VALUE != LIGHT_LIMIT_PWM) value = map(value, 0, LIGHT_MAX_VALUE, 0, LIGHT_LIMIT_PWM);
  350. if (reverse) value = LIGHT_LIMIT_PWM - value;
  351. return value;
  352. }
  353. // Returns a PWM value for the given channel ID
  354. unsigned int _toPWM(unsigned char id) {
  355. bool useGamma = _light_use_gamma && _light_has_color && (id < 3);
  356. return _toPWM(_light_channel[id].shadow, useGamma, _light_channel[id].reverse);
  357. }
  358. void _shadow() {
  359. // Update transition ticker
  360. _light_steps_left--;
  361. if (_light_steps_left == 0) _light_transition_ticker.detach();
  362. // Transitions
  363. unsigned char target;
  364. for (unsigned int i=0; i < _light_channel.size(); i++) {
  365. target = _light_state ? _light_channel[i].value : 0;
  366. if (_light_steps_left == 0) {
  367. _light_channel[i].current = target;
  368. } else {
  369. double difference = (double) (target - _light_channel[i].current) / (_light_steps_left + 1);
  370. _light_channel[i].current = _light_channel[i].current + difference;
  371. }
  372. _light_channel[i].shadow = _light_channel[i].current;
  373. }
  374. }
  375. void _lightProviderUpdate() {
  376. _shadow();
  377. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  378. for (unsigned char i=0; i<_light_channel.size(); i++) {
  379. _my92xx->setChannel(_light_channel_map[i], _toPWM(i));
  380. }
  381. _my92xx->setState(true);
  382. _my92xx->update();
  383. #endif
  384. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  385. for (unsigned int i=0; i < _light_channel.size(); i++) {
  386. pwm_set_duty(_toPWM(i), i);
  387. }
  388. pwm_start();
  389. #endif
  390. }
  391. // -----------------------------------------------------------------------------
  392. // PERSISTANCE
  393. // -----------------------------------------------------------------------------
  394. void _lightColorSave() {
  395. for (unsigned int i=0; i < _light_channel.size(); i++) {
  396. setSetting("ch", i, _light_channel[i].inputValue);
  397. }
  398. setSetting("brightness", _light_brightness);
  399. setSetting("mireds", _light_mireds);
  400. saveSettings();
  401. }
  402. void _lightColorRestore() {
  403. for (unsigned int i=0; i < _light_channel.size(); i++) {
  404. _light_channel[i].inputValue = getSetting("ch", i, i==0 ? 255 : 0).toInt();
  405. }
  406. _light_brightness = getSetting("brightness", LIGHT_MAX_BRIGHTNESS).toInt();
  407. _light_mireds = getSetting("mireds", _light_mireds).toInt();
  408. lightUpdate(false, false);
  409. }
  410. // -----------------------------------------------------------------------------
  411. // MQTT
  412. // -----------------------------------------------------------------------------
  413. #if MQTT_SUPPORT
  414. void _lightMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  415. String mqtt_group_color = getSetting("mqttGroupColor");
  416. if (type == MQTT_CONNECT_EVENT) {
  417. if (_light_has_color) {
  418. mqttSubscribe(MQTT_TOPIC_BRIGHTNESS);
  419. mqttSubscribe(MQTT_TOPIC_MIRED);
  420. mqttSubscribe(MQTT_TOPIC_KELVIN);
  421. mqttSubscribe(MQTT_TOPIC_COLOR_RGB);
  422. mqttSubscribe(MQTT_TOPIC_COLOR_HSV);
  423. }
  424. // Group color
  425. if (mqtt_group_color.length() > 0) mqttSubscribeRaw(mqtt_group_color.c_str());
  426. // Channels
  427. char buffer[strlen(MQTT_TOPIC_CHANNEL) + 3];
  428. snprintf_P(buffer, sizeof(buffer), PSTR("%s/+"), MQTT_TOPIC_CHANNEL);
  429. mqttSubscribe(buffer);
  430. }
  431. if (type == MQTT_MESSAGE_EVENT) {
  432. // Group color
  433. if ((mqtt_group_color.length() > 0) & (mqtt_group_color.equals(topic))) {
  434. lightColor(payload, true);
  435. lightUpdate(true, mqttForward(), false);
  436. return;
  437. }
  438. // Match topic
  439. String t = mqttMagnitude((char *) topic);
  440. // Color temperature in mireds
  441. if (t.equals(MQTT_TOPIC_MIRED)) {
  442. _fromMireds(atol(payload));
  443. lightUpdate(true, mqttForward());
  444. return;
  445. }
  446. // Color temperature in kelvins
  447. if (t.equals(MQTT_TOPIC_KELVIN)) {
  448. _fromKelvin(atol(payload));
  449. lightUpdate(true, mqttForward());
  450. return;
  451. }
  452. // Color
  453. if (t.equals(MQTT_TOPIC_COLOR_RGB)) {
  454. lightColor(payload, true);
  455. lightUpdate(true, mqttForward());
  456. return;
  457. }
  458. if (t.equals(MQTT_TOPIC_COLOR_HSV)) {
  459. lightColor(payload, false);
  460. lightUpdate(true, mqttForward());
  461. return;
  462. }
  463. // Brightness
  464. if (t.equals(MQTT_TOPIC_BRIGHTNESS)) {
  465. _light_brightness = constrain(atoi(payload), 0, LIGHT_MAX_BRIGHTNESS);
  466. lightUpdate(true, mqttForward());
  467. return;
  468. }
  469. // Channel
  470. if (t.startsWith(MQTT_TOPIC_CHANNEL)) {
  471. unsigned int channelID = t.substring(strlen(MQTT_TOPIC_CHANNEL)+1).toInt();
  472. if (channelID >= _light_channel.size()) {
  473. DEBUG_MSG_P(PSTR("[LIGHT] Wrong channelID (%d)\n"), channelID);
  474. return;
  475. }
  476. lightChannel(channelID, atoi(payload));
  477. lightUpdate(true, mqttForward());
  478. return;
  479. }
  480. }
  481. }
  482. void lightMQTT() {
  483. char buffer[20];
  484. if (_light_has_color) {
  485. // Color
  486. if (getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1) {
  487. _toRGB(buffer, sizeof(buffer));
  488. } else {
  489. _toLong(buffer, sizeof(buffer));
  490. }
  491. mqttSend(MQTT_TOPIC_COLOR_RGB, buffer);
  492. _toHSV(buffer, sizeof(buffer));
  493. mqttSend(MQTT_TOPIC_COLOR_HSV, buffer);
  494. // Brightness
  495. snprintf_P(buffer, sizeof(buffer), PSTR("%d"), _light_brightness);
  496. mqttSend(MQTT_TOPIC_BRIGHTNESS, buffer);
  497. // Mireds
  498. snprintf_P(buffer, sizeof(buffer), PSTR("%d"), _light_mireds);
  499. mqttSend(MQTT_TOPIC_MIRED, buffer);
  500. }
  501. // Channels
  502. for (unsigned int i=0; i < _light_channel.size(); i++) {
  503. itoa(_light_channel[i].inputValue, buffer, 10);
  504. mqttSend(MQTT_TOPIC_CHANNEL, i, buffer);
  505. }
  506. }
  507. void lightMQTTGroup() {
  508. String mqtt_group_color = getSetting("mqttGroupColor");
  509. if (mqtt_group_color.length()>0) {
  510. char buffer[20];
  511. _toCSV(buffer, sizeof(buffer), true);
  512. mqttSendRaw(mqtt_group_color.c_str(), buffer);
  513. }
  514. }
  515. #endif
  516. // -----------------------------------------------------------------------------
  517. // Broker
  518. // -----------------------------------------------------------------------------
  519. #if BROKER_SUPPORT
  520. void lightBroker() {
  521. char buffer[10];
  522. for (unsigned int i=0; i < _light_channel.size(); i++) {
  523. itoa(_light_channel[i].inputValue, buffer, 10);
  524. brokerPublish(MQTT_TOPIC_CHANNEL, i, buffer);
  525. }
  526. }
  527. #endif
  528. // -----------------------------------------------------------------------------
  529. // API
  530. // -----------------------------------------------------------------------------
  531. unsigned char lightChannels() {
  532. return _light_channel.size();
  533. }
  534. bool lightHasColor() {
  535. return _light_has_color;
  536. }
  537. void lightUpdate(bool save, bool forward, bool group_forward) {
  538. _generateBrightness();
  539. // Configure color transition
  540. _light_steps_left = _light_use_transitions ? _light_transition_time / LIGHT_TRANSITION_STEP : 1;
  541. _light_transition_ticker.attach_ms(LIGHT_TRANSITION_STEP, _lightProviderUpdate);
  542. // Report channels to local broker
  543. #if BROKER_SUPPORT
  544. lightBroker();
  545. #endif
  546. // Report color & brightness to MQTT broker
  547. #if MQTT_SUPPORT
  548. if (forward) lightMQTT();
  549. if (group_forward) lightMQTTGroup();
  550. #endif
  551. // Report color to WS clients (using current brightness setting)
  552. #if WEB_SUPPORT
  553. wsSend(_lightWebSocketOnSend);
  554. #endif
  555. #if LIGHT_SAVE_ENABLED
  556. // Delay saving to EEPROM 5 seconds to avoid wearing it out unnecessarily
  557. if (save) _light_save_ticker.once(LIGHT_SAVE_DELAY, _lightColorSave);
  558. #endif
  559. };
  560. void lightUpdate(bool save, bool forward) {
  561. lightUpdate(save, forward, true);
  562. }
  563. #if LIGHT_SAVE_ENABLED == 0
  564. void lightSave() {
  565. _lightColorSave();
  566. }
  567. #endif
  568. void lightState(unsigned char i, bool state) {
  569. _light_channel[i].state = state;
  570. }
  571. bool lightState(unsigned char i) {
  572. return _light_channel[i].state;
  573. }
  574. void lightState(bool state) {
  575. _light_state = state;
  576. }
  577. bool lightState() {
  578. return _light_state;
  579. }
  580. void lightColor(const char * color, bool rgb) {
  581. DEBUG_MSG_P(PSTR("[LIGHT] %s: %s\n"), rgb ? "RGB" : "HSV", color);
  582. if (rgb) {
  583. _fromRGB(color);
  584. } else {
  585. _fromHSV(color);
  586. }
  587. }
  588. void lightColor(const char * color) {
  589. lightColor(color, true);
  590. }
  591. void lightColor(unsigned long color) {
  592. _fromLong(color, false);
  593. }
  594. String lightColor(bool rgb) {
  595. char str[12];
  596. if (rgb) {
  597. _toRGB(str, sizeof(str));
  598. } else {
  599. _toHSV(str, sizeof(str));
  600. }
  601. return String(str);
  602. }
  603. String lightColor() {
  604. return lightColor(true);
  605. }
  606. unsigned int lightChannel(unsigned char id) {
  607. if (id <= _light_channel.size()) {
  608. return _light_channel[id].inputValue;
  609. }
  610. return 0;
  611. }
  612. void lightChannel(unsigned char id, unsigned int value) {
  613. if (id <= _light_channel.size()) {
  614. _light_channel[id].inputValue = constrain(value, 0, LIGHT_MAX_VALUE);
  615. }
  616. }
  617. unsigned int lightBrightness() {
  618. return _light_brightness;
  619. }
  620. void lightBrightness(int b) {
  621. _light_brightness = constrain(b, 0, LIGHT_MAX_BRIGHTNESS);
  622. }
  623. void lightBrightnessStep(int steps) {
  624. lightBrightness(_light_brightness + steps * LIGHT_STEP);
  625. }
  626. // -----------------------------------------------------------------------------
  627. // SETUP
  628. // -----------------------------------------------------------------------------
  629. #if WEB_SUPPORT
  630. bool _lightWebSocketOnReceive(const char * key, JsonVariant& value) {
  631. if (strncmp(key, "light", 5) == 0) return true;
  632. if (strncmp(key, "use", 3) == 0) return true;
  633. return false;
  634. }
  635. void _lightWebSocketOnSend(JsonObject& root) {
  636. root["colorVisible"] = 1;
  637. root["mqttGroupColor"] = getSetting("mqttGroupColor");
  638. root["useColor"] = _light_has_color;
  639. root["useWhite"] = _light_use_white;
  640. root["useColdWhite"] = _light_use_cold_white;
  641. root["useGamma"] = _light_use_gamma;
  642. root["useTransitions"] = _light_use_transitions;
  643. root["lightTime"] = _light_transition_time;
  644. root["useCSS"] = getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1;
  645. bool useRGB = getSetting("useRGB", LIGHT_USE_RGB).toInt() == 1;
  646. root["useRGB"] = useRGB;
  647. if (_light_has_color) {
  648. if (useRGB) {
  649. root["rgb"] = lightColor(true);
  650. root["brightness"] = lightBrightness();
  651. } else {
  652. root["hsv"] = lightColor(false);
  653. }
  654. }
  655. JsonArray& channels = root.createNestedArray("channels");
  656. for (unsigned char id=0; id < _light_channel.size(); id++) {
  657. channels.add(lightChannel(id));
  658. }
  659. }
  660. void _lightWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  661. if (_light_has_color) {
  662. if (strcmp(action, "color") == 0) {
  663. if (data.containsKey("rgb")) {
  664. lightColor(data["rgb"], true);
  665. lightUpdate(true, true);
  666. }
  667. if (data.containsKey("hsv")) {
  668. lightColor(data["hsv"], false);
  669. lightUpdate(true, true);
  670. }
  671. if (data.containsKey("brightness")) {
  672. lightBrightness(data["brightness"]);
  673. lightUpdate(true, true);
  674. }
  675. }
  676. }
  677. if (strcmp(action, "channel") == 0) {
  678. if (data.containsKey("id") && data.containsKey("value")) {
  679. lightChannel(data["id"], data["value"]);
  680. lightUpdate(true, true);
  681. }
  682. }
  683. }
  684. void _lightAPISetup() {
  685. // API entry points (protected with apikey)
  686. if (_light_has_color) {
  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);
  691. } else {
  692. _toLong(buffer, len);
  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<_light_channel.size(); 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_cold_white = getSetting("useColdWhite", LIGHT_USE_COLD_WHITE).toInt() == 1;
  832. if (_light_use_cold_white && ((_light_channel.size() < 5) || !_light_use_white)) {
  833. _light_use_cold_white = false;
  834. setSetting("useColdWhite", _light_use_cold_white);
  835. }
  836. _light_use_gamma = getSetting("useGamma", LIGHT_USE_GAMMA).toInt() == 1;
  837. _light_use_transitions = getSetting("useTransitions", LIGHT_USE_TRANSITIONS).toInt() == 1;
  838. _light_transition_time = getSetting("lightTime", LIGHT_TRANSITION_TIME).toInt();
  839. }
  840. void lightSetup() {
  841. #ifdef LIGHT_ENABLE_PIN
  842. pinMode(LIGHT_ENABLE_PIN, OUTPUT);
  843. digitalWrite(LIGHT_ENABLE_PIN, HIGH);
  844. #endif
  845. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  846. _my92xx = new my92xx(MY92XX_MODEL, MY92XX_CHIPS, MY92XX_DI_PIN, MY92XX_DCKI_PIN, MY92XX_COMMAND);
  847. for (unsigned char i=0; i<LIGHT_CHANNELS; i++) {
  848. _light_channel.push_back((channel_t) {0, false, true, 0, 0, 0});
  849. }
  850. #endif
  851. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  852. #ifdef LIGHT_CH1_PIN
  853. _light_channel.push_back((channel_t) {LIGHT_CH1_PIN, LIGHT_CH1_INVERSE, true, 0, 0, 0});
  854. #endif
  855. #ifdef LIGHT_CH2_PIN
  856. _light_channel.push_back((channel_t) {LIGHT_CH2_PIN, LIGHT_CH2_INVERSE, true, 0, 0, 0});
  857. #endif
  858. #ifdef LIGHT_CH3_PIN
  859. _light_channel.push_back((channel_t) {LIGHT_CH3_PIN, LIGHT_CH3_INVERSE, true, 0, 0, 0});
  860. #endif
  861. #ifdef LIGHT_CH4_PIN
  862. _light_channel.push_back((channel_t) {LIGHT_CH4_PIN, LIGHT_CH4_INVERSE, true, 0, 0, 0});
  863. #endif
  864. #ifdef LIGHT_CH5_PIN
  865. _light_channel.push_back((channel_t) {LIGHT_CH5_PIN, LIGHT_CH5_INVERSE, true, 0, 0, 0});
  866. #endif
  867. uint32 pwm_duty_init[PWM_CHANNEL_NUM_MAX];
  868. uint32 io_info[PWM_CHANNEL_NUM_MAX][3];
  869. for (unsigned int i=0; i < _light_channel.size(); i++) {
  870. pwm_duty_init[i] = 0;
  871. io_info[i][0] = getIOMux(_light_channel[i].pin);
  872. io_info[i][1] = getIOFunc(_light_channel[i].pin);
  873. io_info[i][2] = _light_channel[i].pin;
  874. pinMode(_light_channel[i].pin, OUTPUT);
  875. }
  876. pwm_init(LIGHT_MAX_PWM, pwm_duty_init, PWM_CHANNEL_NUM_MAX, io_info);
  877. pwm_start();
  878. #endif
  879. DEBUG_MSG_P(PSTR("[LIGHT] LIGHT_PROVIDER = %d\n"), LIGHT_PROVIDER);
  880. DEBUG_MSG_P(PSTR("[LIGHT] Number of channels: %d\n"), _light_channel.size());
  881. _lightConfigure();
  882. _lightColorRestore();
  883. #if WEB_SUPPORT
  884. _lightAPISetup();
  885. wsOnSendRegister(_lightWebSocketOnSend);
  886. wsOnActionRegister(_lightWebSocketOnAction);
  887. wsOnReceiveRegister(_lightWebSocketOnReceive);
  888. wsOnAfterParseRegister([]() {
  889. #if LIGHT_SAVE_ENABLED == 0
  890. lightSave();
  891. #endif
  892. _lightConfigure();
  893. });
  894. #endif
  895. #if MQTT_SUPPORT
  896. mqttRegister(_lightMQTTCallback);
  897. #endif
  898. #if TERMINAL_SUPPORT
  899. _lightInitCommands();
  900. #endif
  901. }
  902. #endif // LIGHT_PROVIDER != LIGHT_PROVIDER_NONE