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.

1084 lines
31 KiB

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