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.

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