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.

1047 lines
30 KiB

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