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.

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