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.

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