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.

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