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.

1460 lines
44 KiB

6 years ago
6 years ago
6 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. /*
  2. LIGHT MODULE
  3. Copyright (C) 2016-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #include "light.h"
  6. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  7. #include "api.h"
  8. #include "broker.h"
  9. #include "mqtt.h"
  10. #include "rpc.h"
  11. #include "rtcmem.h"
  12. #include "tuya.h"
  13. #include "ws.h"
  14. #include "light_config.h"
  15. #include <Ticker.h>
  16. #include <Schedule.h>
  17. #include <ArduinoJson.h>
  18. #include <vector>
  19. extern "C" {
  20. #include "libs/fs_math.h"
  21. }
  22. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  23. // default is 8, we only need up to 5
  24. #define PWM_CHANNEL_NUM_MAX Light::ChannelsMax
  25. extern "C" {
  26. #include "libs/pwm.h"
  27. }
  28. #endif
  29. // -----------------------------------------------------------------------------
  30. struct channel_t {
  31. channel_t();
  32. channel_t(unsigned char pin, bool inverse);
  33. unsigned char pin; // real GPIO pin
  34. bool inverse; // whether we should invert the value before using it
  35. bool state; // is the channel ON
  36. unsigned char inputValue; // raw value, without the brightness
  37. unsigned char value; // normalized value, including brightness
  38. unsigned char target; // target value
  39. double current; // transition value
  40. };
  41. Ticker _light_comms_ticker;
  42. Ticker _light_save_ticker;
  43. Ticker _light_transition_ticker;
  44. std::vector<channel_t> _light_channels;
  45. bool _light_has_color = false;
  46. bool _light_use_white = false;
  47. bool _light_use_cct = false;
  48. bool _light_use_gamma = false;
  49. bool _light_provider_update = false;
  50. bool _light_use_transitions = false;
  51. unsigned int _light_transition_time = LIGHT_TRANSITION_TIME;
  52. bool _light_dirty = false;
  53. bool _light_state = false;
  54. unsigned char _light_brightness = Light::BRIGHTNESS_MAX;
  55. // Default to the Philips Hue value that HA also use.
  56. // https://developers.meethue.com/documentation/core-concepts
  57. long _light_cold_mireds = LIGHT_COLDWHITE_MIRED;
  58. long _light_warm_mireds = LIGHT_WARMWHITE_MIRED;
  59. long _light_cold_kelvin = (1000000L / _light_cold_mireds);
  60. long _light_warm_kelvin = (1000000L / _light_warm_mireds);
  61. long _light_mireds = lround((_light_cold_mireds + _light_warm_mireds) / 2L);
  62. using light_brightness_func_t = void();
  63. light_brightness_func_t* _light_brightness_func = nullptr;
  64. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  65. #include <my92xx.h>
  66. my92xx * _my92xx;
  67. unsigned char _light_channel_map[] {
  68. MY92XX_MAPPING
  69. };
  70. #endif
  71. // UI hint about channel distribution
  72. const char _light_channel_desc[5][5] PROGMEM = {
  73. {'W', 0, 0, 0, 0},
  74. {'W', 'C', 0, 0, 0},
  75. {'R', 'G', 'B', 0, 0},
  76. {'R', 'G', 'B', 'W', 0},
  77. {'R', 'G', 'B', 'W', 'C'}
  78. };
  79. static_assert((LIGHT_CHANNELS * LIGHT_CHANNELS) <= (sizeof(_light_channel_desc)), "Out-of-bounds array access");
  80. // Gamma Correction lookup table (8 bit)
  81. const unsigned char _light_gamma_table[] PROGMEM = {
  82. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  83. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
  84. 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6,
  85. 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 11,
  86. 12, 12, 13, 13, 14, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19,
  87. 19, 20, 20, 21, 22, 22, 23, 23, 24, 25, 25, 26, 26, 27, 28, 28,
  88. 29, 30, 30, 31, 32, 33, 33, 34, 35, 35, 36, 37, 38, 39, 39, 40,
  89. 41, 42, 43, 43, 44, 45, 46, 47, 48, 49, 50, 50, 51, 52, 53, 54,
  90. 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 71,
  91. 72, 73, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84, 86, 87, 88, 89,
  92. 91, 92, 93, 94, 96, 97, 98, 100, 101, 102, 104, 105, 106, 108, 109, 110,
  93. 112, 113, 115, 116, 118, 119, 121, 122, 123, 125, 126, 128, 130, 131, 133, 134,
  94. 136, 137, 139, 140, 142, 144, 145, 147, 149, 150, 152, 154, 155, 157, 159, 160,
  95. 162, 164, 166, 167, 169, 171, 173, 175, 176, 178, 180, 182, 184, 186, 187, 189,
  96. 191, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 217, 219, 221,
  97. 223, 225, 227, 229, 231, 233, 235, 238, 240, 242, 244, 246, 248, 251, 253, 255
  98. };
  99. static_assert(Light::VALUE_MAX <= sizeof(_light_gamma_table), "Out-of-bounds array access");
  100. // -----------------------------------------------------------------------------
  101. // UTILS
  102. // -----------------------------------------------------------------------------
  103. channel_t::channel_t() :
  104. pin(GPIO_NONE),
  105. inverse(false),
  106. state(true),
  107. inputValue(0),
  108. value(0),
  109. target(0),
  110. current(0.0)
  111. {}
  112. channel_t::channel_t(unsigned char pin, bool inverse) :
  113. pin(pin),
  114. inverse(inverse),
  115. state(true),
  116. inputValue(0),
  117. value(0),
  118. target(0),
  119. current(0.0)
  120. {
  121. pinMode(pin, OUTPUT);
  122. }
  123. void _setValue(const unsigned char id, const unsigned int value) {
  124. if (_light_channels[id].value != value) {
  125. _light_channels[id].value = value;
  126. _light_dirty = true;
  127. }
  128. }
  129. void _setInputValue(const unsigned char id, const unsigned int value) {
  130. _light_channels[id].inputValue = value;
  131. }
  132. void _setRGBInputValue(unsigned char red, unsigned char green, unsigned char blue) {
  133. _setInputValue(0, constrain(red, Light::VALUE_MIN, Light::VALUE_MAX));
  134. _setInputValue(1, constrain(green, Light::VALUE_MIN, Light::VALUE_MAX));
  135. _setInputValue(2, constrain(blue, Light::VALUE_MIN, Light::VALUE_MAX));
  136. }
  137. void _setCCTInputValue(unsigned char warm, unsigned char cold) {
  138. _setInputValue(0, constrain(warm, Light::VALUE_MIN, Light::VALUE_MAX));
  139. _setInputValue(1, constrain(cold, Light::VALUE_MIN, Light::VALUE_MAX));
  140. }
  141. void _lightApplyBrightness(size_t channels = lightChannels()) {
  142. double brightness = static_cast<double>(_light_brightness) / static_cast<double>(Light::BRIGHTNESS_MAX);
  143. channels = std::min(channels, lightChannels());
  144. for (unsigned char i=0; i < lightChannels(); i++) {
  145. if (i >= channels) brightness = 1;
  146. _setValue(i, _light_channels[i].inputValue * brightness);
  147. }
  148. }
  149. void _lightApplyBrightnessColor() {
  150. double brightness = static_cast<double>(_light_brightness) / static_cast<double>(Light::BRIGHTNESS_MAX);
  151. // Substract the common part from RGB channels and add it to white channel. So [250,150,50] -> [200,100,0,50]
  152. unsigned char white = std::min(_light_channels[0].inputValue, std::min(_light_channels[1].inputValue, _light_channels[2].inputValue));
  153. for (unsigned int i=0; i < 3; i++) {
  154. _setValue(i, _light_channels[i].inputValue - white);
  155. }
  156. // Split the White Value across 2 White LED Strips.
  157. if (_light_use_cct) {
  158. // This change the range from 153-500 to 0-347 so we get a value between 0 and 1 in the end.
  159. double miredFactor = ((double) _light_mireds - (double) _light_cold_mireds)/((double) _light_warm_mireds - (double) _light_cold_mireds);
  160. // set cold white
  161. _light_channels[3].inputValue = 0;
  162. _setValue(3, lround(((double) 1.0 - miredFactor) * white));
  163. // set warm white
  164. _light_channels[4].inputValue = 0;
  165. _setValue(4, lround(miredFactor * white));
  166. } else {
  167. _light_channels[3].inputValue = 0;
  168. _setValue(3, white);
  169. }
  170. // Scale up to equal input values. So [250,150,50] -> [200,100,0,50] -> [250, 125, 0, 63]
  171. unsigned char max_in = std::max(_light_channels[0].inputValue, std::max(_light_channels[1].inputValue, _light_channels[2].inputValue));
  172. unsigned char max_out = std::max(std::max(_light_channels[0].value, _light_channels[1].value), std::max(_light_channels[2].value, _light_channels[3].value));
  173. unsigned char channelSize = _light_use_cct ? 5 : 4;
  174. if (_light_use_cct) {
  175. max_out = std::max(max_out, _light_channels[4].value);
  176. }
  177. double factor = (max_out > 0) ? (double) (max_in / max_out) : 0;
  178. for (unsigned char i=0; i < channelSize; i++) {
  179. _setValue(i, lround((double) _light_channels[i].value * factor * brightness));
  180. }
  181. // Scale white channel to match brightness
  182. for (unsigned char i=3; i < channelSize; i++) {
  183. _setValue(i, constrain(static_cast<unsigned int>(_light_channels[i].value * LIGHT_WHITE_FACTOR), Light::BRIGHTNESS_MIN, Light::BRIGHTNESS_MAX));
  184. }
  185. // For the rest of channels, don't apply brightness, it is already in the inputValue
  186. // i should be 4 when RGBW and 5 when RGBWW
  187. for (unsigned char i=channelSize; i < _light_channels.size(); i++) {
  188. _setValue(i, _light_channels[i].inputValue);
  189. }
  190. }
  191. String lightDesc(unsigned char id) {
  192. if (id >= _light_channels.size()) return FPSTR(pstr_unknown);
  193. const char tag = pgm_read_byte(&_light_channel_desc[_light_channels.size() - 1][id]);
  194. switch (tag) {
  195. case 'W': return F("WARM WHITE");
  196. case 'C': return F("COLD WHITE");
  197. case 'R': return F("RED");
  198. case 'G': return F("GREEN");
  199. case 'B': return F("BLUE");
  200. default: break;
  201. }
  202. return FPSTR(pstr_unknown);
  203. }
  204. // -----------------------------------------------------------------------------
  205. // Input Values
  206. // -----------------------------------------------------------------------------
  207. void _fromLong(unsigned long value, bool brightness) {
  208. if (brightness) {
  209. _setRGBInputValue((value >> 24) & 0xFF, (value >> 16) & 0xFF, (value >> 8) & 0xFF);
  210. lightBrightness((value & 0xFF) * Light::BRIGHTNESS_MAX / 255);
  211. } else {
  212. _setRGBInputValue((value >> 16) & 0xFF, (value >> 8) & 0xFF, (value) & 0xFF);
  213. }
  214. }
  215. void _fromRGB(const char * rgb) {
  216. // 9 char #........ , 11 char ...,...,...
  217. if (!_light_has_color) return;
  218. if (!rgb || (strlen(rgb) == 0)) return;
  219. // HEX value is always prefixed, like CSS
  220. // values are interpreted like RGB + optional brightness
  221. if (rgb[0] == '#') {
  222. _fromLong(strtoul(rgb + 1, nullptr, 16), strlen(rgb + 1) > 7);
  223. // With comma separated string, assume decimal values
  224. } else {
  225. const auto channels = _light_channels.size();
  226. unsigned char count = 0;
  227. char buf[16] = {0};
  228. strncpy(buf, rgb, sizeof(buf) - 1);
  229. char *tok = strtok(buf, ",");
  230. while (tok != NULL) {
  231. _setInputValue(count, atoi(tok));
  232. if (++count == channels) break;
  233. tok = strtok(NULL, ",");
  234. }
  235. // If less than 3 values received, set the rest to 0
  236. if (count < 2) _setInputValue(1, 0);
  237. if (count < 3) _setInputValue(2, 0);
  238. return;
  239. }
  240. }
  241. // HSV string is expected to be "H,S,V", where:
  242. // 0 <= H <= 360
  243. // 0 <= S <= 100
  244. // 0 <= V <= 100
  245. void _fromHSV(const char * hsv) {
  246. if (!_light_has_color) return;
  247. if (strlen(hsv) == 0) return;
  248. char buf[16] = {0};
  249. strncpy(buf, hsv, sizeof(buf) - 1);
  250. unsigned char count = 0;
  251. unsigned int value[3] = {0};
  252. char * tok = strtok(buf, ",");
  253. while (tok != NULL) {
  254. value[count] = atoi(tok);
  255. if (++count == 3) break;
  256. tok = strtok(NULL, ",");
  257. }
  258. if (count != 3) return;
  259. // HSV to RGB transformation -----------------------------------------------
  260. //INPUT: [0,100,57]
  261. //IS: [145,0,0]
  262. //SHOULD: [255,0,0]
  263. const double h = (value[0] == 360) ? 0 : (double) value[0] / 60.0;
  264. const double f = (h - floor(h));
  265. const double s = (double) value[1] / 100.0;
  266. _light_brightness = lround((double) value[2] * (static_cast<double>(Light::BRIGHTNESS_MAX) / 100.0)); // (default 255/100)
  267. const unsigned char p = lround(Light::VALUE_MAX * (1.0 - s));
  268. const unsigned char q = lround(Light::VALUE_MAX * (1.0 - s * f));
  269. const unsigned char t = lround(Light::VALUE_MAX * (1.0 - s * (1.0 - f)));
  270. switch (int(h)) {
  271. case 0:
  272. _setRGBInputValue(Light::VALUE_MAX, t, p);
  273. break;
  274. case 1:
  275. _setRGBInputValue(q, Light::VALUE_MAX, p);
  276. break;
  277. case 2:
  278. _setRGBInputValue(p, Light::VALUE_MAX, t);
  279. break;
  280. case 3:
  281. _setRGBInputValue(p, q, Light::VALUE_MAX);
  282. break;
  283. case 4:
  284. _setRGBInputValue(t, p, Light::VALUE_MAX);
  285. break;
  286. case 5:
  287. _setRGBInputValue(Light::VALUE_MAX, p, q);
  288. break;
  289. default:
  290. _setRGBInputValue(Light::VALUE_MIN, Light::VALUE_MIN, Light::VALUE_MIN);
  291. break;
  292. }
  293. }
  294. // Thanks to Sacha Telgenhof for sharing this code in his AiLight library
  295. // https://github.com/stelgenhof/AiLight
  296. // Color temperature is measured in mireds (kelvin = 1e6/mired)
  297. long _toKelvin(const long mireds) {
  298. return constrain(static_cast<long>(1000000L / mireds), _light_warm_kelvin, _light_cold_kelvin);
  299. }
  300. long _toMireds(const long kelvin) {
  301. return constrain(static_cast<long>(lround(1000000L / kelvin)), _light_cold_mireds, _light_warm_mireds);
  302. }
  303. void _lightMireds(const long kelvin) {
  304. _light_mireds = _toMireds(kelvin);
  305. }
  306. void _lightMiredsCCT(const long kelvin) {
  307. _lightMireds(kelvin);
  308. // This change the range from 153-500 to 0-347 so we get a value between 0 and 1 in the end.
  309. const double factor = ((double) _light_mireds - (double) _light_cold_mireds)/((double) _light_warm_mireds - (double) _light_cold_mireds);
  310. _setCCTInputValue(
  311. lround(factor * Light::VALUE_MAX),
  312. lround(((double) 1.0 - factor) * Light::VALUE_MAX)
  313. );
  314. }
  315. void _fromKelvin(long kelvin) {
  316. if (!_light_has_color) {
  317. if (!_light_use_cct) return;
  318. _lightMiredsCCT(kelvin);
  319. return;
  320. }
  321. _lightMireds(kelvin);
  322. if (_light_use_cct) {
  323. _setRGBInputValue(Light::VALUE_MAX, Light::VALUE_MAX, Light::VALUE_MAX);
  324. return;
  325. }
  326. // Calculate colors
  327. kelvin /= 100;
  328. const unsigned int red = (kelvin <= 66)
  329. ? Light::VALUE_MAX
  330. : 329.698727446 * fs_pow((double) (kelvin - 60), -0.1332047592);
  331. const unsigned int green = (kelvin <= 66)
  332. ? 99.4708025861 * fs_log(kelvin) - 161.1195681661
  333. : 288.1221695283 * fs_pow((double) kelvin, -0.0755148492);
  334. const unsigned int blue = (kelvin >= 66)
  335. ? Light::VALUE_MAX
  336. : ((kelvin <= 19)
  337. ? 0
  338. : 138.5177312231 * fs_log(kelvin - 10) - 305.0447927307);
  339. _setRGBInputValue(red, green, blue);
  340. }
  341. void _fromMireds(const long mireds) {
  342. _fromKelvin(_toKelvin(mireds));
  343. }
  344. // -----------------------------------------------------------------------------
  345. // Output Values
  346. // -----------------------------------------------------------------------------
  347. void _toRGB(char * rgb, size_t len, bool target = false) {
  348. unsigned long value = 0;
  349. value += target ? _light_channels[0].target : _light_channels[0].inputValue;
  350. value <<= 8;
  351. value += target ? _light_channels[1].target : _light_channels[1].inputValue;
  352. value <<= 8;
  353. value += target ? _light_channels[2].target : _light_channels[2].inputValue;
  354. snprintf_P(rgb, len, PSTR("#%06X"), value);
  355. }
  356. void _toHSV(char * hsv, size_t len) {
  357. double h {0.}, s {0.}, v {0.};
  358. double r {0.}, g {0.}, b {0.};
  359. double min {0.}, max {0.};
  360. r = static_cast<double>(_light_channels[0].target) / Light::VALUE_MAX;
  361. g = static_cast<double>(_light_channels[1].target) / Light::VALUE_MAX;
  362. b = static_cast<double>(_light_channels[2].target) / Light::VALUE_MAX;
  363. min = std::min(r, std::min(g, b));
  364. max = std::max(r, std::max(g, b));
  365. v = 100.0 * max;
  366. if (v == 0) {
  367. h = s = 0;
  368. } else {
  369. s = 100.0 * (max - min) / max;
  370. if (s == 0) {
  371. h = 0;
  372. } else {
  373. if (max == r) {
  374. if (g >= b) {
  375. h = 0.0 + 60.0 * (g - b) / (max - min);
  376. } else {
  377. h = 360.0 + 60.0 * (g - b) / (max - min);
  378. }
  379. } else if (max == g) {
  380. h = 120.0 + 60.0 * (b - r) / (max - min);
  381. } else {
  382. h = 240.0 + 60.0 * (r - g) / (max - min);
  383. }
  384. }
  385. }
  386. // Convert to string. Using lround, since we can't (yet) printf floats
  387. snprintf(hsv, len, "%d,%d,%d",
  388. static_cast<int>(lround(h)),
  389. static_cast<int>(lround(s)),
  390. static_cast<int>(lround(v))
  391. );
  392. }
  393. void _toLong(char * color, size_t len, bool target) {
  394. if (!_light_has_color) return;
  395. snprintf_P(color, len, PSTR("%u,%u,%u"),
  396. (target ? _light_channels[0].target : _light_channels[0].inputValue),
  397. (target ? _light_channels[1].target : _light_channels[1].inputValue),
  398. (target ? _light_channels[2].target : _light_channels[2].inputValue)
  399. );
  400. }
  401. void _toLong(char * color, size_t len) {
  402. _toLong(color, len, false);
  403. }
  404. String _toCSV(bool target) {
  405. const auto channels = lightChannels();
  406. String result;
  407. result.reserve(4 * channels);
  408. for (auto& channel : _light_channels) {
  409. if (result.length()) result += ',';
  410. result += String(target ? channel.target : channel.inputValue);
  411. }
  412. return result;
  413. }
  414. // See cores/esp8266/WMath.cpp::map
  415. // Redefining as local method here to avoid breaking in unexpected ways in inputs like (0, 0, 0, 0, 1)
  416. template <typename T, typename Tin, typename Tout> T _lightMap(T x, Tin in_min, Tin in_max, Tout out_min, Tout out_max) {
  417. auto divisor = (in_max - in_min);
  418. if (divisor == 0){
  419. return -1; //AVR returns -1, SAM returns 0
  420. }
  421. return (x - in_min) * (out_max - out_min) / divisor + out_min;
  422. }
  423. int _lightAdjustValue(const int& value, const String& operation) {
  424. if (!operation.length()) return value;
  425. // if prefixed with a sign, treat expression as numerical operation
  426. // otherwise, use as the new value
  427. int updated = operation.toInt();
  428. if (operation[0] == '+' || operation[0] == '-') {
  429. updated = value + updated;
  430. }
  431. return updated;
  432. }
  433. void _lightAdjustBrightness(const char *payload) {
  434. lightBrightness(_lightAdjustValue(lightBrightness(), payload));
  435. }
  436. void _lightAdjustChannel(unsigned char id, const char *payload) {
  437. lightChannel(id, _lightAdjustValue(lightChannel(id), payload));
  438. }
  439. void _lightAdjustKelvin(const char *payload) {
  440. _fromKelvin(_lightAdjustValue(_toKelvin(_light_mireds), payload));
  441. }
  442. void _lightAdjustMireds(const char *payload) {
  443. _fromMireds(_lightAdjustValue(_light_mireds, payload));
  444. }
  445. // -----------------------------------------------------------------------------
  446. // PROVIDER
  447. // -----------------------------------------------------------------------------
  448. unsigned int _toPWM(unsigned int value, bool gamma, bool inverse) {
  449. value = constrain(value, Light::VALUE_MIN, Light::VALUE_MAX);
  450. if (gamma) value = pgm_read_byte(_light_gamma_table + value);
  451. if (Light::VALUE_MAX != Light::PWM_LIMIT) value = _lightMap(value, Light::VALUE_MIN, Light::VALUE_MAX, Light::PWM_MIN, Light::PWM_LIMIT);
  452. if (inverse) value = LIGHT_LIMIT_PWM - value;
  453. return value;
  454. }
  455. // Returns a PWM value for the given channel ID
  456. unsigned int _toPWM(unsigned char id) {
  457. bool useGamma = _light_use_gamma && _light_has_color && (id < 3);
  458. return _toPWM(_light_channels[id].current, useGamma, _light_channels[id].inverse);
  459. }
  460. void _lightTransition(unsigned long step) {
  461. // Transitions based on current step. If step == 0, then it is the last transition
  462. for (auto& channel : _light_channels) {
  463. if (!step) {
  464. channel.current = channel.target;
  465. } else {
  466. channel.current += (double) (channel.target - channel.current) / (step + 1);
  467. }
  468. }
  469. }
  470. void _lightProviderScheduleUpdate(unsigned long steps);
  471. void _lightProviderUpdate(unsigned long steps) {
  472. if (_light_provider_update) return;
  473. _light_provider_update = true;
  474. _lightTransition(--steps);
  475. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  476. for (unsigned char i=0; i<_light_channels.size(); i++) {
  477. _my92xx->setChannel(_light_channel_map[i], _toPWM(i));
  478. }
  479. _my92xx->setState(true);
  480. _my92xx->update();
  481. #endif
  482. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  483. for (unsigned int i=0; i < _light_channels.size(); i++) {
  484. pwm_set_duty(_toPWM(i), i);
  485. }
  486. pwm_start();
  487. #endif
  488. // This is not the final value, update again
  489. if (steps) _light_transition_ticker.once_ms(LIGHT_TRANSITION_STEP, _lightProviderScheduleUpdate, steps);
  490. _light_provider_update = false;
  491. }
  492. void _lightProviderScheduleUpdate(unsigned long steps) {
  493. schedule_function(std::bind(_lightProviderUpdate, steps));
  494. }
  495. // -----------------------------------------------------------------------------
  496. // PERSISTANCE
  497. // -----------------------------------------------------------------------------
  498. union light_rtcmem_t {
  499. struct {
  500. uint8_t channels[Light::ChannelsMax];
  501. uint8_t brightness;
  502. uint16_t mired;
  503. } __attribute__((packed)) packed;
  504. uint64_t value;
  505. };
  506. void _lightSaveRtcmem() {
  507. if (lightChannels() > Light::ChannelsMax) return;
  508. light_rtcmem_t light;
  509. for (unsigned int i=0; i < lightChannels(); i++) {
  510. light.packed.channels[i] = _light_channels[i].inputValue;
  511. }
  512. light.packed.brightness = _light_brightness;
  513. light.packed.mired = _light_mireds;
  514. Rtcmem->light = light.value;
  515. }
  516. void _lightRestoreRtcmem() {
  517. if (lightChannels() > Light::ChannelsMax) return;
  518. light_rtcmem_t light;
  519. light.value = Rtcmem->light;
  520. for (unsigned int i=0; i < lightChannels(); i++) {
  521. _light_channels[i].inputValue = light.packed.channels[i];
  522. }
  523. _light_brightness = light.packed.brightness;
  524. _light_mireds = light.packed.mired;
  525. }
  526. void _lightSaveSettings() {
  527. for (unsigned char i=0; i < _light_channels.size(); ++i) {
  528. setSetting({"ch", i}, _light_channels[i].inputValue);
  529. }
  530. setSetting("brightness", _light_brightness);
  531. setSetting("mireds", _light_mireds);
  532. saveSettings();
  533. }
  534. void _lightRestoreSettings() {
  535. for (unsigned char i=0; i < _light_channels.size(); ++i) {
  536. _light_channels[i].inputValue = getSetting({"ch", i}, (i == 0) ? Light::VALUE_MAX : 0);
  537. }
  538. _light_brightness = getSetting("brightness", Light::BRIGHTNESS_MAX);
  539. _light_mireds = getSetting("mireds", _light_mireds);
  540. }
  541. // -----------------------------------------------------------------------------
  542. // MQTT
  543. // -----------------------------------------------------------------------------
  544. #if MQTT_SUPPORT
  545. void _lightMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  546. String mqtt_group_color = getSetting("mqttGroupColor");
  547. if (type == MQTT_CONNECT_EVENT) {
  548. mqttSubscribe(MQTT_TOPIC_BRIGHTNESS);
  549. if (_light_has_color) {
  550. mqttSubscribe(MQTT_TOPIC_COLOR_RGB);
  551. mqttSubscribe(MQTT_TOPIC_COLOR_HSV);
  552. mqttSubscribe(MQTT_TOPIC_TRANSITION);
  553. }
  554. if (_light_has_color || _light_use_cct) {
  555. mqttSubscribe(MQTT_TOPIC_MIRED);
  556. mqttSubscribe(MQTT_TOPIC_KELVIN);
  557. }
  558. // Group color
  559. if (mqtt_group_color.length() > 0) mqttSubscribeRaw(mqtt_group_color.c_str());
  560. // Channels
  561. char buffer[strlen(MQTT_TOPIC_CHANNEL) + 3];
  562. snprintf_P(buffer, sizeof(buffer), PSTR("%s/+"), MQTT_TOPIC_CHANNEL);
  563. mqttSubscribe(buffer);
  564. }
  565. if (type == MQTT_MESSAGE_EVENT) {
  566. // Group color
  567. if ((mqtt_group_color.length() > 0) && (mqtt_group_color.equals(topic))) {
  568. lightColor(payload, true);
  569. lightUpdate(true, mqttForward(), false);
  570. return;
  571. }
  572. // Match topic
  573. String t = mqttMagnitude((char *) topic);
  574. // Color temperature in mireds
  575. if (t.equals(MQTT_TOPIC_MIRED)) {
  576. _lightAdjustMireds(payload);
  577. lightUpdate(true, mqttForward());
  578. return;
  579. }
  580. // Color temperature in kelvins
  581. if (t.equals(MQTT_TOPIC_KELVIN)) {
  582. _lightAdjustKelvin(payload);
  583. lightUpdate(true, mqttForward());
  584. return;
  585. }
  586. // Color
  587. if (t.equals(MQTT_TOPIC_COLOR_RGB)) {
  588. lightColor(payload, true);
  589. lightUpdate(true, mqttForward());
  590. return;
  591. }
  592. if (t.equals(MQTT_TOPIC_COLOR_HSV)) {
  593. lightColor(payload, false);
  594. lightUpdate(true, mqttForward());
  595. return;
  596. }
  597. // Brightness
  598. if (t.equals(MQTT_TOPIC_BRIGHTNESS)) {
  599. _lightAdjustBrightness(payload);
  600. lightUpdate(true, mqttForward());
  601. return;
  602. }
  603. // Transitions
  604. if (t.equals(MQTT_TOPIC_TRANSITION)) {
  605. lightTransitionTime(atol(payload));
  606. return;
  607. }
  608. // Channel
  609. if (t.startsWith(MQTT_TOPIC_CHANNEL)) {
  610. unsigned int channelID = t.substring(strlen(MQTT_TOPIC_CHANNEL)+1).toInt();
  611. if (channelID >= _light_channels.size()) {
  612. DEBUG_MSG_P(PSTR("[LIGHT] Wrong channelID (%d)\n"), channelID);
  613. return;
  614. }
  615. _lightAdjustChannel(channelID, payload);
  616. lightUpdate(true, mqttForward());
  617. return;
  618. }
  619. }
  620. }
  621. void lightMQTT() {
  622. char buffer[20];
  623. if (_light_has_color) {
  624. // Color
  625. if (getSetting("useCSS", 1 == LIGHT_USE_CSS)) {
  626. _toRGB(buffer, sizeof(buffer), true);
  627. } else {
  628. _toLong(buffer, sizeof(buffer), true);
  629. }
  630. mqttSend(MQTT_TOPIC_COLOR_RGB, buffer);
  631. _toHSV(buffer, sizeof(buffer));
  632. mqttSend(MQTT_TOPIC_COLOR_HSV, buffer);
  633. }
  634. if (_light_has_color || _light_use_cct) {
  635. // Mireds
  636. snprintf_P(buffer, sizeof(buffer), PSTR("%d"), _light_mireds);
  637. mqttSend(MQTT_TOPIC_MIRED, buffer);
  638. }
  639. // Channels
  640. for (unsigned int i=0; i < _light_channels.size(); i++) {
  641. itoa(_light_channels[i].target, buffer, 10);
  642. mqttSend(MQTT_TOPIC_CHANNEL, i, buffer);
  643. }
  644. // Brightness
  645. snprintf_P(buffer, sizeof(buffer), PSTR("%d"), _light_brightness);
  646. mqttSend(MQTT_TOPIC_BRIGHTNESS, buffer);
  647. }
  648. void lightMQTTGroup() {
  649. const String mqtt_group_color = getSetting("mqttGroupColor");
  650. if (mqtt_group_color.length()) {
  651. mqttSendRaw(mqtt_group_color.c_str(), _toCSV(false).c_str());
  652. }
  653. }
  654. #endif
  655. // -----------------------------------------------------------------------------
  656. // Broker
  657. // -----------------------------------------------------------------------------
  658. #if BROKER_SUPPORT
  659. void lightBroker() {
  660. for (unsigned int id = 0; id < _light_channels.size(); ++id) {
  661. StatusBroker::Publish(MQTT_TOPIC_CHANNEL, id, _light_channels[id].value);
  662. }
  663. }
  664. #endif
  665. // -----------------------------------------------------------------------------
  666. // API
  667. // -----------------------------------------------------------------------------
  668. #if API_SUPPORT
  669. void _lightApiSetup() {
  670. // Note that we expect a fixed number of entries.
  671. // Otherwise, underlying vector will reserve more than we need (likely, *2 of the current size)
  672. apiReserve(
  673. (_light_has_color ? 4u : 0u) + 2u + _light_channels.size()
  674. );
  675. if (_light_has_color) {
  676. apiRegister({
  677. MQTT_TOPIC_COLOR_RGB, Api::Type::Basic, ApiUnusedArg,
  678. [](const Api&, ApiBuffer& buffer) {
  679. if (getSetting("useCSS", 1 == LIGHT_USE_CSS)) {
  680. _toRGB(buffer.data, buffer.size, true);
  681. } else {
  682. _toLong(buffer.data, buffer.size, true);
  683. }
  684. },
  685. [](const Api&, ApiBuffer& buffer) {
  686. lightColor(buffer.data, true);
  687. lightUpdate(true, true);
  688. }
  689. });
  690. apiRegister({
  691. MQTT_TOPIC_COLOR_HSV, Api::Type::Basic, ApiUnusedArg,
  692. [](const Api&, ApiBuffer& buffer) {
  693. _toHSV(buffer.data, buffer.size);
  694. },
  695. [](const Api&, ApiBuffer& buffer) {
  696. lightColor(buffer.data, false);
  697. lightUpdate(true, true);
  698. }
  699. });
  700. apiRegister({
  701. MQTT_TOPIC_MIRED, Api::Type::Basic, ApiUnusedArg,
  702. [](const Api&, ApiBuffer& buffer) {
  703. sprintf(buffer.data, PSTR("%d"), _light_mireds);
  704. },
  705. [](const Api&, ApiBuffer& buffer) {
  706. _lightAdjustMireds(buffer.data);
  707. lightUpdate(true, true);
  708. }
  709. });
  710. apiRegister({
  711. MQTT_TOPIC_KELVIN, Api::Type::Basic, ApiUnusedArg,
  712. [](const Api&, ApiBuffer& buffer) {
  713. sprintf(buffer.data, PSTR("%d"), _toKelvin(_light_mireds));
  714. },
  715. [](const Api&, ApiBuffer& buffer) {
  716. _lightAdjustKelvin(buffer.data);
  717. lightUpdate(true, true);
  718. }
  719. });
  720. }
  721. apiRegister({
  722. MQTT_TOPIC_TRANSITION, Api::Type::Basic, ApiUnusedArg,
  723. [](const Api&, ApiBuffer& buffer) {
  724. snprintf_P(buffer.data, buffer.size, PSTR("%u"), lightTransitionTime());
  725. },
  726. [](const Api&, ApiBuffer& buffer) {
  727. lightTransitionTime(atol(buffer.data));
  728. }
  729. });
  730. apiRegister({
  731. MQTT_TOPIC_BRIGHTNESS, Api::Type::Basic, ApiUnusedArg,
  732. [](const Api&, ApiBuffer& buffer) {
  733. snprintf_P(buffer.data, buffer.size, PSTR("%u"), _light_brightness);
  734. },
  735. [](const Api&, ApiBuffer& buffer) {
  736. _lightAdjustBrightness(buffer.data);
  737. lightUpdate(true, true);
  738. }
  739. });
  740. char path[32] = {0};
  741. for (unsigned char id = 0; id < _light_channels.size(); ++id) {
  742. snprintf_P(path, sizeof(path), PSTR(MQTT_TOPIC_CHANNEL "/%u"), id);
  743. apiRegister({
  744. path, Api::Type::Basic, id,
  745. [](const Api& api, ApiBuffer& buffer) {
  746. snprintf_P(buffer.data, buffer.size, PSTR("%u"), _light_channels[api.arg].target);
  747. },
  748. [](const Api& api, ApiBuffer& buffer) {
  749. _lightAdjustChannel(api.arg, buffer.data);
  750. lightUpdate(true, true);
  751. }
  752. });
  753. }
  754. }
  755. #endif // API_SUPPORT
  756. #if WEB_SUPPORT
  757. bool _lightWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  758. if (strncmp(key, "light", 5) == 0) return true;
  759. if (strncmp(key, "use", 3) == 0) return true;
  760. return false;
  761. }
  762. void _lightWebSocketStatus(JsonObject& root) {
  763. if (_light_has_color) {
  764. if (getSetting("useRGB", 1 == LIGHT_USE_RGB)) {
  765. root["rgb"] = lightColor(true);
  766. } else {
  767. root["hsv"] = lightColor(false);
  768. }
  769. }
  770. if (_light_use_cct) {
  771. JsonObject& mireds = root.createNestedObject("mireds");
  772. mireds["value"] = _light_mireds;
  773. mireds["cold"] = _light_cold_mireds;
  774. mireds["warm"] = _light_warm_mireds;
  775. root["useCCT"] = _light_use_cct;
  776. }
  777. JsonArray& channels = root.createNestedArray("channels");
  778. for (unsigned char id=0; id < _light_channels.size(); id++) {
  779. channels.add(lightChannel(id));
  780. }
  781. root["brightness"] = lightBrightness();
  782. }
  783. void _lightWebSocketOnVisible(JsonObject& root) {
  784. root["colorVisible"] = 1;
  785. }
  786. void _lightWebSocketOnConnected(JsonObject& root) {
  787. root["mqttGroupColor"] = getSetting("mqttGroupColor");
  788. root["useColor"] = _light_has_color;
  789. root["useWhite"] = _light_use_white;
  790. root["useGamma"] = _light_use_gamma;
  791. root["useTransitions"] = _light_use_transitions;
  792. root["useCSS"] = getSetting("useCSS", 1 == LIGHT_USE_CSS);
  793. root["useRGB"] = getSetting("useRGB", 1 == LIGHT_USE_RGB);
  794. root["lightTime"] = _light_transition_time;
  795. _lightWebSocketStatus(root);
  796. }
  797. void _lightWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  798. if (_light_has_color) {
  799. if (strcmp(action, "color") == 0) {
  800. if (data.containsKey("rgb")) {
  801. lightColor(data["rgb"], true);
  802. lightUpdate(true, true);
  803. }
  804. if (data.containsKey("hsv")) {
  805. lightColor(data["hsv"], false);
  806. lightUpdate(true, true);
  807. }
  808. }
  809. }
  810. if (_light_use_cct) {
  811. if (strcmp(action, "mireds") == 0) {
  812. _fromMireds(data["mireds"]);
  813. lightUpdate(true, true);
  814. }
  815. }
  816. if (strcmp(action, "channel") == 0) {
  817. if (data.containsKey("id") && data.containsKey("value")) {
  818. lightChannel(data["id"].as<unsigned char>(), data["value"].as<int>());
  819. lightUpdate(true, true);
  820. }
  821. }
  822. if (strcmp(action, "brightness") == 0) {
  823. if (data.containsKey("value")) {
  824. lightBrightness(data["value"].as<int>());
  825. lightUpdate(true, true);
  826. }
  827. }
  828. }
  829. #endif
  830. #if TERMINAL_SUPPORT
  831. void _lightChannelDebug(unsigned char id) {
  832. DEBUG_MSG_P(PSTR("Channel #%u (%s): %d\n"), id, lightDesc(id).c_str(), lightChannel(id));
  833. }
  834. void _lightInitCommands() {
  835. terminalRegisterCommand(F("BRIGHTNESS"), [](const terminal::CommandContext& ctx) {
  836. if (ctx.argc > 1) {
  837. _lightAdjustBrightness(ctx.argv[1].c_str());
  838. lightUpdate(true, true);
  839. }
  840. DEBUG_MSG_P(PSTR("Brightness: %u\n"), lightBrightness());
  841. terminalOK();
  842. });
  843. terminalRegisterCommand(F("CHANNEL"), [](const terminal::CommandContext& ctx) {
  844. if (!lightChannels()) return;
  845. auto id = -1;
  846. if (ctx.argc > 1) {
  847. id = ctx.argv[1].toInt();
  848. }
  849. if (id < 0 || id >= static_cast<decltype(id)>(lightChannels())) {
  850. for (unsigned char index = 0; index < lightChannels(); ++index) {
  851. _lightChannelDebug(index);
  852. }
  853. return;
  854. }
  855. if (ctx.argc > 2) {
  856. _lightAdjustChannel(id, ctx.argv[2].c_str());
  857. lightUpdate(true, true);
  858. }
  859. _lightChannelDebug(id);
  860. terminalOK();
  861. });
  862. terminalRegisterCommand(F("COLOR"), [](const terminal::CommandContext& ctx) {
  863. if (ctx.argc > 1) {
  864. lightColor(ctx.argv[1].c_str());
  865. lightUpdate(true, true);
  866. }
  867. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  868. terminalOK();
  869. });
  870. terminalRegisterCommand(F("KELVIN"), [](const terminal::CommandContext& ctx) {
  871. if (ctx.argc > 1) {
  872. _lightAdjustKelvin(ctx.argv[1].c_str());
  873. lightUpdate(true, true);
  874. }
  875. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  876. terminalOK();
  877. });
  878. terminalRegisterCommand(F("MIRED"), [](const terminal::CommandContext& ctx) {
  879. if (ctx.argc > 1) {
  880. _lightAdjustMireds(ctx.argv[1].c_str());
  881. lightUpdate(true, true);
  882. }
  883. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  884. terminalOK();
  885. });
  886. }
  887. #endif // TERMINAL_SUPPORT
  888. size_t lightChannels() {
  889. return _light_channels.size();
  890. }
  891. bool lightHasColor() {
  892. return _light_has_color;
  893. }
  894. bool lightUseCCT() {
  895. return _light_use_cct;
  896. }
  897. void _lightComms(unsigned char mask) {
  898. // Report color and brightness to MQTT broker
  899. #if MQTT_SUPPORT
  900. if (mask & Light::COMMS_NORMAL) lightMQTT();
  901. if (mask & Light::COMMS_GROUP) lightMQTTGroup();
  902. #endif
  903. // Report color to WS clients (using current brightness setting)
  904. #if WEB_SUPPORT
  905. wsPost(_lightWebSocketStatus);
  906. #endif
  907. // Report channels to local broker
  908. #if BROKER_SUPPORT
  909. lightBroker();
  910. #endif
  911. }
  912. void lightUpdate(bool save, bool forward, bool group_forward) {
  913. // Calculate values based on inputs and brightness
  914. _light_brightness_func();
  915. // Only update if a channel has changed
  916. if (!_light_dirty) return;
  917. _light_dirty = false;
  918. // Update channels
  919. for (unsigned int i=0; i < _light_channels.size(); i++) {
  920. _light_channels[i].target = _light_state && _light_channels[i].state ? _light_channels[i].value : 0;
  921. //DEBUG_MSG_P("[LIGHT] Channel #%u target value: %u\n", i, _light_channels[i].target);
  922. }
  923. // Channel transition will be handled by the provider function
  924. // User can configure total transition time, step time is a fixed value
  925. const unsigned long steps = _light_use_transitions ? _light_transition_time / LIGHT_TRANSITION_STEP : 1;
  926. _light_transition_ticker.once_ms(LIGHT_TRANSITION_STEP, _lightProviderScheduleUpdate, steps);
  927. // Delay every communication 100ms to avoid jamming
  928. const unsigned char mask =
  929. ((forward) ? Light::COMMS_NORMAL : Light::COMMS_NONE) |
  930. ((group_forward) ? Light::COMMS_GROUP : Light::COMMS_NONE);
  931. _light_comms_ticker.once_ms(LIGHT_COMMS_DELAY, _lightComms, mask);
  932. _lightSaveRtcmem();
  933. #if LIGHT_SAVE_ENABLED
  934. // Delay saving to EEPROM 5 seconds to avoid wearing it out unnecessarily
  935. if (save) _light_save_ticker.once(LIGHT_SAVE_DELAY, _lightSaveSettings);
  936. #endif
  937. };
  938. void lightUpdate(bool save, bool forward) {
  939. lightUpdate(save, forward, true);
  940. }
  941. #if LIGHT_SAVE_ENABLED == 0
  942. void lightSave() {
  943. _lightSaveSettings();
  944. }
  945. #endif
  946. void lightState(unsigned char id, bool state) {
  947. if (id >= _light_channels.size()) return;
  948. if (_light_channels[id].state != state) {
  949. _light_channels[id].state = state;
  950. _light_dirty = true;
  951. }
  952. }
  953. bool lightState(unsigned char id) {
  954. if (id >= _light_channels.size()) return false;
  955. return _light_channels[id].state;
  956. }
  957. void lightState(bool state) {
  958. if (_light_state != state) {
  959. _light_state = state;
  960. _light_dirty = true;
  961. }
  962. }
  963. bool lightState() {
  964. return _light_state;
  965. }
  966. void lightColor(const char * color, bool rgb) {
  967. DEBUG_MSG_P(PSTR("[LIGHT] %s: %s\n"), rgb ? "RGB" : "HSV", color);
  968. if (rgb) {
  969. _fromRGB(color);
  970. } else {
  971. _fromHSV(color);
  972. }
  973. }
  974. void lightColor(const char * color) {
  975. lightColor(color, true);
  976. }
  977. void lightColor(unsigned long color) {
  978. _fromLong(color, false);
  979. }
  980. String lightColor(bool rgb) {
  981. char str[12];
  982. if (rgb) {
  983. _toRGB(str, sizeof(str));
  984. } else {
  985. _toHSV(str, sizeof(str));
  986. }
  987. return String(str);
  988. }
  989. String lightColor() {
  990. return lightColor(true);
  991. }
  992. long lightChannel(unsigned char id) {
  993. if (id >= _light_channels.size()) return 0;
  994. return _light_channels[id].inputValue;
  995. }
  996. void lightChannel(unsigned char id, long value) {
  997. if (id >= _light_channels.size()) return;
  998. _setInputValue(id, constrain(value, Light::VALUE_MIN, Light::VALUE_MAX));
  999. }
  1000. void lightChannelStep(unsigned char id, long steps, long multiplier) {
  1001. lightChannel(id, static_cast<int>(lightChannel(id)) + (steps * multiplier));
  1002. }
  1003. long lightBrightness() {
  1004. return _light_brightness;
  1005. }
  1006. void lightBrightness(long brightness) {
  1007. _light_brightness = constrain(brightness, Light::BRIGHTNESS_MIN, Light::BRIGHTNESS_MAX);
  1008. }
  1009. void lightBrightnessStep(long steps, long multiplier) {
  1010. lightBrightness(static_cast<int>(_light_brightness) + (steps * multiplier));
  1011. }
  1012. unsigned int lightTransitionTime() {
  1013. if (_light_use_transitions) {
  1014. return _light_transition_time;
  1015. } else {
  1016. return 0;
  1017. }
  1018. }
  1019. void lightTransitionTime(unsigned long ms) {
  1020. if (0 == ms) {
  1021. _light_use_transitions = false;
  1022. } else {
  1023. _light_use_transitions = true;
  1024. _light_transition_time = ms;
  1025. }
  1026. setSetting("useTransitions", _light_use_transitions);
  1027. setSetting("lightTime", _light_transition_time);
  1028. saveSettings();
  1029. }
  1030. // -----------------------------------------------------------------------------
  1031. // SETUP
  1032. // -----------------------------------------------------------------------------
  1033. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  1034. const unsigned long _light_iomux[16] PROGMEM = {
  1035. PERIPHS_IO_MUX_GPIO0_U, PERIPHS_IO_MUX_U0TXD_U, PERIPHS_IO_MUX_GPIO2_U, PERIPHS_IO_MUX_U0RXD_U,
  1036. PERIPHS_IO_MUX_GPIO4_U, PERIPHS_IO_MUX_GPIO5_U, PERIPHS_IO_MUX_SD_CLK_U, PERIPHS_IO_MUX_SD_DATA0_U,
  1037. PERIPHS_IO_MUX_SD_DATA1_U, PERIPHS_IO_MUX_SD_DATA2_U, PERIPHS_IO_MUX_SD_DATA3_U, PERIPHS_IO_MUX_SD_CMD_U,
  1038. PERIPHS_IO_MUX_MTDI_U, PERIPHS_IO_MUX_MTCK_U, PERIPHS_IO_MUX_MTMS_U, PERIPHS_IO_MUX_MTDO_U
  1039. };
  1040. const unsigned long _light_iofunc[16] PROGMEM = {
  1041. FUNC_GPIO0, FUNC_GPIO1, FUNC_GPIO2, FUNC_GPIO3,
  1042. FUNC_GPIO4, FUNC_GPIO5, FUNC_GPIO6, FUNC_GPIO7,
  1043. FUNC_GPIO8, FUNC_GPIO9, FUNC_GPIO10, FUNC_GPIO11,
  1044. FUNC_GPIO12, FUNC_GPIO13, FUNC_GPIO14, FUNC_GPIO15
  1045. };
  1046. #endif
  1047. void _lightConfigure() {
  1048. _light_has_color = getSetting("useColor", 1 == LIGHT_USE_COLOR);
  1049. if (_light_has_color && (_light_channels.size() < 3)) {
  1050. _light_has_color = false;
  1051. setSetting("useColor", _light_has_color);
  1052. }
  1053. _light_use_white = getSetting("useWhite", 1 == LIGHT_USE_WHITE);
  1054. if (_light_use_white && (_light_channels.size() < 4) && (_light_channels.size() != 2)) {
  1055. _light_use_white = false;
  1056. setSetting("useWhite", _light_use_white);
  1057. }
  1058. if (_light_has_color) {
  1059. if (_light_use_white) {
  1060. _light_brightness_func = _lightApplyBrightnessColor;
  1061. } else {
  1062. _light_brightness_func = []() { _lightApplyBrightness(3); };
  1063. }
  1064. } else {
  1065. _light_brightness_func = []() { _lightApplyBrightness(); };
  1066. }
  1067. _light_use_cct = getSetting("useCCT", 1 == LIGHT_USE_CCT);
  1068. if (_light_use_cct && (((_light_channels.size() < 5) && (_light_channels.size() != 2)) || !_light_use_white)) {
  1069. _light_use_cct = false;
  1070. setSetting("useCCT", _light_use_cct);
  1071. }
  1072. _light_cold_mireds = getSetting("lightColdMired", LIGHT_COLDWHITE_MIRED);
  1073. _light_warm_mireds = getSetting("lightWarmMired", LIGHT_WARMWHITE_MIRED);
  1074. _light_cold_kelvin = (1000000L / _light_cold_mireds);
  1075. _light_warm_kelvin = (1000000L / _light_warm_mireds);
  1076. _light_use_gamma = getSetting("useGamma", 1 == LIGHT_USE_GAMMA);
  1077. _light_use_transitions = getSetting("useTransitions", 1 == LIGHT_USE_TRANSITIONS);
  1078. _light_transition_time = getSetting("lightTime", LIGHT_TRANSITION_TIME);
  1079. }
  1080. // Dummy channel setup for light providers without real GPIO
  1081. void lightSetupChannels(unsigned char size) {
  1082. size = constrain(size, 0, Light::ChannelsMax);
  1083. if (size == _light_channels.size()) return;
  1084. _light_channels.resize(size);
  1085. }
  1086. void lightSetup() {
  1087. const auto enable_pin = getSetting("ltEnableGPIO", _lightEnablePin());
  1088. if (enable_pin != GPIO_NONE) {
  1089. pinMode(enable_pin, OUTPUT);
  1090. digitalWrite(enable_pin, HIGH);
  1091. }
  1092. _light_channels.reserve(Light::ChannelsMax);
  1093. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  1094. _my92xx = new my92xx(MY92XX_MODEL, MY92XX_CHIPS, MY92XX_DI_PIN, MY92XX_DCKI_PIN, MY92XX_COMMAND);
  1095. lightSetupChannels(LIGHT_CHANNELS);
  1096. #endif
  1097. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  1098. // Initial duty value (will be passed to pwm_set_duty(...), OFF in this case)
  1099. uint32_t pwm_duty_init[Light::ChannelsMax] = {0};
  1100. // 3-tuples of MUX_REGISTER, MUX_VALUE and GPIO number
  1101. uint32_t io_info[Light::ChannelsMax][3];
  1102. for (unsigned char index = 0; index < Light::ChannelsMax; ++index) {
  1103. // Load up until first GPIO_NONE. Allow settings to override, but not remove values
  1104. const auto pin = getSetting({"ltDimmerGPIO", index}, _lightChannelPin(index));
  1105. if (!gpioValid(pin)) {
  1106. break;
  1107. }
  1108. _light_channels.emplace_back(pin, getSetting({"ltDimmerInv", index}, _lightInverse(index)));
  1109. io_info[index][0] = pgm_read_dword(&_light_iomux[pin]);
  1110. io_info[index][1] = pgm_read_dword(&_light_iofunc[pin]);
  1111. io_info[index][2] = pin;
  1112. pinMode(pin, OUTPUT);
  1113. }
  1114. // with 0 channels this should not do anything at all and provider will never call pwm_set_duty(...)
  1115. pwm_init(Light::PWM_MAX, pwm_duty_init, _light_channels.size(), io_info);
  1116. pwm_start();
  1117. #endif
  1118. #if LIGHT_PROVIDER == LIGHT_PROVIDER_TUYA
  1119. Tuya::tuyaSetupLight();
  1120. #endif
  1121. DEBUG_MSG_P(PSTR("[LIGHT] LIGHT_PROVIDER = %d\n"), LIGHT_PROVIDER);
  1122. DEBUG_MSG_P(PSTR("[LIGHT] Number of channels: %d\n"), _light_channels.size());
  1123. _lightConfigure();
  1124. if (rtcmemStatus()) {
  1125. _lightRestoreRtcmem();
  1126. } else {
  1127. _lightRestoreSettings();
  1128. }
  1129. lightUpdate(false, false);
  1130. #if WEB_SUPPORT
  1131. wsRegister()
  1132. .onVisible(_lightWebSocketOnVisible)
  1133. .onConnected(_lightWebSocketOnConnected)
  1134. .onAction(_lightWebSocketOnAction)
  1135. .onKeyCheck(_lightWebSocketOnKeyCheck);
  1136. #endif
  1137. #if API_SUPPORT
  1138. _lightApiSetup();
  1139. #endif
  1140. #if MQTT_SUPPORT
  1141. mqttRegister(_lightMQTTCallback);
  1142. #endif
  1143. #if TERMINAL_SUPPORT
  1144. _lightInitCommands();
  1145. #endif
  1146. // Main callbacks
  1147. espurnaRegisterReload([]() {
  1148. #if LIGHT_SAVE_ENABLED == 0
  1149. lightSave();
  1150. #endif
  1151. _lightConfigure();
  1152. });
  1153. }
  1154. #endif // LIGHT_PROVIDER != LIGHT_PROVIDER_NONE