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.

1142 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. // Apply brightness equally to all channels
  121. for (unsigned char i=0; i < _light_channel.size(); i++) {
  122. _light_channel[i].value = _light_channel[i].inputValue * brightness;
  123. }
  124. }
  125. }
  126. // -----------------------------------------------------------------------------
  127. // Input Values
  128. // -----------------------------------------------------------------------------
  129. void _fromLong(unsigned long value, bool brightness) {
  130. if (brightness) {
  131. _setRGBInputValue((value >> 24) & 0xFF, (value >> 16) & 0xFF, (value >> 8) & 0xFF);
  132. _light_brightness = (value & 0xFF) * LIGHT_MAX_BRIGHTNESS / 255;
  133. } else {
  134. _setRGBInputValue((value >> 16) & 0xFF, (value >> 8) & 0xFF, (value) & 0xFF);
  135. }
  136. }
  137. void _fromRGB(const char * rgb) {
  138. char * p = (char *) rgb;
  139. if (strlen(p) == 0) return;
  140. switch (p[0]) {
  141. case '#': // HEX Value
  142. if (_light_has_color) {
  143. ++p;
  144. unsigned long value = strtoul(p, NULL, 16);
  145. // RGBA values are interpreted like RGB + brightness
  146. _fromLong(value, strlen(p) > 7);
  147. }
  148. break;
  149. case 'M': // Mired Value
  150. _fromMireds(atol(p + 1));
  151. break;
  152. case 'K': // Kelvin Value
  153. _fromKelvin(atol(p + 1));
  154. break;
  155. default: // assume decimal values separated by commas
  156. char * tok;
  157. unsigned char count = 0;
  158. unsigned char channels = _light_channel.size();
  159. tok = strtok(p, ",");
  160. while (tok != NULL) {
  161. _light_channel[count].inputValue = atoi(tok);
  162. if (++count == channels) break;
  163. tok = strtok(NULL, ",");
  164. }
  165. // RGB but less than 3 values received, assume it is 0
  166. if (_light_has_color && (count < 3)) {
  167. // check channel 1 and 2:
  168. for (int i = 1; i <= 2; i++) {
  169. if (count < (i+1)) {
  170. _light_channel[i].inputValue = 0;
  171. }
  172. }
  173. }
  174. break;
  175. }
  176. }
  177. // HSV string is expected to be "H,S,V", where:
  178. // 0 <= H <= 360
  179. // 0 <= S <= 100
  180. // 0 <= V <= 100
  181. void _fromHSV(const char * hsv) {
  182. char * ptr = (char *) hsv;
  183. if (strlen(ptr) == 0) return;
  184. if (!_light_has_color) return;
  185. char * tok;
  186. unsigned char count = 0;
  187. unsigned int value[3] = {0};
  188. tok = strtok(ptr, ",");
  189. while (tok != NULL) {
  190. value[count] = atoi(tok);
  191. if (++count == 3) break;
  192. tok = strtok(NULL, ",");
  193. }
  194. if (count != 3) return;
  195. // HSV to RGB transformation -----------------------------------------------
  196. //INPUT: [0,100,57]
  197. //IS: [145,0,0]
  198. //SHOULD: [255,0,0]
  199. double h = (value[0] == 360) ? 0 : (double) value[0] / 60.0;
  200. double f = (h - floor(h));
  201. double s = (double) value[1] / 100.0;
  202. _light_brightness = round((double) value[2] * 2.55); // (255/100)
  203. unsigned char p = round(255 * (1.0 - s));
  204. unsigned char q = round(255 * (1.0 - s * f));
  205. unsigned char t = round(255 * (1.0 - s * (1.0 - f)));
  206. switch (int(h)) {
  207. case 0:
  208. _setRGBInputValue(255, t, p);
  209. break;
  210. case 1:
  211. _setRGBInputValue(q, 255, p);
  212. break;
  213. case 2:
  214. _setRGBInputValue(p, 255, t);
  215. break;
  216. case 3:
  217. _setRGBInputValue(p, q, 255);
  218. break;
  219. case 4:
  220. _setRGBInputValue(t, p, 255);
  221. break;
  222. case 5:
  223. _setRGBInputValue(255, p, q);
  224. break;
  225. default:
  226. _setRGBInputValue(0, 0, 0);
  227. break;
  228. }
  229. }
  230. // Thanks to Sacha Telgenhof for sharing this code in his AiLight library
  231. // https://github.com/stelgenhof/AiLight
  232. void _fromKelvin(unsigned long kelvin) {
  233. if (!_light_has_color) return;
  234. _light_mireds = constrain(round(1000000UL / kelvin), LIGHT_MIN_MIREDS, LIGHT_MAX_MIREDS);
  235. if (_light_use_cct) {
  236. _setRGBInputValue(LIGHT_MAX_VALUE, LIGHT_MAX_VALUE, LIGHT_MAX_VALUE);
  237. return;
  238. }
  239. // Calculate colors
  240. kelvin /= 100;
  241. unsigned int red = (kelvin <= 66)
  242. ? LIGHT_MAX_VALUE
  243. : 329.698727446 * fs_pow((double) (kelvin - 60), -0.1332047592);
  244. unsigned int green = (kelvin <= 66)
  245. ? 99.4708025861 * fs_log(kelvin) - 161.1195681661
  246. : 288.1221695283 * fs_pow((double) kelvin, -0.0755148492);
  247. unsigned int blue = (kelvin >= 66)
  248. ? LIGHT_MAX_VALUE
  249. : ((kelvin <= 19)
  250. ? 0
  251. : 138.5177312231 * fs_log(kelvin - 10) - 305.0447927307);
  252. _setRGBInputValue(red, green, blue);
  253. }
  254. // Color temperature is measured in mireds (kelvin = 1e6/mired)
  255. void _fromMireds(unsigned long mireds) {
  256. unsigned long kelvin = constrain(1000000UL / mireds, 1000, 40000);
  257. _fromKelvin(kelvin);
  258. }
  259. // -----------------------------------------------------------------------------
  260. // Output Values
  261. // -----------------------------------------------------------------------------
  262. void _toRGB(char * rgb, size_t len) {
  263. unsigned long value = 0;
  264. value += _light_channel[0].inputValue;
  265. value <<= 8;
  266. value += _light_channel[1].inputValue;
  267. value <<= 8;
  268. value += _light_channel[2].inputValue;
  269. snprintf_P(rgb, len, PSTR("#%06X"), value);
  270. }
  271. void _toHSV(char * hsv, size_t len) {
  272. double h, s, v;
  273. double brightness = (double) _light_brightness / LIGHT_MAX_BRIGHTNESS;
  274. double r = (double) (_light_channel[0].inputValue * brightness) / 255.0;
  275. double g = (double) (_light_channel[1].inputValue * brightness) / 255.0;
  276. double b = (double) (_light_channel[2].inputValue * brightness) / 255.0;
  277. double min = std::min(r, std::min(g, b));
  278. double max = std::max(r, std::max(g, b));
  279. v = 100.0 * max;
  280. if (v == 0) {
  281. h = s = 0;
  282. } else {
  283. s = 100.0 * (max - min) / max;
  284. if (s == 0) {
  285. h = 0;
  286. } else {
  287. if (max == r) {
  288. if (g >= b) {
  289. h = 0.0 + 60.0 * (g - b) / (max - min);
  290. } else {
  291. h = 360.0 + 60.0 * (g - b) / (max - min);
  292. }
  293. } else if (max == g) {
  294. h = 120.0 + 60.0 * (b - r) / (max - min);
  295. } else {
  296. h = 240.0 + 60.0 * (r - g) / (max - min);
  297. }
  298. }
  299. }
  300. // String
  301. snprintf_P(hsv, len, PSTR("%d,%d,%d"), round(h), round(s), round(v));
  302. }
  303. void _toLong(char * color, size_t len) {
  304. if (!_light_has_color) return;
  305. snprintf_P(color, len, PSTR("%d,%d,%d"),
  306. (int) _light_channel[0].inputValue,
  307. (int) _light_channel[1].inputValue,
  308. (int) _light_channel[2].inputValue
  309. );
  310. }
  311. void _toCSV(char * buffer, size_t len, bool applyBrightness) {
  312. char num[10];
  313. float b = applyBrightness ? (float) _light_brightness / LIGHT_MAX_BRIGHTNESS : 1;
  314. for (unsigned char i=0; i<_light_channel.size(); i++) {
  315. itoa(_light_channel[i].inputValue * b, num, 10);
  316. if (i>0) strncat(buffer, ",", len--);
  317. strncat(buffer, num, len);
  318. len = len - strlen(num);
  319. }
  320. }
  321. // -----------------------------------------------------------------------------
  322. // PROVIDER
  323. // -----------------------------------------------------------------------------
  324. unsigned int _toPWM(unsigned long value, bool gamma, bool inverse) {
  325. value = constrain(value, 0, LIGHT_MAX_VALUE);
  326. if (gamma) value = _light_gamma_table[value];
  327. if (LIGHT_MAX_VALUE != LIGHT_LIMIT_PWM) value = map(value, 0, LIGHT_MAX_VALUE, 0, LIGHT_LIMIT_PWM);
  328. if (inverse) value = LIGHT_LIMIT_PWM - value;
  329. return value;
  330. }
  331. // Returns a PWM value for the given channel ID
  332. unsigned int _toPWM(unsigned char id) {
  333. bool useGamma = _light_use_gamma && _light_has_color && (id < 3);
  334. return _toPWM(_light_channel[id].shadow, useGamma, _light_channel[id].inverse);
  335. }
  336. void _shadow() {
  337. // Update transition ticker
  338. _light_steps_left--;
  339. if (_light_steps_left == 0) _light_transition_ticker.detach();
  340. // Transitions
  341. unsigned char target;
  342. for (unsigned int i=0; i < _light_channel.size(); i++) {
  343. target = _light_state && _light_channel[i].state ? _light_channel[i].value : 0;
  344. if (_light_steps_left == 0) {
  345. _light_channel[i].current = target;
  346. } else {
  347. double difference = (double) (target - _light_channel[i].current) / (_light_steps_left + 1);
  348. _light_channel[i].current = _light_channel[i].current + difference;
  349. }
  350. _light_channel[i].shadow = _light_channel[i].current;
  351. }
  352. }
  353. void _lightProviderUpdate() {
  354. _shadow();
  355. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  356. for (unsigned char i=0; i<_light_channel.size(); i++) {
  357. _my92xx->setChannel(_light_channel[i].mapping, _toPWM(i));
  358. }
  359. _my92xx->setState(true);
  360. _my92xx->update();
  361. #endif
  362. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  363. for (unsigned int i=0; i < _light_channel.size(); i++) {
  364. pwm_set_duty(_toPWM(i), i);
  365. }
  366. pwm_start();
  367. #endif
  368. }
  369. // -----------------------------------------------------------------------------
  370. // PERSISTANCE
  371. // -----------------------------------------------------------------------------
  372. void _lightColorSave() {
  373. for (unsigned int i=0; i < _light_channel.size(); i++) {
  374. setSetting("litCH", i, _light_channel[i].inputValue);
  375. }
  376. setSetting("litBright", _light_brightness);
  377. setSetting("litMireds", _light_mireds);
  378. saveSettings();
  379. }
  380. void _lightColorRestore() {
  381. for (unsigned int i=0; i < _light_channel.size(); i++) {
  382. _light_channel[i].inputValue = getSetting("litCH", i, i==0 ? 255 : 0).toInt();
  383. }
  384. _light_brightness = getSetting("litBright", LIGHT_MAX_BRIGHTNESS).toInt();
  385. _light_mireds = getSetting("litMireds", _light_mireds).toInt();
  386. lightUpdate(false, false);
  387. }
  388. // -----------------------------------------------------------------------------
  389. // MQTT
  390. // -----------------------------------------------------------------------------
  391. #if MQTT_SUPPORT
  392. void _lightMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  393. String mqtt_group_color = getSetting("mqttGroupColor");
  394. if (type == MQTT_CONNECT_EVENT) {
  395. if (_light_has_color) {
  396. mqttSubscribe(MQTT_TOPIC_BRIGHTNESS);
  397. mqttSubscribe(MQTT_TOPIC_MIRED);
  398. mqttSubscribe(MQTT_TOPIC_KELVIN);
  399. mqttSubscribe(MQTT_TOPIC_COLOR_RGB);
  400. mqttSubscribe(MQTT_TOPIC_COLOR_HSV);
  401. }
  402. // Group color
  403. if (mqtt_group_color.length() > 0) mqttSubscribeRaw(mqtt_group_color.c_str());
  404. // Channels
  405. char buffer[strlen(MQTT_TOPIC_CHANNEL) + 3];
  406. snprintf_P(buffer, sizeof(buffer), PSTR("%s/+"), MQTT_TOPIC_CHANNEL);
  407. mqttSubscribe(buffer);
  408. }
  409. if (type == MQTT_MESSAGE_EVENT) {
  410. // Group color
  411. if ((mqtt_group_color.length() > 0) & (mqtt_group_color.equals(topic))) {
  412. lightColor(payload, true);
  413. lightUpdate(true, mqttForward(), false);
  414. return;
  415. }
  416. // Match topic
  417. String t = mqttMagnitude((char *) topic);
  418. // Color temperature in mireds
  419. if (t.equals(MQTT_TOPIC_MIRED)) {
  420. _fromMireds(atol(payload));
  421. lightUpdate(true, mqttForward());
  422. return;
  423. }
  424. // Color temperature in kelvins
  425. if (t.equals(MQTT_TOPIC_KELVIN)) {
  426. _fromKelvin(atol(payload));
  427. lightUpdate(true, mqttForward());
  428. return;
  429. }
  430. // Color
  431. if (t.equals(MQTT_TOPIC_COLOR_RGB)) {
  432. lightColor(payload, true);
  433. lightUpdate(true, mqttForward());
  434. return;
  435. }
  436. if (t.equals(MQTT_TOPIC_COLOR_HSV)) {
  437. lightColor(payload, false);
  438. lightUpdate(true, mqttForward());
  439. return;
  440. }
  441. // Brightness
  442. if (t.equals(MQTT_TOPIC_BRIGHTNESS)) {
  443. _light_brightness = constrain(atoi(payload), 0, LIGHT_MAX_BRIGHTNESS);
  444. lightUpdate(true, mqttForward());
  445. return;
  446. }
  447. // Channel
  448. if (t.startsWith(MQTT_TOPIC_CHANNEL)) {
  449. unsigned int channelID = t.substring(strlen(MQTT_TOPIC_CHANNEL)+1).toInt();
  450. if (channelID >= _light_channel.size()) {
  451. DEBUG_MSG_P(PSTR("[LIGHT] Wrong channelID (%d)\n"), channelID);
  452. return;
  453. }
  454. lightChannel(channelID, atoi(payload));
  455. lightUpdate(true, mqttForward());
  456. return;
  457. }
  458. }
  459. }
  460. void lightMQTT() {
  461. char buffer[20];
  462. if (_light_has_color) {
  463. // Color
  464. if (getSetting("litCSS", LIGHT_USE_CSS).toInt() == 1) {
  465. _toRGB(buffer, sizeof(buffer));
  466. } else {
  467. _toLong(buffer, sizeof(buffer));
  468. }
  469. mqttSend(MQTT_TOPIC_COLOR_RGB, buffer);
  470. _toHSV(buffer, sizeof(buffer));
  471. mqttSend(MQTT_TOPIC_COLOR_HSV, buffer);
  472. // Mireds
  473. snprintf_P(buffer, sizeof(buffer), PSTR("%d"), _light_mireds);
  474. mqttSend(MQTT_TOPIC_MIRED, buffer);
  475. }
  476. // Channels
  477. for (unsigned int i=0; i < _light_channel.size(); i++) {
  478. itoa(_light_channel[i].inputValue, buffer, 10);
  479. mqttSend(MQTT_TOPIC_CHANNEL, i, buffer);
  480. }
  481. // Brightness
  482. snprintf_P(buffer, sizeof(buffer), PSTR("%d"), _light_brightness);
  483. mqttSend(MQTT_TOPIC_BRIGHTNESS, buffer);
  484. }
  485. void lightMQTTGroup() {
  486. String mqtt_group_color = getSetting("mqttGroupColor");
  487. if (mqtt_group_color.length()>0) {
  488. char buffer[20];
  489. _toCSV(buffer, sizeof(buffer), true);
  490. mqttSendRaw(mqtt_group_color.c_str(), buffer);
  491. }
  492. }
  493. #endif
  494. // -----------------------------------------------------------------------------
  495. // Broker
  496. // -----------------------------------------------------------------------------
  497. #if BROKER_SUPPORT
  498. void lightBroker() {
  499. char buffer[10];
  500. for (unsigned int i=0; i < _light_channel.size(); i++) {
  501. itoa(_light_channel[i].inputValue, buffer, 10);
  502. brokerPublish(MQTT_TOPIC_CHANNEL, i, buffer);
  503. }
  504. }
  505. #endif
  506. // -----------------------------------------------------------------------------
  507. // API
  508. // -----------------------------------------------------------------------------
  509. unsigned char lightChannels() {
  510. return _light_channel.size();
  511. }
  512. bool lightHasColor() {
  513. return _light_has_color;
  514. }
  515. void lightUpdate(bool save, bool forward, bool group_forward) {
  516. _generateBrightness();
  517. // Configure color transition
  518. _light_steps_left = _light_use_transitions ? _light_transition_time / LIGHT_TRANSITION_STEP : 1;
  519. _light_transition_ticker.attach_ms(LIGHT_TRANSITION_STEP, _lightProviderUpdate);
  520. // Report channels to local broker
  521. #if BROKER_SUPPORT
  522. lightBroker();
  523. #endif
  524. // Report color & brightness to MQTT broker
  525. #if MQTT_SUPPORT
  526. if (forward) lightMQTT();
  527. if (group_forward) lightMQTTGroup();
  528. #endif
  529. // Report color to WS clients (using current brightness setting)
  530. #if WEB_SUPPORT
  531. wsSend(_lightWebSocketOnSend);
  532. #endif
  533. #if LIGHT_SAVE_ENABLED
  534. // Delay saving to EEPROM 5 seconds to avoid wearing it out unnecessarily
  535. if (save) _light_save_ticker.once(LIGHT_SAVE_DELAY, _lightColorSave);
  536. #endif
  537. };
  538. void lightUpdate(bool save, bool forward) {
  539. lightUpdate(save, forward, true);
  540. }
  541. #if LIGHT_SAVE_ENABLED == 0
  542. void lightSave() {
  543. _lightColorSave();
  544. }
  545. #endif
  546. void lightState(unsigned char i, bool state) {
  547. _light_channel[i].state = state;
  548. }
  549. bool lightState(unsigned char i) {
  550. return _light_channel[i].state;
  551. }
  552. void lightState(bool state) {
  553. _light_state = state;
  554. }
  555. bool lightState() {
  556. return _light_state;
  557. }
  558. void lightColor(const char * color, bool rgb) {
  559. DEBUG_MSG_P(PSTR("[LIGHT] %s: %s\n"), rgb ? "RGB" : "HSV", color);
  560. if (rgb) {
  561. _fromRGB(color);
  562. } else {
  563. _fromHSV(color);
  564. }
  565. }
  566. void lightColor(const char * color) {
  567. lightColor(color, true);
  568. }
  569. void lightColor(unsigned long color) {
  570. _fromLong(color, false);
  571. }
  572. String lightColor(bool rgb) {
  573. char str[12];
  574. if (rgb) {
  575. _toRGB(str, sizeof(str));
  576. } else {
  577. _toHSV(str, sizeof(str));
  578. }
  579. return String(str);
  580. }
  581. String lightColor() {
  582. return lightColor(true);
  583. }
  584. unsigned int lightChannel(unsigned char id) {
  585. if (id <= _light_channel.size()) {
  586. return _light_channel[id].inputValue;
  587. }
  588. return 0;
  589. }
  590. void lightChannel(unsigned char id, int value) {
  591. if (id <= _light_channel.size()) {
  592. _light_channel[id].inputValue = constrain(value, 0, LIGHT_MAX_VALUE);
  593. }
  594. }
  595. void lightChannelStep(unsigned char id, int steps) {
  596. lightChannel(id, lightChannel(id) + steps * LIGHT_STEP);
  597. }
  598. unsigned int lightBrightness() {
  599. return _light_brightness;
  600. }
  601. void lightBrightness(int b) {
  602. _light_brightness = constrain(b, 0, LIGHT_MAX_BRIGHTNESS);
  603. }
  604. void lightBrightnessStep(int steps) {
  605. lightBrightness(_light_brightness + steps * LIGHT_STEP);
  606. }
  607. // -----------------------------------------------------------------------------
  608. // SETUP
  609. // -----------------------------------------------------------------------------
  610. #if WEB_SUPPORT
  611. void _lightWebSocketOnSend(JsonObject& root) {
  612. root["litVisible"] = 1;
  613. root["mqttGroupColor"] = getSetting("mqttGroupColor");
  614. root["litColor"] = _light_has_color;
  615. root["litWhite"] = _light_use_white;
  616. root["litGamma"] = _light_use_gamma;
  617. root["litTrans"] = _light_use_transitions;
  618. root["litTime"] = _light_transition_time;
  619. root["litCSS"] = getSetting("litCSS", LIGHT_USE_CSS).toInt() == 1;
  620. bool useRGB = getSetting("litRGB", LIGHT_USE_RGB).toInt() == 1;
  621. root["litRGB"] = useRGB;
  622. if (_light_has_color) {
  623. if (_light_use_cct) {
  624. root["litCCT"] = _light_use_cct;
  625. root["mireds"] = _light_mireds;
  626. }
  627. if (useRGB) {
  628. root["rgb"] = lightColor(true);
  629. } else {
  630. root["hsv"] = lightColor(false);
  631. }
  632. }
  633. JsonArray& channels = root.createNestedArray("channels");
  634. for (unsigned char id=0; id < _light_channel.size(); id++) {
  635. channels.add(lightChannel(id));
  636. }
  637. root["brightness"] = lightBrightness();
  638. }
  639. void _lightWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  640. if (_light_has_color) {
  641. if (strcmp(action, "color") == 0) {
  642. if (data.containsKey("rgb")) {
  643. lightColor(data["rgb"], true);
  644. lightUpdate(true, true);
  645. }
  646. if (data.containsKey("hsv")) {
  647. lightColor(data["hsv"], false);
  648. lightUpdate(true, true);
  649. }
  650. }
  651. if (_light_use_cct) {
  652. if (strcmp(action, "mireds") == 0) {
  653. _fromMireds(data["mireds"]);
  654. lightUpdate(true, true);
  655. }
  656. }
  657. }
  658. if (strcmp(action, "channel") == 0) {
  659. if (data.containsKey("id") && data.containsKey("value")) {
  660. lightChannel(data["id"], data["value"]);
  661. lightUpdate(true, true);
  662. }
  663. }
  664. if (strcmp(action, "brightness") == 0) {
  665. if (data.containsKey("value")) {
  666. lightBrightness(data["value"]);
  667. lightUpdate(true, true);
  668. }
  669. }
  670. }
  671. #endif
  672. #if API_SUPPORT
  673. void _lightAPISetup() {
  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_KELVIN,
  698. [](char * buffer, size_t len) {},
  699. [](const char * payload) {
  700. _fromKelvin(atol(payload));
  701. lightUpdate(true, true);
  702. }
  703. );
  704. apiRegister(MQTT_TOPIC_MIRED,
  705. [](char * buffer, size_t len) {},
  706. [](const char * payload) {
  707. _fromMireds(atol(payload));
  708. lightUpdate(true, true);
  709. }
  710. );
  711. }
  712. for (unsigned int id=0; id<_light_channel.size(); id++) {
  713. char key[15];
  714. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_CHANNEL, id);
  715. apiRegister(key,
  716. [id](char * buffer, size_t len) {
  717. snprintf_P(buffer, len, PSTR("%d"), lightChannel(id));
  718. },
  719. [id](const char * payload) {
  720. lightChannel(id, atoi(payload));
  721. lightUpdate(true, true);
  722. }
  723. );
  724. }
  725. apiRegister(MQTT_TOPIC_BRIGHTNESS,
  726. [](char * buffer, size_t len) {
  727. snprintf_P(buffer, len, PSTR("%d"), _light_brightness);
  728. },
  729. [](const char * payload) {
  730. lightBrightness(atoi(payload));
  731. lightUpdate(true, true);
  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. #endif
  905. #if API_SUPPORT
  906. _lightAPISetup();
  907. #endif
  908. #if MQTT_SUPPORT
  909. mqttRegister(_lightMQTTCallback);
  910. #endif
  911. #if TERMINAL_SUPPORT
  912. _lightInitCommands();
  913. #endif
  914. settingsRegisterKeyCheck(_lightKeyCheck);
  915. // Main callbacks
  916. espurnaRegisterReload([]() {
  917. #if LIGHT_SAVE_ENABLED == 0
  918. lightSave();
  919. #endif
  920. _lightConfigure();
  921. });
  922. }
  923. #endif // LIGHT_PROVIDER != LIGHT_PROVIDER_NONE