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.

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