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.

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