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.

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