From 50e2750fc5a2b0fefabfe33eec986c5993c1be5f Mon Sep 17 00:00:00 2001
From: antcsny <131650489+antcsny@users.noreply.github.com>
Date: Fri, 24 May 2024 16:28:17 +0200
Subject: [PATCH] Working : trace stop after robot run end

- Debug from previous commit
- added more clarity to the end status of data collection in graph_window
- bug fix of showing an empty figure when ploting variables
- checkboxes in variable plot are now by defaut at false
---
 kuka/reader.py               | 16 +++++++++-------
 kuka/trace.py                | 19 ++++++++++---------
 main.py                      |  2 +-
 robot/KRL/Data_collector.sub |  3 ++-
 ui/graph_window.py           |  2 +-
 ui/measure_robot.py          |  3 +++
 ui/ui_data.py                |  4 ++--
 ui/ui_trace.py               |  2 +-
 8 files changed, 29 insertions(+), 22 deletions(-)

diff --git a/kuka/reader.py b/kuka/reader.py
index 95bcd00..c69e170 100644
--- a/kuka/reader.py
+++ b/kuka/reader.py
@@ -151,7 +151,7 @@ class KUKA_DataReader:
         return [ (1 if i == motor else 0) for i in range(1,7) ]
 
     ## Get data
-    def get_data (self) -> Tuple[List[float|int], bool, bool]:
+    def get_data (self) -> Tuple[List[float|int], bool, int]:
         """Collects the latest sample made available by the Data collector sub
 
         Raises:
@@ -180,11 +180,11 @@ class KUKA_DataReader:
         return (
                 data, 
                 TAB1[self.__TAB1_DATA_AVAILABLE] == 1,              # Data available flag
-                TAB1[self.__TAB1_DONE] == 1                         # PyDone flag
+                TAB1[self.__TAB1_DONE]                        # PyDone status
                 )
 
     ## Reading function for the queue
-    def read (self, time_before, load: int = 0) -> Tuple[List[float|int], bool, bool]:
+    def read (self, time_before, load: int = 0) -> Tuple[List[float|int], bool, int]:
         """Reads a sample from the data collection sub
 
         Args:
@@ -272,6 +272,7 @@ class KUKA_DataReader:
 
         # Flag indicating the state of the collection
         self._read_done = False
+        trace_stoped = False
         
         while self._read_done != 1 :
             
@@ -310,7 +311,8 @@ class KUKA_DataReader:
 
             else:
                 # Sleeping to wait for the next data to be sampled, stop de trace if robot movement done
-                if self._read_done == 2:
+                if self._read_done == 2 and not(trace_stoped):
+                    trace_stoped = True
                     self.trace.Trace_Stop()
                 sleep(self.rate/2)
         
@@ -338,7 +340,7 @@ class KUKA_DataReader:
             Tuple[pd.DataFrame, int]: The collected data and the number of samples
         """        
 
-        data_trace = self.trace.Trace_Download(dir, True)
+        data_trace = self.trace.Trace_Download(dir, False)
         
         dataset_length = len(data_trace['Sample'])
         data_trace['Speed'] = [f'{speed}%'] * dataset_length
@@ -420,8 +422,8 @@ class KUKA_DataReader:
             
             # KUKA Trace
             if self.tracing:
-                self.trace.Trace_Stop()
-                sleep(0.1)
+                # self.trace.Trace_Stop()
+                sleep(5)
                 data_trace, _ = self.get_trace_data(speed, load, trace_sampling, temp_dir)
 
             # Indicating the end of this run
diff --git a/kuka/trace.py b/kuka/trace.py
index af71ce7..e2d61f7 100644
--- a/kuka/trace.py
+++ b/kuka/trace.py
@@ -41,17 +41,17 @@ class KUKA_Trace:
         if self.enable:
             config_path = fr'\\{self.rob_instance.ipAddress}\roboter\TRACE\{configuration}.xml'
 
-            try:
-                tree = et.parse(config_path)
-                root = tree.getroot()
+            # try:         # Comented to not modify the xml file
+            #     tree = et.parse(config_path)
+            #     root = tree.getroot()
 
-                for time_element in root.iter('Time'):
-                    time_element.text = duration
-                tree.write(config_path)
+            #     for time_element in root.iter('Time'):
+            #         time_element.text = duration
+            #     tree.write(config_path)
 
 
-            except Exception as e:
-                print(f"XML writing error: {e}")
+            # except Exception as e:
+            #     print(f"XML writing error: {e}")
 
             if type(name) == str and type(configuration) == str:
                 self.rob_instance.KUKA_WriteVar('$TRACE.CONFIG[]', f'"{configuration}.xml"')
@@ -100,7 +100,8 @@ class KUKA_Trace:
         """
         if self.enable:
             self.rob_instance.KUKA_WriteVar('$TRACE.MODE', '#T_STOP')
