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
33 KiB

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