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.

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