klipper icon indicating copy to clipboard operation
klipper copied to clipboard

menu command "realtime" attribute problem

Open mcmatrix opened this issue 8 years ago • 31 comments

# This is oscillating when doing long moves
[menu __control __move_10mm __axis_x]
type: input
name: "X:{0:05.1f} "
parameter: toolhead.xpos
input_min: -41
input_max: 250.0
input_step: 10.0
realtime: true
gcode: G1 X{0:.1f}

Thanks to user @bruce356, who reported about this problem.

On all axis (XYZ) when realtime is set to "true" and one makes larger moves say Z axis after homing is resting at 5mm and I want to raise it to say 170mm, while rotating the rotary encoder and setting the distance to 170mm, Z axis starts to rise but after some distance the axis begins to oscillate randomly up and down, this up and down may continue several times before the Z axis will eventually reach the setpoint of 170mm. Small movements are not affected by this.

@Arksine

Also, I have a theory on why the menu's realtime mode could cause oscillation. The menu initializes the input value using the toolhead class. If the user has a gcode transform active this value won't reflect the actual toolhead position while editing, as the input value isn't reset until the user has finished editing. When I get a chance this evening I'll test this theory to see what happens.

I am looking forward to the results of your test.

mcmatrix avatar Aug 29 '18 18:08 mcmatrix

Okay, I had a chance to look at this. When I read the report by @bruce356 I was certain that my original hypothesis was off, as the gcode transform classes only affect the Z Axis.

So I went about trying to reproduce the behavior, and was successful. When turning the encoder quickly with realtime enabled in 10mm steps, the toolhead would move correctly for the first 50mm or so, then randomly switch between moving up and down. I was able to trace down what is happening, lets start with what we expect.

Assume that toolhead is at Z=0, and we use the encoder to move to Z=100 in 10 mm steps. We expect menu.py to send the following gcodes:

G1 Z0
G1 Z10
G1 Z20
G1 Z30
...
G1 Z100

This is happening correctly, and in the correct order. The issue seems to be in gcode.py:

def run_script(self, script):
        curtime = self.reactor.monotonic()
        for line in script.split('\n'):
            while 1:
                try:
                    res = self.process_batch(line)
                except:
                    break
                if res:
                    break
                curtime = self.reactor.pause(curtime + 0.100)

So what happens is that each time the encoder callback is triggered, run_script is called. This calls, self.process_batch() which eventually makes its way to toolhead.move(). When the toolhead's move queue is full, it stalls, which pauses the reactor. Based on my understanding of the Reactor, this allows the next encoder callback to be triggered. However in this case self.process_batch() will return False, as its still waiting on the previous gcode to execute. This too pauses the reactor. This will continue so that several gcodes are alternating through the while 1: loop, pausing until process_batch returns true. Any of the several gcodes alternating through that loop could execute, causing random movement along the axis.

I'm thinking we could solve this by doing something like the following:

def run_script(self, script):
        self.batch_queue.put_nowait(script)
        if self.is_processing_batch is False:
                self.is_processing_batch = True
                while 1:
                        try:
                                script = self.batch_queue.get_nowait()
                        except Queue.Empty:
                                self.is_processing_batch = False
                                break
                        curtime = self.reactor.monotonic()
                        for line in script.split('\n'):
                            while 1:
                                try:
                                    res = self.process_batch(line)
                                except:
                                    break
                                if res:
                                    break
                                curtime = self.reactor.pause(curtime + 0.100)

Arksine avatar Aug 30 '18 16:08 Arksine

Good catch! We could queue the messages in gcode.py, but is the menu code itself re-entrant safe? That is, will the menu code properly handle the case where a call to run_script() pauses and another button event occurs during that pause. I looked briefly and I suspect that it may not be. In that case, I think we should build a queuing mechanism (eg, queue_script() ) which never pauses so as to avoid any reentrant issues.

-Kevin

KevinOConnor avatar Aug 30 '18 18:08 KevinOConnor