-        print('Trace stopped')
+        if self.rob_instance.KUKA_ReadVar('$TRACE.STATE') in [b'#T_END', b'#T_WRITING']:
+            print('Trace stopped')
 
     def Trace_State(self):
         """
diff --git a/main.py b/main.py
index 4e1c2a8..3c560ec 100644
--- a/main.py
+++ b/main.py
@@ -233,7 +233,7 @@ class MainProgram (MainWindow):
         for i, var in enumerate(self.data._var_totrace):
             if(self.data._do_trace_var[i]):
                 self.dataframe.plot(x="Sample_time_s",y=[f"{var}_A{i}" for i in a], grid=True),plt.ylabel(f"Motor {var}")
-            plt.tight_layout()
+                plt.tight_layout()
             plt.pause(0.1) # Alternative to plt.show() that is not blocking
 
     def trace_sampling (self):
diff --git a/robot/KRL/Data_collector.sub b/robot/KRL/Data_collector.sub
index b5638c7..eb239e0 100644
--- a/robot/KRL/Data_collector.sub
+++ b/robot/KRL/Data_collector.sub
@@ -205,11 +205,12 @@ DEF COMMUNICATION_ROUTINE ()
       __TAB_1[35] = 1    ;  __PYTHON_DATA_AVAILABLE = TRUE
       ENDIF
       
-      IF (NOT ColRUN) AND  THEN
+      IF (NOT ColRUN) THEN
          IF SAMPLE_NUMBER == SAMPLE_READ THEN
             __TAB_1[36] = 1   ;  __READ_DONE
          ELSE
             __TAB_1[36] = 2   ;  TRACE_STOP
+         ENDIF
       ELSE
          __TAB_1[36] = 0
       ENDIF
diff --git a/ui/graph_window.py b/ui/graph_window.py
index 2f6db56..56128d1 100644
--- a/ui/graph_window.py
+++ b/ui/graph_window.py
@@ -46,7 +46,7 @@ class CollectionGraphWindow (sg.Window):
         self._subtitle = sg.Text("Collecting sample n°...", key="Subtitle")
         self._canvas_elem = sg.Canvas(size=(480,360), key="-CANVAS-")
         self._status = sg.Text("",key="-colstatus-",text_color="#000", font="Helvetica 15")
-        self._exit = sg.Button("Exit", key='-colexit-',font="Helvetica 11", size=(15,1))
+        self._exit = sg.Button("Exit", key='-colexit-',font="Helvetica 11", size=(15,1),button_color='#F0F0F0')
         
         layout = [
             [ sg.Push(), self._title, sg.Push() ],
diff --git a/ui/measure_robot.py b/ui/measure_robot.py
index 10b6909..f3835bf 100644
--- a/ui/measure_robot.py
+++ b/ui/measure_robot.py
@@ -112,6 +112,7 @@ class Measure_robot (CollectionGraphWindow):
         try:
             self.data.to_excel(file_name)
             self.trace_data.to_excel(trace_file_name)
+            self.storing_data_done = True
         except Exception as e:
             traceback.print_exception(e)
             print("Lost data from " + self.name)
@@ -132,9 +133,11 @@ class Measure_robot (CollectionGraphWindow):
         if self.collecting_data_done :
             self.collecting_data_done = False
             self._status.update("Collection Done",text_color="#00f")
+            self._exit.update(disabled=True)
         elif self.storing_data_done :
             self.storing_data_done = False
             self._status.update("Successfully stored data", text_color='#0c2')
+            self._exit.update(disabled=False)
         else:
             self.redraw()
         return True
diff --git a/ui/ui_data.py b/ui/ui_data.py
index 245fe12..212429f 100644
--- a/ui/ui_data.py
+++ b/ui/ui_data.py
@@ -119,8 +119,8 @@ class UI_Data (sg.Frame):
             if '_A1' in col: # sorting the variables per axis
                 colname = col.rsplit('_A1', 1)[0] 
                 self._var_totrace.append(colname)
-                self.var_checkbox.append(sg.Checkbox('Motor ' + colname, enable_events=True, default=True, key=f'-varplot_cbx{i}-'))
+                self.var_checkbox.append(sg.Checkbox('Motor ' + colname, enable_events=True, default=False, key=f'-varplot_cbx{i}-'))
                 win.extend_layout(win['-col_var_to_plot-'], [[sg.pin(sg.Col([[self.var_checkbox[i]]], key=f'-varplot_line{i}-', pad=(1,0.2)))]])
-                self._do_trace_var.append(True)
+                self._do_trace_var.append(False)
                 i+=1
     
diff --git a/ui/ui_trace.py b/ui/ui_trace.py
index 2bf1683..cee285b 100644
--- a/ui/ui_trace.py
+++ b/ui/ui_trace.py
@@ -13,7 +13,7 @@ class UI_KUKATrace( sg.Frame):
 
     def __make_layout (self):
 
-        self._sampling_rate = sg.Combo(['12_ms','12_ms_v2','4_ms'], key='-Trace_config-', default_value='12_ms', size=(20, 1))
+        self._sampling_rate = sg.Combo(['12_ms','12_ms_v2','4_ms_v2'], key='-Trace_config-', default_value='12_ms_v2', size=(20, 1))
         self._do_delfile = sg.Checkbox('Delete files from KRC?',key='-delete-',default=True, disabled=True)
 
         self._layout = [
-- 
GitLab