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.

493 lines
17 KiB

  1. /*
  2. GARLAND MODULE
  3. Copyright (C) 2020 by Dmitry Blinov <dblinov76 at gmail dot com>
  4. Inspired by https://github.com/Vasil-Pahomov/ArWs2812 (currently https://github.com/Vasil-Pahomov/Liana)
  5. Tested on 300 led strip.
  6. The most time consuming operation is actually showing leds by Adafruit Neopixel. It take about 1870 mcs.
  7. More long strip can take more time to show.
  8. Currently animation calculation, brightness calculation/transition and showing makes in one loop cycle.
  9. Debug output shows timings. Overal timing should be not more that 3000 ms.
  10. */
  11. #include "garland.h"
  12. #if GARLAND_SUPPORT
  13. #include <Adafruit_NeoPixel.h>
  14. #include <vector>
  15. #include "garland/color.h"
  16. #include "garland/palette.h"
  17. #include "garland/scene.h"
  18. #include "ws.h"
  19. const char* NAME_GARLAND_ENABLED = "garlandEnabled";
  20. const char* NAME_GARLAND_BRIGHTNESS = "garlandBrightness";
  21. const char* NAME_GARLAND_SPEED = "garlandSpeed";
  22. const char* NAME_GARLAND_SWITCH = "garland_switch";
  23. const char* NAME_GARLAND_SET_BRIGHTNESS = "garland_set_brightness";
  24. const char* NAME_GARLAND_SET_SPEED = "garland_set_speed";
  25. const char* NAME_GARLAND_SET_DEFAULT = "garland_set_default";
  26. #define EFFECT_UPDATE_INTERVAL_MIN 7000 // 5 sec
  27. #define EFFECT_UPDATE_INTERVAL_MAX 12000 // 10 sec
  28. #define NUMLEDS_CAN_CAUSE_WDT_RESET 100
  29. bool _garland_enabled = true;
  30. unsigned long _last_update = 0;
  31. unsigned long _interval_effect_update;
  32. // Palette should
  33. Palette pals[] = {
  34. // palettes below are taken from http://www.color-hex.com/color-palettes/ (and modified)
  35. // RGB: Red,Green,Blue sequence
  36. Palette("RGB", {0xFF0000, 0x00FF00, 0x0000FF}),
  37. // Rainbow: Rainbow colors
  38. Palette("Rainbow", {0xFF0000, 0xAB5500, 0xABAB00, 0x00FF00, 0x00AB55, 0x0000FF, 0x5500AB, 0xAB0055}),
  39. // RainbowStripe: Rainbow colors with alternating stripes of black
  40. Palette("Stripe", {0xFF0000, 0x000000, 0xAB5500, 0x000000, 0xABAB00, 0x000000, 0x00FF00, 0x000000,
  41. 0x00AB55, 0x000000, 0x0000FF, 0x000000, 0x5500AB, 0x000000, 0xAB0055, 0x000000}),
  42. // Party: Blue purple ping red orange yellow (and back). Basically, everything but the greens.
  43. // This palette is good for lighting at a club or party.
  44. Palette("Party", {0x5500AB, 0x84007C, 0xB5004B, 0xE5001B, 0xE81700, 0xB84700, 0xAB7700, 0xABAB00,
  45. 0xAB5500, 0xDD2200, 0xF2000E, 0xC2003E, 0x8F0071, 0x5F00A1, 0x2F00D0, 0x0007F9}),
  46. // Heat: Approximate "black body radiation" palette, akin to the FastLED 'HeatColor' function.
  47. // Recommend that you use values 0-240 rather than the usual 0-255, as the last 15 colors will be
  48. // 'wrapping around' from the hot end to the cold end, which looks wrong.
  49. Palette("Heat", {0x700070, 0xFF0000, 0xFFFF00, 0xFFFFCC}),
  50. // Fire:
  51. Palette("Fire", {0x000000, 0x220000, 0x880000, 0xFF0000, 0xFF6600, 0xFFCC00}),
  52. // Blue:
  53. Palette("Blue", {0xffffff, 0x0000ff, 0x00ffff}),
  54. // Sun: Slice Of The Sun
  55. Palette("Sun", {0xfff95b, 0xffe048, 0xffc635, 0xffad22, 0xff930f}),
  56. // Lime: yellow green mix
  57. Palette("Lime", {0x51f000, 0x6fff00, 0x96ff00, 0xc9ff00, 0xf0ff00}),
  58. // Pastel: Pastel Fruity Mixture
  59. Palette("Pastel", {0x75aa68, 0x5960ae, 0xe4be6c, 0xca5959, 0x8366ac})};
  60. constexpr size_t palsSize() { return sizeof(pals)/sizeof(pals[0]); }
  61. Adafruit_NeoPixel pixels = Adafruit_NeoPixel(GARLAND_LEDS, GARLAND_D_PIN, NEO_GRB + NEO_KHZ800);
  62. Scene scene(&pixels);
  63. Anim* anims[] = {new AnimStart(), new AnimPixieDust(), new AnimSparkr(), new AnimRun(), new AnimStars(), new AnimSpread(),
  64. new AnimRandCyc(), new AnimFly(), new AnimComets(), new AnimAssemble(), new AnimDolphins(), new AnimSalut()};
  65. constexpr size_t animsSize() { return sizeof(anims)/sizeof(anims[0]); }
  66. //------------------------------------------------------------------------------
  67. void garlandDisable() {
  68. pixels.clear();
  69. }
  70. //------------------------------------------------------------------------------
  71. void garlandEnabled(bool enabled) {
  72. _garland_enabled = enabled;
  73. }
  74. //------------------------------------------------------------------------------
  75. bool garlandEnabled() {
  76. return _garland_enabled;
  77. }
  78. //------------------------------------------------------------------------------
  79. // Setup
  80. //------------------------------------------------------------------------------
  81. void _garlandConfigure() {
  82. _garland_enabled = getSetting(NAME_GARLAND_ENABLED, true);
  83. DEBUG_MSG_P(PSTR("[GARLAND] _garland_enabled = %d\n"), _garland_enabled);
  84. byte brightness = getSetting(NAME_GARLAND_BRIGHTNESS, 255);
  85. scene.setBrightness(brightness);
  86. DEBUG_MSG_P(PSTR("[GARLAND] brightness = %d\n"), brightness);
  87. float speed = getSetting(NAME_GARLAND_SPEED, 50);
  88. scene.setSpeed(speed);
  89. }
  90. //------------------------------------------------------------------------------
  91. void _garlandReload() {
  92. _garlandConfigure();
  93. }
  94. #if WEB_SUPPORT
  95. //------------------------------------------------------------------------------
  96. void _garlandWebSocketOnConnected(JsonObject& root) {
  97. root[NAME_GARLAND_ENABLED] = garlandEnabled();
  98. root[NAME_GARLAND_BRIGHTNESS] = scene.getBrightness();
  99. root[NAME_GARLAND_SPEED] = scene.getSpeed();
  100. root["garlandVisible"] = 1;
  101. }
  102. //------------------------------------------------------------------------------
  103. bool _garlandWebSocketOnKeyCheck(const char* key, JsonVariant& value) {
  104. if (strncmp(key, NAME_GARLAND_ENABLED, strlen(NAME_GARLAND_ENABLED)) == 0) return true;
  105. if (strncmp(key, NAME_GARLAND_BRIGHTNESS, strlen(NAME_GARLAND_BRIGHTNESS)) == 0) return true;
  106. if (strncmp(key, NAME_GARLAND_SPEED, strlen(NAME_GARLAND_SPEED)) == 0) return true;
  107. return false;
  108. }
  109. //------------------------------------------------------------------------------
  110. void _garlandWebSocketOnAction(uint32_t client_id, const char* action, JsonObject& data) {
  111. if (strcmp(action, NAME_GARLAND_SWITCH) == 0) {
  112. if (data.containsKey("status") && data.is<int>("status")) {
  113. _garland_enabled = (1 == data["status"].as<int>());
  114. setSetting(NAME_GARLAND_ENABLED, _garland_enabled);
  115. if (!_garland_enabled) {
  116. schedule_function([](){
  117. pixels.clear();
  118. pixels.show();
  119. });
  120. }
  121. }
  122. }
  123. if (strcmp(action, NAME_GARLAND_SET_BRIGHTNESS) == 0) {
  124. if (data.containsKey("brightness")) {
  125. byte new_brightness = data.get<byte>("brightness");
  126. DEBUG_MSG_P(PSTR("[GARLAND] new brightness = %d\n"), new_brightness);
  127. setSetting(NAME_GARLAND_BRIGHTNESS, new_brightness);
  128. scene.setBrightness(new_brightness);
  129. }
  130. }
  131. if (strcmp(action, NAME_GARLAND_SET_SPEED) == 0) {
  132. if (data.containsKey("speed")) {
  133. byte new_speed = data.get<byte>("speed");
  134. DEBUG_MSG_P(PSTR("[GARLAND] new speed = %d\n"), new_speed);
  135. setSetting(NAME_GARLAND_SPEED, new_speed);
  136. scene.setSpeed(new_speed);
  137. }
  138. }
  139. if (strcmp(action, NAME_GARLAND_SET_DEFAULT) == 0) {
  140. scene.setDefault();
  141. byte brightness = scene.getBrightness();
  142. setSetting(NAME_GARLAND_BRIGHTNESS, brightness);
  143. byte speed = scene.getSpeed();
  144. setSetting(NAME_GARLAND_SPEED, speed);
  145. char buffer[128];
  146. snprintf_P(buffer, sizeof(buffer), PSTR("{\"garlandBrightness\": %d, \"garlandSpeed\": %d}"), brightness, speed);
  147. wsSend(buffer);
  148. }
  149. }
  150. #endif
  151. //------------------------------------------------------------------------------
  152. // Loop
  153. //------------------------------------------------------------------------------
  154. void garlandLoop(void) {
  155. if (!garlandEnabled())
  156. return;
  157. scene.run();
  158. unsigned long animation_time = millis() - _last_update;
  159. if (animation_time > _interval_effect_update && scene.finishedAnimCycle()) {
  160. _last_update = millis();
  161. _interval_effect_update = secureRandom(EFFECT_UPDATE_INTERVAL_MIN, EFFECT_UPDATE_INTERVAL_MAX);
  162. static int animInd = 0;
  163. int prevAnimInd = animInd;
  164. while (prevAnimInd == animInd) animInd = secureRandom(1, animsSize());
  165. static int paletteInd = 0;
  166. int prevPalInd = paletteInd;
  167. while (prevPalInd == paletteInd) paletteInd = secureRandom(palsSize());
  168. int numShows = scene.getNumShows();
  169. int frameRate = animation_time > 0 ? numShows * 1000 / animation_time : 0;
  170. DEBUG_MSG_P(PSTR("[GARLAND] Anim: %-10s Pal: %-8s timings: calc: %4d pixl: %3d show: %4d frate: %d\n"),
  171. anims[prevAnimInd]->name(), pals[prevPalInd].name(),
  172. scene.getAvgCalcTime(), scene.getAvgPixlTime(), scene.getAvgShowTime(), frameRate);
  173. DEBUG_MSG_P(PSTR("[GARLAND] Anim: %-10s Pal: %-8s Inter: %d\n"),
  174. anims[animInd]->name(), pals[paletteInd].name(), _interval_effect_update);
  175. scene.setAnim(anims[animInd]);
  176. scene.setPalette(&pals[paletteInd]);
  177. scene.setup();
  178. }
  179. }
  180. //------------------------------------------------------------------------------
  181. void garlandSetup() {
  182. _garlandConfigure();
  183. // Websockets
  184. #if WEB_SUPPORT
  185. wsRegister()
  186. .onConnected(_garlandWebSocketOnConnected)
  187. .onKeyCheck(_garlandWebSocketOnKeyCheck)
  188. .onAction(_garlandWebSocketOnAction);
  189. #endif
  190. espurnaRegisterLoop(garlandLoop);
  191. espurnaRegisterReload(_garlandReload);
  192. pixels.begin();
  193. scene.setAnim(anims[0]);
  194. scene.setPalette(&pals[0]);
  195. scene.setup();
  196. _interval_effect_update = secureRandom(EFFECT_UPDATE_INTERVAL_MIN, EFFECT_UPDATE_INTERVAL_MAX);
  197. }
  198. /*#######################################################################
  199. _____
  200. / ____|
  201. | (___ ___ ___ _ __ ___
  202. \___ \ / __| / _ \ | '_ \ / _ \
  203. ____) | | (__ | __/ | | | | | __/
  204. |_____/ \___| \___| |_| |_| \___|
  205. #######################################################################*/
  206. #define GARLAND_SCENE_TRANSITION_MS 1000 // transition time between animations, ms
  207. #define GARLAND_SCENE_SPEED_MAX 70
  208. #define GARLAND_SCENE_SPEED_FACTOR 10
  209. #define GARLAND_SCENE_DEFAULT_SPEED 50
  210. #define GARLAND_SCENE_DEFAULT_BRIGHTNESS 255
  211. Scene::Scene(Adafruit_NeoPixel* pixels)
  212. : _pixels(pixels),
  213. _numLeds(pixels->numPixels()),
  214. _leds1(_numLeds),
  215. _leds2(_numLeds),
  216. _ledstmp(_numLeds),
  217. _seq(_numLeds) {
  218. }
  219. void Scene::setPalette(Palette* palette) {
  220. _palette = palette;
  221. if (setUpOnPalChange) {
  222. setupImpl();
  223. }
  224. }
  225. void Scene::setBrightness(byte brightness) {
  226. DEBUG_MSG_P(PSTR("[GARLAND] Scene::setBrightness = %d\n"), brightness);
  227. this->brightness = brightness;
  228. }
  229. byte Scene::getBrightness() {
  230. DEBUG_MSG_P(PSTR("[GARLAND] Scene::getBrightness = %d\n"), brightness);
  231. return brightness;
  232. }
  233. // Speed is reverse to cycleFactor and 10x
  234. void Scene::setSpeed(byte speed) {
  235. this->speed = speed;
  236. cycleFactor = (float)(GARLAND_SCENE_SPEED_MAX - speed) / GARLAND_SCENE_SPEED_FACTOR;
  237. DEBUG_MSG_P(PSTR("[GARLAND] Scene::setSpeed %d cycleFactor = %d\n"), speed, (int)(cycleFactor * 1000));
  238. }
  239. byte Scene::getSpeed() {
  240. DEBUG_MSG_P(PSTR("[GARLAND] Scene::getSpeed %d cycleFactor = %d\n"), speed, (int)(cycleFactor * 1000));
  241. return speed;
  242. }
  243. void Scene::setDefault() {
  244. speed = GARLAND_SCENE_DEFAULT_SPEED;
  245. cycleFactor = (float)(GARLAND_SCENE_SPEED_MAX - speed) / GARLAND_SCENE_SPEED_FACTOR;
  246. brightness = GARLAND_SCENE_DEFAULT_BRIGHTNESS;
  247. DEBUG_MSG_P(PSTR("[GARLAND] Scene::setDefault speed = %d cycleFactor = %d brightness = %d\n"), speed, (int)(cycleFactor * 1000), brightness);
  248. }
  249. void Scene::run() {
  250. unsigned long iteration_start_time = micros();
  251. if (state == Calculate || cyclesRemain < 1) {
  252. // Calculate number of cycles for this animation iteration
  253. float cycleSum = cycleFactor * (_anim ? _anim->getCycleFactor() : 1.0) + cycleTail;
  254. cyclesRemain = cycleSum;
  255. if (cyclesRemain < 1) {
  256. cyclesRemain = 1;
  257. cycleSum = 0;
  258. cycleTail = 0;
  259. } else {
  260. cycleTail = cycleSum - cyclesRemain;
  261. }
  262. if (_anim) {
  263. _anim->Run();
  264. }
  265. sum_calc_time += (micros() - iteration_start_time);
  266. iteration_start_time = micros();
  267. ++calc_num;
  268. state = Transition;
  269. }
  270. if (state == Transition && cyclesRemain < 3) {
  271. // transition coef, if within 0..1 - transition is active
  272. // changes from 1 to 0 during transition, so we interpolate from current
  273. // color to previous
  274. float transc = (float)((long)transms - (long)millis()) / GARLAND_SCENE_TRANSITION_MS;
  275. Color* leds_prev = (_leds == &_leds1[0]) ? &_leds2[0] : &_leds1[0];
  276. if (transc > 0) {
  277. for (int i = 0; i < _numLeds; i++) {
  278. // transition is in progress
  279. Color c = _leds[i].interpolate(leds_prev[i], transc);
  280. byte r = (int)(bri_lvl[c.r]) * brightness / 256;
  281. byte g = (int)(bri_lvl[c.g]) * brightness / 256;
  282. byte b = (int)(bri_lvl[c.b]) * brightness / 256;
  283. _pixels->setPixelColor(i, _pixels->Color(r, g, b));
  284. }
  285. } else {
  286. for (int i = 0; i < _numLeds; i++) {
  287. // regular operation
  288. byte r = (int)(bri_lvl[_leds[i].r]) * brightness / 256;
  289. byte g = (int)(bri_lvl[_leds[i].g]) * brightness / 256;
  290. byte b = (int)(bri_lvl[_leds[i].b]) * brightness / 256;
  291. _pixels->setPixelColor(i, _pixels->Color(r, g, b));
  292. }
  293. }
  294. sum_pixl_time += (micros() - iteration_start_time);
  295. iteration_start_time = micros();
  296. ++pixl_num;
  297. state = Show;
  298. }
  299. if (state == Show && cyclesRemain < 2) {
  300. /* Showing pixels (actually transmitting their RGB data) is most time consuming operation in the
  301. garland workflow. Using 800 kHz gives 1.25 μs per bit. -> 30 μs (0.03 ms) per RGB LED.
  302. So for example 3 ms for 100 LEDs. Unfortunately it can't be postponed and resumed later as it
  303. will lead to reseting the transmition operation. From other hand, long operation can cause
  304. Soft WDT reset. To avoid wdt reset we need to switch soft wdt off for long strips.
  305. It is not best practice, but assuming that it is only garland, it can be acceptable.
  306. Tested up to 300 leds. */
  307. if (_numLeds > NUMLEDS_CAN_CAUSE_WDT_RESET) {
  308. ESP.wdtDisable();
  309. }
  310. _pixels->show();
  311. if (_numLeds > NUMLEDS_CAN_CAUSE_WDT_RESET) {
  312. ESP.wdtEnable(5000);
  313. }
  314. sum_show_time += (micros() - iteration_start_time);
  315. ++show_num;
  316. state = Calculate;
  317. ++numShows;
  318. }
  319. --cyclesRemain;
  320. }
  321. void Scene::setupImpl() {
  322. transms = millis() + GARLAND_SCENE_TRANSITION_MS;
  323. // switch operation buffers (for transition to operate)
  324. if (_leds == &_leds1[0]) {
  325. _leds = &_leds2[0];
  326. } else {
  327. _leds = &_leds1[0];
  328. }
  329. if (_anim) {
  330. _anim->Setup(_palette, _numLeds, _leds, &_ledstmp[0], &_seq[0]);
  331. }
  332. }
  333. void Scene::setup() {
  334. sum_calc_time = 0;
  335. sum_pixl_time = 0;
  336. sum_show_time = 0;
  337. calc_num = 0;
  338. pixl_num = 0;
  339. show_num = 0;
  340. numShows = 0;
  341. if (!setUpOnPalChange) {
  342. setupImpl();
  343. }
  344. }
  345. unsigned long Scene::getAvgCalcTime() { return sum_calc_time / calc_num; }
  346. unsigned long Scene::getAvgPixlTime() { return sum_pixl_time / pixl_num; }
  347. unsigned long Scene::getAvgShowTime() { return sum_show_time / show_num; }
  348. /*#######################################################################
  349. _ _ _
  350. /\ (_) | | (_)
  351. / \ _ __ _ _ __ ___ __ _ | |_ _ ___ _ __
  352. / /\ \ | '_ \ | | | '_ ` _ \ / _` | | __| | | / _ \ | '_ \
  353. / ____ \ | | | | | | | | | | | | | (_| | | |_ | | | (_) | | | | |
  354. /_/ \_\ |_| |_| |_| |_| |_| |_| \__,_| \__| |_| \___/ |_| |_|
  355. #######################################################################*/
  356. Anim::Anim(const char* name) : _name(name) {}
  357. void Anim::Setup(Palette* palette, uint16_t numLeds, Color* leds, Color* ledstmp, byte* seq) {
  358. this->palette = palette;
  359. this->numLeds = numLeds;
  360. this->leds = leds;
  361. this->ledstmp = ledstmp;
  362. this->seq = seq;
  363. SetupImpl();
  364. }
  365. void Anim::initSeq() {
  366. for (int i = 0; i < numLeds; ++i)
  367. seq[i] = i;
  368. }
  369. void Anim::shuffleSeq() {
  370. for (int i = 0; i < numLeds; ++i) {
  371. byte ind = (unsigned int)(rngb() * numLeds / 256);
  372. if (ind != i) {
  373. std::swap(seq[ind], seq[i]);
  374. }
  375. }
  376. }
  377. void Anim::glowSetUp() {
  378. braPhaseSpd = secureRandom(4, 13);
  379. if (braPhaseSpd > 8) {
  380. braPhaseSpd = braPhaseSpd - 17;
  381. }
  382. braFreq = secureRandom(20, 60);
  383. }
  384. void Anim::glowForEachLed(int i) {
  385. int8 bra = braPhase + i * braFreq;
  386. bra = BRA_OFFSET + (abs(bra) >> BRA_AMP_SHIFT);
  387. leds[i] = leds[i].brightness(bra);
  388. }
  389. void Anim::glowRun() { braPhase += braPhaseSpd; }
  390. bool operator== (const Color &c1, const Color &c2)
  391. {
  392. return (c1.r == c2.r && c1.g == c2.g && c1.b == c2.b);
  393. }
  394. unsigned int rng() {
  395. static unsigned int y = 0;
  396. y += micros(); // seeded with changing number
  397. y ^= y << 2;
  398. y ^= y >> 7;
  399. y ^= y << 7;
  400. return (y);
  401. }
  402. // Ranom numbers generator in byte range (256) much faster than secureRandom.
  403. // For usage in time-critical places.
  404. byte rngb() { return (byte)rng(); }
  405. #endif // GARLAND_SUPPORT