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.

1274 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. // Mireds
  531. snprintf_P(buffer, sizeof(buffer), PSTR("%d"), _light_mireds);
  532. mqttSend(MQTT_TOPIC_MIRED, buffer);
  533. }
  534. // Channels
  535. for (unsigned int i=0; i < _light_channel.size(); i++) {
  536. itoa(_light_channel[i].target, buffer, 10);
  537. mqttSend(MQTT_TOPIC_CHANNEL, i, buffer);
  538. }
  539. // Brightness
  540. snprintf_P(buffer, sizeof(buffer), PSTR("%d"), _light_brightness);
  541. mqttSend(MQTT_TOPIC_BRIGHTNESS, buffer);
  542. }
  543. void lightMQTTGroup() {
  544. String mqtt_group_color = getSetting("mqttGroupColor");
  545. if (mqtt_group_color.length()>0) {
  546. char buffer[20];
  547. _toCSV(buffer, sizeof(buffer), true);
  548. mqttSendRaw(mqtt_group_color.c_str(), buffer);
  549. }
  550. }
  551. #endif
  552. // -----------------------------------------------------------------------------
  553. // Broker
  554. // -----------------------------------------------------------------------------
  555. #if BROKER_SUPPORT
  556. void lightBroker() {
  557. char buffer[10];
  558. for (unsigned int i=0; i < _light_channel.size(); i++) {
  559. itoa(_light_channel[i].inputValue, buffer, 10);
  560. brokerPublish(BROKER_MSG_TYPE_STATUS, MQTT_TOPIC_CHANNEL, i, buffer);
  561. }
  562. }
  563. #endif
  564. // -----------------------------------------------------------------------------
  565. // API
  566. // -----------------------------------------------------------------------------
  567. unsigned char lightChannels() {
  568. return _light_channel.size();
  569. }
  570. bool lightHasColor() {
  571. return _light_has_color;
  572. }
  573. bool lightUseCCT() {
  574. return _light_use_cct;
  575. }
  576. void _lightComms(unsigned char mask) {
  577. // Report color & brightness to MQTT broker
  578. #if MQTT_SUPPORT
  579. if (mask & 0x01) lightMQTT();
  580. if (mask & 0x02) lightMQTTGroup();
  581. #endif
  582. // Report color to WS clients (using current brightness setting)
  583. #if WEB_SUPPORT
  584. wsSend(_lightWebSocketStatus);
  585. #endif
  586. // Report channels to local broker
  587. #if BROKER_SUPPORT
  588. lightBroker();
  589. #endif
  590. }
  591. void lightUpdate(bool save, bool forward, bool group_forward) {
  592. _generateBrightness();
  593. // Update channels
  594. for (unsigned int i=0; i < _light_channel.size(); i++) {
  595. _light_channel[i].target = _light_state && _light_channel[i].state ? _light_channel[i].value : 0;
  596. //DEBUG_MSG_P("[LIGHT] Channel #%u target value: %u\n", i, _light_channel[i].target);
  597. }
  598. // Configure color transition
  599. _light_steps_left = _light_use_transitions ? _light_transition_time / LIGHT_TRANSITION_STEP : 1;
  600. _light_transition_ticker.attach_ms(LIGHT_TRANSITION_STEP, _lightProviderUpdate);
  601. // Delay every communication 100ms to avoid jamming
  602. unsigned char mask = 0;
  603. if (forward) mask += 1;
  604. if (group_forward) mask += 2;
  605. _light_comms_ticker.once_ms(LIGHT_COMMS_DELAY, _lightComms, mask);
  606. _lightSaveRtcmem();
  607. #if LIGHT_SAVE_ENABLED
  608. // Delay saving to EEPROM 5 seconds to avoid wearing it out unnecessarily
  609. if (save) _light_save_ticker.once(LIGHT_SAVE_DELAY, _lightSaveSettings);
  610. #endif
  611. };
  612. void lightUpdate(bool save, bool forward) {
  613. lightUpdate(save, forward, true);
  614. }
  615. #if LIGHT_SAVE_ENABLED == 0
  616. void lightSave() {
  617. _lightSaveSettings();
  618. }
  619. #endif
  620. void lightState(unsigned char i, bool state) {
  621. _light_channel[i].state = state;
  622. }
  623. bool lightState(unsigned char i) {
  624. return _light_channel[i].state;
  625. }
  626. void lightState(bool state) {
  627. _light_state = state;
  628. }
  629. bool lightState() {
  630. return _light_state;
  631. }
  632. void lightColor(const char * color, bool rgb) {
  633. DEBUG_MSG_P(PSTR("[LIGHT] %s: %s\n"), rgb ? "RGB" : "HSV", color);
  634. if (rgb) {
  635. _fromRGB(color);
  636. } else {
  637. _fromHSV(color);
  638. }
  639. }
  640. void lightColor(const char * color) {
  641. lightColor(color, true);
  642. }
  643. void lightColor(unsigned long color) {
  644. _fromLong(color, false);
  645. }
  646. String lightColor(bool rgb) {
  647. char str[12];
  648. if (rgb) {
  649. _toRGB(str, sizeof(str));
  650. } else {
  651. _toHSV(str, sizeof(str));
  652. }
  653. return String(str);
  654. }
  655. String lightColor() {
  656. return lightColor(true);
  657. }
  658. unsigned int lightChannel(unsigned char id) {
  659. if (id <= _light_channel.size()) {
  660. return _light_channel[id].inputValue;
  661. }
  662. return 0;
  663. }
  664. void lightChannel(unsigned char id, int value) {
  665. if (id <= _light_channel.size()) {
  666. _light_channel[id].inputValue = constrain(value, 0, LIGHT_MAX_VALUE);
  667. }
  668. }
  669. void lightChannelStep(unsigned char id, int steps) {
  670. lightChannel(id, lightChannel(id) + steps * LIGHT_STEP);
  671. }
  672. unsigned int lightBrightness() {
  673. return _light_brightness;
  674. }
  675. void lightBrightness(int b) {
  676. _light_brightness = constrain(b, 0, LIGHT_MAX_BRIGHTNESS);
  677. }
  678. void lightBrightnessStep(int steps) {
  679. lightBrightness(_light_brightness + steps * LIGHT_STEP);
  680. }
  681. unsigned long lightTransitionTime() {
  682. if (_light_use_transitions) {
  683. return _light_transition_time;
  684. } else {
  685. return 0;
  686. }
  687. }
  688. void lightTransitionTime(unsigned long m) {
  689. if (0 == m) {
  690. _light_use_transitions = false;
  691. } else {
  692. _light_use_transitions = true;
  693. _light_transition_time = m;
  694. }
  695. setSetting("useTransitions", _light_use_transitions);
  696. setSetting("lightTime", _light_transition_time);
  697. saveSettings();
  698. }
  699. // -----------------------------------------------------------------------------
  700. // SETUP
  701. // -----------------------------------------------------------------------------
  702. #if WEB_SUPPORT
  703. bool _lightWebSocketOnReceive(const char * key, JsonVariant& value) {
  704. if (strncmp(key, "light", 5) == 0) return true;
  705. if (strncmp(key, "use", 3) == 0) return true;
  706. return false;
  707. }
  708. void _lightWebSocketStatus(JsonObject& root) {
  709. if (_light_has_color) {
  710. if (getSetting("useRGB", LIGHT_USE_RGB).toInt() == 1) {
  711. root["rgb"] = lightColor(true);
  712. } else {
  713. root["hsv"] = lightColor(false);
  714. }
  715. }
  716. if (_light_use_cct) {
  717. root["useCCT"] = _light_use_cct;
  718. root["mireds"] = _light_mireds;
  719. }
  720. JsonArray& channels = root.createNestedArray("channels");
  721. for (unsigned char id=0; id < _light_channel.size(); id++) {
  722. channels.add(lightChannel(id));
  723. }
  724. root["brightness"] = lightBrightness();
  725. }
  726. void _lightWebSocketOnSend(JsonObject& root) {
  727. root["colorVisible"] = 1;
  728. root["mqttGroupColor"] = getSetting("mqttGroupColor");
  729. root["useColor"] = _light_has_color;
  730. root["useWhite"] = _light_use_white;
  731. root["useGamma"] = _light_use_gamma;
  732. root["useTransitions"] = _light_use_transitions;
  733. root["useCSS"] = getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1;
  734. root["useRGB"] = getSetting("useRGB", LIGHT_USE_RGB).toInt() == 1;
  735. root["lightTime"] = _light_transition_time;
  736. _lightWebSocketStatus(root);
  737. }
  738. void _lightWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  739. if (_light_has_color) {
  740. if (strcmp(action, "color") == 0) {
  741. if (data.containsKey("rgb")) {
  742. lightColor(data["rgb"], true);
  743. lightUpdate(true, true);
  744. }
  745. if (data.containsKey("hsv")) {
  746. lightColor(data["hsv"], false);
  747. lightUpdate(true, true);
  748. }
  749. }
  750. }
  751. if (_light_use_cct) {
  752. if (strcmp(action, "mireds") == 0) {
  753. _fromMireds(data["mireds"]);
  754. lightUpdate(true, true);
  755. }
  756. }
  757. if (strcmp(action, "channel") == 0) {
  758. if (data.containsKey("id") && data.containsKey("value")) {
  759. lightChannel(data["id"], data["value"]);
  760. lightUpdate(true, true);
  761. }
  762. }
  763. if (strcmp(action, "brightness") == 0) {
  764. if (data.containsKey("value")) {
  765. lightBrightness(data["value"]);
  766. lightUpdate(true, true);
  767. }
  768. }
  769. }
  770. #endif
  771. #if API_SUPPORT
  772. void _lightAPISetup() {
  773. if (_light_has_color) {
  774. apiRegister(MQTT_TOPIC_COLOR_RGB,
  775. [](char * buffer, size_t len) {
  776. if (getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1) {
  777. _toRGB(buffer, len, true);
  778. } else {
  779. _toLong(buffer, len, true);
  780. }
  781. },
  782. [](const char * payload) {
  783. lightColor(payload, true);
  784. lightUpdate(true, true);
  785. }
  786. );
  787. apiRegister(MQTT_TOPIC_COLOR_HSV,
  788. [](char * buffer, size_t len) {
  789. _toHSV(buffer, len, true);
  790. },
  791. [](const char * payload) {
  792. lightColor(payload, false);
  793. lightUpdate(true, true);
  794. }
  795. );
  796. apiRegister(MQTT_TOPIC_KELVIN,
  797. [](char * buffer, size_t len) {},
  798. [](const char * payload) {
  799. _fromKelvin(atol(payload));
  800. lightUpdate(true, true);
  801. }
  802. );
  803. apiRegister(MQTT_TOPIC_MIRED,
  804. [](char * buffer, size_t len) {},
  805. [](const char * payload) {
  806. _fromMireds(atol(payload));
  807. lightUpdate(true, true);
  808. }
  809. );
  810. }
  811. for (unsigned int id=0; id<_light_channel.size(); id++) {
  812. char key[15];
  813. snprintf_P(key, sizeof(key), PSTR("%s/%d"), MQTT_TOPIC_CHANNEL, id);
  814. apiRegister(key,
  815. [id](char * buffer, size_t len) {
  816. snprintf_P(buffer, len, PSTR("%d"), _light_channel[id].target);
  817. },
  818. [id](const char * payload) {
  819. lightChannel(id, atoi(payload));
  820. lightUpdate(true, true);
  821. }
  822. );
  823. }
  824. apiRegister(MQTT_TOPIC_TRANSITION,
  825. [](char * buffer, size_t len) {
  826. snprintf_P(buffer, len, PSTR("%d"), lightTransitionTime());
  827. },
  828. [](const char * payload) {
  829. lightTransitionTime(atol(payload));
  830. }
  831. );
  832. apiRegister(MQTT_TOPIC_BRIGHTNESS,
  833. [](char * buffer, size_t len) {
  834. snprintf_P(buffer, len, PSTR("%d"), _light_brightness);
  835. },
  836. [](const char * payload) {
  837. lightBrightness(atoi(payload));
  838. lightUpdate(true, true);
  839. }
  840. );
  841. }
  842. #endif // API_SUPPORT
  843. #if TERMINAL_SUPPORT
  844. void _lightInitCommands() {
  845. terminalRegisterCommand(F("BRIGHTNESS"), [](Embedis* e) {
  846. if (e->argc > 1) {
  847. const String value(e->argv[1]);
  848. if( value.length() > 0 ) {
  849. if( value[0] == '+' || value[0] == '-' ) {
  850. lightBrightness(lightBrightness()+String(e->argv[1]).toInt());
  851. } else {
  852. lightBrightness(String(e->argv[1]).toInt());
  853. }
  854. lightUpdate(true, true);
  855. }
  856. }
  857. DEBUG_MSG_P(PSTR("Brightness: %d\n"), lightBrightness());
  858. terminalOK();
  859. });
  860. terminalRegisterCommand(F("CHANNEL"), [](Embedis* e) {
  861. if (e->argc < 2) {
  862. terminalError(F("Wrong arguments"));
  863. }
  864. int id = String(e->argv[1]).toInt();
  865. if (e->argc > 2) {
  866. int value = String(e->argv[2]).toInt();
  867. lightChannel(id, value);
  868. lightUpdate(true, true);
  869. }
  870. DEBUG_MSG_P(PSTR("Channel #%d: %d\n"), id, lightChannel(id));
  871. terminalOK();
  872. });
  873. terminalRegisterCommand(F("COLOR"), [](Embedis* e) {
  874. if (e->argc > 1) {
  875. String color = String(e->argv[1]);
  876. lightColor(color.c_str());
  877. lightUpdate(true, true);
  878. }
  879. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  880. terminalOK();
  881. });
  882. terminalRegisterCommand(F("KELVIN"), [](Embedis* e) {
  883. if (e->argc > 1) {
  884. String color = String("K") + String(e->argv[1]);
  885. lightColor(color.c_str());
  886. lightUpdate(true, true);
  887. }
  888. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  889. terminalOK();
  890. });
  891. terminalRegisterCommand(F("MIRED"), [](Embedis* e) {
  892. if (e->argc > 1) {
  893. const String value(e->argv[1]);
  894. String color = String("M");
  895. if( value.length() > 0 ) {
  896. if( value[0] == '+' || value[0] == '-' ) {
  897. color += String(_light_mireds + String(e->argv[1]).toInt());
  898. } else {
  899. color += String(e->argv[1]);
  900. }
  901. lightColor(color.c_str());
  902. lightUpdate(true, true);
  903. }
  904. }
  905. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  906. terminalOK();
  907. });
  908. }
  909. #endif // TERMINAL_SUPPORT
  910. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  911. unsigned long getIOMux(unsigned long gpio) {
  912. unsigned long muxes[16] = {
  913. PERIPHS_IO_MUX_GPIO0_U, PERIPHS_IO_MUX_U0TXD_U, PERIPHS_IO_MUX_GPIO2_U, PERIPHS_IO_MUX_U0RXD_U,
  914. PERIPHS_IO_MUX_GPIO4_U, PERIPHS_IO_MUX_GPIO5_U, PERIPHS_IO_MUX_SD_CLK_U, PERIPHS_IO_MUX_SD_DATA0_U,
  915. PERIPHS_IO_MUX_SD_DATA1_U, PERIPHS_IO_MUX_SD_DATA2_U, PERIPHS_IO_MUX_SD_DATA3_U, PERIPHS_IO_MUX_SD_CMD_U,
  916. PERIPHS_IO_MUX_MTDI_U, PERIPHS_IO_MUX_MTCK_U, PERIPHS_IO_MUX_MTMS_U, PERIPHS_IO_MUX_MTDO_U
  917. };
  918. return muxes[gpio];
  919. }
  920. unsigned long getIOFunc(unsigned long gpio) {
  921. unsigned long funcs[16] = {
  922. FUNC_GPIO0, FUNC_GPIO1, FUNC_GPIO2, FUNC_GPIO3,
  923. FUNC_GPIO4, FUNC_GPIO5, FUNC_GPIO6, FUNC_GPIO7,
  924. FUNC_GPIO8, FUNC_GPIO9, FUNC_GPIO10, FUNC_GPIO11,
  925. FUNC_GPIO12, FUNC_GPIO13, FUNC_GPIO14, FUNC_GPIO15
  926. };
  927. return funcs[gpio];
  928. }
  929. #endif
  930. void _lightConfigure() {
  931. _light_has_color = getSetting("useColor", LIGHT_USE_COLOR).toInt() == 1;
  932. if (_light_has_color && (_light_channel.size() < 3)) {
  933. _light_has_color = false;
  934. setSetting("useColor", _light_has_color);
  935. }
  936. _light_use_white = getSetting("useWhite", LIGHT_USE_WHITE).toInt() == 1;
  937. if (_light_use_white && (_light_channel.size() < 4) && (_light_channel.size() != 2)) {
  938. _light_use_white = false;
  939. setSetting("useWhite", _light_use_white);
  940. }
  941. _light_use_cct = getSetting("useCCT", LIGHT_USE_CCT).toInt() == 1;
  942. if (_light_use_cct && (((_light_channel.size() < 5) && (_light_channel.size() != 2)) || !_light_use_white)) {
  943. _light_use_cct = false;
  944. setSetting("useCCT", _light_use_cct);
  945. }
  946. _light_use_gamma = getSetting("useGamma", LIGHT_USE_GAMMA).toInt() == 1;
  947. _light_use_transitions = getSetting("useTransitions", LIGHT_USE_TRANSITIONS).toInt() == 1;
  948. _light_transition_time = getSetting("lightTime", LIGHT_TRANSITION_TIME).toInt();
  949. }
  950. void lightSetup() {
  951. #ifdef LIGHT_ENABLE_PIN
  952. pinMode(LIGHT_ENABLE_PIN, OUTPUT);
  953. digitalWrite(LIGHT_ENABLE_PIN, HIGH);
  954. #endif
  955. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  956. _my92xx = new my92xx(MY92XX_MODEL, MY92XX_CHIPS, MY92XX_DI_PIN, MY92XX_DCKI_PIN, MY92XX_COMMAND);
  957. for (unsigned char i=0; i<LIGHT_CHANNELS; i++) {
  958. _light_channel.push_back((channel_t) {0, false, true, 0, 0, 0});
  959. }
  960. #endif
  961. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  962. #ifdef LIGHT_CH1_PIN
  963. _light_channel.push_back((channel_t) {LIGHT_CH1_PIN, LIGHT_CH1_INVERSE, true, 0, 0, 0});
  964. #endif
  965. #ifdef LIGHT_CH2_PIN
  966. _light_channel.push_back((channel_t) {LIGHT_CH2_PIN, LIGHT_CH2_INVERSE, true, 0, 0, 0});
  967. #endif
  968. #ifdef LIGHT_CH3_PIN
  969. _light_channel.push_back((channel_t) {LIGHT_CH3_PIN, LIGHT_CH3_INVERSE, true, 0, 0, 0});
  970. #endif
  971. #ifdef LIGHT_CH4_PIN
  972. _light_channel.push_back((channel_t) {LIGHT_CH4_PIN, LIGHT_CH4_INVERSE, true, 0, 0, 0});
  973. #endif
  974. #ifdef LIGHT_CH5_PIN
  975. _light_channel.push_back((channel_t) {LIGHT_CH5_PIN, LIGHT_CH5_INVERSE, true, 0, 0, 0});
  976. #endif
  977. uint32 pwm_duty_init[PWM_CHANNEL_NUM_MAX];
  978. uint32 io_info[PWM_CHANNEL_NUM_MAX][3];
  979. for (unsigned int i=0; i < _light_channel.size(); i++) {
  980. pwm_duty_init[i] = 0;
  981. io_info[i][0] = getIOMux(_light_channel[i].pin);
  982. io_info[i][1] = getIOFunc(_light_channel[i].pin);
  983. io_info[i][2] = _light_channel[i].pin;
  984. pinMode(_light_channel[i].pin, OUTPUT);
  985. }
  986. pwm_init(LIGHT_MAX_PWM, pwm_duty_init, PWM_CHANNEL_NUM_MAX, io_info);
  987. pwm_start();
  988. #endif
  989. DEBUG_MSG_P(PSTR("[LIGHT] LIGHT_PROVIDER = %d\n"), LIGHT_PROVIDER);
  990. DEBUG_MSG_P(PSTR("[LIGHT] Number of channels: %d\n"), _light_channel.size());
  991. _lightConfigure();
  992. if (rtcmemStatus()) {
  993. _lightRestoreRtcmem();
  994. } else {
  995. _lightRestoreSettings();
  996. }
  997. #if WEB_SUPPORT
  998. wsOnSendRegister(_lightWebSocketOnSend);
  999. wsOnActionRegister(_lightWebSocketOnAction);
  1000. wsOnReceiveRegister(_lightWebSocketOnReceive);
  1001. #endif
  1002. #if API_SUPPORT
  1003. _lightAPISetup();
  1004. #endif
  1005. #if MQTT_SUPPORT
  1006. mqttRegister(_lightMQTTCallback);
  1007. #endif
  1008. #if TERMINAL_SUPPORT
  1009. _lightInitCommands();
  1010. #endif
  1011. // Main callbacks
  1012. espurnaRegisterReload([]() {
  1013. #if LIGHT_SAVE_ENABLED == 0
  1014. lightSave();
  1015. #endif
  1016. _lightConfigure();
  1017. });
  1018. }
  1019. #endif // LIGHT_PROVIDER != LIGHT_PROVIDER_NONE