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.

1058 lines
32 KiB

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