-
Notifications
You must be signed in to change notification settings - Fork 0
/
ErYbLi-oven_control.py
executable file
·1734 lines (1481 loc) · 76.9 KB
/
ErYbLi-oven_control.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
#-*- coding: latin-1 -*-
"""Main file for ErYbLi-oven control program."""
import numpy
import multiprocessing
from datetime import datetime
#from threading import Thread, Timer
#import time
import paho.mqtt.client as mqtt
import json
import wx
import matplotlib
matplotlib.use ('WXAgg')
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.figure import Figure
from controlGUI import ControlGUI
import configuration
import thermocouple
import thermocouple_process
import takasago
import powersupply_process
import interlock
import pidthread
#import heater
#import PID
import mailsystem
import buzzer
import logging_mysql as logger
# start by loading the main configuration file into the global config
config = configuration.Configuration ()
config.load ()
class MainWindow (ControlGUI):
"""ErYbLi-oven control program main window functions"""
def __init__ (self, *args, **kwds):
"""Define the application
This includes
- setting up the GUI
- initializing the thermocouple object
- initializing the powersupply object
"""
ControlGUI.__init__ (self, *args, **kwds)
# important variables
self.totalramptime = 0
self.oven_status = 'idle'
self.automatic_startup = None
self.oven_buttonlist = [self.button_ramp_high,
self.button_ramp_low,
self.button_ramp_off,
self.button_ramp_emergency]
# thermocouples
# We need to maintain a list of installed but not used, i.e. 'inactive'
# thermocouples. Those need to be enabled anyway, such that their chip select
# pin is pulled to high. Otherwise the chips won't be inactive and interfere
# with the actually used thermocouples' data output.
tc_complete_list = [int (pin) for pin in config.getGeneral('thermocouple_pins').split (',')]
self.thermocouples = {}
for pos, tc in enumerate (config.getThermocoupleNames ()):
# configure 'active' thermocouples
self.thermocouples[tc] = thermocouple.Thermocouple (
type = config.getThermocouple (tc)['type'],
pin = config.getThermocouple (tc)['pin'],
position = pos
)
tc_complete_list = filter (lambda pin: pin != config.getThermocouple (tc)['pin'], tc_complete_list)
self.thermocouples_inactive = {}
for pin in tc_complete_list:
# configure 'inactive' thermocouples
self.thermocouples_inactive[pin] = thermocouple.Thermocouple (
pin = pin
)
# powersupplies
self.powersupplies = {}
for pos, psu in enumerate (config.getPowersupplyNames ()):
self.powersupplies[psu] = takasago.TakasagoPowersupply (
device = config.getGeneral ('serial_device'),
address = config.getPowersupply (psu)['address'],
max_current = config.getPowersupply (psu)['max_current'],
model = config.getPowersupply (psu)['model'],
position = pos
)
# set up shared memory space to hold latest process values and message queues
self.shmem_temperatures = multiprocessing.Array ('f', len (self.thermocouples))
self.shmem_currents = multiprocessing.Array ('f', len (self.powersupplies))
self.shmem_voltages = multiprocessing.Array ('f', len (self.powersupplies))
self.shmem_current_setpoints = multiprocessing.Array ('f', len (self.powersupplies))
self.queue_temperatures = multiprocessing.Queue ()
self.queue_powersupplies = multiprocessing.Queue ()
# now that we have the shared variables, set up the interlock
self.interlock = interlock.Interlock (config, self.shmem_temperatures, self.shmem_currents, self.shmem_voltages)
self.interlock_oldstatus = -1
self.interlock_is_critical = False
self.interlock_is_critical_oldstate = False
self.interlock_ignore_mask = 0 # bitmask of interlocks to be ignored
self.buzzer = buzzer.Buzzer (int (config.getGeneral ('buzzer_pin')))
# populate initial temperature and currents
for sensor in self.thermocouples:
pos = self.thermocouples[sensor].position
try:
temptry = self.thermocouples[sensor].updateBothTemperatures ()
if temptry != None:
self.shmem_temperatures[pos] = self.thermocouples[sensor].correctTemperature (temptry['sensor'], temptry['rj'])
else:
self.shmem_temperatures[pos] = -1
except TypeError:
self.shmem_temperatures[pos] = -1
for psu in self.powersupplies:
pos = self.powersupplies[psu].position
try:
self.shmem_currents[pos] = self.powersupplies[psu].getCurrent ()
except TypeError:
self.shmem_currents[pos] = -1
try:
self.shmem_voltages[pos] = self.powersupplies[psu].getVoltage ()
except TypeError:
self.shmem_voltages[pos] = -1
self.shmem_current_setpoints[pos] = -1
# set up periodic database logging
self.logger = logger.DataLogger (config, self.shmem_temperatures, self.shmem_currents, self.shmem_voltages)
self.logger_timer = wx.Timer (self)
self.Bind (wx.EVT_TIMER, self.updateDatabaseLogs, self.logger_timer)
self.logger_timer.Start (5000)
# set up information publishing via MQTT
if config.getDatabase ('mqtt_broker'):
self.mqtt_client = mqtt.Client (client_id = "ErYbLi-oven_control")
self.mqtt_client.connect (config.getDatabase ('mqtt_broker'))
self.mqtt_client.loop_start ()
self.mqtt_topic_prefix = config.getDatabase ('mqtt_topic_prefix')
else:
self.mqtt_client = None
# add a button for each configured oven
self.button_oven = {}
for oven in config.getOvenNames ():
# control page
self.button_oven[oven] = wx.ToggleButton (self.page_control, wx.ID_ANY, config.getOven (oven)['name'])
self.button_oven[oven].Bind (wx.EVT_TOGGLEBUTTON, self.OnOvenBtnClick)
self.sizer_horiz_oven_selection.Add (self.button_oven[oven], 1, wx.ALL|wx.EXPAND, 10)
# automatic startup preparations
self.check_list_box_oven_selection.SetItems (config.getOvenNames ())
self.startup_timer = wx.Timer (self)
self.Bind (wx.EVT_TIMER, self._startup_timer_callback, self.startup_timer)
# populate temperature list
column = self.list_ctrl_temperatures.GetColumn (1)
column.SetAlign (wx.LIST_FORMAT_RIGHT)
self.list_ctrl_temperatures.SetColumn (1, column)
column = self.list_ctrl_temperatures.GetColumn (2)
column.SetAlign (wx.LIST_FORMAT_RIGHT)
self.list_ctrl_temperatures.SetColumn (2, column)
for listpos, sensor in enumerate (config.getThermocoupleNames ()):
self.list_ctrl_temperatures.InsertStringItem (listpos, sensor)
# catch double clicks and enter on temperature list item
self.list_ctrl_temperatures.Bind (wx.EVT_LIST_ITEM_ACTIVATED, self.OnTempListDoubleClick)
matplotlib.rc ('xtick', labelsize = 8)
matplotlib.rc ('ytick', labelsize = 8)
# add temperature plot
self.ydata_temperature = {}
self.ydata_error = {}
self.temp_figure = Figure (figsize = (3,1), constrained_layout = True)
self.temp_axes = self.temp_figure.add_subplot (111)
self.temp_canvas = FigureCanvas (self.page_monitor, -1, self.temp_figure)
self.temp_axes.tick_params (direction = 'in', top = True, right = True)
self.temp_axes.grid (axis = 'y', linewidth = 1)
self.temp_axes.set_xmargin (0.)
self.temp_axes.set_ylabel ("Is Temperature (C)", size = 8)
self.temp_axes.xaxis.set_major_formatter (matplotlib.dates.DateFormatter ('%H:%M'))
self.temp_canvas.mpl_connect ('button_release_event', self.OnTempPlotClicked)
self.plot_error_signal = False
self.temp_line = {}
for listpos, sensor in enumerate (config.getThermocoupleNames ()):
self.ydata_temperature[sensor] = []
self.ydata_error[sensor] = []
self.temp_line[sensor], = self.temp_axes.plot_date ([], [],
fmt = '-', tz = None, xdate = True, lw = 2)
# set color in list to same as plot line color
color = self.temp_line[sensor].get_color ()
self.list_ctrl_temperatures.SetItemBackgroundColour (listpos, self._color_variant (color, 30))
self.sizer_horiz_temp.Add (self.temp_canvas, 1, wx.ALL|wx.EXPAND, 3)
# populate powersupply list
column = self.list_ctrl_currents.GetColumn (1)
column.SetAlign (wx.LIST_FORMAT_LEFT)
column = self.list_ctrl_currents.GetColumn (2)
column.SetAlign (wx.LIST_FORMAT_LEFT)
for listpos, psu in enumerate (config.getPowersupplyNames ()):
self.list_ctrl_currents.InsertStringItem (listpos, config.getPowersupply (psu)['name'])
# catch double clicks and enter on powersupply list item
self.list_ctrl_currents.Bind (wx.EVT_LIST_ITEM_ACTIVATED, self.OnPsuListDoubleClick)
# add powersupply plot
self.ydata_current = {}
self.ydata_power = {}
self.psu_figure = Figure (figsize = (3,1), constrained_layout = True)
self.psu_axes = self.psu_figure.add_subplot (111)
self.psu_canvas = FigureCanvas (self.page_monitor, -1, self.psu_figure)
self.psu_axes.tick_params (direction = 'in', top = True, right = True)
self.psu_axes.grid (axis = 'y', linewidth = 1)
self.psu_axes.set_xmargin (0.)
self.psu_axes.set_ylabel ("Is current (A)", size = 8)
self.psu_axes.xaxis.set_major_formatter (matplotlib.dates.DateFormatter ('%H:%M'))
self.psu_canvas.mpl_connect ('button_release_event', self.OnPSUPlotClicked)
self.plot_power_signal = False
self.psu_line = {}
for listpos, psu in enumerate (config.getPowersupplyNames ()):
self.ydata_current[psu] = []
self.ydata_power[psu] = []
self.psu_line[psu], = self.psu_axes.plot_date ([], [],
fmt = '-', tz = None, xdate = True, lw = 2)
# set color in list to same as plot line color
color = self.psu_line[psu].get_color ()
self.list_ctrl_currents.SetItemBackgroundColour (listpos, self._color_variant (color,30))
self.sizer_horiz_current.Add (self.psu_canvas, 1, wx.ALL|wx.EXPAND, 3)
# populate heater setting combo box
self.combo_box_heater_sel.SetItems (config.getHeaterNames ())
self.combo_box_heater_sel.SetSelection (0)
self.OnHeaterSelected (None)
# set number of digits for PID parameters
self.spin_ctrl_low_p.SetDigits (2)
self.spin_ctrl_low_i.SetDigits (2)
self.spin_ctrl_low_d.SetDigits (2)
self.spin_ctrl_high_p.SetDigits (2)
self.spin_ctrl_high_i.SetDigits (2)
self.spin_ctrl_high_d.SetDigits (2)
self.spin_ctrl_ramp_standard.SetDigits (1)
self.spin_ctrl_ramp_emergency.SetDigits (1)
self.spin_ctrl_low_p.SetIncrement (0.1)
self.spin_ctrl_low_i.SetIncrement (0.01)
self.spin_ctrl_low_d.SetIncrement (0.01)
self.spin_ctrl_high_p.SetIncrement (0.1)
self.spin_ctrl_high_i.SetIncrement (0.01)
self.spin_ctrl_high_d.SetIncrement (0.01)
# populate e-mail recipients list
self.populateRecipients ()
# fill in actual values in general settings section
self.spin_ctrl_plot_update_interval.SetValue (
float (config.getGeneral ('plot_update_interval'))
)
self.spin_ctrl_plots_max_points.SetValue (
float (config.getGeneral ('plot_max_points'))
)
self.spin_ctrl_off_state_temp.SetValue (
float (config.getGeneral ('off_state_temperature'))
)
if config.getDatabase ('logging_enabled') == 'True':
self.combo_box_db_logging.SetSelection (0)
else:
self.combo_box_db_logging.SetSelection (1)
# select today in calendar widget and set periodic update every 30 minutes
self._calendar_update_lowerdate ()
self.calendar_update_timer = wx.Timer (self)
self.Bind (wx.EVT_TIMER, self._calendar_update_lowerdate, self.calendar_update_timer)
self.calendar_update_timer.Start (30 * 60 * 1000)
### mostly finished setting up the GUI ###
# start thermocouple and powersupply updater processes
self.thermocouple_process = multiprocessing.Process (
target = thermocouple_process.thermocouple_process,
args = (self.thermocouples,
float (config.getGeneral ('thermocouple_polling_interval')),
int (config.getGeneral ('thermocouple_averaging')),
self.shmem_temperatures,
self.queue_temperatures
)
)
self.thermocouple_process.start ()
self.powersupply_process = multiprocessing.Process (
target = powersupply_process.powersupply_process,
args = (self.powersupplies,
float (config.getGeneral ('powersupply_polling_interval')),
self.shmem_currents,
self.shmem_voltages,
self.shmem_current_setpoints,
self.queue_powersupplies
)
)
self.powersupply_process.start ()
# Update the status area in periodic intervals
self.status_timer = wx.Timer (self)
self.Bind (wx.EVT_TIMER, self._status_timer_callback, self.status_timer)
self.status_timer.Start (1000)
# PID thread initialization
self.queue_PIDs = multiprocessing.Queue ()
self.PIDthread = pidthread.PIDthread (
self.shmem_temperatures,
self.shmem_current_setpoints,
self.shmem_currents,
config,
self.queue_PIDs
)
self.PIDthread.start ()
# refresh temperature and powersupply list and plots, and set timer
self._updateTempAndPowersupply ()
self.timer_temp_and_psu = wx.Timer (self)
self.Bind (wx.EVT_TIMER, self._updateTempAndPowersupply, self.timer_temp_and_psu)
self.timer_temp_and_psu.Start (
1000 * float (config.getGeneral ('list_update_interval'))
)
# Events
self.Bind (wx.EVT_CLOSE, self.OnExit)
# Done
self.SetOvenStatusText ("Idle...")
self.SetTimedStatusText ("Startup done", 3)
self.MqttPublish ("state", "idle", True)
"""General functions"""
def SetTimedStatusText (self, text, timeout = None):
"""Set a statusbar message that is cleared after <timeout> sec"""
self.SetStatusText (text)
if timeout != None:
self.timer = wx.Timer (self)
self.Bind (wx.EVT_TIMER, self.ClearStatusText, self.timer)
self.timer.Start (timeout * 1000, oneShot = True)
def ClearStatusText (self, e):
"""Clear the status text in the 1st (left) status bar field"""
self.SetStatusText ("")
def SetOvenStatusText (self, text):
"""Set the status text in the 2nd (right) statusbar field"""
self.SetStatusText (text, 1);
def MqttPublish (self, topic, payload, retain = False):
"""Publish oven status information to an MQTT broker.
It payload is a dictionary the data will be transmitted in JSON form."""
if not self.mqtt_client:
return
try:
(rc, mid) = self.mqtt_client.publish (
topic = "{}/{}".format (self.mqtt_topic_prefix, topic),
payload = json.dumps (payload),
qos = 1,
retain = retain
)
if rc != mqtt.MQTT_ERR_SUCCESS:
# error while trying to publish
# just in case try to reconnect to the MQTT broker
# and pusblish the message again
self.mqtt_client.reconnect ()
self.mqtt_client.publish (
topic = "{}/{}".format (self.mqtt_topic_prefix, topic),
payload = json.dumps (payload),
qos = 1,
retain = retain
)
except:
pass
def OnExit (self, e):
"""Exit application with proper cleanup"""
dlg = wx.MessageDialog (self,
" Do you really want to close \n the YbErLi-oven control program?",
"Confirm Exit", wx.OK|wx.CANCEL|wx.ICON_QUESTION)
result = dlg.ShowModal ()
dlg.Destroy ()
self.buzzer.AcknowledgeBeepShort ()
if result == wx.ID_OK:
self.SetTimedStatusText ("Wating for processes to shut down")
self.MqttPublish ("state", "program exited", True)
# signal all child processes and threads to quit
self.queue_PIDs.put ('q')
self.queue_temperatures.put ('q')
self.queue_powersupplies.put ('q')
self.PIDthread.join ()
self.thermocouple_process.join ()
self.powersupply_process.join ()
# close GUI
self.Destroy ()
def _color_variant (self, hex_color, brightness_offset = 1):
"""Take a color like #87c95f and produces a lighter or darker variant
Taken from https://chase-seibert.github.io/blog/2011/07/29/python-calculate-lighterdarker-rgb-colors.html
"""
if len (hex_color) != 7:
raise Exception ("Passed %s into color_variant(), needs to be in #87c95f format." % hex_color)
rgb_hex = [hex_color[x:x+2] for x in [1, 3, 5]]
new_rgb_int = [int (hex_value, 16) + brightness_offset for hex_value in rgb_hex]
new_rgb_int = [min ([255, max ([0, i])]) for i in new_rgb_int] # make sure new values are between 0 and 255
# hex() produces "0x88", we want just "88"
return "#" + "".join([hex(i)[2:] for i in new_rgb_int])
"""Functions of the oven control page"""
def OnOvenBtnClick (self, evt):
"""Activate oven buttons"""
button = evt.GetEventObject ()
self.buzzer.AcknowledgeBeepShort ()
if self.oven_status not in ['is off', 'is low', 'idle']:
button.SetValue (not button.GetValue ())
dlg = wx.MessageDialog (self,
"Cannot change the oven selection.\n\n"
"This is only possible if the oven is\n"
"in Off, Low or Idle state.", "Information",
wx.OK|wx.ICON_INFORMATION)
dlg.ShowModal ()
dlg.Destroy ()
self.buzzer.AcknowledgeBeepShort ()
return
if button.GetValue ():
button.SetBackgroundColour ((150, 255, 150))
else:
button.SetBackgroundColour (wx.NullColour)
def OnHighClicked (self, evt = None, automatic = False):
"""Start ramp up of selected ovens"""
selected = self._getSelectedOvens ()
self.buzzer.AcknowledgeBeepShort ()
# Confirm that interlock is fine
if self._interlockCheckBeforeRamp ():
self.button_ramp_high.SetValue (False)
return
# Confirm that some oven is selected
if len (selected) == 0:
dlg = wx.MessageDialog (self,
"Please select oven(s) for heating first.", "Information",
wx.OK|wx.ICON_INFORMATION)
dlg.ShowModal ()
dlg.Destroy ()
self.buzzer.AcknowledgeBeepShort ()
self.button_ramp_high.SetValue (False)
return True
# Oven is already hot
if not automatic and self.oven_status.endswith (' high'):
if self._confirmFreeze () == wx.ID_OK:
# stop ramp and freeze powersupplies
self._stopRampAndFreezePowersupplies (selected)
else:
self.SetTimedStatusText ("Heating not interrupted", 3)
# Do not execute remaining function
return True
# Confirm that the user really wants to start heating
if not automatic and self._confirmStartRamp ("HEATING") != wx.ID_OK:
self.SetTimedStatusText ("Heating not started", 3)
self.button_ramp_high.SetValue (False)
return True
self.interlock_is_critical = True
# First set all ovens that are not selected to go to low temperature ...
not_selected = list (set (config.getOvenNames ()) - set (selected))
if len (not_selected) > 0:
self._updateHeaterSetpoints (not_selected, 'a', 'temp_low')
# ... then set everything selected to ramp to high
self._updateHeaterSetpoints (selected, 'a', 'temp_high')
self.totalramptime = self._calculate_ramp_time ()
self.gauge_oven_ramp.SetValue (0)
self.oven_status = 'ramp to high'
for button in self.oven_buttonlist:
if button != self.button_ramp_high:
button.SetValue (False)
button.SetBackgroundColour (wx.NullColour)
self.button_ramp_high.SetBackgroundColour ((255, 255, 150))
self.SetTimedStatusText ("Ramp to High started", 3)
self.SetOvenStatusText ("Ramping to High...")
self.MqttPublish ("state", "ramp to high", True)
def OnLowClicked (self, evt = None, automatic = False):
"""Start ramp down of all ovens"""
# Get all ovens as selected for this target
selected = config.getOvenNames ()
self.buzzer.AcknowledgeBeepShort ()
# Confirm that interlock is fine
if self._interlockCheckBeforeRamp ():
self.button_ramp_low.SetValue (False)
return
# Oven is already low
if not automatic and self.oven_status.endswith (' low'):
if self._confirmFreeze () == wx.ID_OK:
# stop ramp and freeze powersupplies
self._stopRampAndFreezePowersupplies (selected)
else:
self.SetTimedStatusText ("Cooling not interrupted", 3)
# Do not execute remaining function
return True
# Confirm that the user really wants to start cooling
if not automatic and self._confirmStartRamp ("COOLING") != wx.ID_OK:
self.button_ramp_low.SetValue (False)
self.SetTimedStatusText ("Cooling not started", 3)
return True
self.interlock_is_critical = True
self._updateHeaterSetpoints (selected, 'a', 'temp_low')
self.totalramptime = self._calculate_ramp_time ()
self.gauge_oven_ramp.SetValue (0)
self.oven_status = 'ramp to low'
for button in self.oven_buttonlist:
if button != self.button_ramp_low:
button.SetValue (False)
button.SetBackgroundColour (wx.NullColour)
self.button_ramp_low.SetBackgroundColour ((255, 255, 150))
self.SetTimedStatusText ("Ramp to Low started", 3)
self.SetOvenStatusText ("Ramping to Low...")
self.MqttPublish ("state", "ramp to low", True)
def OnOffClicked (self, evt = None, automatic = False):
"""Start ramp to off of all ovens"""
# Get all ovens as selected for this target
selected = config.getOvenNames ()
self.buzzer.AcknowledgeBeepShort (3)
# Oven already ramps to off
if not automatic and self.oven_status == "ramp to off":
if self._confirmFreeze () == wx.ID_OK:
# stop ramp and freeze powersupplies
self._stopRampAndFreezePowersupplies (selected)
return True
# Oven is already in off or emergency-off
if not automatic and self.oven_status.startswith ('is') and self.oven_status.endswith ('off'):
dlg = wx.MessageDialog (self,
"Oven and powersupplies are already in an off state.\n"\
"There is nothing more to be done.",
"Oven notice", wx.OK|wx.ICON_INFORMATION)
dlg.ShowModal ()
dlg.Destroy ()
self.buzzer.AcknowledgeBeepShort ()
# Do not execute remaining function
return True
# The oven was not already off, so better check the interlock
if self._interlockCheckBeforeRamp ():
self.button_ramp_off.SetValue (False)
return
# Confirm that the user really wants to start cooling
if not automatic and self._confirmStartRamp ("TURNING OFF") != wx.ID_OK:
self.button_ramp_off.SetValue (False)
self.SetTimedStatusText ("Cooling to off not started", 3)
return True
self.interlock_is_critical = True
self._updateHeaterSetpoints (selected, 'a', 'temp_off')
self.totalramptime = self._calculate_ramp_time ()
if self.totalramptime == 0:
self.button_ramp_off.SetValue (False)
dlg = wx.MessageDialog (self,
"Oven is already at or below the off-state temperature.\n"\
"There is nothing more to be done.",
"Oven notice", wx.OK|wx.ICON_INFORMATION)
dlg.ShowModal ()
dlg.Destroy ()
return True
self.gauge_oven_ramp.SetValue (0)
self.oven_status = 'ramp to off'
for button in self.oven_buttonlist:
if button != self.button_ramp_high:
button.SetValue (False)
button.SetBackgroundColour (wx.NullColour)
self.button_ramp_off.SetBackgroundColour ((255, 255, 150))
self.SetTimedStatusText ("Ramp to Off started", 3)
self.SetOvenStatusText ("Ramping to Off...")
self.MqttPublish ("state", "ramp to off", True)
def OnEmergencyClicked (self, evt):
"""Start fast emergency ramp to off of all ovens"""
# Get all ovens as selected for this target
selected = config.getOvenNames ()
self.buzzer.AcknowledgeBeepShort (3)
# Oven already ramps to off
if self.oven_status == "ramp to emergency-off":
if self._confirmFreeze () == wx.ID_OK:
# stop ramp and freeze powersupplies
self._stopRampAndFreezePowersupplies (selected)
return True
# Oven is already in off or emergency-off
if self.oven_status.startswith ('is') and self.oven_status.endswith ('off'):
dlg = wx.MessageDialog (self,
"Oven and powersupplies are already in an off state.\n"\
"There is nothing more to be done.",
"Oven notice", wx.OK|wx.ICON_INFORMATION)
dlg.ShowModal ()
dlg.Destroy ()
self.buzzer.AcknowledgeBeepShort ()
# Do not execute remaining function
return True
# Confirm that the user really wants to start cooling
if self._confirmStartRamp ("EMERGENCY COOLING") != wx.ID_OK:
self.button_ramp_emergency.SetValue (False)
self.SetTimedStatusText ("Emergency cooling not started", 3)
return True
# The whole point of the emergency ramp is to bring the oven down in
# case something goes wrong. So disable the interlock.
self.interlock_is_critical = False
self._updateHeaterSetpoints (selected, 'e', 'temp_off')
self.totalramptime = self._calculate_ramp_time ()
if self.totalramptime == 0:
self.button_ramp_off.SetValue (False)
dlg = wx.MessageDialog (self,
"Oven is already at or below the off-state temperature.\n"\
"There is nothing more to be done.",
"Oven notice", wx.OK|wx.ICON_INFORMATION)
dlg.ShowModal ()
dlg.Destroy ()
return True
self.gauge_oven_ramp.SetValue (0)
self.oven_status = 'ramp to emergency-off'
for button in self.oven_buttonlist:
if button != self.button_ramp_high:
button.SetValue (False)
button.SetBackgroundColour (wx.NullColour)
self.button_ramp_emergency.SetBackgroundColour ((255, 150, 150))
self.SetTimedStatusText ("Emergency ramp to Off started", 3)
self.SetOvenStatusText ("Emergency ramping to Off...")
self.MqttPublish ("state", "emergency ramp to off", True)
def OnInterlockDClicked (self, evt):
"""Disable/Enable individual interlocks"""
statictext = evt.GetEventObject ()
labellist = (
("CHILLER", self.label_interlock_water, interlock.Interlock.WATER_FAIL),
("TEMPERATURE", self.label_interlock_temp, interlock.Interlock.TEMP_FAIL),
("HEATER", self.label_interlock_heater, interlock.Interlock.HEATER_FAIL),
("POWER SUPPLY", self.label_interlock_powersupply, interlock.Interlock.PSU_FAIL),
("UPS", self.label_interlock_ups, interlock.Interlock.UPS_FAIL)
)
for (name, label, bitmask) in labellist:
if statictext == label:
# found label that was clicked
if not self.interlock_ignore_mask & bitmask:
# interlock is currently enabled -> ask for confirmation before disable
self.buzzer.AcknowledgeBeepShort ()
if self._confirmDisableInterlock (name) == wx.ID_OK:
self.interlock_ignore_mask ^= bitmask
self.buzzer.AcknowledgeBeepShort (3)
else:
# interlock is currently disabled -> enable without confirmation check
self.interlock_ignore_mask ^= bitmask
self.buzzer.AcknowledgeBeepShort (2)
# force full update of interlock status
# (this will also give the label the proper background color)
self.interlock_oldstatus = -1
self._update_interlock ()
def _confirmDisableInterlock (self, name):
"""Confirmation dialog before disabling an interlock
:param name: name string of interlock to be disabled
:return: return value of MessageDialog, is wx.ID_OK if user confirms
"""
dlg = wx.MessageDialog (self,
"You are about to disable the {}\n"
"interlock. Please confirm to proceed.".format (name),
"Confirmation",
wx.OK|wx.CANCEL|wx.ICON_EXCLAMATION)
result = dlg.ShowModal ()
dlg.Destroy ()
return result
def _getSelectedOvens (self):
"""Determine currently selected ovens
:return: list of selected oven names
"""
selected = []
for oven in config.getOvenNames ():
if self.button_oven[oven].GetValue ():
selected.append (oven)
return selected
def _confirmFreeze (self):
"""Confirmation dialog to interrupt ramp to to freeze ovens
:return: return value of MessageDialog, is wx.ID_OK if user confirms
"""
if self.oven_status.startswith ('ramp '):
dlg = wx.MessageDialog (self,
"This target is currently running.\n\n"
"Do you want to interrupt the ramp and freeze\n"
"the powersupplies at their current settings?",
"Confirmation", wx.OK|wx.CANCEL|wx.ICON_QUESTION)
else:
dlg = wx.MessageDialog (self,
"This target is currently active.\n\n"
"Do you want to interrupt active temperature\n"
"stabilization and freeze the powersupplies\n"
"at their current settings?",
"Confirmation", wx.OK|wx.CANCEL|wx.ICON_QUESTION)
result = dlg.ShowModal ()
dlg.Destroy ()
self.buzzer.AcknowledgeBeepShort ()
return result
def _stopRampAndFreezePowersupplies (self, selected):
"""Stop an ongoing ramp and freeze the powersupply output at its current value.
:param selected: List of powersupply names to be frozen
"""
self._updateHeaterSetpoints (selected, 'f', 'current')
self.totalramptime = self._calculate_ramp_time ()
self.gauge_oven_ramp.SetValue (0)
self.oven_status = 'idle'
for button in self.oven_buttonlist:
button.SetBackgroundColour (wx.NullColour)
button.SetValue (False)
self.SetTimedStatusText ("Temperature ramp interrupted on user request", 3)
self.SetOvenStatusText ("Idle...")
self.MqttPublish ("state", "idle", True)
def _confirmStartRamp (self, action):
"""Confirmation dialog at start of oven ramp
:param action: string of action to do, e.g. "HEATING"
:return: return value of MessageDialog, is wx.ID_OK if user confirms
"""
dlg = wx.MessageDialog (self,
"Do you really want to start\n{} the oven?".format (action),
"Confirmation", wx.OK|wx.CANCEL|wx.ICON_QUESTION)
result = dlg.ShowModal ()
dlg.Destroy ()
self.buzzer.AcknowledgeBeepShort ()
return result
def _interlockCheckBeforeRamp (self):
"""Make sure that the interlock all green before bringing up the
powersupplies from the off status
:return: True on interlock failure, False if everything is OK
"""
# get "effective" interlock status by considering also masked interlocks
effective_interlock_status = self.interlock.status & ~self.interlock_ignore_mask
if effective_interlock_status == interlock.Interlock.ALL_OK:
return False
dlg = wx.MessageDialog (self,
"Interlock failure status.\n\n"\
"Cannot start oven ramp as interlock is not\n"
"all green. Interlock failure details:\n{}".format (self.interlock.details),
"Interlock notice", wx.OK|wx.ICON_INFORMATION)
dlg.ShowModal ()
dlg.Destroy ()
self.buzzer.AcknowledgeBeepShort ()
return True
def _updateHeaterSetpoints (self, ovens, state, target):
"""Helper function for clicked oven button to update heater objects.
Update the target temperatures, set the temperature setpoint to the
current temperature and turn on the powersupply.
:param ovens: list of oven names to be updated (will do all their heaters)
:param state: state of heater, i.e. 'a'ctive, 'e'mergency, 'o'ff or 'f'reeze
:param target: name of temperature target,
i.e. 'temp_high', 'temp_low', 'temp_off' or 'current'
"""
for oven in ovens:
for heatername in config.getOven (oven)['heaters']:
self.PIDthread.heaters[heatername].state = state
# current temperature of the heater's thermocouple for later use
is_temperature = self.shmem_temperatures[
self.thermocouples[
self.PIDthread.heaters[heatername].info['thermocouple']
].position
]
if state == 'f':
# setting output to -1 will cause the PID to be reset on the next start
self.PIDthread.PIDs[heatername].output = -1
if target == 'temp_high' or target == 'temp_low':
self.PIDthread.heaters[heatername].target = self.PIDthread.heaters[heatername].info[target]
elif target == 'temp_off':
off_temperature = float (config.getGeneral ('off_state_temperature'))
# only set off state temperature if current temperature is actually higher
if off_temperature < is_temperature:
self.PIDthread.heaters[heatername].target = off_temperature
else:
self.PIDthread.heaters[heatername].target = is_temperature
else: # must be 'current' by now, the special target for a freeze operation
self.PIDthread.heaters[heatername].target = is_temperature
if state != 'f':
# start with the present temperature as setpoint
self.PIDthread.heaters[heatername].setpoint = is_temperature
else:
# for a frozen target there is no setpoint temperature
self.PIDthread.heaters[heatername].setpoint = -1
self.PIDthread.PIDstability[heatername]['startup_check'] = False
if target != "temp_off" and state != "f":
# check for a "cold start", that is, if we are at very low temperatures
# we will make the PID less agressive and reduce the ramping speed in
# pidthread.py to prevent catastrohpic overshoots. Once we are then out
# off this startup mode the PID thread will reset the flag to False.
self.PIDthread.PIDstability[heatername]['startup_check'] = True
# Notify powersupply thread to turn on powersupply output
self.queue_powersupplies.put ('on ' + self.PIDthread.heaters[heatername].info['powersupply'])
# notify the PID thread in case we are ramping to off
if target == 'temp_off':
self.PIDthread.ramp_to_off = True
else:
self.PIDthread.ramp_to_off = False
# special addition: if a ramp has started disable temperature smoothing
self.queue_temperatures.put (1) # smoothing factor 1 equals no smoothing
def _calculate_ramp_time (self):
"""Estimate how much time the remaining ramp will take"""
heaters = self.PIDthread.heaters
longest = 0
remaining = 0
for heater in heaters.values ():
# Calculate the remaining time for this oven
if heater.state == 'a':
remaining = abs ((heater.target - heater.setpoint) / (heater.info['ramp_speed']/60.))
if heater.state == 'e':
remaining = abs ((heater.target - heater.setpoint) / (heater.info['emergency_ramp_speed']/60.))
if remaining > longest:
longest = remaining
remaining = 0
return longest
def _status_timer_callback (self, e):
"""Update oven ramp and interlock statuses"""
self._update_interlock ()
time_remaining = self._calculate_ramp_time ()
fraction = 1.
if self.totalramptime > 0:
fraction = max(0, min (1, (self.totalramptime - time_remaining) / self.totalramptime))
if time_remaining < 1:
fraction = 1.
self.gauge_oven_ramp.SetValue (100. * fraction)
if time_remaining > 0:
# update with remaining time information
minutes, seconds = divmod (time_remaining, 60)
hours, minutes = divmod (minutes, 60)
time_string = "%02d:%02d:%02d" % (hours, minutes, seconds)
self.label_oven_status.SetLabel ("Remaining time for ramp: " + time_string)
self.MqttPublish ("ramp_status", {"ETA": time_string, "fraction": round (fraction, 4)})
elif self.label_oven_status.GetLabel().startswith ("Remaining "):
# a ramp just finished
self.queue_temperatures.put (1) # enable temperature smoothing (OK, not really for now)
if self.oven_status == 'ramp to high':
self.label_oven_status.SetLabel ("Oven is in HOT state")
self.button_ramp_high.SetBackgroundColour ((150, 255, 150))
self.SetTimedStatusText ("Ramp to High finished", 3)
self.SetOvenStatusText ("Oven is HOT")
self.MqttPublish ("state", "oven is hot", True)
self.oven_status = 'is high'
self.interlock_is_critical = True
self.sendMailRampFinished ()
self.buzzer.AcknowledgeBeepLong ()
if self.oven_status == 'ramp to low':
self.label_oven_status.SetLabel ("Oven is in LOW state")
self.button_ramp_low.SetBackgroundColour ((150, 255, 150))
self.SetTimedStatusText ("Ramp to Low finished", 3)
self.SetOvenStatusText ("Oven is LOW")
self.MqttPublish ("state", "oven is low", True)
self.oven_status = 'is low'
self.interlock_is_critical = True
self.sendMailRampFinished ()
self.buzzer.AcknowledgeBeepLong ()
if self.oven_status == 'ramp to off' or \
self.oven_status == 'ramp to emergency-off':
self.label_oven_status.SetLabel ("Oven is in OFF state")
if self.oven_status == 'ramp to off':
self.button_ramp_off.SetBackgroundColour ((150, 255, 150))
else:
self.button_ramp_emergency.SetBackgroundColour ((150, 255, 150))
self.SetTimedStatusText ("Ramp to Off finished", 3)
self.SetOvenStatusText ("Oven is OFF")
self.MqttPublish ("state", "oven is off", True)
# put all powersupply currents to -1
# this puts the acutal set current to 0 A and shows as "----" in the list
for psu in self.powersupplies:
pos = self.powersupplies[psu].position
self.shmem_current_setpoints[pos] = -1
for heater in self.PIDthread.heaters.values ():
# turn off PIDs for heater
heater.state = 'o'
# indicate that there is no temperature setpoint
heater.setpoint = -1
# disable powersupply output (processed by powersupply_process)
self.queue_powersupplies.put ('off ' + heater.info['powersupply'])
self.oven_status = 'is off'
self.PIDthread.ramp_to_off = False
self.interlock_is_critical = False
self.sendMailRampFinished ()
self.buzzer.AcknowledgeBeepLong ()
if self.oven_status == 'idle':
self.label_oven_status.SetLabel ("Oven is idle")
self.label_oven_status.GetParent().Layout ()
def _update_interlock (self):
"""Update status of the various interlock systems"""
self.interlock.update ()
# get "effective" interlock status by considering also masked interlocks
effective_interlock_status = self.interlock.status & ~self.interlock_ignore_mask
if effective_interlock_status == self.interlock_oldstatus:
# interlock status unchanged
if (self.interlock_is_critical == self.interlock_is_critical_oldstate) \
and (effective_interlock_status != interlock.Interlock.ALL_OK):
# No change in the interlock criticality either, so no need to continue.
# However, skip the rest only if the interlock fails as otherwise the
# interlock has come back to good condition and we need to update the
# interlock indicators to green.
return
self.interlock_is_critical_oldstate = self.interlock_is_critical
# prepare interlock summary for MQTT publishing
interlock_summary = {
"cooling": "ok",
"temperature": "ok",
"heater": "ok",
"powersupplies": "ok",
"ups": "ok",
"overall": "ok"
}
if self.interlock_ignore_mask & interlock.Interlock.WATER_FAIL:
interlock_summary['cooling'] = "disabled"
if self.interlock_ignore_mask & interlock.Interlock.TEMP_FAIL:
interlock_summary['temperature'] = "disabled"
if self.interlock_ignore_mask & interlock.Interlock.HEATER_FAIL:
interlock_summary['heater'] = "disabled"
if self.interlock_ignore_mask & interlock.Interlock.PSU_FAIL:
interlock_summary['powersupplies'] = "disabled"
if self.interlock_ignore_mask & interlock.Interlock.UPS_FAIL:
interlock_summary['ups'] = "disabled"