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.

718 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()};
  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) newAnim = anims[secureRandom(START_ANIMATION + 1, animsSize())];
  328. Palette* newPalette = _currentPalette;
  329. while (newPalette == _currentPalette)
  330. newPalette = &pals[secureRandom(palsSize())];
  331. unsigned long newAnimDuration = secureRandom(EFFECT_UPDATE_INTERVAL_MIN, EFFECT_UPDATE_INTERVAL_MAX);
  332. setupScene(newAnim, newPalette, newAnimDuration);
  333. }
  334. }
  335. }
  336. //------------------------------------------------------------------------------
  337. void garlandMqttCallback(unsigned int type, const char * topic, const char * payload) {
  338. if (type == MQTT_CONNECT_EVENT) {
  339. mqttSubscribe(MQTT_TOPIC_GARLAND);
  340. }
  341. if (type == MQTT_MESSAGE_EVENT) {
  342. // Match topic
  343. String t = mqttMagnitude((char*)topic);
  344. if (t.equals(MQTT_TOPIC_GARLAND)) {
  345. // Parse JSON input
  346. DynamicJsonBuffer jsonBuffer;
  347. JsonObject& root = jsonBuffer.parseObject(payload);
  348. if (!root.success()) {
  349. DEBUG_MSG_P(PSTR("[GARLAND] Error parsing mqtt data\n"));
  350. return;
  351. }
  352. String command = MQTT_COMMAND_IMMEDIATE;
  353. if (root.containsKey(MQTT_PAYLOAD_COMMAND)) {
  354. command = root[MQTT_PAYLOAD_COMMAND].as<String>();
  355. }
  356. if (command == MQTT_COMMAND_IMMEDIATE) {
  357. _immediate_command = payload;
  358. } else if (command == MQTT_COMMAND_RESET) {
  359. std::queue<String> empty_queue;
  360. std::swap(_command_queue, empty_queue);
  361. std::vector<String> empty_sequence;
  362. std::swap(_command_sequence, empty_sequence);
  363. _immediate_command.clear();
  364. _currentDuration = 0;
  365. setDefault();
  366. garlandEnabled(true);
  367. } else if (command == MQTT_COMMAND_QUEUE) {
  368. _command_queue.push(payload);
  369. } else if (command == MQTT_COMMAND_SEQUENCE) {
  370. _command_sequence.push_back(payload);
  371. }
  372. }
  373. }
  374. }
  375. //------------------------------------------------------------------------------
  376. void garlandSetup() {
  377. _garlandConfigure();
  378. mqttRegister(garlandMqttCallback);
  379. // Websockets
  380. #if WEB_SUPPORT
  381. wsRegister()
  382. .onConnected(_garlandWebSocketOnConnected)
  383. .onKeyCheck(_garlandWebSocketOnKeyCheck)
  384. .onAction(_garlandWebSocketOnAction);
  385. #endif
  386. espurnaRegisterLoop(garlandLoop);
  387. espurnaRegisterReload(_garlandReload);
  388. pixels.begin();
  389. scene.setAnim(_currentAnim);
  390. scene.setPalette(_currentPalette);
  391. scene.setup();
  392. _currentDuration = secureRandom(EFFECT_UPDATE_INTERVAL_MIN, EFFECT_UPDATE_INTERVAL_MAX);
  393. }
  394. /*#######################################################################
  395. _____
  396. / ____|
  397. | (___ ___ ___ _ __ ___
  398. \___ \ / __| / _ \ | '_ \ / _ \
  399. ____) | | (__ | __/ | | | | | __/
  400. |_____/ \___| \___| |_| |_| \___|
  401. #######################################################################*/
  402. #define GARLAND_SCENE_TRANSITION_MS 1000 // transition time between animations, ms
  403. #define GARLAND_SCENE_SPEED_MAX 70
  404. #define GARLAND_SCENE_SPEED_FACTOR 10
  405. #define GARLAND_SCENE_DEFAULT_SPEED 50
  406. #define GARLAND_SCENE_DEFAULT_BRIGHTNESS 255
  407. Scene::Scene(Adafruit_NeoPixel* pixels)
  408. : _pixels(pixels),
  409. _numLeds(pixels->numPixels()),
  410. _leds1(_numLeds),
  411. _leds2(_numLeds),
  412. _ledstmp(_numLeds),
  413. _seq(_numLeds) {
  414. }
  415. void Scene::setPalette(Palette* palette) {
  416. _palette = palette;
  417. if (setUpOnPalChange) {
  418. setupImpl();
  419. }
  420. }
  421. void Scene::setBrightness(byte brightness) {
  422. DEBUG_MSG_P(PSTR("[GARLAND] Scene::setBrightness = %d\n"), brightness);
  423. this->brightness = brightness;
  424. }
  425. byte Scene::getBrightness() {
  426. DEBUG_MSG_P(PSTR("[GARLAND] Scene::getBrightness = %d\n"), brightness);
  427. return brightness;
  428. }
  429. // Speed is reverse to cycleFactor and 10x
  430. void Scene::setSpeed(byte speed) {
  431. this->speed = speed;
  432. cycleFactor = (float)(GARLAND_SCENE_SPEED_MAX - speed) / GARLAND_SCENE_SPEED_FACTOR;
  433. DEBUG_MSG_P(PSTR("[GARLAND] Scene::setSpeed %d cycleFactor = %d\n"), speed, (int)(cycleFactor * 1000));
  434. }
  435. byte Scene::getSpeed() {
  436. DEBUG_MSG_P(PSTR("[GARLAND] Scene::getSpeed %d cycleFactor = %d\n"), speed, (int)(cycleFactor * 1000));
  437. return speed;
  438. }
  439. void Scene::setDefault() {
  440. speed = GARLAND_SCENE_DEFAULT_SPEED;
  441. cycleFactor = (float)(GARLAND_SCENE_SPEED_MAX - speed) / GARLAND_SCENE_SPEED_FACTOR;
  442. brightness = GARLAND_SCENE_DEFAULT_BRIGHTNESS;
  443. DEBUG_MSG_P(PSTR("[GARLAND] Scene::setDefault speed = %d cycleFactor = %d brightness = %d\n"), speed, (int)(cycleFactor * 1000), brightness);
  444. }
  445. void Scene::run() {
  446. unsigned long iteration_start_time = micros();
  447. if (state == Calculate || cyclesRemain < 1) {
  448. // Calculate number of cycles for this animation iteration
  449. float cycleSum = cycleFactor * (_anim ? _anim->getCycleFactor() : 1.0) + cycleTail;
  450. cyclesRemain = cycleSum;
  451. if (cyclesRemain < 1) {
  452. cyclesRemain = 1;
  453. cycleSum = 0;
  454. cycleTail = 0;
  455. } else {
  456. cycleTail = cycleSum - cyclesRemain;
  457. }
  458. if (_anim) {
  459. _anim->Run();
  460. }
  461. sum_calc_time += (micros() - iteration_start_time);
  462. iteration_start_time = micros();
  463. ++calc_num;
  464. state = Transition;
  465. }
  466. if (state == Transition && cyclesRemain < 3) {
  467. // transition coef, if within 0..1 - transition is active
  468. // changes from 1 to 0 during transition, so we interpolate from current
  469. // color to previous
  470. float transc = (float)((long)transms - (long)millis()) / GARLAND_SCENE_TRANSITION_MS;
  471. Color* leds_prev = (_leds == &_leds1[0]) ? &_leds2[0] : &_leds1[0];
  472. if (transc > 0) {
  473. for (int i = 0; i < _numLeds; i++) {
  474. // transition is in progress
  475. Color c = _leds[i].interpolate(leds_prev[i], transc);
  476. byte r = (int)(bri_lvl[c.r]) * brightness / 256;
  477. byte g = (int)(bri_lvl[c.g]) * brightness / 256;
  478. byte b = (int)(bri_lvl[c.b]) * brightness / 256;
  479. _pixels->setPixelColor(i, _pixels->Color(r, g, b));
  480. }
  481. } else {
  482. for (int i = 0; i < _numLeds; i++) {
  483. // regular operation
  484. byte r = (int)(bri_lvl[_leds[i].r]) * brightness / 256;
  485. byte g = (int)(bri_lvl[_leds[i].g]) * brightness / 256;
  486. byte b = (int)(bri_lvl[_leds[i].b]) * brightness / 256;
  487. _pixels->setPixelColor(i, _pixels->Color(r, g, b));
  488. }
  489. }
  490. sum_pixl_time += (micros() - iteration_start_time);
  491. iteration_start_time = micros();
  492. ++pixl_num;
  493. state = Show;
  494. }
  495. if (state == Show && cyclesRemain < 2) {
  496. /* Showing pixels (actually transmitting their RGB data) is most time consuming operation in the
  497. garland workflow. Using 800 kHz gives 1.25 μs per bit. -> 30 μs (0.03 ms) per RGB LED.
  498. So for example 3 ms for 100 LEDs. Unfortunately it can't be postponed and resumed later as it
  499. will lead to reseting the transmition operation. From other hand, long operation can cause
  500. Soft WDT reset. To avoid wdt reset we need to switch soft wdt off for long strips.
  501. It is not best practice, but assuming that it is only garland, it can be acceptable.
  502. Tested up to 300 leds. */
  503. if (_numLeds > NUMLEDS_CAN_CAUSE_WDT_RESET) {
  504. ESP.wdtDisable();
  505. }
  506. _pixels->show();
  507. if (_numLeds > NUMLEDS_CAN_CAUSE_WDT_RESET) {
  508. ESP.wdtEnable(5000);
  509. }
  510. sum_show_time += (micros() - iteration_start_time);
  511. ++show_num;
  512. state = Calculate;
  513. ++numShows;
  514. }
  515. --cyclesRemain;
  516. }
  517. void Scene::setupImpl() {
  518. transms = millis() + GARLAND_SCENE_TRANSITION_MS;
  519. // switch operation buffers (for transition to operate)
  520. if (_leds == &_leds1[0]) {
  521. _leds = &_leds2[0];
  522. } else {
  523. _leds = &_leds1[0];
  524. }
  525. if (_anim) {
  526. _anim->Setup(_palette, _numLeds, _leds, &_ledstmp[0], &_seq[0]);
  527. }
  528. }
  529. void Scene::setup() {
  530. sum_calc_time = 0;
  531. sum_pixl_time = 0;
  532. sum_show_time = 0;
  533. calc_num = 0;
  534. pixl_num = 0;
  535. show_num = 0;
  536. numShows = 0;
  537. if (!setUpOnPalChange) {
  538. setupImpl();
  539. }
  540. }
  541. unsigned long Scene::getAvgCalcTime() { return sum_calc_time / calc_num; }
  542. unsigned long Scene::getAvgPixlTime() { return sum_pixl_time / pixl_num; }
  543. unsigned long Scene::getAvgShowTime() { return sum_show_time / show_num; }
  544. /*#######################################################################
  545. _ _ _
  546. /\ (_) | | (_)
  547. / \ _ __ _ _ __ ___ __ _ | |_ _ ___ _ __
  548. / /\ \ | '_ \ | | | '_ ` _ \ / _` | | __| | | / _ \ | '_ \
  549. / ____ \ | | | | | | | | | | | | | (_| | | |_ | | | (_) | | | | |
  550. /_/ \_\ |_| |_| |_| |_| |_| |_| \__,_| \__| |_| \___/ |_| |_|
  551. #######################################################################*/
  552. Anim::Anim(const char* name) : _name(name) {}
  553. void Anim::Setup(Palette* palette, uint16_t numLeds, Color* leds, Color* ledstmp, byte* seq) {
  554. this->palette = palette;
  555. this->numLeds = numLeds;
  556. this->leds = leds;
  557. this->ledstmp = ledstmp;
  558. this->seq = seq;
  559. SetupImpl();
  560. }
  561. void Anim::initSeq() {
  562. for (int i = 0; i < numLeds; ++i)
  563. seq[i] = i;
  564. }
  565. void Anim::shuffleSeq() {
  566. for (int i = 0; i < numLeds; ++i) {
  567. byte ind = (unsigned int)(rngb() * numLeds / 256);
  568. if (ind != i) {
  569. std::swap(seq[ind], seq[i]);
  570. }
  571. }
  572. }
  573. void Anim::glowSetUp() {
  574. braPhaseSpd = secureRandom(4, 13);
  575. if (braPhaseSpd > 8) {
  576. braPhaseSpd = braPhaseSpd - 17;
  577. }
  578. braFreq = secureRandom(20, 60);
  579. }
  580. void Anim::glowForEachLed(int i) {
  581. int8 bra = braPhase + i * braFreq;
  582. bra = BRA_OFFSET + (abs(bra) >> BRA_AMP_SHIFT);
  583. leds[i] = leds[i].brightness(bra);
  584. }
  585. void Anim::glowRun() { braPhase += braPhaseSpd; }
  586. bool operator== (const Color &c1, const Color &c2)
  587. {
  588. return (c1.r == c2.r && c1.g == c2.g && c1.b == c2.b);
  589. }
  590. unsigned int rng() {
  591. static unsigned int y = 0;
  592. y += micros(); // seeded with changing number
  593. y ^= y << 2;
  594. y ^= y >> 7;
  595. y ^= y << 7;
  596. return (y);
  597. }
  598. // Ranom numbers generator in byte range (256) much faster than secureRandom.
  599. // For usage in time-critical places.
  600. byte rngb() { return (byte)rng(); }
  601. #endif // GARLAND_SUPPORT