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.

1183 lines
36 KiB

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