Hi Kevin! I believe you are correct, there is nothing in the menu code itself that handles semi-concurrent calls to run_script. So create queue_script() function to queue the script, then perhaps have a timer periodically check the queue to see if there is something in it?

Arksine avatar Aug 30 '18 21:08 Arksine

Yes. I was thinking something like the below (totally untested):

--- a/klippy/extras/display/menu.py
+++ b/klippy/extras/display/menu.py
@@ -512,7 +512,7 @@ class MenuInput(MenuCommand):
         return self._input_value is not None
 
     def _onchange(self):
-        self._manager.run_script(self.get_gcode())
+        self._manager.queue_gcode(self.get_gcode())
 
     def init_value(self):
         self._input_value = None
@@ -901,6 +901,7 @@ class MenuManager:
         self.lcd_chip = lcd_chip
         self.printer = config.get_printer()
         self.gcode = self.printer.lookup_object('gcode')
+        self.gcode_queue = []
         self.parameters = {}
         self.objs = {}
         self.root = None
@@ -1111,8 +1112,8 @@ class MenuManager:
             raise error("Wrong type, expected MenuContainer")
         top = self.stack_peek()
         if top is not None:
-            self.run_script(top.get_leave_gcode())
-        self.run_script(container.get_enter_gcode())
+            self.queue_gcode(top.get_leave_gcode())
+        self.queue_gcode(container.get_enter_gcode())
         if not container.is_editing():
             container.update_items()
         self.menustack.append(container)
@@ -1129,10 +1130,10 @@ class MenuManager:
                     raise error("Wrong type, expected MenuContainer")
                 if not top.is_editing():
                     top.update_items()
-                self.run_script(container.get_leave_gcode())
-                self.run_script(top.get_enter_gcode())
+                self.queue_gcode(container.get_leave_gcode())
+                self.queue_gcode(top.get_enter_gcode())
             else:
-                self.run_script(container.get_leave_gcode())
+                self.queue_gcode(container.get_leave_gcode())
         return container
 
     def stack_size(self):
@@ -1307,13 +1308,13 @@ class MenuManager:
                 self.selected = 0
             elif isinstance(current, MenuInput):
                 if current.is_editing():
-                    self.run_script(current.get_gcode())
+                    self.queue_gcode(current.get_gcode())
                     current.reset_value()
                 else:
                     current.init_value()
             elif isinstance(current, MenuCommand):
                 current()
-                self.run_script(current.get_gcode())
+                self.queue_gcode(current.get_gcode())
 
     def exit(self, force=False):
         container = self.stack_peek()
@@ -1322,7 +1323,7 @@ class MenuManager:
             if (not force and isinstance(current, (MenuInput, MenuGroup))
                     and current.is_editing()):
                 return
-            self.run_script(container.get_leave_gcode())
+            self.queue_gcode(container.get_leave_gcode())
             self.running = False
 
     def run_action(self, action, *args):
@@ -1339,12 +1340,21 @@ class MenuManager:
         except Exception:
             logging.exception("Malformed action call")
 
-    def run_script(self, script):
-        if script is not None:
+    def queue_gcode(self, script):
+        if script is None:
+            return
+        if not self.gcode_queue:
+            reactor = self.printer.get_reactor()
+            reactor.register_callback(self.dispatch_gcode)
+        self.gcode_queue.append(script)
+    def dispatch_gcode(self, eventtime):
+        while self.gcode_queue:
+            script = self.gcode_queue[0]
             try:
                 self.gcode.run_script(script)
             except Exception:
                 logging.exception("Script running error")
+            self.gcode_queue.pop(0)
 
     def add_menuitem(self, name, menu):
         if name in self.menuitems:

KevinOConnor avatar Aug 30 '18 21:08 KevinOConnor

Also, somewhat unrelated, if the menu g-code issues a G1 it probably should always issue an M82 first.

-Kevin

KevinOConnor avatar Aug 30 '18 21:08 KevinOConnor

