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.

573 lines
16 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(rgb, len, "#%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;
  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(buffer, "%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(buffer, "%d", _brightness);
  282. mqttSend(MQTT_TOPIC_BRIGHTNESS, buffer);
  283. }
  284. // Channels
  285. for (unsigned int i=0; i < _channels.size(); i++) {
  286. sprintf(buffer, "%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. {
  296. DynamicJsonBuffer jsonBuffer;
  297. JsonObject& root = jsonBuffer.createObject();
  298. root["colorVisible"] = 1;
  299. root["useColor"] = getSetting("useColor", LIGHT_USE_COLOR).toInt() == 1;
  300. root["useWhite"] = getSetting("useWhite", LIGHT_USE_WHITE).toInt() == 1;
  301. root["useGamma"] = getSetting("useGamma", LIGHT_USE_GAMMA).toInt() == 1;
  302. if (lightHasColor()) {
  303. root["color"] = lightColor();
  304. root["brightness"] = lightBrightness();
  305. }
  306. JsonArray& channels = root.createNestedArray("channels");
  307. for (unsigned char id=0; id < lightChannels(); id++) {
  308. channels.add(lightChannel(id));
  309. }
  310. String output;
  311. root.printTo(output);
  312. wsSend(output.c_str());
  313. }
  314. // Delay saving to EEPROM 5 seconds to avoid wearing it out unnecessarily
  315. if (save) colorTicker.once(LIGHT_SAVE_DELAY, _lightColorSave);
  316. };
  317. void lightState(bool state) {
  318. _lightState = state;
  319. }
  320. bool lightState() {
  321. return _lightState;
  322. }
  323. void lightColor(const char * color) {
  324. _fromRGB(color);
  325. }
  326. String lightColor() {
  327. char rgb[8];
  328. _toRGB(rgb, 8, false);
  329. return String(rgb);
  330. }
  331. unsigned int lightChannel(unsigned char id) {
  332. if (id <= _channels.size()) {
  333. return _channels[id].value;
  334. }
  335. return 0;
  336. }
  337. void lightChannel(unsigned char id, unsigned int value) {
  338. if (id <= _channels.size()) {
  339. _channels[id].value = constrain(value, 0, LIGHT_MAX_VALUE);
  340. }
  341. }
  342. unsigned int lightBrightness() {
  343. return _brightness;
  344. }
  345. void lightBrightness(unsigned int b) {
  346. _brightness = constrain(b, 0, LIGHT_MAX_BRIGHTNESS);
  347. }
  348. // -----------------------------------------------------------------------------
  349. // SETUP
  350. // -----------------------------------------------------------------------------
  351. void _lightAPISetup() {
  352. // API entry points (protected with apikey)
  353. if (lightHasColor()) {
  354. apiRegister(MQTT_TOPIC_COLOR, MQTT_TOPIC_COLOR,
  355. [](char * buffer, size_t len) {
  356. _toRGB(buffer, len, false);
  357. },
  358. [](const char * payload) {
  359. lightColor(payload);
  360. lightUpdate(true, true);
  361. }
  362. );
  363. apiRegister(MQTT_TOPIC_BRIGHTNESS, MQTT_TOPIC_BRIGHTNESS,
  364. [](char * buffer, size_t len) {
  365. snprintf(buffer, len, "%d", _brightness);
  366. },
  367. [](const char * payload) {
  368. lightBrightness(atoi(payload));
  369. lightUpdate(true, true);
  370. }
  371. );
  372. apiRegister(MQTT_TOPIC_KELVIN, MQTT_TOPIC_KELVIN,
  373. [](char * buffer, size_t len) {},
  374. [](const char * payload) {
  375. _fromKelvin(atol(payload));
  376. lightUpdate(true, true);
  377. }
  378. );
  379. apiRegister(MQTT_TOPIC_MIRED, MQTT_TOPIC_MIRED,
  380. [](char * buffer, size_t len) {},
  381. [](const char * payload) {
  382. _fromMireds(atol(payload));
  383. lightUpdate(true, true);
  384. }
  385. );
  386. }
  387. for (unsigned int id=0; id<lightChannels(); id++) {
  388. char url[15];
  389. sprintf(url, "%s/%d", MQTT_TOPIC_CHANNEL, id);
  390. char key[10];
  391. sprintf(key, "%s%d", MQTT_TOPIC_CHANNEL, id);
  392. apiRegister(url, key,
  393. [id](char * buffer, size_t len) {
  394. snprintf(buffer, len, "%d", lightChannel(id));
  395. },
  396. [id](const char * payload) {
  397. lightChannel(id, atoi(payload));
  398. lightUpdate(true, true);
  399. }
  400. );
  401. }
  402. }
  403. void lightSetup() {
  404. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY9192
  405. _my9291 = new my9291(MY9291_DI_PIN, MY9291_DCKI_PIN, MY9291_COMMAND);
  406. _channels.push_back((channel_t) {0, false, 0});
  407. _channels.push_back((channel_t) {0, false, 0});
  408. _channels.push_back((channel_t) {0, false, 0});
  409. _channels.push_back((channel_t) {0, false, 0});
  410. #endif
  411. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  412. #ifdef LIGHT_CH1_PIN
  413. _channels.push_back((channel_t) {LIGHT_CH1_PIN, LIGHT_CH1_INVERSE, 0});
  414. #endif
  415. #ifdef LIGHT_CH2_PIN
  416. _channels.push_back((channel_t) {LIGHT_CH2_PIN, LIGHT_CH2_INVERSE, 0});
  417. #endif
  418. #ifdef LIGHT_CH3_PIN
  419. _channels.push_back((channel_t) {LIGHT_CH3_PIN, LIGHT_CH3_INVERSE, 0});
  420. #endif
  421. #ifdef LIGHT_CH4_PIN
  422. _channels.push_back((channel_t) {LIGHT_CH4_PIN, LIGHT_CH4_INVERSE, 0});
  423. #endif
  424. #ifdef LIGHT_CH5_PIN
  425. _channels.push_back((channel_t) {LIGHT_CH5_PIN, LIGHT_CH5_INVERSE, 0});
  426. #endif
  427. analogWriteRange(LIGHT_MAX_PWM+1);
  428. analogWriteFreq(LIGHT_PWM_FREQUENCY);
  429. for (unsigned int i=0; i < _channels.size(); i++) {
  430. pinMode(_channels[i].pin, OUTPUT);
  431. }
  432. #endif
  433. _lightColorRestore();
  434. _lightAPISetup();
  435. mqttRegister(_lightMQTTCallback);
  436. }
  437. #endif // LIGHT_PROVIDER != LIGHT_PROVIDER_NONE