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.

1169 lines
35 KiB

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