That looks good to me. I'll apply the patch and test it, then report back. I think the menu can handle multiple gcodes in the config, so I'll add M82 to it as well.

Arksine avatar Aug 30 '18 22:08 Arksine

@KevinOConnor May I ask why a M82 is needed? Isn't this extruder absolute mode and not related to XYZ axis? While if one wants to extrude by menu it may be better to use relative mode anyway?

oderwat avatar Aug 30 '18 22:08 oderwat

Patch tested and solves the issue. Didn't notice any adverse affects.

@oderwat Travels should probably use G90. With the way the menu is set up, you are right that it should use relative extrusion via M83.

Arksine avatar Aug 30 '18 23:08 Arksine

Sorry - I meant G90. Darn g-codes are hard to keep track of.

-Kevin

KevinOConnor avatar Aug 31 '18 03:08 KevinOConnor

Thanks, guys. Nice work. Please do whatever fixes are needed for this. As I mentioned in another comment that I don't have fully working Klipper printer therefor I'm not able to perform any test related with real Axis movements.

mcmatrix avatar Aug 31 '18 06:08 mcmatrix

Hi, has this been applied to the Master version, if not where (which file) do I apply this patch. thanks - bruce

bruce356 avatar Sep 01 '18 09:09 bruce356

Okay - I committed the patch above (commit ce79b6ca).

-Kevin

KevinOConnor avatar Sep 02 '18 18:09 KevinOConnor

Thanks!

@bruce356 How realtime items are working now? Did this patch solved oscillation issue?

mcmatrix avatar Sep 04 '18 09:09 mcmatrix

@mcmatrix @Arksine Hi, thanks for fixing the "realtime: true" for axis XYZ. I have found an erratic movement problem using "Babystepping" with realtime set to true. It is very obvious if the encoder is rotated to the maximum limits as set below to say 0.254, the Z axis on my printer moves very rapidly up by several millimetres. If realtime is not active Babystepping works normally as expected.

[menu babystep_adj] type: input enable: true name: "BabySt Z:{0:05.3f}" parameter: 0 input_min: -0.254 ;-0.010" thou of an inch input_max: 0.254 ;+0.010" thou of an inch input_step: 0.00508 ;0.00508mm = 0.0002" thou of an inch realtime: true ; true currently not working correctly gcode: SET_GCODE_OFFSET Z_ADJUST={0:.3f}

Thanks and regards - bruce

bruce356 avatar Sep 05 '18 05:09 bruce356

@bruce356 Hi, correct me if I'm wrong but using real-time mode with the relative offset adjustment is not the correct way.

If the X_ADJUST style parameters are used, then the adjustment will be added to any existing offset (eg, "SET_GCODE_OFFSET Z=-0.2" followed by "SET_GCODE_OFFSET Z_ADJUST=0.3" would result in a total Z offset of 0.1).

It will add that amount to existing offset not setting absolute offset value. In real-time mode, every change in value will execute gcode.

Dummy example step: 1, min: 0, max 5. You start from 0 and will scroll to 5.
The executed gcode sequence will be:
SET_GCODE_OFFSET Z_ADJUST=1
SET_GCODE_OFFSET Z_ADJUST=2
SET_GCODE_OFFSET Z_ADJUST=3
SET_GCODE_OFFSET Z_ADJUST=4
SET_GCODE_OFFSET Z_ADJUST=5
and exit from edit mode will execute it again with last value.
SET_GCODE_OFFSET Z_ADJUST=5
So the final offset will be [existing offset]+1+2+3+4+5+5

You have to use absolute offset setting. SET_GCODE_OFFSET Z=0.2 The problem is that currently there's no parameter for existing offset value. I have plan to extend gcode module parameter output with home and offset values. Then it'll be easier to set absolute offset with a menu.

mcmatrix avatar Sep 06 '18 08:09 mcmatrix

