Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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