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.

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