@mcmatrix hi, thanks for the extensive explanation, it explains why the Z axis moved several millimetres. I remember reading that section some time ago but had forgotten it. Have changed from SET_GCODE_OFFSET Z_ADJUST={0:.3f} to SET_GCODE_OFFSET Z={0:.3f} and now realtime: true works perfectly. Thank you very much regards - bruce

bruce356 avatar Sep 06 '18 15:09 bruce356

@mcmatrix hi, Realtime with the extruder is a problem because for some reason each movement amount adds to the previous amount, example, encoder is set to 10mm movement per notch, if encoder is rotated one notch(+) movement is 10mm (GLCD display shows 10mm), rotate another notch(+) (GLCD display shows 20mm) and movement amount is then another 20mm (so a total so far of 30mm movement). Instead of each notch moving the extruder by 10mm it seems to move the extruder by the total amount shown on the GLCD display.

Also if the encoder is then pressed to leave this menu option the extruder will then rotate a further 20mm (or whatever amount is displayed on the GLCD at time of pressing the encoder). In this example that means the extruder has moved a total of 50mm instead of only 20mm.

If encoder is rotated one notch(+) movement is 10mm, then rotate encoder back to 0mm there is no movement. Rotate encoder one notch(-) movement is 10mm in reverse, then rotate encoder back to 0mm there is no movement.

With realtime active but without M83 or G91 there is also unexpected behavour. The movements and the amount of movement per notch is normal and as expected. The problem is that if the encoder is pressed to leave the Move E menu option the display returns to 0 and if the Move E menu option is re-selected the extruder returns to its original 0 position instead of remaining at its current position.

Explanation or reply from Arksine:- The logic for realtime mode seems to be designed with absolute coordinates in mind. That means the parameter must be toolhead.epos, if it is set to 0 it wont correctly represent the extruder position. Regardless, I don't think realtime mode is well suited for extrusion. Relative extrusion without realtime active best achieves the correct functionality.

Is there any way to program/set the E movement to Relative coordinates so that it functions normally in Relative mode using the Realtime option.

Hope this description/explanation is understandable and not too long.

Many thanks again for the great work, regards - bruce

bruce356 avatar Sep 13 '18 04:09 bruce356

@bruce356 Hi, could you post your menu config for that extruder movement. So that I can replicate that action. Or it's the same as in std menu only with realtime: true ?

[menu __control __move_10mm __axis_e]
type: input
enable: !toolhead.is_printing
name: "Move E:{0:+06.1f}"
parameter: 0
input_min: -250.0
input_max: 250.0
input_step: 10.0
gcode: G1 E{0:.1f} F240

mcmatrix avatar Sep 17 '18 07:09 mcmatrix

@mcmatrix hi I have used the 10mm move as an example, behaviour is the same for 1mm and 0.01mm.

[menu __control __move_10mm __axis_e] type: input enable: !toolhead.is_printing name: "Move E:{0:+06.1f}" parameter: 0 input_min: -250.0 input_max: 250.0 input_step: 10.0 #realtime: true ;Extruder not function normally with Realtime gcode: M83 G1 E{0:.1f} F240

[menu __control __move_1mm __axis_e] type: input enable: !toolhead.is_printing name: "Move E:{0:+06.1f}" parameter: 0 input_min: -100.0 input_max: 100.0 input_step: 1.0 #realtime: true ;Extruder not function normally with Realtime gcode: M83 G1 E{0:.1f} F240

[menu __control __move_01mm __axis_e] type: input enable: !toolhead.is_printing name: "Move E:{0:+06.1f}" parameter: 0 input_min: -50.0 input_max: 50.0 input_step: 0.1 #realtime: true ;Extruder not function normally with Realtime gcode: M83 G1 E{0:.1f} F240

Thanks - bruce PS the gcode: has indent but the formatting here does not show it.

bruce356 avatar Sep 17 '18 07:09 bruce356

@bruce356 Thanks. Btw you can select your code/config part and use Code markup. image

mcmatrix avatar Sep 17 '18 08:09 mcmatrix