From ce9c4c4d3a5cd382c0ef6a0a8a64c73a52990aa5 Mon Sep 17 00:00:00 2001
From: Martin Killenberg <martin.killenberg@desy.de>
Date: Fri, 20 Jan 2023 12:00:20 +0100
Subject: [PATCH] Catch plotting error when closing measurement window.

The program continues normally with the summary plot after closing the measurement to cancel the measurement.
---
 Python_script/MeasurementPlot.py | 13 +++++++--
 Python_script/prototype.py       | 47 +++++++++++++++++++++-----------
 2 files changed, 42 insertions(+), 18 deletions(-)

diff --git a/Python_script/MeasurementPlot.py b/Python_script/MeasurementPlot.py
index b9d616e..e26c23e 100644
--- a/Python_script/MeasurementPlot.py
+++ b/Python_script/MeasurementPlot.py
@@ -3,6 +3,12 @@ import matplotlib.pyplot as plt
 import numpy as np
 import time
 
+# Different exceptions can be thrown while plotting, depending on the backend.
+# We catch them all locally and raise our own exception instead
+class PlottingError(Exception):
+    "Raised when plotting fails"
+    pass
+
 class MeasurementPlot:
     def __init__(self, title=''):
         self.fig, self.ax1 = plt.subplots(2, figsize=(12, 10))
@@ -81,8 +87,11 @@ class MeasurementPlot:
 
         plt.show()
         if plt.isinteractive():
-            self.fig.canvas.draw()
-            self.fig.canvas.flush_events()
+            try:
+                self.fig.canvas.draw()
+                self.fig.canvas.flush_events()
+            except Exception as e:
+                raise PlottingError from e
 
     # add 5 % of the distance between min and max to the range
     @staticmethod
diff --git a/Python_script/prototype.py b/Python_script/prototype.py
index 9e09a5e..4a04b3a 100755
--- a/Python_script/prototype.py
+++ b/Python_script/prototype.py
@@ -84,6 +84,10 @@ class Measurements:
 
             except KeyboardInterrupt:
                 pass
+            except MeasurementPlot.PlottingError:
+                # Just the plotting failed, probably because the window was closed
+                # The measurement was partly done and should be plottet, so the following code has to see the correct number of successful measurements
+                measurement_number += 1
 
         plt.close()
 
@@ -101,22 +105,33 @@ class Measurements:
             current_val = round(current_val + step_val, 1)
         sweep_values.append(stop_val)
 
-        for val in sweep_values:
-            if sweep_type == 'temperature':
-                target_temp = val
-                target_hum = const_param
-            elif sweep_type == 'humidity':
-                target_temp = const_param
-                target_hum = val
-            else:
-                raise Exception('Unknown sweep type: '+sweep_type)
-
-            output_name = self.output_basename + '_'+str(target_temp)+'deg_'+str(target_hum)+'rh.csv'
-            self.measurement_plot.fig.suptitle(sweep_type + " sweep measurement "+str(sweep_values.index(val)+1)+
-                                               '/'+str(len(sweep_values))+': ' + str(target_temp)+' degC, '
-                                               + str(target_hum) + ' rel. hum.',
-                                               color="red")
-            self.perform_single_measurement(output_name, target_temp, target_hum, soaking_time, n_stable_reads)
+        successful_sweep_values = []
+        try:
+            for val in sweep_values:
+                if sweep_type == 'temperature':
+                    target_temp = val
+                    target_hum = const_param
+                elif sweep_type == 'humidity':
+                    target_temp = const_param
+                    target_hum = val
+                else:
+                    raise Exception('Unknown sweep type: '+sweep_type)
+
+                output_name = self.output_basename + '_'+str(target_temp)+'deg_'+str(target_hum)+'rh.csv'
+                self.measurement_plot.fig.suptitle(sweep_type + " sweep measurement "+str(sweep_values.index(val)+1)+
+                                                   '/'+str(len(sweep_values))+': ' + str(target_temp)+' degC, '
+                                                   + str(target_hum) + ' rel. hum.',
+                                                   color="red")
+                self.perform_single_measurement(output_name, target_temp, target_hum, soaking_time, n_stable_reads)
+
+        except KeyboardInterrupt:
+            pass
+        except MeasurementPlot.PlottingError:
+            # Remove the remaining measurements from the list.
+            # One measurement was partly done and should be plottet, so we leave 'val' in the list
+            del sweep_values[sweep_values.index(val)+1 : ]
+
+
 
         plt.close()
         return sweep_values
-- 
GitLab