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.

648 lines
18 KiB

7 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-2017 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  6. #ifndef LIGHT_PROVIDER_EXPERIMENTAL_RGB_ONLY_HSV_IR
  7. #include <Ticker.h>
  8. #include <ArduinoJson.h>
  9. #include <vector>
  10. Ticker colorTicker;
  11. typedef struct {
  12. unsigned char pin;
  13. bool reverse;
  14. unsigned char value;
  15. unsigned char shadow;
  16. } channel_t;
  17. std::vector<channel_t> _channels;
  18. bool _lightState = false;
  19. unsigned int _brightness = LIGHT_MAX_BRIGHTNESS;
  20. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY9192
  21. #include <my9291.h>
  22. my9291 * _my9291;
  23. #endif
  24. // Gamma Correction lookup table for gamma=2.8 and 12 bit (4095) full scale
  25. // TODO: move to PROGMEM
  26. const unsigned short gamma_table[LIGHT_MAX_VALUE+1] = {
  27. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,
  28. 2, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 8, 8, 9, 10, 11,
  29. 12, 13, 15, 16, 17, 18, 20, 21, 23, 25, 26, 28, 30, 32, 34, 36,
  30. 38, 40, 43, 45, 48, 50, 53, 56, 59, 62, 65, 68, 71, 75, 78, 82,
  31. 85, 89, 93, 97, 101, 105, 110, 114, 119, 123, 128, 133, 138, 143, 149, 154,
  32. 159, 165, 171, 177, 183, 189, 195, 202, 208, 215, 222, 229, 236, 243, 250, 258,
  33. 266, 273, 281, 290, 298, 306, 315, 324, 332, 341, 351, 360, 369, 379, 389, 399,
  34. 409, 419, 430, 440, 451, 462, 473, 485, 496, 508, 520, 532, 544, 556, 569, 582,
  35. 594, 608, 621, 634, 648, 662, 676, 690, 704, 719, 734, 749, 764, 779, 795, 811,
  36. 827, 843, 859, 876, 893, 910, 927, 944, 962, 980, 998,1016,1034,1053,1072,1091,
  37. 1110,1130,1150,1170,1190,1210,1231,1252,1273,1294,1316,1338,1360,1382,1404,1427,
  38. 1450,1473,1497,1520,1544,1568,1593,1617,1642,1667,1693,1718,1744,1770,1797,1823,
  39. 1850,1877,1905,1932,1960,1988,2017,2045,2074,2103,2133,2162,2192,2223,2253,2284,
  40. 2315,2346,2378,2410,2442,2474,2507,2540,2573,2606,2640,2674,2708,2743,2778,2813,
  41. 2849,2884,2920,2957,2993,3030,3067,3105,3143,3181,3219,3258,3297,3336,3376,3416,
  42. 3456,3496,3537,3578,3619,3661,3703,3745,3788,3831,3874,3918,3962,4006,4050,4095 };
  43. // -----------------------------------------------------------------------------
  44. // UTILS
  45. // -----------------------------------------------------------------------------
  46. void _fromLong(unsigned long value, bool brightness) {
  47. if (brightness) {
  48. _channels[0].value = (value >> 24) & 0xFF;
  49. _channels[1].value = (value >> 16) & 0xFF;
  50. _channels[2].value = (value >> 8) & 0xFF;
  51. _brightness = (value & 0xFF) * LIGHT_MAX_BRIGHTNESS / 255;
  52. } else {
  53. _channels[0].value = (value >> 16) & 0xFF;
  54. _channels[1].value = (value >> 8) & 0xFF;
  55. _channels[2].value = (value) & 0xFF;
  56. }
  57. }
  58. void _fromRGB(const char * rgb) {
  59. char * p = (char *) rgb;
  60. if (strlen(p) == 0) return;
  61. // if color begins with a # then assume HEX RGB
  62. if (p[0] == '#') {
  63. if (lightHasColor()) {
  64. ++p;
  65. unsigned long value = strtoul(p, NULL, 16);
  66. // RGBA values are interpreted like RGB + brightness
  67. _fromLong(value, strlen(p) > 7);
  68. }
  69. // it's a temperature in mireds
  70. } else if (p[0] == 'M') {
  71. if (lightHasColor()) {
  72. unsigned long mireds = atol(p + 1);
  73. _fromMireds(mireds);
  74. }
  75. // it's a temperature in kelvin
  76. } else if (p[0] == 'K') {
  77. if (lightHasColor()) {
  78. unsigned long kelvin = atol(p + 1);
  79. _fromKelvin(kelvin);
  80. }
  81. // otherwise assume decimal values separated by commas
  82. } else {
  83. char * tok;
  84. unsigned char count = 0;
  85. unsigned char channels = _channels.size();
  86. tok = strtok(p, ",");
  87. while (tok != NULL) {
  88. _channels[count].value = atoi(tok);
  89. if (++count == channels) break;
  90. tok = strtok(NULL, ",");
  91. }
  92. // RGB but less than 3 values received
  93. if (lightHasColor() && (count < 3)) {
  94. _channels[1].value = _channels[0].value;
  95. _channels[2].value = _channels[0].value;
  96. }
  97. }
  98. }
  99. void _toRGB(char * rgb, size_t len, bool applyBrightness) {
  100. if (!lightHasColor()) return;
  101. float b = applyBrightness ? (float) _brightness / LIGHT_MAX_BRIGHTNESS : 1;
  102. unsigned long value = 0;
  103. value += _channels[0].value * b;
  104. value <<= 8;
  105. value += _channels[1].value * b;
  106. value <<= 8;
  107. value += _channels[2].value * b;
  108. snprintf_P(rgb, len, PSTR("#%06X"), value);
  109. }
  110. void _toRGB(char * rgb, size_t len) {
  111. _toRGB(rgb, len, false);
  112. }
  113. void _toLong(char * color, size_t len, bool applyBrightness) {
  114. if (!lightHasColor()) return;
  115. float b = applyBrightness ? (float) _brightness / LIGHT_MAX_BRIGHTNESS : 1;
  116. snprintf_P(color, len, PSTR("%d,%d,%d"),
  117. (int) (_channels[0].value * b),
  118. (int) (_channels[1].value * b),
  119. (int) (_channels[2].value * b)
  120. );
  121. }
  122. void _toLong(char * color, size_t len) {
  123. _toLong(color, len, false);
  124. }
  125. // Thanks to Sacha Telgenhof for sharing this code in his AiLight library
  126. // https://github.com/stelgenhof/AiLight
  127. void _fromKelvin(unsigned long kelvin) {
  128. // Check we have RGB channels
  129. if (!lightHasColor()) return;
  130. // Calculate colors
  131. unsigned int red = (kelvin <= 66)
  132. ? LIGHT_MAX_VALUE
  133. : 329.698727446 * pow((kelvin - 60), -0.1332047592);
  134. unsigned int green = (kelvin <= 66)
  135. ? 99.4708025861 * log(kelvin) - 161.1195681661
  136. : 288.1221695283 * pow(kelvin, -0.0755148492);
  137. unsigned int blue = (kelvin >= 66)
  138. ? LIGHT_MAX_VALUE
  139. : ((kelvin <= 19)
  140. ? 0
  141. : 138.5177312231 * log(kelvin - 10) - 305.0447927307);
  142. // Save values
  143. _channels[0].value = constrain(red, 0, LIGHT_MAX_VALUE);
  144. _channels[1].value = constrain(green, 0, LIGHT_MAX_VALUE);
  145. _channels[2].value = constrain(blue, 0, LIGHT_MAX_VALUE);
  146. }
  147. // Color temperature is measured in mireds (kelvin = 1e6/mired)
  148. void _fromMireds(unsigned long mireds) {
  149. if (mireds == 0) mireds = 1;
  150. unsigned long kelvin = constrain(1000000UL / mireds, 1000, 40000) / 100;
  151. _fromKelvin(kelvin);
  152. }
  153. unsigned int _toPWM(unsigned long value, bool bright, bool gamma, bool reverse) {
  154. value = constrain(value, 0, LIGHT_MAX_VALUE);
  155. if (bright) value *= ((float) _brightness / LIGHT_MAX_BRIGHTNESS);
  156. unsigned int pwm = gamma ? gamma_table[value] : map(value, 0, LIGHT_MAX_VALUE, 0, LIGHT_LIMIT_PWM);
  157. if (reverse) pwm = LIGHT_LIMIT_PWM - pwm;
  158. return pwm;
  159. }
  160. // Returns a PWM valule for the given channel ID
  161. unsigned int _toPWM(unsigned char id) {
  162. if (id < _channels.size()) {
  163. bool isColor = lightHasColor() && (id < 3);
  164. bool bright = isColor;
  165. bool gamma = isColor & (getSetting("useGamma", LIGHT_USE_GAMMA).toInt() == 1);
  166. return _toPWM(_channels[id].shadow, bright, gamma, _channels[id].reverse);
  167. }
  168. return 0;
  169. }
  170. // -----------------------------------------------------------------------------
  171. // PROVIDER
  172. // -----------------------------------------------------------------------------
  173. void _shadow() {
  174. for (unsigned int i=0; i < _channels.size(); i++) {
  175. _channels[i].shadow = _lightState ? _channels[i].value : 0;
  176. }
  177. if (lightHasColor()) {
  178. bool useWhite = getSetting("useWhite", LIGHT_USE_WHITE).toInt() == 1;
  179. if (_lightState && useWhite && (_channels.size() > 3)) {
  180. if (_channels[0].shadow == _channels[1].shadow && _channels[1].shadow == _channels[2].shadow ) {
  181. _channels[3].shadow = _channels[0].shadow * ((float) _brightness / LIGHT_MAX_BRIGHTNESS);
  182. _channels[2].shadow = 0;
  183. _channels[1].shadow = 0;
  184. _channels[0].shadow = 0;
  185. }
  186. }
  187. }
  188. }
  189. void _lightProviderUpdate() {
  190. _shadow();
  191. #ifdef LIGHT_ENABLE_PIN
  192. digitalWrite(LIGHT_ENABLE_PIN, _lightState);
  193. #endif
  194. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY9192
  195. if (_lightState) {
  196. float ratio = (float) LIGHT_MAX_VALUE / LIGHT_MAX_PWM;
  197. unsigned int red = _toPWM(0) * ratio;
  198. unsigned int green = _toPWM(1) * ratio;
  199. unsigned int blue = _toPWM(2) * ratio;
  200. unsigned int white = _toPWM(3) * ratio;
  201. unsigned int warm = _toPWM(4) * ratio;
  202. _my9291->setColor((my9291_color_t) { red, green, blue, white, warm });
  203. _my9291->setState(true);
  204. } else {
  205. _my9291->setColor((my9291_color_t) { 0, 0, 0, 0, 0 });
  206. _my9291->setState(false);
  207. }
  208. #endif
  209. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  210. for (unsigned int i=0; i < _channels.size(); i++) {
  211. analogWrite(_channels[i].pin, _toPWM(i));
  212. }
  213. #endif
  214. }
  215. // -----------------------------------------------------------------------------
  216. // PERSISTANCE
  217. // -----------------------------------------------------------------------------
  218. void _lightColorSave() {
  219. for (unsigned int i=0; i < _channels.size(); i++) {
  220. setSetting("ch", i, _channels[i].value);
  221. }
  222. setSetting("brightness", _brightness);
  223. saveSettings();
  224. }
  225. void _lightColorRestore() {
  226. for (unsigned int i=0; i < _channels.size(); i++) {
  227. _channels[i].value = getSetting("ch", i, i==0 ? 255 : 0).toInt();
  228. }
  229. _brightness = getSetting("brightness", LIGHT_MAX_BRIGHTNESS).toInt();
  230. lightUpdate(false, false);
  231. }
  232. // -----------------------------------------------------------------------------
  233. // MQTT
  234. // -----------------------------------------------------------------------------
  235. void _lightMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  236. if (type == MQTT_CONNECT_EVENT) {
  237. if (lightHasColor()) {
  238. mqttSubscribe(MQTT_TOPIC_BRIGHTNESS);
  239. mqttSubscribe(MQTT_TOPIC_MIRED);
  240. mqttSubscribe(MQTT_TOPIC_KELVIN);
  241. mqttSubscribe(MQTT_TOPIC_COLOR);
  242. }
  243. char buffer[strlen(MQTT_TOPIC_CHANNEL) + 3];
  244. snprintf_P(buffer, sizeof(buffer), PSTR("%s/+"), MQTT_TOPIC_CHANNEL);
  245. mqttSubscribe(buffer);
  246. }
  247. if (type == MQTT_MESSAGE_EVENT) {
  248. // Match topic
  249. String t = mqttSubtopic((char *) topic);
  250. // Color temperature in mireds
  251. if (t.equals(MQTT_TOPIC_MIRED)) {
  252. _fromMireds(atol(payload));
  253. lightUpdate(true, mqttForward());
  254. }
  255. // Color temperature in kelvins
  256. if (t.equals(MQTT_TOPIC_KELVIN)) {
  257. _fromKelvin(atol(payload));
  258. lightUpdate(true, mqttForward());
  259. }
  260. // Color
  261. if (t.equals(MQTT_TOPIC_COLOR)) {
  262. lightColor(payload);
  263. lightUpdate(true, mqttForward());
  264. }
  265. // Brightness
  266. if (t.equals(MQTT_TOPIC_BRIGHTNESS)) {
  267. _brightness = constrain(atoi(payload), 0, LIGHT_MAX_BRIGHTNESS);
  268. lightUpdate(true, mqttForward());
  269. }
  270. // Channel
  271. if (t.startsWith(MQTT_TOPIC_CHANNEL)) {
  272. unsigned int channelID = t.substring(strlen(MQTT_TOPIC_CHANNEL)+1).toInt();
  273. if (channelID >= _channels.size()) {
  274. DEBUG_MSG_P(PSTR("[LIGHT] Wrong channelID (%d)\n"), channelID);
  275. return;
  276. }
  277. lightChannel(channelID, atoi(payload));
  278. lightUpdate(true, mqttForward());
  279. }
  280. }
  281. }
  282. // -----------------------------------------------------------------------------
  283. // API
  284. // -----------------------------------------------------------------------------
  285. unsigned char lightChannels() {
  286. return _channels.size();
  287. }
  288. bool lightHasColor() {
  289. bool useColor = getSetting("useColor", LIGHT_USE_COLOR).toInt() == 1;
  290. return useColor && (_channels.size() > 2);
  291. }
  292. unsigned char lightWhiteChannels() {
  293. return _channels.size() % 3;
  294. }
  295. void lightMQTT() {
  296. char buffer[12];
  297. if (lightHasColor()) {
  298. // Color
  299. if (getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1) {
  300. _toRGB(buffer, 12, false);
  301. } else {
  302. _toLong(buffer, 12, false);
  303. }
  304. mqttSend(MQTT_TOPIC_COLOR, buffer);
  305. // Brightness
  306. snprintf_P(buffer, sizeof(buffer), PSTR("%d"), _brightness);
  307. mqttSend(MQTT_TOPIC_BRIGHTNESS, buffer);
  308. }
  309. // Channels
  310. for (unsigned int i=0; i < _channels.size(); i++) {
  311. snprintf_P(buffer, sizeof(buffer), PSTR("%d"), _channels[i].value);
  312. mqttSend(MQTT_TOPIC_CHANNEL, i, buffer);
  313. }
  314. }
  315. void lightUpdate(bool save, bool forward) {
  316. _lightProviderUpdate();
  317. // Report color & brightness to MQTT broker
  318. if (forward) lightMQTT();
  319. // Report color to WS clients (using current brightness setting)
  320. #if WEB_SUPPORT
  321. {
  322. DynamicJsonBuffer jsonBuffer;
  323. JsonObject& root = jsonBuffer.createObject();
  324. root["colorVisible"] = 1;
  325. root["useColor"] = getSetting("useColor", LIGHT_USE_COLOR).toInt() == 1;
  326. root["useWhite"] = getSetting("useWhite", LIGHT_USE_WHITE).toInt() == 1;
  327. root["useGamma"] = getSetting("useGamma", LIGHT_USE_GAMMA).toInt() == 1;
  328. if (lightHasColor()) {
  329. root["color"] = lightColor();
  330. root["brightness"] = lightBrightness();
  331. }
  332. JsonArray& channels = root.createNestedArray("channels");
  333. for (unsigned char id=0; id < lightChannels(); id++) {
  334. channels.add(lightChannel(id));
  335. }
  336. String output;
  337. root.printTo(output);
  338. wsSend(output.c_str());
  339. }
  340. #endif
  341. #if LIGHT_SAVE_ENABLED
  342. // Delay saving to EEPROM 5 seconds to avoid wearing it out unnecessarily
  343. if (save) colorTicker.once(LIGHT_SAVE_DELAY, _lightColorSave);
  344. #endif
  345. };
  346. #if LIGHT_SAVE_ENABLED == 0
  347. void lightSave() {
  348. _lightColorSave();
  349. }
  350. #endif
  351. void lightState(bool state) {
  352. _lightState = state;
  353. }
  354. bool lightState() {
  355. return _lightState;
  356. }
  357. void lightColor(const char * color) {
  358. _fromRGB(color);
  359. }
  360. void lightColor(unsigned long color) {
  361. _fromLong(color, false);
  362. }
  363. String lightColor() {
  364. char rgb[8];
  365. _toRGB(rgb, 8, false);
  366. return String(rgb);
  367. }
  368. unsigned int lightChannel(unsigned char id) {
  369. if (id <= _channels.size()) {
  370. return _channels[id].value;
  371. }
  372. return 0;
  373. }
  374. void lightChannel(unsigned char id, unsigned int value) {
  375. if (id <= _channels.size()) {
  376. _channels[id].value = constrain(value, 0, LIGHT_MAX_VALUE);
  377. }
  378. }
  379. unsigned int lightBrightness() {
  380. return _brightness;
  381. }
  382. void lightBrightness(unsigned int b) {
  383. _brightness = constrain(b, 0, LIGHT_MAX_BRIGHTNESS);
  384. }
  385. void lightBrightnessStep(int steps) {
  386. lightBrightness(_brightness + steps * LIGHT_STEP);
  387. }
  388. // -----------------------------------------------------------------------------
  389. // SETUP
  390. // -----------------------------------------------------------------------------
  391. void _lightAPISetup() {
  392. #if WEB_SUPPORT
  393. // API entry points (protected with apikey)
  394. if (lightHasColor()) {
  395. apiRegister(MQTT_TOPIC_COLOR, MQTT_TOPIC_COLOR,
  396. [](char * buffer, size_t len) {
  397. if (getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1) {
  398. _toRGB(buffer, len, false);
  399. } else {
  400. _toLong(buffer, len, false);
  401. }
  402. },
  403. [](const char * payload) {
  404. lightColor(payload);
  405. lightUpdate(true, true);
  406. }
  407. );
  408. apiRegister(MQTT_TOPIC_BRIGHTNESS, MQTT_TOPIC_BRIGHTNESS,
  409. [](char * buffer, size_t len) {
  410. snprintf_P(buffer, len, PSTR("%d"), _brightness);
  411. },
  412. [](const char * payload) {
  413. lightBrightness(atoi(payload));
  414. lightUpdate(true, true);
  415. }
  416. );
  417. apiRegister(MQTT_TOPIC_KELVIN, MQTT_TOPIC_KELVIN,
  418. [](char * buffer, size_t len) {},
  419. [](const char * payload) {
  420. _fromKelvin(atol(payload));
  421. lightUpdate(true, true);
  422. }
  423. );
  424. apiRegister(MQTT_TOPIC_MIRED, MQTT_TOPIC_MIRED,
  425. [](char * buffer, size_t len) {},
  426. [](const char * payload) {
  427. _fromMireds(atol(payload));
  428. lightUpdate(true, true);
  429. }
  430. );
  431. }
  432. for (unsigned int id=0; id<lightChannels(); id++) {
  433. char url[15];
  434. snprintf_P(url, sizeof(url), PSTR("%s/%d"), MQTT_TOPIC_CHANNEL, id);
  435. char key[10];
  436. snprintf_P(key, sizeof(key), PSTR("%s%d"), MQTT_TOPIC_CHANNEL, id);
  437. apiRegister(url, key,
  438. [id](char * buffer, size_t len) {
  439. snprintf_P(buffer, len, PSTR("%d"), lightChannel(id));
  440. },
  441. [id](const char * payload) {
  442. lightChannel(id, atoi(payload));
  443. lightUpdate(true, true);
  444. }
  445. );
  446. }
  447. #endif // WEB_SUPPORT
  448. }
  449. void lightSetup() {
  450. #ifdef LIGHT_ENABLE_PIN
  451. pinMode(LIGHT_ENABLE_PIN, OUTPUT);
  452. #endif
  453. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY9192
  454. _my9291 = new my9291(MY9291_DI_PIN, MY9291_DCKI_PIN, MY9291_COMMAND, MY9291_CHANNELS);
  455. for (unsigned char i=0; i<MY9291_CHANNELS; i++) {
  456. _channels.push_back((channel_t) {0, false, 0});
  457. }
  458. #endif
  459. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  460. #ifdef LIGHT_CH1_PIN
  461. _channels.push_back((channel_t) {LIGHT_CH1_PIN, LIGHT_CH1_INVERSE, 0});
  462. #endif
  463. #ifdef LIGHT_CH2_PIN
  464. _channels.push_back((channel_t) {LIGHT_CH2_PIN, LIGHT_CH2_INVERSE, 0});
  465. #endif
  466. #ifdef LIGHT_CH3_PIN
  467. _channels.push_back((channel_t) {LIGHT_CH3_PIN, LIGHT_CH3_INVERSE, 0});
  468. #endif
  469. #ifdef LIGHT_CH4_PIN
  470. _channels.push_back((channel_t) {LIGHT_CH4_PIN, LIGHT_CH4_INVERSE, 0});
  471. #endif
  472. #ifdef LIGHT_CH5_PIN
  473. _channels.push_back((channel_t) {LIGHT_CH5_PIN, LIGHT_CH5_INVERSE, 0});
  474. #endif
  475. analogWriteRange(LIGHT_MAX_PWM+1);
  476. analogWriteFreq(LIGHT_PWM_FREQUENCY);
  477. for (unsigned int i=0; i < _channels.size(); i++) {
  478. pinMode(_channels[i].pin, OUTPUT);
  479. }
  480. #endif
  481. DEBUG_MSG_P(PSTR("[LIGHT] LIGHT_PROVIDER = %d\n"), LIGHT_PROVIDER);
  482. DEBUG_MSG_P(PSTR("[LIGHT] Number of channels: %d\n"), _channels.size());
  483. _lightColorRestore();
  484. _lightAPISetup();
  485. mqttRegister(_lightMQTTCallback);
  486. }
  487. void lightLoop(){
  488. }
  489. #endif // LIGHT_PROVIDER_EXPERIMENTAL_RGB_ONLY_HSV_IR
  490. #endif // LIGHT_PROVIDER != LIGHT_PROVIDER_NONE