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.

1065 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. 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. itoa(_light_channel[i].value, buffer, 10);
  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. // Broker
  466. // -----------------------------------------------------------------------------
  467. #if BROKER_SUPPORT
  468. void lightBroker() {
  469. char buffer[10];
  470. for (unsigned int i=0; i < _light_channel.size(); i++) {
  471. itoa(_light_channel[i].value, buffer, 10);
  472. brokerPublish(MQTT_TOPIC_CHANNEL, i, buffer);
  473. }
  474. }
  475. #endif
  476. // -----------------------------------------------------------------------------
  477. // API
  478. // -----------------------------------------------------------------------------
  479. unsigned char lightChannels() {
  480. return _light_channel.size();
  481. }
  482. bool lightHasColor() {
  483. return _light_has_color;
  484. }
  485. unsigned char lightWhiteChannels() {
  486. return _light_channel.size() % 3;
  487. }
  488. void lightUpdate(bool save, bool forward, bool group_forward) {
  489. // Configure color transition
  490. _light_steps_left = _light_use_transitions ? LIGHT_TRANSITION_STEPS : 1;
  491. _light_transition_ticker.attach_ms(LIGHT_TRANSITION_STEP, _lightProviderUpdate);
  492. // Report channels to local broker
  493. #if BROKER_SUPPORT
  494. lightBroker();
  495. #endif
  496. // Report color & brightness to MQTT broker
  497. #if MQTT_SUPPORT
  498. if (forward) lightMQTT();
  499. if (group_forward) lightMQTTGroup();
  500. #endif
  501. // Report color to WS clients (using current brightness setting)
  502. #if WEB_SUPPORT
  503. wsSend(_lightWebSocketOnSend);
  504. #endif
  505. #if LIGHT_SAVE_ENABLED
  506. // Delay saving to EEPROM 5 seconds to avoid wearing it out unnecessarily
  507. if (save) _light_save_ticker.once(LIGHT_SAVE_DELAY, _lightColorSave);
  508. #endif
  509. };
  510. void lightUpdate(bool save, bool forward) {
  511. lightUpdate(save, forward, true);
  512. }
  513. #if LIGHT_SAVE_ENABLED == 0
  514. void lightSave() {
  515. _lightColorSave();
  516. }
  517. #endif
  518. void lightState(bool state) {
  519. _light_state = state;
  520. }
  521. bool lightState() {
  522. return _light_state;
  523. }
  524. void lightColor(const char * color, bool rgb) {
  525. DEBUG_MSG_P(PSTR("[LIGHT] %s: %s\n"), rgb ? "RGB" : "HSV", color);
  526. if (rgb) {
  527. _fromRGB(color);
  528. } else {
  529. _fromHSV(color);
  530. }
  531. }
  532. void lightColor(const char * color) {
  533. lightColor(color, true);
  534. }
  535. void lightColor(unsigned long color) {
  536. _fromLong(color, false);
  537. }
  538. String lightColor(bool rgb) {
  539. char str[12];
  540. if (rgb) {
  541. _toRGB(str, sizeof(str), false);
  542. } else {
  543. _toHSV(str, sizeof(str));
  544. }
  545. return String(str);
  546. }
  547. String lightColor() {
  548. return lightColor(true);
  549. }
  550. unsigned int lightChannel(unsigned char id) {
  551. if (id <= _light_channel.size()) {
  552. return _light_channel[id].value;
  553. }
  554. return 0;
  555. }
  556. void lightChannel(unsigned char id, unsigned int value) {
  557. if (id <= _light_channel.size()) {
  558. _light_channel[id].value = constrain(value, 0, LIGHT_MAX_VALUE);
  559. }
  560. }
  561. unsigned int lightBrightness() {
  562. return _light_brightness;
  563. }
  564. void lightBrightness(int b) {
  565. _light_brightness = constrain(b, 0, LIGHT_MAX_BRIGHTNESS);
  566. }
  567. void lightBrightnessStep(int steps) {
  568. lightBrightness(_light_brightness + steps * LIGHT_STEP);
  569. }
  570. // -----------------------------------------------------------------------------
  571. // SETUP
  572. // -----------------------------------------------------------------------------
  573. #if WEB_SUPPORT
  574. void _lightWebSocketOnSend(JsonObject& root) {
  575. root["colorVisible"] = 1;
  576. root["mqttGroupColor"] = getSetting("mqttGroupColor");
  577. root["useColor"] = _light_has_color;
  578. root["useWhite"] = _light_use_white;
  579. root["useGamma"] = _light_use_gamma;
  580. root["useTransitions"] = _light_use_transitions;
  581. root["useCSS"] = getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1;
  582. bool useRGB = getSetting("useRGB", LIGHT_USE_RGB).toInt() == 1;
  583. root["useRGB"] = useRGB;
  584. if (_light_has_color) {
  585. if (useRGB) {
  586. root["rgb"] = lightColor(true);
  587. root["brightness"] = lightBrightness();
  588. } else {
  589. root["hsv"] = lightColor(false);
  590. }
  591. }
  592. JsonArray& channels = root.createNestedArray("channels");
  593. for (unsigned char id=0; id < lightChannels(); id++) {
  594. channels.add(lightChannel(id));
  595. }
  596. }
  597. void _lightWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  598. if (_light_has_color) {
  599. if (strcmp(action, "color") == 0) {
  600. if (data.containsKey("rgb")) {
  601. lightColor(data["rgb"], true);
  602. lightUpdate(true, true);
  603. }
  604. if (data.containsKey("hsv")) {
  605. lightColor(data["hsv"], false);
  606. lightUpdate(true, true);
  607. }
  608. if (data.containsKey("brightness")) {
  609. lightBrightness(data["brightness"]);
  610. lightUpdate(true, true);
  611. }
  612. }
  613. }
  614. if (strcmp(action, "channel") == 0) {
  615. if (data.containsKey("id") && data.containsKey("value")) {
  616. lightChannel(data["id"], data["value"]);
  617. lightUpdate(true, true);
  618. }
  619. }
  620. }
  621. void _lightAPISetup() {
  622. // API entry points (protected with apikey)
  623. if (_light_has_color) {
  624. // DEPRECATE
  625. apiRegister(MQTT_TOPIC_COLOR,
  626. [](char * buffer, size_t len) {
  627. if (getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1) {
  628. _toRGB(buffer, len, false);
  629. } else {
  630. _toLong(buffer, len, false);
  631. }
  632. },
  633. [](const char * payload) {
  634. lightColor(payload, true);
  635. lightUpdate(true, true);
  636. }
  637. );
  638. apiRegister(MQTT_TOPIC_COLOR_RGB,
  639. [](char * buffer, size_t len) {
  640. if (getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1) {
  641. _toRGB(buffer, len, false);
  642. } else {
  643. _toLong(buffer, len, false);
  644. }
  645. },
  646. [](const char * payload) {
  647. lightColor(payload, true);
  648. lightUpdate(true, true);
  649. }
  650. );
  651. apiRegister(MQTT_TOPIC_COLOR_HSV,
  652. [](char * buffer, size_t len) {
  653. _toHSV(buffer, len);
  654. },
  655. [](const char * payload) {
  656. lightColor(payload, false);
  657. lightUpdate(true, true);
  658. }
  659. );
  660. apiRegister(MQTT_TOPIC_BRIGHTNESS,
  661. [](char * buffer, size_t len) {
  662. snprintf_P(buffer, len, PSTR("%d"), _light_brightness);
  663. },
  664. [](const char * payload) {
  665. lightBrightness(atoi(payload));
  666. lightUpdate(true, true);
  667. }
  668. );
  669. apiRegister(MQTT_TOPIC_KELVIN,
  670. [](char * buffer, size_t len) {},
  671. [](const char * payload) {
  672. _fromKelvin(atol(payload));
  673. lightUpdate(true, true);
  674. }
  675. );
  676. apiRegister(MQTT_TOPIC_MIRED,
  677. [](char * buffer, size_t len) {},
  678. [](const char * payload) {
  679. _fromMireds(atol(payload));
  680. lightUpdate(true, true);
  681. }
  682. );
  683. }
  684. for (unsigned int id=0; id<lightChannels(); id++) {
  685. char key[15];
  686. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_CHANNEL, id);
  687. apiRegister(key,
  688. [id](char * buffer, size_t len) {
  689. snprintf_P(buffer, len, PSTR("%d"), lightChannel(id));
  690. },
  691. [id](const char * payload) {
  692. lightChannel(id, atoi(payload));
  693. lightUpdate(true, true);
  694. }
  695. );
  696. }
  697. }
  698. #endif // WEB_SUPPORT
  699. #if TERMINAL_SUPPORT
  700. void _lightInitCommands() {
  701. settingsRegisterCommand(F("BRIGHTNESS"), [](Embedis* e) {
  702. if (e->argc > 1) {
  703. lightBrightness(String(e->argv[1]).toInt());
  704. lightUpdate(true, true);
  705. }
  706. DEBUG_MSG_P(PSTR("Brightness: %d\n"), lightBrightness());
  707. DEBUG_MSG_P(PSTR("+OK\n"));
  708. });
  709. settingsRegisterCommand(F("CHANNEL"), [](Embedis* e) {
  710. if (e->argc < 2) {
  711. DEBUG_MSG_P(PSTR("-ERROR: Wrong arguments\n"));
  712. }
  713. int id = String(e->argv[1]).toInt();
  714. if (e->argc > 2) {
  715. int value = String(e->argv[2]).toInt();
  716. lightChannel(id, value);
  717. lightUpdate(true, true);
  718. }
  719. DEBUG_MSG_P(PSTR("Channel #%d: %d\n"), id, lightChannel(id));
  720. DEBUG_MSG_P(PSTR("+OK\n"));
  721. });
  722. settingsRegisterCommand(F("COLOR"), [](Embedis* e) {
  723. if (e->argc > 1) {
  724. String color = String(e->argv[1]);
  725. lightColor(color.c_str());
  726. lightUpdate(true, true);
  727. }
  728. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  729. DEBUG_MSG_P(PSTR("+OK\n"));
  730. });
  731. settingsRegisterCommand(F("KELVIN"), [](Embedis* e) {
  732. if (e->argc > 1) {
  733. String color = String("K") + String(e->argv[1]);
  734. lightColor(color.c_str());
  735. lightUpdate(true, true);
  736. }
  737. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  738. DEBUG_MSG_P(PSTR("+OK\n"));
  739. });
  740. settingsRegisterCommand(F("MIRED"), [](Embedis* e) {
  741. if (e->argc > 1) {
  742. String color = String("M") + String(e->argv[1]);
  743. lightColor(color.c_str());
  744. lightUpdate(true, true);
  745. }
  746. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  747. DEBUG_MSG_P(PSTR("+OK\n"));
  748. });
  749. }
  750. #endif // TERMINAL_SUPPORT
  751. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  752. unsigned long getIOMux(unsigned long gpio) {
  753. unsigned long muxes[16] = {
  754. PERIPHS_IO_MUX_GPIO0_U, PERIPHS_IO_MUX_U0TXD_U, PERIPHS_IO_MUX_GPIO2_U, PERIPHS_IO_MUX_U0RXD_U,
  755. PERIPHS_IO_MUX_GPIO4_U, PERIPHS_IO_MUX_GPIO5_U, PERIPHS_IO_MUX_SD_CLK_U, PERIPHS_IO_MUX_SD_DATA0_U,
  756. PERIPHS_IO_MUX_SD_DATA1_U, PERIPHS_IO_MUX_SD_DATA2_U, PERIPHS_IO_MUX_SD_DATA3_U, PERIPHS_IO_MUX_SD_CMD_U,
  757. PERIPHS_IO_MUX_MTDI_U, PERIPHS_IO_MUX_MTCK_U, PERIPHS_IO_MUX_MTMS_U, PERIPHS_IO_MUX_MTDO_U
  758. };
  759. return muxes[gpio];
  760. }
  761. unsigned long getIOFunc(unsigned long gpio) {
  762. unsigned long funcs[16] = {
  763. FUNC_GPIO0, FUNC_GPIO1, FUNC_GPIO2, FUNC_GPIO3,
  764. FUNC_GPIO4, FUNC_GPIO5, FUNC_GPIO6, FUNC_GPIO7,
  765. FUNC_GPIO8, FUNC_GPIO9, FUNC_GPIO10, FUNC_GPIO11,
  766. FUNC_GPIO12, FUNC_GPIO13, FUNC_GPIO14, FUNC_GPIO15
  767. };
  768. return funcs[gpio];
  769. }
  770. #endif
  771. void _lightConfigure() {
  772. _light_has_color = getSetting("useColor", LIGHT_USE_COLOR).toInt() == 1;
  773. if (_light_has_color && (_light_channel.size() < 3)) {
  774. _light_has_color = false;
  775. setSetting("useColor", _light_has_color);
  776. }
  777. _light_use_white = getSetting("useWhite", LIGHT_USE_WHITE).toInt() == 1;
  778. if (_light_use_white && (_light_channel.size() < 4)) {
  779. _light_use_white = false;
  780. setSetting("useWhite", _light_use_white);
  781. }
  782. _light_use_gamma = getSetting("useGamma", LIGHT_USE_GAMMA).toInt() == 1;
  783. _light_use_transitions = getSetting("useTransitions", LIGHT_USE_TRANSITIONS).toInt() == 1;
  784. }
  785. void lightSetup() {
  786. #ifdef LIGHT_ENABLE_PIN
  787. pinMode(LIGHT_ENABLE_PIN, OUTPUT);
  788. digitalWrite(LIGHT_ENABLE_PIN, HIGH);
  789. #endif
  790. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  791. _my92xx = new my92xx(MY92XX_MODEL, MY92XX_CHIPS, MY92XX_DI_PIN, MY92XX_DCKI_PIN, MY92XX_COMMAND);
  792. for (unsigned char i=0; i<LIGHT_CHANNELS; i++) {
  793. _light_channel.push_back((channel_t) {0, false, 0, 0, 0});
  794. }
  795. #endif
  796. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  797. #ifdef LIGHT_CH1_PIN
  798. _light_channel.push_back((channel_t) {LIGHT_CH1_PIN, LIGHT_CH1_INVERSE, 0, 0, 0});
  799. #endif
  800. #ifdef LIGHT_CH2_PIN
  801. _light_channel.push_back((channel_t) {LIGHT_CH2_PIN, LIGHT_CH2_INVERSE, 0, 0, 0});
  802. #endif
  803. #ifdef LIGHT_CH3_PIN
  804. _light_channel.push_back((channel_t) {LIGHT_CH3_PIN, LIGHT_CH3_INVERSE, 0, 0, 0});
  805. #endif
  806. #ifdef LIGHT_CH4_PIN
  807. _light_channel.push_back((channel_t) {LIGHT_CH4_PIN, LIGHT_CH4_INVERSE, 0, 0, 0});
  808. #endif
  809. #ifdef LIGHT_CH5_PIN
  810. _light_channel.push_back((channel_t) {LIGHT_CH5_PIN, LIGHT_CH5_INVERSE, 0, 0, 0});
  811. #endif
  812. uint32 pwm_duty_init[PWM_CHANNEL_NUM_MAX];
  813. uint32 io_info[PWM_CHANNEL_NUM_MAX][3];
  814. for (unsigned int i=0; i < _light_channel.size(); i++) {
  815. pwm_duty_init[i] = 0;
  816. io_info[i][0] = getIOMux(_light_channel[i].pin);
  817. io_info[i][1] = getIOFunc(_light_channel[i].pin);
  818. io_info[i][2] = _light_channel[i].pin;
  819. pinMode(_light_channel[i].pin, OUTPUT);
  820. }
  821. pwm_init(LIGHT_MAX_PWM, pwm_duty_init, PWM_CHANNEL_NUM_MAX, io_info);
  822. pwm_start();
  823. #endif
  824. DEBUG_MSG_P(PSTR("[LIGHT] LIGHT_PROVIDER = %d\n"), LIGHT_PROVIDER);
  825. DEBUG_MSG_P(PSTR("[LIGHT] Number of channels: %d\n"), _light_channel.size());
  826. _lightColorRestore();
  827. _lightConfigure();
  828. #if WEB_SUPPORT
  829. _lightAPISetup();
  830. wsOnSendRegister(_lightWebSocketOnSend);
  831. wsOnActionRegister(_lightWebSocketOnAction);
  832. wsOnAfterParseRegister([]() {
  833. #if LIGHT_SAVE_ENABLED == 0
  834. lightSave();
  835. #endif
  836. _lightConfigure();
  837. });
  838. #endif
  839. #if MQTT_SUPPORT
  840. mqttRegister(_lightMQTTCallback);
  841. #endif
  842. #if TERMINAL_SUPPORT
  843. _lightInitCommands();
  844. #endif
  845. }
  846. #endif // LIGHT_PROVIDER != LIGHT_PROVIDER_NONE