From d9219b134897b52da6e2e8d0320fec24be7c33a4 Mon Sep 17 00:00:00 2001 From: Anonoei Date: Wed, 11 Oct 2023 17:24:58 -1000 Subject: [PATCH] Initial working commit --- LICENSE | 21 ++++ README.md | 169 ++++++++++++++----------- auto_speed.py | 343 ++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 459 insertions(+), 74 deletions(-) create mode 100644 LICENSE create mode 100644 auto_speed.py diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..b289a62 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Anonoei + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 2080754..581c28d 100644 --- a/README.md +++ b/README.md @@ -1,92 +1,113 @@ -# klipper_auto_speed +# Klipper Auto Speed + Klipper module for automatically calculating your printer's maximum acceleration/velocity +**This module is under development**: Nothing should go wrong, but please keep an eye on your printer, as this will push it to it's physical limits. +This module automatically performs [Ellis' TEST_SPEED macro](https://ellis3dp.com/Print-Tuning-Guide/articles/determining_max_speeds_accels.html), and measured the missed steps on your steppers at various accelerations/velocities. Depending on your ACCEL_START and VELOCITY_START, this may take a long time to finish. -## Getting started +# Table of Contents + - [Overview](https://github.com/Anonoei/klipper_auto_speed#overview) + - [How does it work](https://github.com/Anonoei/klipper_auto_speed#how-does-it-work) + - [Using Klipper Auto Speed](https://github.com/Anonoei/klipper_auto_speed#using-klipper-auto-speed) + - [Installation](https://github.com/Anonoei/klipper_auto_speed#installation) + - [Moonraker Update Manager](https://github.com/Anonoei/klipper_auto_speed#moonraker-update-manager) + - [Configuration](https://github.com/Anonoei/klipper_auto_speed#configuration) + - [Macro](https://github.com/Anonoei/klipper_auto_speed#macro) -To make it easy for you to get started with GitLab, here's a list of recommended next steps. +## Overview + - License: MIT -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! +## How does it work? + 1. Home your printer + 2. If your print is enclosed, heat soak it. You want to run this module at the typical state your printer is in when you're printing. + 3. Run `AUTO_SPEED` + 1. Check endstop variance + - Validate the endstops are accurate enough for `MAX_MISSED` + 2. Find the maximum acceleration + - Given `ACCEL_START`, `ACCEL_STOP_` `ACCEL_STEP`, increase acceleration until we miss more than `MAX_MISSED` steps. Move the toolhead over the pattern at each velocity `TEST_ITERATION` times + 3. Find maximum velocity + - Given `VELOCITY_START`, `VELOCITY_STOP_` `VELOCITY_STEP`, increase velocity until we miss more than `MAX_MISSED` steps. Move the toolhead over the pattern at each velocity `TEST_ITERATION` times + 4. Stress test + - Start at max acceleration/velocity and slowly decrease both until less than `MAX_MISSED` steps are lost after `STRESS_INTERATION`s. -## Add your files +## Using Klipper Auto Speed -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: +### Installation + To install this module you need to clone the repository and run the `install.sh` script +#### Automatic installation ``` -cd existing_repo -git remote add origin https://git.anonoei.com/anonoei/klipper_auto_speed.git -git branch -M main -git push -uf origin main +cd ~ +git clone https://github.com/Anonoei/klipper_auto_speed.git +cd klipper_auto_speed +chmod +x install.sh +./install.sh ``` -## Integrate with your tools +#### Manual installation +1. Clone the repository + 1. `cd ~` + 2. `git clone https://github.com/Anonoei/klipper_auto_speed.git` + 3. `cd klipper_auto_speed` +2. Link auto_speed to klipper + 1. `ln -sf ~/klipper_auto_speed/auto_speed.py ~/klipper/klippy/extras/auto_speed.py` +3. Restart klipper + 1. `sudo systemctl restart klipper` -- [ ] [Set up project integrations](https://git.anonoei.com/anonoei/klipper_auto_speed/-/settings/integrations) +### Moonraker Update Manager +``` +[update_manager klipper_auto_speed] +type: git_repo +path: ~/klipper_auto_speed +origin: https://github.com/anonoei/klipper_auto_speed.git +primary_branch: main +install_script: install.sh +managed_services: klipper +``` -## Collaborate with your team +### Configuration +Place this in your printer.cfg +``` +[auto_speed] +``` +The values listed below are the defaults Auto Speed uses. You can include them if you wish to change their values or run into issues. +``` +[auto_speed] +z: 50 ; Z position to run Auto Speed +margin: 20 ; How far away from your axis maximums to perform the test movement +pattern_margin: 20 ; How far from your axis centers to perform the small test movement -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) +settling_home: True ; Perform settling home before starting Auto Speed +max_missed: 1.0 ; Maximum full steps that can be missed +endstop_samples: 3 ; How many endstop samples to take for endstop variance -## Test and Deploy +test_interations: 2 ; While testing for maximum, perform the test movement this many times +stress_iterations: 50 ; While finding final maximums, perform the test movement this many times -Use the built-in continuous integration in GitLab. +accel_start: Unset ; Starting acceleration, Defaults to your printer's current acceleration +accel_stop: 50000.0 ; Maximum possible acceleration the test will go to +accel_step: 1000.0 ; Increase accel_start by this amount each test -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) +velocity_start: Unset ; Starting velocity, Defaults to your printer's current velocity +velocity_stop: 5000.0 ; Maximum possible velocity the test will go to +velocity_step: 50.0 ; Increase velocity_start by this amount each test +``` -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. - -## License -For open source projects, say how it is licensed. - -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +### Macro +Run the klipper command `AUTO_SPEED`. You can also use the arguments below +Argument | Default | Description +----------------- | ------- | ----------- +Z | 50 | Z position to run Auto Speed +MARGIN | 20 | How far away from your axis maximums to perform the test movement +PATTERN_MARGIN | 20 | How far from your axis centers to perform the small test movement +SETTLING_HOME | 1 | Perform settling home before starting Auto Speed +MAX_MISSED | 1.0 | Maximum full steps that can be missed +ENDSTOP_SAMPLES | 3 | How many endstop samples to take for endstop variance +TEST_ITERATIONS | 2 | While testing for maximum, perform the test movement this many times +STRESS_ITERATIONS | 50 | While finding final maximums, perform the test movement this many times +ACCEL_START | Unset | Starting acceleration, Defaults to your printer's current acceleration +ACCEL_STOP | 50000.0 | Maximum possible acceleration the test will go to +ACCEL_STEP | 1000.0 | Increase accel_start by this amount each test +VELOCITY_START | Unset | Starting velocity, Defaults to your printer's current velocity +VELOCITY_STOP | 5000.0 | Maximum possible velocity the test will go to +VELOCITY_STEP | 50.0 | Increase velocity_start by this amount each test \ No newline at end of file diff --git a/auto_speed.py b/auto_speed.py new file mode 100644 index 0000000..34b40e4 --- /dev/null +++ b/auto_speed.py @@ -0,0 +1,343 @@ +# Find your printers max speed before losing steps +# +# Copyright (C) 2023 Anonoei +# +# This file may be distributed under the terms of the MIT license. +from extras.homing import Homing +from extras.gcode_macro import PrinterGCodeMacro + +class AutoSpeed: + def __init__(self, config): + self.config = config + self.printer = config.get_printer() + + self.z = config.getfloat('z', default=50) + self.margin = config.getint('margin', default=20) + self.pattern_margin = config.getint('pattern_margin', default=20) + + self.settling_home = config.getboolean('settling_home', default=True) + self.max_missed = config.getfloat('max_missed', default=1.0) + self.endstop_samples = config.getint('endstop_samples', default=3) + + self.test_iterations = config.getint('test_iterations', default=2) + self.stress_iterations = config.getint('stress_iterations', default=50) + + self.accel_start = config.getfloat('accel_start', default=None) + self.accel_stop = config.getfloat('accel_stop', default=50000.0) + self.accel_step = config.getfloat('accel_step', default=1000.0) + + self.veloc_start = config.getfloat('velocity_start', default=None) + self.veloc_stop = config.getfloat('velocity_stop', default=5000.0) + self.veloc_step = config.getfloat('velocity_step', default=50.0) + + self.gcode_move = self.printer.lookup_object('gcode_move') + self.toolhead = None + self.printer.register_event_handler("klippy:connect", self.handle_connect) + self.printer.register_event_handler("homing:home_rails_end", self.handle_home_rails_end) + + self.gcode = self.printer.lookup_object('gcode') + self.gcode.register_command('AUTO_SPEED', + self.cmd_AUTO_SPEED, + desc=self.cmd_AUTO_SPEED_help) + + self.th_veloc = None + self.th_accel = None + self.level = None + self.level_applied = False + + self.steppers = {} + self.axes = {} + + def handle_connect(self): + self.toolhead = self.printer.lookup_object('toolhead') + self.th_accel = self.toolhead.max_accel + self.th_veloc = self.toolhead.max_velocity + + if self.accel_start is None: + self.accel_start = self.th_accel + if self.veloc_start is None: + self.veloc_start = self.th_veloc + + # Find and define leveling method + if self.printer.lookup_object("quad_gantry_level", None) is not None: + self.level = "QGL" + elif self.printer.lookup_object("screw_tilt_adjust", None) is not None: + self.level = "STA" + else: + self.level = None + self.level_applied = True + + def handle_home_rails_end(self, homing_state, rails): + # Get rail min and max values + # Get x/y stepper microsteps + if not len(self.steppers.keys()) == 3: + for rail in rails: + pos_min, pos_max = rail.get_range() + for stepper in rail.get_steppers(): + name = stepper._name + #microsteps = (stepper._steps_per_rotation / full_steps / gearing) + if name in ["stepper_x", "stepper_y", "stepper_z"]: + config = self.printer.lookup_object('configfile').status_raw_config[name] + microsteps = int(config["microsteps"]) + self.steppers[name[-1]] = [pos_min, pos_max, microsteps] + + if self.steppers.get("x", None) is not None: + self.axes["x"] = { + "min": self.steppers["x"][0], + "max": self.steppers["x"][1], + "center": (self.steppers["x"][0] + self.steppers["x"][1]) / 2 + } + if self.steppers.get("y", None) is not None: + self.axes["y"] = { + "min": self.steppers["y"][0], + "max": self.steppers["y"][1], + "center": (self.steppers["y"][0] + self.steppers["y"][1]) / 2 + } + + cmd_AUTO_SPEED_help = ("Automatically calculate your printer's maximum acceleration/velocity") + def cmd_AUTO_SPEED(self, gcmd): + if not len(self.steppers.keys()) == 3: + raise gcmd.error(f"Printer must be homed first! Found {len(self.steppers.keys())} homed axes.") + z = gcmd.get_float("Z", self.z) + margin = gcmd.get_float("MARGIN", self.margin) + pattern_margin = gcmd.get_float('PATTERN_MARGIN', self.pattern_margin) + + settling_home = gcmd.get_int("SETTLING_HOME", default=self.settling_home, minval=0, maxval=1) + max_missed = gcmd.get_float('MAX_MISSED', self.max_missed, above=0.0) + endstop_samples = gcmd.get_int('ENDSTOP_SAMPLES', self.endstop_samples, minval=2) + + test_iterations = gcmd.get_int("TEST_ITERATIONS", self.test_iterations) + stress_iterations = gcmd.get_int("STRESS_ITERATIONS", self.stress_iterations) + + accel_start = gcmd.get_float('ACCEL_START', self.accel_start, above=0.0) + accel_stop = gcmd.get_float('ACCEL_STOP', self.accel_stop, above=accel_start) + accel_step = gcmd.get_float('ACCEL_STEP', self.accel_step, above=0.0) + + veloc_start = gcmd.get_float('VELOCITY_START', self.veloc_start, above=0.0) + veloc_stop = gcmd.get_float('VELOCITY_STOP', self.veloc_stop, above=veloc_start) + veloc_step = gcmd.get_float('VELOCITY_STEP', self.veloc_step, above=0.0) + + + if self.level is not None and not self.level_applied: + lookup = None + name = None + if self.level == "QGL": + lookup = "quad_gantry_level" + name = "QUAD_GANTRY_LEVEL" + elif self.level == "STA": + lookup = "screw_tilt_adjust" + name = "Z_TILT_ADJUST" + else: + raise gcmd.error(f"Unknown leveling method '{self.level}'.") + level = self.printer.lookup_object(lookup) + if level.z_status.applied is False: + self.gcode.respond_info(f"AUTO SPEED leveling with {name}...") + self.gcode._process_commands([name], False) + if level.z_status.applied is False: + raise gcmd.error(f"Failed to level printer! Please manually ensure your printer is level.") + self.level_applied = True + self._move([self.axes["x"]["center"], self.axes["y"]["center"], z], veloc_start) + + if settling_home: + self.toolhead.wait_moves() + self._home(True, True, False) + + # Check endstop variance + endstops = { + "x": [], + "y": [], + "steps": { + "x": None, + "y": None + } + } + self.gcode.respond_info(f"AUTO SPEED checking endstop variance over {endstop_samples} samples") + for step in range(0, endstop_samples): + #self._move([self.axes["x"]["center"], self.axes["y"]["center"], None], veloc_start) + self.toolhead.wait_moves() + self._home(True, True, False) + steps = self._get_steps() + #self.gcode.respond_info(f"Got {steps = }") + + if endstops["steps"]["x"] is not None: + x_dif = abs(endstops["steps"]["x"] - steps["x"]) + y_dif = abs(endstops["steps"]["y"] - steps["y"]) + + missed_x = x_dif/self.steppers['x'][2] + missed_y = y_dif/self.steppers['y'][2] + endstops["x"].append(missed_x) + endstops["y"].append(missed_y) + #self.gcode.respond_info(f"AUTO SPEED endstop variance measurement {step + 1}\nMissed X:{missed_x:.2f} steps, Y:{missed_y:.2f} steps") + endstops["steps"]["x"] = steps["x"] + endstops["steps"]["y"] = steps["y"] + + x_max = max(endstops["x"]) + y_max = max(endstops["y"]) + self.gcode.respond_info(f"AUTO SPEED endstop variance:\nMissed X:{x_max:.2f} steps, Y:{y_max:.2f} steps") + + del endstops + if x_max >= max_missed or y_max >= max_missed: + raise gcmd.error(f"Please increase MAX_MISSED (currently {max_missed}), or tune your steppers/homing macro.") + + # Perform tests + accel_count = int((accel_stop - accel_start) / accel_step) + veloc_count = int((veloc_stop - veloc_start) / veloc_step) + + positions = { + "x": { + "min": self.axes["x"]["min"] + margin, + "max": self.axes["x"]["max"] - margin, + "center_min": self.axes["x"]["center"] - (pattern_margin/2), + "center_max": self.axes["x"]["center"] + (pattern_margin/2), + }, + "y": { + "min": self.axes["y"]["min"] + margin, + "max": self.axes["y"]["max"] - margin, + "center_min": self.axes["y"]["center"] - (pattern_margin/2), + "center_max": self.axes["y"]["center"] + (pattern_margin/2), + } + } + + # Find acceleration maximum + measured_accel = None + for step in range(0, accel_count): + accel = accel_start + (accel_step * step) + veloc = veloc_start + valid, missed_x, missed_y = self._test(veloc, accel, positions, test_iterations, max_missed) + + self.gcode.respond_info(f"AUTO SPEED acceleleration measurement {step+1}\nMissed X {missed_x:.2f}, Y {missed_y:.2f} at a{accel}/v{veloc}") + + if not valid: + measured_accel = step + break + self.gcode.respond_info(f"AUTO SPEED found maximum acceleration {accel_start + (accel_step * measured_accel)}, at velocity {veloc_start}") + + # Find velocity maximum + measured_veloc = None + for step in range(0, veloc_count): + accel = accel_start + (accel_step * (measured_accel - 1)) + veloc = veloc_start + (veloc_step * step) + valid, missed_x, missed_y = self._test(veloc, accel, positions, test_iterations, max_missed) + + self.gcode.respond_info(f"AUTO SPEED velocity measurement {step+1}\nMissed X {missed_x:.2f}, Y {missed_y:.2f} at v{veloc}/a{accel}") + + if not valid: + measured_veloc = step + break + self.gcode.respond_info(f"AUTO SPEED found maximum velocity {veloc_start + (veloc_step * measured_veloc)}, at accel {accel_start + (accel_step * (measured_accel - 1))}") + + # Perform stress test + for step in range(100, 0, -1): + accel = accel_start + (accel_step * (measured_accel - (100 - step))) + veloc = veloc_start + (veloc_step * (measured_veloc - (100 - step))) + + valid, missed_x, missed_y = self._test(veloc, accel, positions, stress_iterations, max_missed) + + self.gcode.respond_info(f"AUTO SPEED stress measurement {(100 - step) + 1}\nMissed X {missed_x:.2f}, Y {missed_y:.2f} at a{accel}/v{veloc}") + + if valid: + measured_accel -= (100 - step) + measured_veloc -= (100 - step) + break + + results = "AUTO SPEED Results:\n" + results += f"Recomended maximum acceleration: {accel_start + (accel_step * (measured_accel))}\n" + results += f"Recomended maximum velocity: {veloc_start + (veloc_step * measured_veloc)}" + self.gcode.respond_info(results) + return + + def _test(self, veloc: float, accel: float, positions, iterations: int, max_missed: float): + self._set_velocity(veloc, accel) + #self._move([self.axes["x"]["center"], self.axes["y"]["center"], None], veloc) + + self.toolhead.wait_moves() + self._home(True, True, False) + start_steps = self._get_steps() + for _ in range(iterations): + self._pattern_move(positions, veloc) + #self._move([self.axes["x"]["center"], self.axes["y"]["center"], None], veloc) + + self.toolhead.wait_moves() + self._home(True, True, False) + stop_steps = self._get_steps() + + + step_dif = { + "x": abs(start_steps["x"] - stop_steps["x"]), + "y": abs(start_steps["y"] - stop_steps["y"]) + } + + #self.gcode.respond_info(f"AUTO SPEED got pos\nStart: {start_steps}\nStop: {stop_steps}\nDifference: {step_dif}") + + missed_x = step_dif['x']/self.steppers['x'][2] + missed_y = step_dif['y']/self.steppers['y'][2] + valid = True + if missed_x > max_missed: + valid = False + if missed_y > max_missed: + valid = False + return valid, missed_x, missed_y + + def _pattern_move(self, pos, speed): + # Large pattern diagonals + self._move([pos["x"]["min"], pos["y"]["min"], None], speed) + self._move([pos["x"]["max"], pos["y"]["max"], None], speed) + self._move([pos["x"]["min"], pos["y"]["min"], None], speed) + self._move([pos["x"]["max"], pos["y"]["min"], None], speed) + self._move([pos["x"]["min"], pos["y"]["max"], None], speed) + self._move([pos["x"]["max"], pos["y"]["min"], None], speed) + + # Large pattern box + self._move([pos["x"]["min"], pos["y"]["min"], None], speed) + self._move([pos["x"]["min"], pos["y"]["max"], None], speed) + self._move([pos["x"]["max"], pos["y"]["max"], None], speed) + self._move([pos["x"]["max"], pos["y"]["min"], None], speed) + + # Small pattern diagonals + self._move([pos["x"]["center_min"], pos["y"]["center_min"], None], speed) + self._move([pos["x"]["center_max"], pos["y"]["center_max"], None], speed) + self._move([pos["x"]["center_min"], pos["y"]["center_min"], None], speed) + self._move([pos["x"]["center_max"], pos["y"]["center_min"], None], speed) + self._move([pos["x"]["center_min"], pos["y"]["center_max"], None], speed) + self._move([pos["x"]["center_max"], pos["y"]["center_min"], None], speed) + + # Small pattern box + self._move([pos["x"]["center_min"], pos["y"]["center_min"], None], speed) + self._move([pos["x"]["center_min"], pos["y"]["center_max"], None], speed) + self._move([pos["x"]["center_max"], pos["y"]["center_max"], None], speed) + self._move([pos["x"]["center_max"], pos["y"]["center_min"], None], speed) + + def _move(self, coord, speed): + self.toolhead.manual_move(coord, speed) + + def _home(self, x=True, y=True, z=True): + command = ["G28"] + if x: + command[-1] += " X0" + if y: + command[-1] += " Y0" + if z: + command[-1] += " Z0" + #self.gcode.respond_info(f"AUTO SPEED running {command[-1]}") + self.gcode._process_commands(command, False) + self.toolhead.wait_moves() + + def _get_steps(self): + kin = self.toolhead.get_kinematics() + steppers = kin.get_steppers() + pos = {} + for s in steppers: + s_name = s.get_name() + if s_name in ["stepper_x", "stepper_y"]: + pos[s_name[-1]] = s.get_mcu_position() + return pos + + def _set_velocity(self, velocity: float, accel: float): + #self.gcode.respond_info(f"AUTO SPEED setting limits to VELOCITY={velocity} ACCEL={accel}") + self.toolhead.max_velocity = velocity + self.toolhead.max_accel = accel + self.toolhead.requested_accel_to_decel = accel/2 + self.toolhead._calc_junction_deviation() + +def load_config(config): + return AutoSpeed(config) \ No newline at end of file