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.

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