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.

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