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.

1133 lines
34 KiB

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