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. bool _lightWebSocketOnReceive(const char * key, JsonVariant& value) {
  612. if (strncmp(key, "lit", 3) == 0) return true;
  613. return false;
  614. }
  615. void _lightWebSocketOnSend(JsonObject& root) {
  616. root["litVisible"] = 1;
  617. root["mqttGroupColor"] = getSetting("mqttGroupColor");
  618. root["litColor"] = _light_has_color;
  619. root["litWhite"] = _light_use_white;
  620. root["litGamma"] = _light_use_gamma;
  621. root["litTrans"] = _light_use_transitions;
  622. root["litTime"] = _light_transition_time;
  623. root["litCSS"] = getSetting("litCSS", LIGHT_USE_CSS).toInt() == 1;
  624. bool useRGB = getSetting("litRGB", LIGHT_USE_RGB).toInt() == 1;
  625. root["litRGB"] = useRGB;
  626. if (_light_has_color) {
  627. if (_light_use_cct) {
  628. root["litCCT"] = _light_use_cct;
  629. root["mireds"] = _light_mireds;
  630. }
  631. if (useRGB) {
  632. root["rgb"] = lightColor(true);
  633. root["brightness"] = lightBrightness();
  634. } else {
  635. root["hsv"] = lightColor(false);
  636. }
  637. }
  638. JsonArray& channels = root.createNestedArray("channels");
  639. for (unsigned char id=0; id < _light_channel.size(); id++) {
  640. channels.add(lightChannel(id));
  641. }
  642. }
  643. void _lightWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  644. if (_light_has_color) {
  645. if (strcmp(action, "color") == 0) {
  646. if (data.containsKey("rgb")) {
  647. lightColor(data["rgb"], true);
  648. lightUpdate(true, true);
  649. }
  650. if (data.containsKey("hsv")) {
  651. lightColor(data["hsv"], false);
  652. lightUpdate(true, true);
  653. }
  654. if (data.containsKey("brightness")) {
  655. lightBrightness(data["brightness"]);
  656. lightUpdate(true, true);
  657. }
  658. }
  659. if (_light_use_cct) {
  660. if (strcmp(action, "mireds") == 0) {
  661. _fromMireds(data["mireds"]);
  662. lightUpdate(true, true);
  663. }
  664. }
  665. }
  666. if (strcmp(action, "channel") == 0) {
  667. if (data.containsKey("id") && data.containsKey("value")) {
  668. lightChannel(data["id"], data["value"]);
  669. lightUpdate(true, true);
  670. }
  671. }
  672. }
  673. void _lightAPISetup() {
  674. // API entry points (protected with apikey)
  675. if (_light_has_color) {
  676. apiRegister(MQTT_TOPIC_COLOR_RGB,
  677. [](char * buffer, size_t len) {
  678. if (getSetting("litCSS", LIGHT_USE_CSS).toInt() == 1) {
  679. _toRGB(buffer, len);
  680. } else {
  681. _toLong(buffer, len);
  682. }
  683. },
  684. [](const char * payload) {
  685. lightColor(payload, true);
  686. lightUpdate(true, true);
  687. }
  688. );
  689. apiRegister(MQTT_TOPIC_COLOR_HSV,
  690. [](char * buffer, size_t len) {
  691. _toHSV(buffer, len);
  692. },
  693. [](const char * payload) {
  694. lightColor(payload, false);
  695. lightUpdate(true, true);
  696. }
  697. );
  698. apiRegister(MQTT_TOPIC_BRIGHTNESS,
  699. [](char * buffer, size_t len) {
  700. snprintf_P(buffer, len, PSTR("%d"), _light_brightness);
  701. },
  702. [](const char * payload) {
  703. lightBrightness(atoi(payload));
  704. lightUpdate(true, true);
  705. }
  706. );
  707. apiRegister(MQTT_TOPIC_KELVIN,
  708. [](char * buffer, size_t len) {},
  709. [](const char * payload) {
  710. _fromKelvin(atol(payload));
  711. lightUpdate(true, true);
  712. }
  713. );
  714. apiRegister(MQTT_TOPIC_MIRED,
  715. [](char * buffer, size_t len) {},
  716. [](const char * payload) {
  717. _fromMireds(atol(payload));
  718. lightUpdate(true, true);
  719. }
  720. );
  721. }
  722. for (unsigned int id=0; id<_light_channel.size(); id++) {
  723. char key[15];
  724. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_CHANNEL, id);
  725. apiRegister(key,
  726. [id](char * buffer, size_t len) {
  727. snprintf_P(buffer, len, PSTR("%d"), lightChannel(id));
  728. },
  729. [id](const char * payload) {
  730. lightChannel(id, atoi(payload));
  731. lightUpdate(true, true);
  732. }
  733. );
  734. }
  735. }
  736. #endif // WEB_SUPPORT
  737. #if TERMINAL_SUPPORT
  738. void _lightInitCommands() {
  739. settingsRegisterCommand(F("brightness"), [](Embedis* e) {
  740. if (e->argc > 1) {
  741. lightBrightness(String(e->argv[1]).toInt());
  742. lightUpdate(true, true);
  743. }
  744. DEBUG_MSG_P(PSTR("Brightness: %d\n"), lightBrightness());
  745. DEBUG_MSG_P(PSTR("+OK\n"));
  746. });
  747. settingsRegisterCommand(F("CHANNEL"), [](Embedis* e) {
  748. if (e->argc < 2) {
  749. DEBUG_MSG_P(PSTR("-ERROR: Wrong arguments\n"));
  750. }
  751. int id = String(e->argv[1]).toInt();
  752. if (e->argc > 2) {
  753. int value = String(e->argv[2]).toInt();
  754. lightChannel(id, value);
  755. lightUpdate(true, true);
  756. }
  757. DEBUG_MSG_P(PSTR("Channel #%d: %d\n"), id, lightChannel(id));
  758. DEBUG_MSG_P(PSTR("+OK\n"));
  759. });
  760. settingsRegisterCommand(F("COLOR"), [](Embedis* e) {
  761. if (e->argc > 1) {
  762. String color = String(e->argv[1]);
  763. lightColor(color.c_str());
  764. lightUpdate(true, true);
  765. }
  766. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  767. DEBUG_MSG_P(PSTR("+OK\n"));
  768. });
  769. settingsRegisterCommand(F("KELVIN"), [](Embedis* e) {
  770. if (e->argc > 1) {
  771. String color = String("K") + String(e->argv[1]);
  772. lightColor(color.c_str());
  773. lightUpdate(true, true);
  774. }
  775. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  776. DEBUG_MSG_P(PSTR("+OK\n"));
  777. });
  778. settingsRegisterCommand(F("MIRED"), [](Embedis* e) {
  779. if (e->argc > 1) {
  780. String color = String("M") + String(e->argv[1]);
  781. lightColor(color.c_str());
  782. lightUpdate(true, true);
  783. }
  784. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  785. DEBUG_MSG_P(PSTR("+OK\n"));
  786. });
  787. }
  788. #endif // TERMINAL_SUPPORT
  789. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  790. unsigned long getIOMux(unsigned long gpio) {
  791. unsigned long muxes[16] = {
  792. PERIPHS_IO_MUX_GPIO0_U, PERIPHS_IO_MUX_U0TXD_U, PERIPHS_IO_MUX_GPIO2_U, PERIPHS_IO_MUX_U0RXD_U,
  793. PERIPHS_IO_MUX_GPIO4_U, PERIPHS_IO_MUX_GPIO5_U, PERIPHS_IO_MUX_SD_CLK_U, PERIPHS_IO_MUX_SD_DATA0_U,
  794. PERIPHS_IO_MUX_SD_DATA1_U, PERIPHS_IO_MUX_SD_DATA2_U, PERIPHS_IO_MUX_SD_DATA3_U, PERIPHS_IO_MUX_SD_CMD_U,
  795. PERIPHS_IO_MUX_MTDI_U, PERIPHS_IO_MUX_MTCK_U, PERIPHS_IO_MUX_MTMS_U, PERIPHS_IO_MUX_MTDO_U
  796. };
  797. return muxes[gpio];
  798. }
  799. unsigned long getIOFunc(unsigned long gpio) {
  800. unsigned long funcs[16] = {
  801. FUNC_GPIO0, FUNC_GPIO1, FUNC_GPIO2, FUNC_GPIO3,
  802. FUNC_GPIO4, FUNC_GPIO5, FUNC_GPIO6, FUNC_GPIO7,
  803. FUNC_GPIO8, FUNC_GPIO9, FUNC_GPIO10, FUNC_GPIO11,
  804. FUNC_GPIO12, FUNC_GPIO13, FUNC_GPIO14, FUNC_GPIO15
  805. };
  806. return funcs[gpio];
  807. }
  808. #endif
  809. void _lightConfigure() {
  810. _light_has_color = getSetting("litColor", LIGHT_USE_COLOR).toInt() == 1;
  811. if (_light_has_color && (_light_channel.size() < 3)) {
  812. _light_has_color = false;
  813. setSetting("litColor", _light_has_color);
  814. }
  815. _light_use_white = getSetting("litWhite", LIGHT_USE_WHITE).toInt() == 1;
  816. if (_light_use_white && (_light_channel.size() < 4)) {
  817. _light_use_white = false;
  818. setSetting("litWhite", _light_use_white);
  819. }
  820. _light_use_cct = getSetting("litCCT", LIGHT_USE_CCT).toInt() == 1;
  821. if (_light_use_cct && ((_light_channel.size() < 5) || !_light_use_white)) {
  822. _light_use_cct = false;
  823. setSetting("litCCT", _light_use_cct);
  824. }
  825. _light_use_gamma = getSetting("litGamma", LIGHT_USE_GAMMA).toInt() == 1;
  826. _light_use_transitions = getSetting("litTrans", LIGHT_USE_TRANSITIONS).toInt() == 1;
  827. _light_transition_time = getSetting("litTime", LIGHT_TRANSITION_TIME).toInt();
  828. }
  829. void _lightBackwards() {
  830. moveSettings("ch", "litCH"); // 1.13.1 - 2018-06-26
  831. moveSetting("useCSS", "litCSS"); // 1.13.1 - 2018-06-26
  832. moveSetting("useRGB", "litRGB"); // 1.13.1 - 2018-06-26
  833. moveSetting("useColor", "litColor"); // 1.13.1 - 2018-06-26
  834. moveSetting("useWhite", "litWhite"); // 1.13.1 - 2018-06-26
  835. moveSetting("useCCT", "litCCT"); // 1.13.1 - 2018-06-26
  836. moveSetting("useGamma", "litGamma"); // 1.13.1 - 2018-06-26
  837. moveSetting("useTransitions", "litTrans"); // 1.13.1 - 2018-06-26
  838. moveSetting("lightTime", "litTime"); // 1.13.1 - 2018-06-26
  839. moveSetting("brightness", "litBright"); // 1.13.1 - 2018-06-26
  840. moveSetting("mireds", "litMireds"); // 1.13.1 - 2018-06-26
  841. }
  842. void lightSetup() {
  843. _lightBackwards();
  844. #ifdef LIGHT_ENABLE_PIN
  845. pinMode(LIGHT_ENABLE_PIN, OUTPUT);
  846. digitalWrite(LIGHT_ENABLE_PIN, HIGH);
  847. #endif
  848. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  849. _my92xx = new my92xx(MY92XX_MODEL, MY92XX_CHIPS, MY92XX_DI_PIN, MY92XX_DCKI_PIN, MY92XX_COMMAND);
  850. for (unsigned char i=0; i<LIGHT_CHANNELS; i++) {
  851. _light_channel.push_back((channel_t) {0, false, true, 0, 0, 0});
  852. }
  853. #endif
  854. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  855. #ifdef LIGHT_CH1_PIN
  856. _light_channel.push_back((channel_t) {LIGHT_CH1_PIN, LIGHT_CH1_INVERSE, true, 0, 0, 0});
  857. #endif
  858. #ifdef LIGHT_CH2_PIN
  859. _light_channel.push_back((channel_t) {LIGHT_CH2_PIN, LIGHT_CH2_INVERSE, true, 0, 0, 0});
  860. #endif
  861. #ifdef LIGHT_CH3_PIN
  862. _light_channel.push_back((channel_t) {LIGHT_CH3_PIN, LIGHT_CH3_INVERSE, true, 0, 0, 0});
  863. #endif
  864. #ifdef LIGHT_CH4_PIN
  865. _light_channel.push_back((channel_t) {LIGHT_CH4_PIN, LIGHT_CH4_INVERSE, true, 0, 0, 0});
  866. #endif
  867. #ifdef LIGHT_CH5_PIN
  868. _light_channel.push_back((channel_t) {LIGHT_CH5_PIN, LIGHT_CH5_INVERSE, true, 0, 0, 0});
  869. #endif
  870. uint32 pwm_duty_init[PWM_CHANNEL_NUM_MAX];
  871. uint32 io_info[PWM_CHANNEL_NUM_MAX][3];
  872. for (unsigned int i=0; i < _light_channel.size(); i++) {
  873. pwm_duty_init[i] = 0;
  874. io_info[i][0] = getIOMux(_light_channel[i].pin);
  875. io_info[i][1] = getIOFunc(_light_channel[i].pin);
  876. io_info[i][2] = _light_channel[i].pin;
  877. pinMode(_light_channel[i].pin, OUTPUT);
  878. }
  879. pwm_init(LIGHT_MAX_PWM, pwm_duty_init, PWM_CHANNEL_NUM_MAX, io_info);
  880. pwm_start();
  881. #endif
  882. DEBUG_MSG_P(PSTR("[LIGHT] LIGHT_PROVIDER = %d\n"), LIGHT_PROVIDER);
  883. DEBUG_MSG_P(PSTR("[LIGHT] Number of channels: %d\n"), _light_channel.size());
  884. _lightConfigure();
  885. _lightColorRestore();
  886. #if WEB_SUPPORT
  887. _lightAPISetup();
  888. wsOnSendRegister(_lightWebSocketOnSend);
  889. wsOnActionRegister(_lightWebSocketOnAction);
  890. wsOnReceiveRegister(_lightWebSocketOnReceive);
  891. wsOnAfterParseRegister([]() {
  892. #if LIGHT_SAVE_ENABLED == 0
  893. lightSave();
  894. #endif
  895. _lightConfigure();
  896. });
  897. #endif
  898. #if MQTT_SUPPORT
  899. mqttRegister(_lightMQTTCallback);
  900. #endif
  901. #if TERMINAL_SUPPORT
  902. _lightInitCommands();
  903. #endif
  904. }
  905. #endif // LIGHT_PROVIDER != LIGHT_PROVIDER_NONE