From 5a6a429bc0c8366512a39b5e87ebad62bd63c740 Mon Sep 17 00:00:00 2001
From: Kevin O'Connor <kevin@koconnor.net>
Date: Mon, 7 Jan 2019 12:05:37 -0500
Subject: [PATCH] bltouch: Take into account clock skew when calculating
 command duration

We want the duration of each command to be an exact multiple of
SIGNAL_PERIOD.  The durations might not be exact if the bltouch is on
a secondary mcu.  Account for this in send_cmd().

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
---
 klippy/extras/bltouch.py | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/klippy/extras/bltouch.py b/klippy/extras/bltouch.py
index 93256707f..52f5d42d2 100644
--- a/klippy/extras/bltouch.py
+++ b/klippy/extras/bltouch.py
@@ -83,7 +83,11 @@ class BLTouchEndstopWrapper:
             self.next_cmd_time = print_time
     def send_cmd(self, cmd, duration=MIN_CMD_TIME):
         self.mcu_pwm.set_pwm(self.next_cmd_time, Commands[cmd] / SIGNAL_PERIOD)
-        self.next_cmd_time += max(duration, MIN_CMD_TIME)
+        # Translate duration to ticks to avoid any secondary mcu clock skew
+        mcu = self.mcu_pwm.get_mcu()
+        cmd_clock = mcu.print_time_to_clock(self.next_cmd_time)
+        cmd_clock += mcu.seconds_to_clock(max(duration, MIN_CMD_TIME))
+        self.next_cmd_time = mcu.clock_to_print_time(cmd_clock)
         return self.next_cmd_time
     def verify_state(self, check_start_time, check_end_time, triggered, msg):
         # Perform endstop check to verify bltouch reports desired state