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.

579 lines
17 KiB

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