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