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.

562 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. typedef struct {
  10. unsigned char pin;
  11. bool reverse;
  12. unsigned char value;
  13. unsigned char shadow;
  14. } channel_t;
  15. std::vector<channel_t> _channels;
  16. Ticker colorTicker;
  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. #if LIGHT_ENABLE_GAMMA
  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. #endif
  44. // -----------------------------------------------------------------------------
  45. // UTILS
  46. // -----------------------------------------------------------------------------
  47. void _fromRGB(const char * rgb) {
  48. char * p = (char *) rgb;
  49. if (strlen(p) == 0) return;
  50. // if color begins with a # then assume HEX RGB
  51. if (p[0] == '#') {
  52. if (!lightHasColor()) return;
  53. ++p;
  54. unsigned long value = strtoul(p, NULL, 16);
  55. // RGBA values are interpreted like RGB + brightness
  56. if (strlen(p) > 7) {
  57. _channels[0].value = (value >> 24) & 0xFF;
  58. _channels[1].value = (value >> 16) & 0xFF;
  59. _channels[2].value = (value >> 8) & 0xFF;
  60. _brightness = (value & 0xFF) * LIGHT_MAX_BRIGHTNESS / 255;
  61. } else {
  62. _channels[0].value = (value >> 16) & 0xFF;
  63. _channels[1].value = (value >> 8) & 0xFF;
  64. _channels[2].value = (value) & 0xFF;
  65. }
  66. // it's a temperature in mireds
  67. } else if (p[0] == 'M') {
  68. unsigned long mireds = atol(p + 1);
  69. _fromMireds(mireds);
  70. // it's a temperature in kelvin
  71. } else if (p[0] == 'K') {
  72. unsigned long kelvin = atol(p + 1);
  73. _fromKelvin(kelvin);
  74. // otherwise assume decimal values separated by commas
  75. } else {
  76. char * tok;
  77. unsigned char count = 0;
  78. unsigned char channels = _channels.size();
  79. tok = strtok(p, ",");
  80. while (tok != NULL) {
  81. _channels[count].value = atoi(tok);
  82. if (++count == channels) break;
  83. tok = strtok(NULL, ",");
  84. }
  85. // RGB but less than 3 values received
  86. if (channels > 2 & count < 3) {
  87. _channels[1].value = _channels[0].value;
  88. _channels[2].value = _channels[0].value;
  89. }
  90. }
  91. }
  92. void _toRGB(char * rgb, size_t len, bool applyBrightness) {
  93. if (!lightHasColor()) return;
  94. float b = applyBrightness ? (float) _brightness / LIGHT_MAX_BRIGHTNESS : 1;
  95. unsigned long value = 0;
  96. value += _channels[0].value * b;
  97. value <<= 8;
  98. value += _channels[1].value * b;
  99. value <<= 8;
  100. value += _channels[2].value * b;
  101. snprintf(rgb, len, "#%06X", value);
  102. }
  103. void _toRGB(char * rgb, size_t len) {
  104. _toRGB(rgb, len, false);
  105. }
  106. // Thanks to Sacha Telgenhof for sharing this code in his AiLight library
  107. // https://github.com/stelgenhof/AiLight
  108. void _fromKelvin(unsigned long kelvin) {
  109. // Check we have RGB channels
  110. if (!lightHasColor()) return;
  111. // Calculate colors
  112. unsigned int red = (kelvin <= 66)
  113. ? LIGHT_MAX_VALUE
  114. : 329.698727446 * pow((kelvin - 60), -0.1332047592);
  115. unsigned int green = (kelvin <= 66)
  116. ? 99.4708025861 * log(kelvin) - 161.1195681661
  117. : 288.1221695283 * pow(kelvin, -0.0755148492);
  118. unsigned int blue = (kelvin >= 66)
  119. ? LIGHT_MAX_VALUE
  120. : ((kelvin <= 19)
  121. ? 0
  122. : 138.5177312231 * log(kelvin - 10) - 305.0447927307);
  123. // Save values
  124. _channels[0].value = constrain(red, 0, LIGHT_MAX_VALUE);
  125. _channels[1].value = constrain(green, 0, LIGHT_MAX_VALUE);
  126. _channels[2].value = constrain(blue, 0, LIGHT_MAX_VALUE);
  127. }
  128. // Color temperature is measured in mireds (kelvin = 1e6/mired)
  129. void _fromMireds(unsigned long mireds) {
  130. if (mireds == 0) mireds = 1;
  131. unsigned long kelvin = constrain(1000000UL / mireds, 1000, 40000) / 100;
  132. _fromKelvin(kelvin);
  133. }
  134. unsigned int _toPWM(unsigned long value, bool gamma, bool reverse) {
  135. value = constrain(value, 0, LIGHT_MAX_VALUE);
  136. value *= ((float) _brightness / LIGHT_MAX_BRIGHTNESS);
  137. #if LIGHT_ENABLE_GAMMA
  138. unsigned int pwm = gamma ? gamma_table[value] : map(value, 0, LIGHT_MAX_VALUE, 0, LIGHT_MAX_PWM);
  139. #else
  140. unsigned int pwm = map(value, 0, LIGHT_MAX_VALUE, 0, LIGHT_MAX_PWM);
  141. #endif
  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. #if LIGHT_ENABLE_GAMMA
  149. bool gamma = (lightHasColor() && id < 3);
  150. #else
  151. bool gamma = false;
  152. #endif
  153. return _toPWM(_channels[id].shadow, gamma, _channels[id].reverse);
  154. }
  155. return 0;
  156. }
  157. // -----------------------------------------------------------------------------
  158. // PROVIDER
  159. // -----------------------------------------------------------------------------
  160. void _shadow() {
  161. bool useWhite = getSetting("useWhite", LIGHT_USE_WHITE).toInt() == 1;
  162. for (unsigned int i=0; i < _channels.size(); i++) {
  163. _channels[i].shadow = _lightState ? _channels[i].value : 0;
  164. }
  165. if (_lightState && useWhite && _channels.size() > 3) {
  166. if (_channels[0].shadow == _channels[1].shadow && _channels[1].shadow == _channels[2].shadow ) {
  167. _channels[3].shadow = _channels[0].shadow;
  168. _channels[2].shadow = 0;
  169. _channels[1].shadow = 0;
  170. _channels[0].shadow = 0;
  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. _my9291->setColor((my9291_color_t) { red, green, blue, white });
  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. mqttSubscribe(MQTT_TOPIC_BRIGHTNESS);
  218. mqttSubscribe(MQTT_TOPIC_MIRED);
  219. mqttSubscribe(MQTT_TOPIC_KELVIN);
  220. mqttSubscribe(MQTT_TOPIC_COLOR);
  221. char buffer[strlen(MQTT_TOPIC_CHANNEL) + 3];
  222. sprintf(buffer, "%s/+", MQTT_TOPIC_CHANNEL);
  223. mqttSubscribe(buffer);
  224. }
  225. if (type == MQTT_MESSAGE_EVENT) {
  226. // Match topic
  227. String t = mqttSubtopic((char *) topic);
  228. // Color temperature in mireds
  229. if (t.equals(MQTT_TOPIC_MIRED)) {
  230. _fromMireds(atol(payload));
  231. lightUpdate(true, mqttForward());
  232. }
  233. // Color temperature in kelvins
  234. if (t.equals(MQTT_TOPIC_KELVIN)) {
  235. _fromKelvin(atol(payload));
  236. lightUpdate(true, mqttForward());
  237. }
  238. // Color
  239. if (t.equals(MQTT_TOPIC_COLOR)) {
  240. lightColor(payload);
  241. lightUpdate(true, mqttForward());
  242. }
  243. // Brightness
  244. if (t.equals(MQTT_TOPIC_BRIGHTNESS)) {
  245. _brightness = constrain(atoi(payload), 0, LIGHT_MAX_BRIGHTNESS);
  246. lightUpdate(true, mqttForward());
  247. }
  248. // Channel
  249. if (t.startsWith(MQTT_TOPIC_CHANNEL)) {
  250. unsigned int channelID = t.substring(strlen(MQTT_TOPIC_CHANNEL)+1).toInt();
  251. if (channelID >= _channels.size()) {
  252. DEBUG_MSG_P(PSTR("[LIGHT] Wrong channelID (%d)\n"), channelID);
  253. return;
  254. }
  255. lightChannel(channelID, atoi(payload));
  256. lightUpdate(true, mqttForward());
  257. }
  258. }
  259. }
  260. // -----------------------------------------------------------------------------
  261. // API
  262. // -----------------------------------------------------------------------------
  263. unsigned char lightChannels() {
  264. return _channels.size();
  265. }
  266. bool lightHasColor() {
  267. return _channels.size() > 2;
  268. }
  269. unsigned char lightWhiteChannels() {
  270. return _channels.size() % 3;
  271. }
  272. void lightMQTT() {
  273. char buffer[8];
  274. // Color
  275. if (lightHasColor()) {
  276. _toRGB(buffer, 8, false);
  277. mqttSend(MQTT_TOPIC_COLOR, buffer);
  278. }
  279. // Channels
  280. for (unsigned int i=0; i < _channels.size(); i++) {
  281. sprintf(buffer, "%d", _channels[i].value);
  282. mqttSend(MQTT_TOPIC_CHANNEL, i, buffer);
  283. }
  284. // Brightness
  285. sprintf(buffer, "%d", _brightness);
  286. mqttSend(MQTT_TOPIC_BRIGHTNESS, buffer);
  287. }
  288. void lightUpdate(bool save, bool forward) {
  289. _lightProviderUpdate();
  290. // Delay saving to EEPROM 5 seconds to avoid wearing it out unnecessarily
  291. if (save) colorTicker.once(LIGHT_SAVE_DELAY, _lightColorSave);
  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["color"] = lightColor();
  300. JsonArray& channels = root.createNestedArray("channels");
  301. for (unsigned char id=0; id < lightChannels(); id++) {
  302. channels.add(lightChannel(id));
  303. }
  304. root["brightness"] = lightBrightness();
  305. String output;
  306. root.printTo(output);
  307. wsSend(output.c_str());
  308. }
  309. };
  310. void lightState(bool state) {
  311. _lightState = state;
  312. }
  313. bool lightState() {
  314. return _lightState;
  315. }
  316. void lightColor(const char * color) {
  317. _fromRGB(color);
  318. }
  319. String lightColor() {
  320. char rgb[8];
  321. _toRGB(rgb, 8, false);
  322. return String(rgb);
  323. }
  324. unsigned int lightChannel(unsigned char id) {
  325. if (id <= _channels.size()) {
  326. return _channels[id].value;
  327. }
  328. return 0;
  329. }
  330. void lightChannel(unsigned char id, unsigned int value) {
  331. if (id <= _channels.size()) {
  332. _channels[id].value = constrain(value, 0, LIGHT_MAX_VALUE);
  333. }
  334. }
  335. unsigned int lightBrightness() {
  336. return _brightness;
  337. }
  338. void lightBrightness(unsigned int b) {
  339. _brightness = constrain(b, 0, LIGHT_MAX_BRIGHTNESS);
  340. }
  341. // -----------------------------------------------------------------------------
  342. // SETUP
  343. // -----------------------------------------------------------------------------
  344. void _lightAPISetup() {
  345. // API entry points (protected with apikey)
  346. if (_channels.size() > 2) {
  347. apiRegister(MQTT_TOPIC_COLOR, MQTT_TOPIC_COLOR,
  348. [](char * buffer, size_t len) {
  349. _toRGB(buffer, len, false);
  350. },
  351. [](const char * payload) {
  352. lightColor(payload);
  353. lightUpdate(true, true);
  354. }
  355. );
  356. }
  357. apiRegister(MQTT_TOPIC_KELVIN, MQTT_TOPIC_KELVIN,
  358. [](char * buffer, size_t len) {},
  359. [](const char * payload) {
  360. _fromKelvin(atol(payload));
  361. lightUpdate(true, true);
  362. }
  363. );
  364. apiRegister(MQTT_TOPIC_MIRED, MQTT_TOPIC_MIRED,
  365. [](char * buffer, size_t len) {},
  366. [](const char * payload) {
  367. _fromMireds(atol(payload));
  368. lightUpdate(true, true);
  369. }
  370. );
  371. apiRegister(MQTT_TOPIC_BRIGHTNESS, MQTT_TOPIC_BRIGHTNESS,
  372. [](char * buffer, size_t len) {
  373. snprintf(buffer, len, "%d", _brightness);
  374. },
  375. [](const char * payload) {
  376. lightBrightness(atoi(payload));
  377. lightUpdate(true, true);
  378. }
  379. );
  380. for (unsigned int id=0; id<lightChannels(); id++) {
  381. char url[15];
  382. sprintf(url, "%s/%d", MQTT_TOPIC_CHANNEL, id);
  383. char key[10];
  384. sprintf(key, "%s%d", MQTT_TOPIC_CHANNEL, id);
  385. apiRegister(url, key,
  386. [id](char * buffer, size_t len) {
  387. snprintf(buffer, len, "%d", lightChannel(id));
  388. },
  389. [id](const char * payload) {
  390. lightChannel(id, atoi(payload));
  391. lightUpdate(true, true);
  392. }
  393. );
  394. }
  395. }
  396. void lightSetup() {
  397. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY9192
  398. _my9291 = new my9291(MY9291_DI_PIN, MY9291_DCKI_PIN, MY9291_COMMAND);
  399. _channels.push_back((channel_t) {0, false, 0});
  400. _channels.push_back((channel_t) {0, false, 0});
  401. _channels.push_back((channel_t) {0, false, 0});
  402. _channels.push_back((channel_t) {0, false, 0});
  403. #endif
  404. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  405. #ifdef LIGHT_CH1_PIN
  406. _channels.push_back((channel_t) {LIGHT_CH1_PIN, LIGHT_CH1_INVERSE, 0});
  407. #endif
  408. #ifdef LIGHT_CH2_PIN
  409. _channels.push_back((channel_t) {LIGHT_CH2_PIN, LIGHT_CH2_INVERSE, 0});
  410. #endif
  411. #ifdef LIGHT_CH3_PIN
  412. _channels.push_back((channel_t) {LIGHT_CH3_PIN, LIGHT_CH3_INVERSE, 0});
  413. #endif
  414. #ifdef LIGHT_CH4_PIN
  415. _channels.push_back((channel_t) {LIGHT_CH4_PIN, LIGHT_CH4_INVERSE, 0});
  416. #endif
  417. #ifdef LIGHT_CH5_PIN
  418. _channels.push_back((channel_t) {LIGHT_CH5_PIN, LIGHT_CH5_INVERSE, 0});
  419. #endif
  420. analogWriteRange(LIGHT_MAX_PWM+1);
  421. analogWriteFreq(LIGHT_PWM_FREQUENCY);
  422. for (unsigned int i=0; i < _channels.size(); i++) {
  423. pinMode(_channels[i].pin, OUTPUT);
  424. }
  425. #endif
  426. _lightColorRestore();
  427. _lightAPISetup();
  428. mqttRegister(_lightMQTTCallback);
  429. }
  430. #endif // LIGHT_PROVIDER != LIGHT_PROVIDER_NONE