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.

1180 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-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_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(_lightWebSocketOnSend);
  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 _lightWebSocketOnSend(JsonObject& root) {
  661. root["colorVisible"] = 1;
  662. root["mqttGroupColor"] = getSetting("mqttGroupColor");
  663. root["useColor"] = _light_has_color;
  664. root["useWhite"] = _light_use_white;
  665. root["useGamma"] = _light_use_gamma;
  666. root["useTransitions"] = _light_use_transitions;
  667. root["lightTime"] = _light_transition_time;
  668. root["useCSS"] = getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1;
  669. bool useRGB = getSetting("useRGB", LIGHT_USE_RGB).toInt() == 1;
  670. root["useRGB"] = useRGB;
  671. if (_light_has_color) {
  672. if (_light_use_cct) {
  673. root["useCCT"] = _light_use_cct;
  674. root["mireds"] = _light_mireds;
  675. }
  676. if (useRGB) {
  677. root["rgb"] = lightColor(true);
  678. } else {
  679. root["hsv"] = lightColor(false);
  680. }
  681. }
  682. JsonArray& channels = root.createNestedArray("channels");
  683. for (unsigned char id=0; id < _light_channel.size(); id++) {
  684. channels.add(lightChannel(id));
  685. }
  686. root["brightness"] = lightBrightness();
  687. }
  688. void _lightWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  689. if (_light_has_color) {
  690. if (strcmp(action, "color") == 0) {
  691. if (data.containsKey("rgb")) {
  692. lightColor(data["rgb"], true);
  693. lightUpdate(true, true);
  694. }
  695. if (data.containsKey("hsv")) {
  696. lightColor(data["hsv"], false);
  697. lightUpdate(true, true);
  698. }
  699. }
  700. if (_light_use_cct) {
  701. if (strcmp(action, "mireds") == 0) {
  702. _fromMireds(data["mireds"]);
  703. lightUpdate(true, true);
  704. }
  705. }
  706. }
  707. if (strcmp(action, "channel") == 0) {
  708. if (data.containsKey("id") && data.containsKey("value")) {
  709. lightChannel(data["id"], data["value"]);
  710. lightUpdate(true, true);
  711. }
  712. }
  713. if (strcmp(action, "brightness") == 0) {
  714. if (data.containsKey("value")) {
  715. lightBrightness(data["value"]);
  716. lightUpdate(true, true);
  717. }
  718. }
  719. }
  720. #endif
  721. #if API_SUPPORT
  722. void _lightAPISetup() {
  723. if (_light_has_color) {
  724. apiRegister(MQTT_TOPIC_COLOR_RGB,
  725. [](char * buffer, size_t len) {
  726. if (getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1) {
  727. _toRGB(buffer, len, true);
  728. } else {
  729. _toLong(buffer, len, true);
  730. }
  731. },
  732. [](const char * payload) {
  733. lightColor(payload, true);
  734. lightUpdate(true, true);
  735. }
  736. );
  737. apiRegister(MQTT_TOPIC_COLOR_HSV,
  738. [](char * buffer, size_t len) {
  739. _toHSV(buffer, len, true);
  740. },
  741. [](const char * payload) {
  742. lightColor(payload, false);
  743. lightUpdate(true, true);
  744. }
  745. );
  746. apiRegister(MQTT_TOPIC_KELVIN,
  747. [](char * buffer, size_t len) {},
  748. [](const char * payload) {
  749. _fromKelvin(atol(payload));
  750. lightUpdate(true, true);
  751. }
  752. );
  753. apiRegister(MQTT_TOPIC_MIRED,
  754. [](char * buffer, size_t len) {},
  755. [](const char * payload) {
  756. _fromMireds(atol(payload));
  757. lightUpdate(true, true);
  758. }
  759. );
  760. }
  761. for (unsigned int id=0; id<_light_channel.size(); id++) {
  762. char key[15];
  763. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_CHANNEL, id);
  764. apiRegister(key,
  765. [id](char * buffer, size_t len) {
  766. snprintf_P(buffer, len, PSTR("%d"), _light_channel[id].target);
  767. },
  768. [id](const char * payload) {
  769. lightChannel(id, atoi(payload));
  770. lightUpdate(true, true);
  771. }
  772. );
  773. }
  774. apiRegister(MQTT_TOPIC_TRANSITION,
  775. [](char * buffer, size_t len) {
  776. snprintf_P(buffer, len, PSTR("%d"), lightTransitionTime());
  777. },
  778. [](const char * payload) {
  779. lightTransitionTime(atol(payload));
  780. }
  781. );
  782. apiRegister(MQTT_TOPIC_BRIGHTNESS,
  783. [](char * buffer, size_t len) {
  784. snprintf_P(buffer, len, PSTR("%d"), _light_brightness);
  785. },
  786. [](const char * payload) {
  787. lightBrightness(atoi(payload));
  788. lightUpdate(true, true);
  789. }
  790. );
  791. }
  792. #endif // API_SUPPORT
  793. #if TERMINAL_SUPPORT
  794. void _lightInitCommands() {
  795. settingsRegisterCommand(F("BRIGHTNESS"), [](Embedis* e) {
  796. if (e->argc > 1) {
  797. lightBrightness(String(e->argv[1]).toInt());
  798. lightUpdate(true, true);
  799. }
  800. DEBUG_MSG_P(PSTR("Brightness: %d\n"), lightBrightness());
  801. DEBUG_MSG_P(PSTR("+OK\n"));
  802. });
  803. settingsRegisterCommand(F("CHANNEL"), [](Embedis* e) {
  804. if (e->argc < 2) {
  805. DEBUG_MSG_P(PSTR("-ERROR: Wrong arguments\n"));
  806. }
  807. int id = String(e->argv[1]).toInt();
  808. if (e->argc > 2) {
  809. int value = String(e->argv[2]).toInt();
  810. lightChannel(id, value);
  811. lightUpdate(true, true);
  812. }
  813. DEBUG_MSG_P(PSTR("Channel #%d: %d\n"), id, lightChannel(id));
  814. DEBUG_MSG_P(PSTR("+OK\n"));
  815. });
  816. settingsRegisterCommand(F("COLOR"), [](Embedis* e) {
  817. if (e->argc > 1) {
  818. String color = String(e->argv[1]);
  819. lightColor(color.c_str());
  820. lightUpdate(true, true);
  821. }
  822. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  823. DEBUG_MSG_P(PSTR("+OK\n"));
  824. });
  825. settingsRegisterCommand(F("KELVIN"), [](Embedis* e) {
  826. if (e->argc > 1) {
  827. String color = String("K") + String(e->argv[1]);
  828. lightColor(color.c_str());
  829. lightUpdate(true, true);
  830. }
  831. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  832. DEBUG_MSG_P(PSTR("+OK\n"));
  833. });
  834. settingsRegisterCommand(F("MIRED"), [](Embedis* e) {
  835. if (e->argc > 1) {
  836. String color = String("M") + String(e->argv[1]);
  837. lightColor(color.c_str());
  838. lightUpdate(true, true);
  839. }
  840. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  841. DEBUG_MSG_P(PSTR("+OK\n"));
  842. });
  843. }
  844. #endif // TERMINAL_SUPPORT
  845. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  846. unsigned long getIOMux(unsigned long gpio) {
  847. unsigned long muxes[16] = {
  848. PERIPHS_IO_MUX_GPIO0_U, PERIPHS_IO_MUX_U0TXD_U, PERIPHS_IO_MUX_GPIO2_U, PERIPHS_IO_MUX_U0RXD_U,
  849. PERIPHS_IO_MUX_GPIO4_U, PERIPHS_IO_MUX_GPIO5_U, PERIPHS_IO_MUX_SD_CLK_U, PERIPHS_IO_MUX_SD_DATA0_U,
  850. PERIPHS_IO_MUX_SD_DATA1_U, PERIPHS_IO_MUX_SD_DATA2_U, PERIPHS_IO_MUX_SD_DATA3_U, PERIPHS_IO_MUX_SD_CMD_U,
  851. PERIPHS_IO_MUX_MTDI_U, PERIPHS_IO_MUX_MTCK_U, PERIPHS_IO_MUX_MTMS_U, PERIPHS_IO_MUX_MTDO_U
  852. };
  853. return muxes[gpio];
  854. }
  855. unsigned long getIOFunc(unsigned long gpio) {
  856. unsigned long funcs[16] = {
  857. FUNC_GPIO0, FUNC_GPIO1, FUNC_GPIO2, FUNC_GPIO3,
  858. FUNC_GPIO4, FUNC_GPIO5, FUNC_GPIO6, FUNC_GPIO7,
  859. FUNC_GPIO8, FUNC_GPIO9, FUNC_GPIO10, FUNC_GPIO11,
  860. FUNC_GPIO12, FUNC_GPIO13, FUNC_GPIO14, FUNC_GPIO15
  861. };
  862. return funcs[gpio];
  863. }
  864. #endif
  865. void _lightConfigure() {
  866. _light_has_color = getSetting("useColor", LIGHT_USE_COLOR).toInt() == 1;
  867. if (_light_has_color && (_light_channel.size() < 3)) {
  868. _light_has_color = false;
  869. setSetting("useColor", _light_has_color);
  870. }
  871. _light_use_white = getSetting("useWhite", LIGHT_USE_WHITE).toInt() == 1;
  872. if (_light_use_white && (_light_channel.size() < 4)) {
  873. _light_use_white = false;
  874. setSetting("useWhite", _light_use_white);
  875. }
  876. _light_use_cct = getSetting("useCCT", LIGHT_USE_CCT).toInt() == 1;
  877. if (_light_use_cct && ((_light_channel.size() < 5) || !_light_use_white)) {
  878. _light_use_cct = false;
  879. setSetting("useCCT", _light_use_cct);
  880. }
  881. _light_use_gamma = getSetting("useGamma", LIGHT_USE_GAMMA).toInt() == 1;
  882. _light_use_transitions = getSetting("useTransitions", LIGHT_USE_TRANSITIONS).toInt() == 1;
  883. _light_transition_time = getSetting("lightTime", LIGHT_TRANSITION_TIME).toInt();
  884. }
  885. void lightSetup() {
  886. #ifdef LIGHT_ENABLE_PIN
  887. pinMode(LIGHT_ENABLE_PIN, OUTPUT);
  888. digitalWrite(LIGHT_ENABLE_PIN, HIGH);
  889. #endif
  890. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  891. _my92xx = new my92xx(MY92XX_MODEL, MY92XX_CHIPS, MY92XX_DI_PIN, MY92XX_DCKI_PIN, MY92XX_COMMAND);
  892. for (unsigned char i=0; i<LIGHT_CHANNELS; i++) {
  893. _light_channel.push_back((channel_t) {0, false, true, 0, 0, 0});
  894. }
  895. #endif
  896. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  897. #ifdef LIGHT_CH1_PIN
  898. _light_channel.push_back((channel_t) {LIGHT_CH1_PIN, LIGHT_CH1_INVERSE, true, 0, 0, 0});
  899. #endif
  900. #ifdef LIGHT_CH2_PIN
  901. _light_channel.push_back((channel_t) {LIGHT_CH2_PIN, LIGHT_CH2_INVERSE, true, 0, 0, 0});
  902. #endif
  903. #ifdef LIGHT_CH3_PIN
  904. _light_channel.push_back((channel_t) {LIGHT_CH3_PIN, LIGHT_CH3_INVERSE, true, 0, 0, 0});
  905. #endif
  906. #ifdef LIGHT_CH4_PIN
  907. _light_channel.push_back((channel_t) {LIGHT_CH4_PIN, LIGHT_CH4_INVERSE, true, 0, 0, 0});
  908. #endif
  909. #ifdef LIGHT_CH5_PIN
  910. _light_channel.push_back((channel_t) {LIGHT_CH5_PIN, LIGHT_CH5_INVERSE, true, 0, 0, 0});
  911. #endif
  912. uint32 pwm_duty_init[PWM_CHANNEL_NUM_MAX];
  913. uint32 io_info[PWM_CHANNEL_NUM_MAX][3];
  914. for (unsigned int i=0; i < _light_channel.size(); i++) {
  915. pwm_duty_init[i] = 0;
  916. io_info[i][0] = getIOMux(_light_channel[i].pin);
  917. io_info[i][1] = getIOFunc(_light_channel[i].pin);
  918. io_info[i][2] = _light_channel[i].pin;
  919. pinMode(_light_channel[i].pin, OUTPUT);
  920. }
  921. pwm_init(LIGHT_MAX_PWM, pwm_duty_init, PWM_CHANNEL_NUM_MAX, io_info);
  922. pwm_start();
  923. #endif
  924. DEBUG_MSG_P(PSTR("[LIGHT] LIGHT_PROVIDER = %d\n"), LIGHT_PROVIDER);
  925. DEBUG_MSG_P(PSTR("[LIGHT] Number of channels: %d\n"), _light_channel.size());
  926. _lightConfigure();
  927. _lightColorRestore();
  928. #if WEB_SUPPORT
  929. wsOnSendRegister(_lightWebSocketOnSend);
  930. wsOnActionRegister(_lightWebSocketOnAction);
  931. wsOnReceiveRegister(_lightWebSocketOnReceive);
  932. #endif
  933. #if API_SUPPORT
  934. _lightAPISetup();
  935. #endif
  936. #if MQTT_SUPPORT
  937. mqttRegister(_lightMQTTCallback);
  938. #endif
  939. #if TERMINAL_SUPPORT
  940. _lightInitCommands();
  941. #endif
  942. // Main callbacks
  943. espurnaRegisterReload([]() {
  944. #if LIGHT_SAVE_ENABLED == 0
  945. lightSave();
  946. #endif
  947. _lightConfigure();
  948. });
  949. }
  950. #endif // LIGHT_PROVIDER != LIGHT_PROVIDER_NONE