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.

633 lines
18 KiB

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 _fromRGB(const char * rgb) {
  47. char * p = (char *) rgb;
  48. if (strlen(p) == 0) return;
  49. // if color begins with a # then assume HEX RGB
  50. if (p[0] == '#') {
  51. if (lightHasColor()) {
  52. ++p;
  53. unsigned long value = strtoul(p, NULL, 16);
  54. // RGBA values are interpreted like RGB + brightness
  55. if (strlen(p) > 7) {
  56. _channels[0].value = (value >> 24) & 0xFF;
  57. _channels[1].value = (value >> 16) & 0xFF;
  58. _channels[2].value = (value >> 8) & 0xFF;
  59. _brightness = (value & 0xFF) * LIGHT_MAX_BRIGHTNESS / 255;
  60. } else {
  61. _channels[0].value = (value >> 16) & 0xFF;
  62. _channels[1].value = (value >> 8) & 0xFF;
  63. _channels[2].value = (value) & 0xFF;
  64. }
  65. }
  66. // it's a temperature in mireds
  67. } else if (p[0] == 'M') {
  68. if (lightHasColor()) {
  69. unsigned long mireds = atol(p + 1);
  70. _fromMireds(mireds);
  71. }
  72. // it's a temperature in kelvin
  73. } else if (p[0] == 'K') {
  74. if (lightHasColor()) {
  75. unsigned long kelvin = atol(p + 1);
  76. _fromKelvin(kelvin);
  77. }
  78. // otherwise assume decimal values separated by commas
  79. } else {
  80. char * tok;
  81. unsigned char count = 0;
  82. unsigned char channels = _channels.size();
  83. tok = strtok(p, ",");
  84. while (tok != NULL) {
  85. _channels[count].value = atoi(tok);
  86. if (++count == channels) break;
  87. tok = strtok(NULL, ",");
  88. }
  89. // RGB but less than 3 values received
  90. if (lightHasColor() && (count < 3)) {
  91. _channels[1].value = _channels[0].value;
  92. _channels[2].value = _channels[0].value;
  93. }
  94. }
  95. }
  96. void _toRGB(char * rgb, size_t len, bool applyBrightness) {
  97. if (!lightHasColor()) return;
  98. float b = applyBrightness ? (float) _brightness / LIGHT_MAX_BRIGHTNESS : 1;
  99. unsigned long value = 0;
  100. value += _channels[0].value * b;
  101. value <<= 8;
  102. value += _channels[1].value * b;
  103. value <<= 8;
  104. value += _channels[2].value * b;
  105. snprintf_P(rgb, len, PSTR("#%06X"), value);
  106. }
  107. void _toRGB(char * rgb, size_t len) {
  108. _toRGB(rgb, len, false);
  109. }
  110. void _toLong(char * color, size_t len, bool applyBrightness) {
  111. if (!lightHasColor()) return;
  112. float b = applyBrightness ? (float) _brightness / LIGHT_MAX_BRIGHTNESS : 1;
  113. snprintf_P(color, len, PSTR("%d,%d,%d"),
  114. (int) (_channels[0].value * b),
  115. (int) (_channels[1].value * b),
  116. (int) (_channels[2].value * b)
  117. );
  118. }
  119. void _toLong(char * color, size_t len) {
  120. _toLong(color, len, false);
  121. }
  122. // Thanks to Sacha Telgenhof for sharing this code in his AiLight library
  123. // https://github.com/stelgenhof/AiLight
  124. void _fromKelvin(unsigned long kelvin) {
  125. // Check we have RGB channels
  126. if (!lightHasColor()) return;
  127. // Calculate colors
  128. unsigned int red = (kelvin <= 66)
  129. ? LIGHT_MAX_VALUE
  130. : 329.698727446 * pow((kelvin - 60), -0.1332047592);
  131. unsigned int green = (kelvin <= 66)
  132. ? 99.4708025861 * log(kelvin) - 161.1195681661
  133. : 288.1221695283 * pow(kelvin, -0.0755148492);
  134. unsigned int blue = (kelvin >= 66)
  135. ? LIGHT_MAX_VALUE
  136. : ((kelvin <= 19)
  137. ? 0
  138. : 138.5177312231 * log(kelvin - 10) - 305.0447927307);
  139. // Save values
  140. _channels[0].value = constrain(red, 0, LIGHT_MAX_VALUE);
  141. _channels[1].value = constrain(green, 0, LIGHT_MAX_VALUE);
  142. _channels[2].value = constrain(blue, 0, LIGHT_MAX_VALUE);
  143. }
  144. // Color temperature is measured in mireds (kelvin = 1e6/mired)
  145. void _fromMireds(unsigned long mireds) {
  146. if (mireds == 0) mireds = 1;
  147. unsigned long kelvin = constrain(1000000UL / mireds, 1000, 40000) / 100;
  148. _fromKelvin(kelvin);
  149. }
  150. unsigned int _toPWM(unsigned long value, bool bright, bool gamma, bool reverse) {
  151. value = constrain(value, 0, LIGHT_MAX_VALUE);
  152. if (bright) value *= ((float) _brightness / LIGHT_MAX_BRIGHTNESS);
  153. unsigned int pwm = gamma ? gamma_table[value] : map(value, 0, LIGHT_MAX_VALUE, 0, LIGHT_MAX_PWM);
  154. if (reverse) pwm = LIGHT_MAX_PWM - pwm;
  155. return pwm;
  156. }
  157. // Returns a PWM valule for the given channel ID
  158. unsigned int _toPWM(unsigned char id) {
  159. if (id < _channels.size()) {
  160. bool isColor = (lightHasColor() && id < 3);
  161. bool bright = isColor;
  162. bool gamma = isColor & (getSetting("useGamma", LIGHT_USE_GAMMA).toInt() == 1);
  163. return _toPWM(_channels[id].shadow, bright, gamma, _channels[id].reverse);
  164. }
  165. return 0;
  166. }
  167. // -----------------------------------------------------------------------------
  168. // PROVIDER
  169. // -----------------------------------------------------------------------------
  170. void _shadow() {
  171. for (unsigned int i=0; i < _channels.size(); i++) {
  172. _channels[i].shadow = _lightState ? _channels[i].value : 0;
  173. }
  174. if (lightHasColor()) {
  175. bool useWhite = getSetting("useWhite", LIGHT_USE_WHITE).toInt() == 1;
  176. if (_lightState && useWhite && _channels.size() > 3) {
  177. if (_channels[0].shadow == _channels[1].shadow && _channels[1].shadow == _channels[2].shadow ) {
  178. _channels[3].shadow = _channels[0].shadow * ((float) _brightness / LIGHT_MAX_BRIGHTNESS);
  179. _channels[2].shadow = 0;
  180. _channels[1].shadow = 0;
  181. _channels[0].shadow = 0;
  182. }
  183. }
  184. }
  185. }
  186. void _lightProviderUpdate() {
  187. _shadow();
  188. #ifdef LIGHT_ENABLE_PIN
  189. digitalWrite(LIGHT_ENABLE_PIN, _lightState);
  190. #endif
  191. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY9192
  192. if (_lightState) {
  193. float ratio = (float) LIGHT_MAX_VALUE / LIGHT_MAX_PWM;
  194. unsigned int red = _toPWM(0) * ratio;
  195. unsigned int green = _toPWM(1) * ratio;
  196. unsigned int blue = _toPWM(2) * ratio;
  197. unsigned int white = _toPWM(3) * ratio;
  198. unsigned int warm = _toPWM(4) * ratio;
  199. _my9291->setColor((my9291_color_t) { red, green, blue, white, warm });
  200. _my9291->setState(true);
  201. } else {
  202. _my9291->setState(false);
  203. }
  204. #endif
  205. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  206. for (unsigned int i=0; i < _channels.size(); i++) {
  207. analogWrite(_channels[i].pin, _toPWM(i));
  208. }
  209. #endif
  210. }
  211. // -----------------------------------------------------------------------------
  212. // PERSISTANCE
  213. // -----------------------------------------------------------------------------
  214. void _lightColorSave() {
  215. for (unsigned int i=0; i < _channels.size(); i++) {
  216. setSetting("ch", i, _channels[i].value);
  217. }
  218. setSetting("brightness", _brightness);
  219. saveSettings();
  220. }
  221. void _lightColorRestore() {
  222. for (unsigned int i=0; i < _channels.size(); i++) {
  223. _channels[i].value = getSetting("ch", i, i==0 ? 255 : 0).toInt();
  224. }
  225. _brightness = getSetting("brightness", LIGHT_MAX_BRIGHTNESS).toInt();
  226. lightUpdate(false, false);
  227. }
  228. // -----------------------------------------------------------------------------
  229. // MQTT
  230. // -----------------------------------------------------------------------------
  231. void _lightMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  232. if (type == MQTT_CONNECT_EVENT) {
  233. if (lightHasColor()) {
  234. mqttSubscribe(MQTT_TOPIC_BRIGHTNESS);
  235. mqttSubscribe(MQTT_TOPIC_MIRED);
  236. mqttSubscribe(MQTT_TOPIC_KELVIN);
  237. mqttSubscribe(MQTT_TOPIC_COLOR);
  238. }
  239. char buffer[strlen(MQTT_TOPIC_CHANNEL) + 3];
  240. snprintf_P(buffer, sizeof(buffer), PSTR("%s/+"), MQTT_TOPIC_CHANNEL);
  241. mqttSubscribe(buffer);
  242. }
  243. if (type == MQTT_MESSAGE_EVENT) {
  244. // Match topic
  245. String t = mqttSubtopic((char *) topic);
  246. // Color temperature in mireds
  247. if (t.equals(MQTT_TOPIC_MIRED)) {
  248. _fromMireds(atol(payload));
  249. lightUpdate(true, mqttForward());
  250. }
  251. // Color temperature in kelvins
  252. if (t.equals(MQTT_TOPIC_KELVIN)) {
  253. _fromKelvin(atol(payload));
  254. lightUpdate(true, mqttForward());
  255. }
  256. // Color
  257. if (t.equals(MQTT_TOPIC_COLOR)) {
  258. lightColor(payload);
  259. lightUpdate(true, mqttForward());
  260. }
  261. // Brightness
  262. if (t.equals(MQTT_TOPIC_BRIGHTNESS)) {
  263. _brightness = constrain(atoi(payload), 0, LIGHT_MAX_BRIGHTNESS);
  264. lightUpdate(true, mqttForward());
  265. }
  266. // Channel
  267. if (t.startsWith(MQTT_TOPIC_CHANNEL)) {
  268. unsigned int channelID = t.substring(strlen(MQTT_TOPIC_CHANNEL)+1).toInt();
  269. if (channelID >= _channels.size()) {
  270. DEBUG_MSG_P(PSTR("[LIGHT] Wrong channelID (%d)\n"), channelID);
  271. return;
  272. }
  273. lightChannel(channelID, atoi(payload));
  274. lightUpdate(true, mqttForward());
  275. }
  276. }
  277. }
  278. // -----------------------------------------------------------------------------
  279. // API
  280. // -----------------------------------------------------------------------------
  281. unsigned char lightChannels() {
  282. return _channels.size();
  283. }
  284. bool lightHasColor() {
  285. bool useColor = getSetting("useColor", LIGHT_USE_COLOR).toInt() == 1;
  286. return useColor && (_channels.size() > 2);
  287. }
  288. unsigned char lightWhiteChannels() {
  289. return _channels.size() % 3;
  290. }
  291. void lightMQTT() {
  292. char buffer[12];
  293. if (lightHasColor()) {
  294. // Color
  295. if (getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1) {
  296. _toRGB(buffer, 12, false);
  297. } else {
  298. _toLong(buffer, 12, false);
  299. }
  300. mqttSend(MQTT_TOPIC_COLOR, buffer);
  301. // Brightness
  302. snprintf_P(buffer, sizeof(buffer), PSTR("%d"), _brightness);
  303. mqttSend(MQTT_TOPIC_BRIGHTNESS, buffer);
  304. }
  305. // Channels
  306. for (unsigned int i=0; i < _channels.size(); i++) {
  307. snprintf_P(buffer, sizeof(buffer), PSTR("%d"), _channels[i].value);
  308. mqttSend(MQTT_TOPIC_CHANNEL, i, buffer);
  309. }
  310. }
  311. void lightUpdate(bool save, bool forward) {
  312. _lightProviderUpdate();
  313. // Report color & brightness to MQTT broker
  314. if (forward) lightMQTT();
  315. // Report color to WS clients (using current brightness setting)
  316. #if WEB_SUPPORT
  317. {
  318. DynamicJsonBuffer jsonBuffer;
  319. JsonObject& root = jsonBuffer.createObject();
  320. root["colorVisible"] = 1;
  321. root["useColor"] = getSetting("useColor", LIGHT_USE_COLOR).toInt() == 1;
  322. root["useWhite"] = getSetting("useWhite", LIGHT_USE_WHITE).toInt() == 1;
  323. root["useGamma"] = getSetting("useGamma", LIGHT_USE_GAMMA).toInt() == 1;
  324. if (lightHasColor()) {
  325. root["color"] = lightColor();
  326. root["brightness"] = lightBrightness();
  327. }
  328. JsonArray& channels = root.createNestedArray("channels");
  329. for (unsigned char id=0; id < lightChannels(); id++) {
  330. channels.add(lightChannel(id));
  331. }
  332. String output;
  333. root.printTo(output);
  334. wsSend(output.c_str());
  335. }
  336. #endif
  337. #if LIGHT_SAVE_ENABLED
  338. // Delay saving to EEPROM 5 seconds to avoid wearing it out unnecessarily
  339. if (save) colorTicker.once(LIGHT_SAVE_DELAY, _lightColorSave);
  340. #endif
  341. };
  342. #if LIGHT_SAVE_ENABLED == 0
  343. void lightSave() {
  344. _lightColorSave();
  345. }
  346. #endif
  347. void lightState(bool state) {
  348. _lightState = state;
  349. }
  350. bool lightState() {
  351. return _lightState;
  352. }
  353. void lightColor(const char * color) {
  354. _fromRGB(color);
  355. }
  356. String lightColor() {
  357. char rgb[8];
  358. _toRGB(rgb, 8, false);
  359. return String(rgb);
  360. }
  361. unsigned int lightChannel(unsigned char id) {
  362. if (id <= _channels.size()) {
  363. return _channels[id].value;
  364. }
  365. return 0;
  366. }
  367. void lightChannel(unsigned char id, unsigned int value) {
  368. if (id <= _channels.size()) {
  369. _channels[id].value = constrain(value, 0, LIGHT_MAX_VALUE);
  370. }
  371. }
  372. unsigned int lightBrightness() {
  373. return _brightness;
  374. }
  375. void lightBrightness(unsigned int b) {
  376. _brightness = constrain(b, 0, LIGHT_MAX_BRIGHTNESS);
  377. }
  378. // -----------------------------------------------------------------------------
  379. // SETUP
  380. // -----------------------------------------------------------------------------
  381. void _lightAPISetup() {
  382. #if WEB_SUPPORT
  383. // API entry points (protected with apikey)
  384. if (lightHasColor()) {
  385. apiRegister(MQTT_TOPIC_COLOR, MQTT_TOPIC_COLOR,
  386. [](char * buffer, size_t len) {
  387. if (getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1) {
  388. _toRGB(buffer, len, false);
  389. } else {
  390. _toLong(buffer, len, false);
  391. }
  392. },
  393. [](const char * payload) {
  394. lightColor(payload);
  395. lightUpdate(true, true);
  396. }
  397. );
  398. apiRegister(MQTT_TOPIC_BRIGHTNESS, MQTT_TOPIC_BRIGHTNESS,
  399. [](char * buffer, size_t len) {
  400. snprintf_P(buffer, len, PSTR("%d"), _brightness);
  401. },
  402. [](const char * payload) {
  403. lightBrightness(atoi(payload));
  404. lightUpdate(true, true);
  405. }
  406. );
  407. apiRegister(MQTT_TOPIC_KELVIN, MQTT_TOPIC_KELVIN,
  408. [](char * buffer, size_t len) {},
  409. [](const char * payload) {
  410. _fromKelvin(atol(payload));
  411. lightUpdate(true, true);
  412. }
  413. );
  414. apiRegister(MQTT_TOPIC_MIRED, MQTT_TOPIC_MIRED,
  415. [](char * buffer, size_t len) {},
  416. [](const char * payload) {
  417. _fromMireds(atol(payload));
  418. lightUpdate(true, true);
  419. }
  420. );
  421. }
  422. for (unsigned int id=0; id<lightChannels(); id++) {
  423. char url[15];
  424. snprintf_P(url, sizeof(url), PSTR("%s/%d"), MQTT_TOPIC_CHANNEL, id);
  425. char key[10];
  426. snprintf_P(key, sizeof(key), PSTR("%s%d"), MQTT_TOPIC_CHANNEL, id);
  427. apiRegister(url, key,
  428. [id](char * buffer, size_t len) {
  429. snprintf_P(buffer, len, PSTR("%d"), lightChannel(id));
  430. },
  431. [id](const char * payload) {
  432. lightChannel(id, atoi(payload));
  433. lightUpdate(true, true);
  434. }
  435. );
  436. }
  437. #endif // WEB_SUPPORT
  438. }
  439. void lightSetup() {
  440. #ifdef LIGHT_ENABLE_PIN
  441. pinMode(LIGHT_ENABLE_PIN, OUTPUT);
  442. #endif
  443. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY9192
  444. _my9291 = new my9291(MY9291_DI_PIN, MY9291_DCKI_PIN, MY9291_COMMAND, MY9291_CHANNELS);
  445. for (unsigned char i=0; i<MY9291_CHANNELS; i++) {
  446. _channels.push_back((channel_t) {0, false, 0});
  447. }
  448. #endif
  449. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  450. #ifdef LIGHT_CH1_PIN
  451. _channels.push_back((channel_t) {LIGHT_CH1_PIN, LIGHT_CH1_INVERSE, 0});
  452. #endif
  453. #ifdef LIGHT_CH2_PIN
  454. _channels.push_back((channel_t) {LIGHT_CH2_PIN, LIGHT_CH2_INVERSE, 0});
  455. #endif
  456. #ifdef LIGHT_CH3_PIN
  457. _channels.push_back((channel_t) {LIGHT_CH3_PIN, LIGHT_CH3_INVERSE, 0});
  458. #endif
  459. #ifdef LIGHT_CH4_PIN
  460. _channels.push_back((channel_t) {LIGHT_CH4_PIN, LIGHT_CH4_INVERSE, 0});
  461. #endif
  462. #ifdef LIGHT_CH5_PIN
  463. _channels.push_back((channel_t) {LIGHT_CH5_PIN, LIGHT_CH5_INVERSE, 0});
  464. #endif
  465. analogWriteRange(LIGHT_MAX_PWM+1);
  466. analogWriteFreq(LIGHT_PWM_FREQUENCY);
  467. for (unsigned int i=0; i < _channels.size(); i++) {
  468. pinMode(_channels[i].pin, OUTPUT);
  469. }
  470. #endif
  471. DEBUG_MSG_P(PSTR("[LIGHT] LIGHT_PROVIDER = %d\n"), LIGHT_PROVIDER);
  472. DEBUG_MSG_P(PSTR("[LIGHT] Number of channels: %d\n"), _channels.size());
  473. _lightColorRestore();
  474. _lightAPISetup();
  475. mqttRegister(_lightMQTTCallback);
  476. }
  477. void lightLoop(){
  478. }
  479. #endif // LIGHT_PROVIDER_EXPERIMENTAL_RGB_ONLY_HSV_IR
  480. #endif // LIGHT_PROVIDER != LIGHT_PROVIDER_NONE