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.

1129 lines
34 KiB

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