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.

1055 lines
31 KiB

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