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. _my9291->setColor((my9291_color_t) { red, green, blue, white });
  183. _my9291->setState(true);
  184. } else {
  185. _my9291->setState(false);
  186. }
  187. #endif
  188. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  189. for (unsigned int i=0; i < _channels.size(); i++) {
  190. analogWrite(_channels[i].pin, _toPWM(i));
  191. }
  192. #endif
  193. }
  194. // -----------------------------------------------------------------------------
  195. // PERSISTANCE
  196. // -----------------------------------------------------------------------------
  197. void _lightColorSave() {
  198. for (unsigned int i=0; i < _channels.size(); i++) {
  199. setSetting("ch", i, _channels[i].value);
  200. }
  201. setSetting("brightness", _brightness);
  202. saveSettings();
  203. }
  204. void _lightColorRestore() {
  205. for (unsigned int i=0; i < _channels.size(); i++) {
  206. _channels[i].value = getSetting("ch", i, 0).toInt();
  207. }
  208. _brightness = getSetting("brightness", LIGHT_MAX_BRIGHTNESS).toInt();
  209. lightUpdate(false, false);
  210. }
  211. // -----------------------------------------------------------------------------
  212. // MQTT
  213. // -----------------------------------------------------------------------------
  214. void _lightMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  215. if (type == MQTT_CONNECT_EVENT) {
  216. if (lightHasColor()) {
  217. mqttSubscribe(MQTT_TOPIC_BRIGHTNESS);
  218. mqttSubscribe(MQTT_TOPIC_MIRED);
  219. mqttSubscribe(MQTT_TOPIC_KELVIN);
  220. mqttSubscribe(MQTT_TOPIC_COLOR);
  221. }
  222. char buffer[strlen(MQTT_TOPIC_CHANNEL) + 3];
  223. sprintf_P(buffer, PSTR("%s/+"), MQTT_TOPIC_CHANNEL);
  224. mqttSubscribe(buffer);
  225. }
  226. if (type == MQTT_MESSAGE_EVENT) {
  227. // Match topic
  228. String t = mqttSubtopic((char *) topic);
  229. // Color temperature in mireds
  230. if (t.equals(MQTT_TOPIC_MIRED)) {
  231. _fromMireds(atol(payload));
  232. lightUpdate(true, mqttForward());
  233. }
  234. // Color temperature in kelvins
  235. if (t.equals(MQTT_TOPIC_KELVIN)) {
  236. _fromKelvin(atol(payload));
  237. lightUpdate(true, mqttForward());
  238. }
  239. // Color
  240. if (t.equals(MQTT_TOPIC_COLOR)) {
  241. lightColor(payload);
  242. lightUpdate(true, mqttForward());
  243. }
  244. // Brightness
  245. if (t.equals(MQTT_TOPIC_BRIGHTNESS)) {
  246. _brightness = constrain(atoi(payload), 0, LIGHT_MAX_BRIGHTNESS);
  247. lightUpdate(true, mqttForward());
  248. }
  249. // Channel
  250. if (t.startsWith(MQTT_TOPIC_CHANNEL)) {
  251. unsigned int channelID = t.substring(strlen(MQTT_TOPIC_CHANNEL)+1).toInt();
  252. if (channelID >= _channels.size()) {
  253. DEBUG_MSG_P(PSTR("[LIGHT] Wrong channelID (%d)\n"), channelID);
  254. return;
  255. }
  256. lightChannel(channelID, atoi(payload));
  257. lightUpdate(true, mqttForward());
  258. }
  259. }
  260. }
  261. // -----------------------------------------------------------------------------
  262. // API
  263. // -----------------------------------------------------------------------------
  264. unsigned char lightChannels() {
  265. return _channels.size();
  266. }
  267. bool lightHasColor() {
  268. bool useColor = getSetting("useColor", LIGHT_USE_COLOR).toInt() == 1;
  269. return useColor && (_channels.size() > 2);
  270. }
  271. unsigned char lightWhiteChannels() {
  272. return _channels.size() % 3;
  273. }
  274. void lightMQTT() {
  275. char buffer[8];
  276. if (lightHasColor()) {
  277. // Color
  278. _toRGB(buffer, 8, false);
  279. mqttSend(MQTT_TOPIC_COLOR, buffer);
  280. // Brightness
  281. sprintf_P(buffer, PSTR("%d"), _brightness);
  282. mqttSend(MQTT_TOPIC_BRIGHTNESS, buffer);
  283. }
  284. // Channels
  285. for (unsigned int i=0; i < _channels.size(); i++) {
  286. sprintf_P(buffer, PSTR("%d"), _channels[i].value);
  287. mqttSend(MQTT_TOPIC_CHANNEL, i, buffer);
  288. }
  289. }
  290. void lightUpdate(bool save, bool forward) {
  291. _lightProviderUpdate();
  292. // Report color & brightness to MQTT broker
  293. if (forward) lightMQTT();
  294. // Report color to WS clients (using current brightness setting)
  295. #if WEB_SUPPORT
  296. {
  297. DynamicJsonBuffer jsonBuffer;
  298. JsonObject& root = jsonBuffer.createObject();
  299. root["colorVisible"] = 1;
  300. root["useColor"] = getSetting("useColor", LIGHT_USE_COLOR).toInt() == 1;
  301. root["useWhite"] = getSetting("useWhite", LIGHT_USE_WHITE).toInt() == 1;
  302. root["useGamma"] = getSetting("useGamma", LIGHT_USE_GAMMA).toInt() == 1;
  303. if (lightHasColor()) {
  304. root["color"] = lightColor();
  305. root["brightness"] = lightBrightness();
  306. }
  307. JsonArray& channels = root.createNestedArray("channels");
  308. for (unsigned char id=0; id < lightChannels(); id++) {
  309. channels.add(lightChannel(id));
  310. }
  311. String output;
  312. root.printTo(output);
  313. wsSend(output.c_str());
  314. }
  315. #endif
  316. // Delay saving to EEPROM 5 seconds to avoid wearing it out unnecessarily
  317. if (save) colorTicker.once(LIGHT_SAVE_DELAY, _lightColorSave);
  318. };
  319. void lightState(bool state) {
  320. _lightState = state;
  321. }
  322. bool lightState() {
  323. return _lightState;
  324. }
  325. void lightColor(const char * color) {
  326. _fromRGB(color);
  327. }
  328. String lightColor() {
  329. char rgb[8];
  330. _toRGB(rgb, 8, false);
  331. return String(rgb);
  332. }
  333. unsigned int lightChannel(unsigned char id) {
  334. if (id <= _channels.size()) {
  335. return _channels[id].value;
  336. }
  337. return 0;
  338. }
  339. void lightChannel(unsigned char id, unsigned int value) {
  340. if (id <= _channels.size()) {
  341. _channels[id].value = constrain(value, 0, LIGHT_MAX_VALUE);
  342. }
  343. }
  344. unsigned int lightBrightness() {
  345. return _brightness;
  346. }
  347. void lightBrightness(unsigned int b) {
  348. _brightness = constrain(b, 0, LIGHT_MAX_BRIGHTNESS);
  349. }
  350. // -----------------------------------------------------------------------------
  351. // SETUP
  352. // -----------------------------------------------------------------------------
  353. void _lightAPISetup() {
  354. #if WEB_SUPPORT
  355. // API entry points (protected with apikey)
  356. if (lightHasColor()) {
  357. apiRegister(MQTT_TOPIC_COLOR, MQTT_TOPIC_COLOR,
  358. [](char * buffer, size_t len) {
  359. _toRGB(buffer, len, false);
  360. },
  361. [](const char * payload) {
  362. lightColor(payload);
  363. lightUpdate(true, true);
  364. }
  365. );
  366. apiRegister(MQTT_TOPIC_BRIGHTNESS, MQTT_TOPIC_BRIGHTNESS,
  367. [](char * buffer, size_t len) {
  368. snprintf_P(buffer, len, PSTR("%d"), _brightness);
  369. },
  370. [](const char * payload) {
  371. lightBrightness(atoi(payload));
  372. lightUpdate(true, true);
  373. }
  374. );
  375. apiRegister(MQTT_TOPIC_KELVIN, MQTT_TOPIC_KELVIN,
  376. [](char * buffer, size_t len) {},
  377. [](const char * payload) {
  378. _fromKelvin(atol(payload));
  379. lightUpdate(true, true);
  380. }
  381. );
  382. apiRegister(MQTT_TOPIC_MIRED, MQTT_TOPIC_MIRED,
  383. [](char * buffer, size_t len) {},
  384. [](const char * payload) {
  385. _fromMireds(atol(payload));
  386. lightUpdate(true, true);
  387. }
  388. );
  389. }
  390. for (unsigned int id=0; id<lightChannels(); id++) {
  391. char url[15];
  392. sprintf_P(url, PSTR("%s/%d"), MQTT_TOPIC_CHANNEL, id);
  393. char key[10];
  394. sprintf_P(key, PSTR("%s%d"), MQTT_TOPIC_CHANNEL, id);
  395. apiRegister(url, key,
  396. [id](char * buffer, size_t len) {
  397. snprintf_P(buffer, len, PSTR("%d"), lightChannel(id));
  398. },
  399. [id](const char * payload) {
  400. lightChannel(id, atoi(payload));
  401. lightUpdate(true, true);
  402. }
  403. );
  404. }
  405. #endif // WEB_SUPPORT
  406. }
  407. void lightSetup() {
  408. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY9192
  409. _my9291 = new my9291(MY9291_DI_PIN, MY9291_DCKI_PIN, MY9291_COMMAND);
  410. _channels.push_back((channel_t) {0, false, 0});
  411. _channels.push_back((channel_t) {0, false, 0});
  412. _channels.push_back((channel_t) {0, false, 0});
  413. _channels.push_back((channel_t) {0, false, 0});
  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