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.

1077 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. void _lightWebSocketOnSend(JsonObject& root) {
  583. root["colorVisible"] = 1;
  584. root["mqttGroupColor"] = getSetting("mqttGroupColor");
  585. root["useColor"] = _light_has_color;
  586. root["useWhite"] = _light_use_white;
  587. root["useGamma"] = _light_use_gamma;
  588. root["useTransitions"] = _light_use_transitions;
  589. root["lightTime"] = _light_transition_time;
  590. root["useCSS"] = getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1;
  591. bool useRGB = getSetting("useRGB", LIGHT_USE_RGB).toInt() == 1;
  592. root["useRGB"] = useRGB;
  593. if (_light_has_color) {
  594. if (useRGB) {
  595. root["rgb"] = lightColor(true);
  596. root["brightness"] = lightBrightness();
  597. } else {
  598. root["hsv"] = lightColor(false);
  599. }
  600. }
  601. JsonArray& channels = root.createNestedArray("channels");
  602. for (unsigned char id=0; id < lightChannels(); id++) {
  603. channels.add(lightChannel(id));
  604. }
  605. }
  606. void _lightWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  607. if (_light_has_color) {
  608. if (strcmp(action, "color") == 0) {
  609. if (data.containsKey("rgb")) {
  610. lightColor(data["rgb"], true);
  611. lightUpdate(true, true);
  612. }
  613. if (data.containsKey("hsv")) {
  614. lightColor(data["hsv"], false);
  615. lightUpdate(true, true);
  616. }
  617. if (data.containsKey("brightness")) {
  618. lightBrightness(data["brightness"]);
  619. lightUpdate(true, true);
  620. }
  621. }
  622. }
  623. if (strcmp(action, "channel") == 0) {
  624. if (data.containsKey("id") && data.containsKey("value")) {
  625. lightChannel(data["id"], data["value"]);
  626. lightUpdate(true, true);
  627. }
  628. }
  629. }
  630. void _lightAPISetup() {
  631. // API entry points (protected with apikey)
  632. if (_light_has_color) {
  633. // DEPRECATE
  634. apiRegister(MQTT_TOPIC_COLOR,
  635. [](char * buffer, size_t len) {
  636. if (getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1) {
  637. _toRGB(buffer, len, false);
  638. } else {
  639. _toLong(buffer, len, false);
  640. }
  641. },
  642. [](const char * payload) {
  643. lightColor(payload, true);
  644. lightUpdate(true, true);
  645. }
  646. );
  647. apiRegister(MQTT_TOPIC_COLOR_RGB,
  648. [](char * buffer, size_t len) {
  649. if (getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1) {
  650. _toRGB(buffer, len, false);
  651. } else {
  652. _toLong(buffer, len, false);
  653. }
  654. },
  655. [](const char * payload) {
  656. lightColor(payload, true);
  657. lightUpdate(true, true);
  658. }
  659. );
  660. apiRegister(MQTT_TOPIC_COLOR_HSV,
  661. [](char * buffer, size_t len) {
  662. _toHSV(buffer, len);
  663. },
  664. [](const char * payload) {
  665. lightColor(payload, false);
  666. lightUpdate(true, true);
  667. }
  668. );
  669. apiRegister(MQTT_TOPIC_BRIGHTNESS,
  670. [](char * buffer, size_t len) {
  671. snprintf_P(buffer, len, PSTR("%d"), _light_brightness);
  672. },
  673. [](const char * payload) {
  674. lightBrightness(atoi(payload));
  675. lightUpdate(true, true);
  676. }
  677. );
  678. apiRegister(MQTT_TOPIC_KELVIN,
  679. [](char * buffer, size_t len) {},
  680. [](const char * payload) {
  681. _fromKelvin(atol(payload));
  682. lightUpdate(true, true);
  683. }
  684. );
  685. apiRegister(MQTT_TOPIC_MIRED,
  686. [](char * buffer, size_t len) {},
  687. [](const char * payload) {
  688. _fromMireds(atol(payload));
  689. lightUpdate(true, true);
  690. }
  691. );
  692. }
  693. for (unsigned int id=0; id<lightChannels(); id++) {
  694. char key[15];
  695. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_CHANNEL, id);
  696. apiRegister(key,
  697. [id](char * buffer, size_t len) {
  698. snprintf_P(buffer, len, PSTR("%d"), lightChannel(id));
  699. },
  700. [id](const char * payload) {
  701. lightChannel(id, atoi(payload));
  702. lightUpdate(true, true);
  703. }
  704. );
  705. }
  706. }
  707. #endif // WEB_SUPPORT
  708. #if TERMINAL_SUPPORT
  709. void _lightInitCommands() {
  710. settingsRegisterCommand(F("BRIGHTNESS"), [](Embedis* e) {
  711. if (e->argc > 1) {
  712. lightBrightness(String(e->argv[1]).toInt());
  713. lightUpdate(true, true);
  714. }
  715. DEBUG_MSG_P(PSTR("Brightness: %d\n"), lightBrightness());
  716. DEBUG_MSG_P(PSTR("+OK\n"));
  717. });
  718. settingsRegisterCommand(F("CHANNEL"), [](Embedis* e) {
  719. if (e->argc < 2) {
  720. DEBUG_MSG_P(PSTR("-ERROR: Wrong arguments\n"));
  721. }
  722. int id = String(e->argv[1]).toInt();
  723. if (e->argc > 2) {
  724. int value = String(e->argv[2]).toInt();
  725. lightChannel(id, value);
  726. lightUpdate(true, true);
  727. }
  728. DEBUG_MSG_P(PSTR("Channel #%d: %d\n"), id, lightChannel(id));
  729. DEBUG_MSG_P(PSTR("+OK\n"));
  730. });
  731. settingsRegisterCommand(F("COLOR"), [](Embedis* e) {
  732. if (e->argc > 1) {
  733. String color = 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("KELVIN"), [](Embedis* e) {
  741. if (e->argc > 1) {
  742. String color = String("K") + 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. settingsRegisterCommand(F("MIRED"), [](Embedis* e) {
  750. if (e->argc > 1) {
  751. String color = String("M") + String(e->argv[1]);
  752. lightColor(color.c_str());
  753. lightUpdate(true, true);
  754. }
  755. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  756. DEBUG_MSG_P(PSTR("+OK\n"));
  757. });
  758. }
  759. #endif // TERMINAL_SUPPORT
  760. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  761. unsigned long getIOMux(unsigned long gpio) {
  762. unsigned long muxes[16] = {
  763. PERIPHS_IO_MUX_GPIO0_U, PERIPHS_IO_MUX_U0TXD_U, PERIPHS_IO_MUX_GPIO2_U, PERIPHS_IO_MUX_U0RXD_U,
  764. PERIPHS_IO_MUX_GPIO4_U, PERIPHS_IO_MUX_GPIO5_U, PERIPHS_IO_MUX_SD_CLK_U, PERIPHS_IO_MUX_SD_DATA0_U,
  765. PERIPHS_IO_MUX_SD_DATA1_U, PERIPHS_IO_MUX_SD_DATA2_U, PERIPHS_IO_MUX_SD_DATA3_U, PERIPHS_IO_MUX_SD_CMD_U,
  766. PERIPHS_IO_MUX_MTDI_U, PERIPHS_IO_MUX_MTCK_U, PERIPHS_IO_MUX_MTMS_U, PERIPHS_IO_MUX_MTDO_U
  767. };
  768. return muxes[gpio];
  769. }
  770. unsigned long getIOFunc(unsigned long gpio) {
  771. unsigned long funcs[16] = {
  772. FUNC_GPIO0, FUNC_GPIO1, FUNC_GPIO2, FUNC_GPIO3,
  773. FUNC_GPIO4, FUNC_GPIO5, FUNC_GPIO6, FUNC_GPIO7,
  774. FUNC_GPIO8, FUNC_GPIO9, FUNC_GPIO10, FUNC_GPIO11,
  775. FUNC_GPIO12, FUNC_GPIO13, FUNC_GPIO14, FUNC_GPIO15
  776. };
  777. return funcs[gpio];
  778. }
  779. #endif
  780. void _lightConfigure() {
  781. _light_has_color = getSetting("useColor", LIGHT_USE_COLOR).toInt() == 1;
  782. if (_light_has_color && (_light_channel.size() < 3)) {
  783. _light_has_color = false;
  784. setSetting("useColor", _light_has_color);
  785. }
  786. _light_use_white = getSetting("useWhite", LIGHT_USE_WHITE).toInt() == 1;
  787. if (_light_use_white && (_light_channel.size() < 4)) {
  788. _light_use_white = false;
  789. setSetting("useWhite", _light_use_white);
  790. }
  791. _light_use_gamma = getSetting("useGamma", LIGHT_USE_GAMMA).toInt() == 1;
  792. _light_use_transitions = getSetting("useTransitions", LIGHT_USE_TRANSITIONS).toInt() == 1;
  793. _light_transition_time = getSetting("lightTime", LIGHT_TRANSITION_TIME).toInt();
  794. }
  795. void lightSetup() {
  796. #ifdef LIGHT_ENABLE_PIN
  797. pinMode(LIGHT_ENABLE_PIN, OUTPUT);
  798. digitalWrite(LIGHT_ENABLE_PIN, HIGH);
  799. #endif
  800. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  801. _my92xx = new my92xx(MY92XX_MODEL, MY92XX_CHIPS, MY92XX_DI_PIN, MY92XX_DCKI_PIN, MY92XX_COMMAND);
  802. for (unsigned char i=0; i<LIGHT_CHANNELS; i++) {
  803. _light_channel.push_back((channel_t) {0, false, true, 0, 0, 0});
  804. }
  805. #endif
  806. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  807. #ifdef LIGHT_CH1_PIN
  808. _light_channel.push_back((channel_t) {LIGHT_CH1_PIN, LIGHT_CH1_INVERSE, true, 0, 0, 0});
  809. #endif
  810. #ifdef LIGHT_CH2_PIN
  811. _light_channel.push_back((channel_t) {LIGHT_CH2_PIN, LIGHT_CH2_INVERSE, true, 0, 0, 0});
  812. #endif
  813. #ifdef LIGHT_CH3_PIN
  814. _light_channel.push_back((channel_t) {LIGHT_CH3_PIN, LIGHT_CH3_INVERSE, true, 0, 0, 0});
  815. #endif
  816. #ifdef LIGHT_CH4_PIN
  817. _light_channel.push_back((channel_t) {LIGHT_CH4_PIN, LIGHT_CH4_INVERSE, true, 0, 0, 0});
  818. #endif
  819. #ifdef LIGHT_CH5_PIN
  820. _light_channel.push_back((channel_t) {LIGHT_CH5_PIN, LIGHT_CH5_INVERSE, true, 0, 0, 0});
  821. #endif
  822. uint32 pwm_duty_init[PWM_CHANNEL_NUM_MAX];
  823. uint32 io_info[PWM_CHANNEL_NUM_MAX][3];
  824. for (unsigned int i=0; i < _light_channel.size(); i++) {
  825. pwm_duty_init[i] = 0;
  826. io_info[i][0] = getIOMux(_light_channel[i].pin);
  827. io_info[i][1] = getIOFunc(_light_channel[i].pin);
  828. io_info[i][2] = _light_channel[i].pin;
  829. pinMode(_light_channel[i].pin, OUTPUT);
  830. }
  831. pwm_init(LIGHT_MAX_PWM, pwm_duty_init, PWM_CHANNEL_NUM_MAX, io_info);
  832. pwm_start();
  833. #endif
  834. DEBUG_MSG_P(PSTR("[LIGHT] LIGHT_PROVIDER = %d\n"), LIGHT_PROVIDER);
  835. DEBUG_MSG_P(PSTR("[LIGHT] Number of channels: %d\n"), _light_channel.size());
  836. _lightColorRestore();
  837. _lightConfigure();
  838. #if WEB_SUPPORT
  839. _lightAPISetup();
  840. wsOnSendRegister(_lightWebSocketOnSend);
  841. wsOnActionRegister(_lightWebSocketOnAction);
  842. wsOnAfterParseRegister([]() {
  843. #if LIGHT_SAVE_ENABLED == 0
  844. lightSave();
  845. #endif
  846. _lightConfigure();
  847. });
  848. #endif
  849. #if MQTT_SUPPORT
  850. mqttRegister(_lightMQTTCallback);
  851. #endif
  852. #if TERMINAL_SUPPORT
  853. _lightInitCommands();
  854. #endif
  855. }
  856. #endif // LIGHT_PROVIDER != LIGHT_PROVIDER_NONE