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.

1074 lines
31 KiB

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