-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathS1Control.py
6792 lines (6085 loc) · 268 KB
/
S1Control.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
# S1Control by ZH for PSS
import os
import sys
import threading
import time
import json
import shutil
import socket
import xmltodict
import struct
import csv
import subprocess
import logging
import serial
import requests
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tkinter as tk
import customtkinter as ctk
from tkinter import ttk, messagebox, font
from tkinter.ttk import Treeview
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from PIL import Image
from decimal import Decimal
from plyer import notification as plyer_notification
from dataclasses import dataclass
from element_string_lists import (
elementstr_symbolsonly,
elementstr_namesonly,
elementstr_symbolswithzinbrackets,
all_xray_lines,
)
__author__ = "Zeb Hall"
__contact__ = "zhall@portaspecs.com"
__version__ = "v1.1.2" # v0.9.6 was the first GeRDA-control version
__versiondate__ = "2024/07/10"
class BrukerInstrument:
def __init__(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.ip = "192.168.137.139"
self.port = 55204 # 55204
# CONNECTION DETAILS FOR WIFI (Not Recommended - Also, DHCP will cause IP to change. Port may change as well?) Wifi is unreliable and prone to massive packet loss and delayed commands/info transmit.
# XRF_IP_WIFI = "192.168.153.167" # '192.168.153.167:55101' found to work for ruffo when on phone hotspot network. both values may change depending on network settings?
# XRF_PORT_WIFI = 55101
# XRF_IP_USB_ALTERNATE = "190.168.137.139" # In some VERY UNUSUAL cases, I have seen instuments come back from Bruker servicing with this IP changed to 190 instead of 192. Worth checking if it breaks.
# vars
self.instr_currentapplication = None
self.instr_currentmethod = None
self.instr_methodsforcurrentapplication = []
self.instr_model = None
self.instr_serialnumber = "UNKNOWN"
self.instr_buildnumber = None
self.instr_detectormodel = None
self.instr_detectortype = None
self.instr_detectorresolution = None
self.instr_detectormaxTemp = None
self.instr_detectorminTemp = None
self.instr_detectorwindowtype = None
self.instr_detectorwindowthickness = None
self.instr_sourcemanufacturer = None
self.instr_sourcetargetZ = None
self.instr_sourcetargetSymbol = None
self.instr_sourcetargetName = None
self.instr_sourcemaxV = None
self.instr_sourceminV = None
self.instr_sourcemaxI = None
self.instr_sourceminI = None
self.instr_sourcemaxP = None
self.instr_sourcespotsize = None
self.instr_sourcehaschangeablecollimator = None
self.instr_firmwareSUPversion = None
self.instr_firmwareUUPversion = None
self.instr_firmwareXILINXversion = None
self.instr_firmwareOMAPkernelversion = None
self.instr_softwareS1version = None
self.instr_isarmed: bool = False
self.instr_isloggedin: bool = False
self.instr_currentphases: list = []
self.instr_currentphase: int = 0
self.instr_phasecount: int = 1
self.instr_currentphaselength_s = 1
self.instr_assayrepeatsselected: int = 1
self.instr_assayrepeatsleft: int = 1
self.instr_assayrepeatschosenforcurrentrun: int = 1
self.instr_estimatedrealisticassaytime: int = 60
self.instr_applicationspresent: list = []
self.instr_filterspresent = []
self.instr_illuminations: list[Illumination] = []
self.instr_currentassayspectra = []
self.instr_currentassayspecenergies = []
self.instr_currentassaylegends = []
self.instr_currentassayresults: pd.DataFrame = None
self.instr_assayisrunning: bool = False
self.instr_currentnosetemp = None
self.instr_currentnosepressure = None
self.s1vermanuallyrequested = False
self.assay_start_time = None
self.assay_end_time = None
self.assay_time_total_set_seconds: int = 0
self.assay_phase_spectrumpacketcounter: int = 0
self.current_working_spectra = []
self.current_working_specenergies = []
self.assay_catalogue = []
self.assay_catalogue_num = 1
self.instr_currentambtemp: str = ""
self.instr_currentambtemp_F: str = ""
self.instr_currentdettemp: str = ""
self.instr_totalspecchannels = 2048
self.specchannelsarray = np.array(list(range(0, self.instr_totalspecchannels)))
self.open_tcp_connection(self.ip, self.port, instant_connect=False)
def open_tcp_connection(
self, connection_ip: str, connection_port: int, instant_connect: bool = False
):
# try:
# ping_result = os.system("ping -n 1 -w 40 " + XRF_IP_USB)
# print('normal ping failed')
if instant_connect:
ping_result = True
else:
ping_result = universalPing(connection_ip, 1)
# print(f'ping = {ping}')
# xrf.connect((XRF_IP_USB, XRF_PORT_USB))
if not ping_result:
if messagebox.askyesno(
f"Connection Problem - S1Control {__version__}",
f"S1Control has not recieved a response from the instrument at {connection_ip}, and is unable to connect. Would you like to continue trying to connect?",
):
connection_attempt_count = 0
while not ping_result:
# ping will only equal 0 if there are no errors or timeouts
ping_result = universalPing(connection_ip, 1)
# os.system('ping -n 1 -w 40 '+XRF_IP_USB)
time.sleep(0.1)
# print(f'ping = {universalPing}')
connection_attempt_count += 1
if connection_attempt_count >= 5:
if messagebox.askyesno(
f"Connection Problem - S1Control {__version__}",
f"S1Control has still not recieved a response from the instrument at {connection_ip}, and is still unable to connect. Would you like to continue trying to connect?",
):
connection_attempt_count = 0
else:
raise SystemExit(0)
closeAllThreads()
gui.destroy()
else:
raise SystemExit(0)
closeAllThreads()
gui.destroy()
try:
self.socket.connect((connection_ip, connection_port))
except Exception as e:
print(
f"Connection Error. Check instrument has booted to login screen and is properly connected before restarting the program. ({repr(e)})"
)
def close_tcp_connection(self):
self.socket.close()
printAndLog("Instrument Connection Closed.", "WARNING")
def receive_chunks(self, expected_len) -> bytes:
"""intermediate function used by receive_data"""
chunks = []
recv_len = 0
while recv_len < expected_len:
chunk = self.socket.recv(expected_len - recv_len)
if chunk == b"":
raise Exception("XRF Socket connection broken")
chunks.append(chunk)
recv_len = recv_len + len(chunk)
return b"".join(chunks)
def receive_data(self) -> tuple[dict, str]:
"""Receives data waiting in buffer from the connected instrument.
structure is handled via indicator bytes in header.
Returns tuple of the receieved data (as an OrderedDict), and the datatype code (see constants)"""
_header = self.receive_chunks(10)
_data_size = int.from_bytes(_header[6:10], "little")
_data = self.receive_chunks(_data_size)
_footer = self.receive_chunks(4)
if _header[4:6] == b"\x17\x80": # 5 - XML PACKET (Usually results?)
_datatype = XML_PACKET
_data = _data.decode("utf-8")
# print(data)
_data = xmltodict.parse(_data)
if (
("Response" in _data)
and ("@status" in _data["Response"])
and ("#text" in _data["Response"])
): # and ('ogged in ' in data['Response']['#text']):
_datatype = XML_SUCCESS_RESPONSE # 5a - XML PACKET, 'success, assay start' 'success, Logged in' etc response
elif (
("Response" in _data)
and ("@parameter" in _data["Response"])
and (_data["Response"]["@parameter"] == "applications")
):
_datatype = XML_APPS_PRESENT_RESPONSE # 5b - XML PACKET, Applications present response
elif (
("Response" in _data)
and ("@parameter" in _data["Response"])
and (_data["Response"]["@parameter"] == "activeapplication")
):
_datatype = XML_ACTIVE_APP_RESPONSE # 5c - XML PACKET, Active Application and Methods present response
return _data, _datatype
# 1 - COOKED SPECTRUM
elif _header[4:6] == b"\x01\x80":
_datatype = COOKED_SPECTRUM
return _data, _datatype
# 2 - RESULTS SET (don't really know when this is used?) // Deprecated?
elif _header[4:6] == b"\x02\x80":
_datatype = RESULTS_SET
return _data, _datatype
# 3 - RAW SPECTRUM // Deprecated?
elif _header[4:6] == b"\x03\x80":
_datatype = RAW_SPECTRUM
return _data, _datatype
# 4 - PDZ FILENAME // Deprecated, no longer works :(
elif _header[4:6] == b"\x04\x80":
_datatype = PDZ_FILENAME
return _data, _datatype
# 6 - STATUS CHANGE (i.e. trigger pulled/released, assay start/stop/complete, phase change, etc.)
elif _header[4:6] == b"\x18\x80":
_datatype = STATUS_CHANGE
_data = (
_data.decode("utf-8")
.replace("\n", "")
.replace("\r", "")
.replace("\t", "")
)
_data = xmltodict.parse(_data)
return _data, _datatype
# 7 - SPECTRUM ENERGY PACKET
elif _header[4:6] == b"\x0b\x80":
_datatype = SPECTRUM_ENERGY_PACKET
return _data, _datatype
# 0 - UNKNOWN DATA
else:
_datatype = UNKNOWN_DATA
printAndLog(f"****debug: unknown datatype. {_header=}, {_data=}")
return _data, _datatype
def send_command(self, command: str):
_msg = '<?xml version="1.0" encoding="utf-8"?>' + command
_msg_data = (
b"\x03\x02\x00\x00\x17\x80"
+ len(_msg).to_bytes(4, "little")
+ _msg.encode("utf-8")
+ b"\x06\x2a\xff\xff"
)
sent = self.socket.sendall(_msg_data)
if sent == 0:
raise Exception("XRF Socket connection broken")
# Commands
def command_login(self):
self.send_command("<Command>Login</Command>")
def command_assay_start(self):
self.send_command('<Command parameter="Assay">Start</Command>')
def command_assay_stop(self):
self.send_command('<Command parameter="Assay">Stop</Command>')
def acknowledge_error(self, TxMsgID):
self.send_command(
f'<Acknowledge RxMsgID="{TxMsgID}" UserAcked="Yes"></Acknowledge>'
)
# Queries
def query_login_state(self):
self.send_command('<Query parameter="Login State"/>')
def query_armed_state(self):
self.send_command('<Query parameter="Armed State"/>')
def query_instrument_definition(self):
self.send_command('<Query parameter="Instrument Definition"/>')
def query_all_applications(self):
self.send_command('<Query parameter="Applications"/>')
def query_current_application_incl_methods(self):
self.send_command(
'<Query parameter="ActiveApplication">Include Methods</Query>'
)
def query_methods_for_current_application(self):
self.send_command('<Query parameter="Method"></Query>')
def query_current_application_prefs(self):
self.send_command('<Query parameter="User Preferences"></Query>')
def query_current_application_phase_times(self):
self.send_command('<Query parameter="Phase Times"/>')
def query_software_version(self):
self.send_command('<Query parameter="Version"/>')
def query_nose_temp(self):
self.send_command('<Query parameter="Nose Temperature"/>')
def query_nose_pressure(self):
self.send_command('<Query parameter="Nose Pressure"/>')
def query_edit_fields(self):
self.send_command('<Query parameter="Edit Fields"/>')
def query_proximity_required(self):
self.send_command('<Query parameter="Proximity Required"/>')
def query_store_results(self):
self.send_command('<Query parameter="Store Results"/>')
def query_store_spectra(self):
self.send_command('<Query parameter="Store Spectra"/>')
# Configuration commands
def configure_transmit_elemental_results_enable(self):
self.send_command(
'<Configure parameter="Transmit Results" grades="Yes" elements="Yes">Yes</Configure>'
)
def configure_transmit_spectra_enable(self):
self.send_command('<Configure parameter="Transmit Spectra">Yes</Configure>')
def configure_transmit_spectra_disable(self):
self.send_command('<Configure parameter="Transmit Spectra">No</Configure>')
def configure_transmit_status_messages_enable(self):
self.send_command('<Configure parameter="Transmit Statusmsg">Yes</Configure>')
def configure_proximity_enable(self):
self.send_command('<Configure parameter="Proximity Required">Yes</Configure>')
def configure_proximity_disable(self):
self.send_command('<Configure parameter="Proximity Required">No</Configure>')
def configure_store_results_enable(self):
self.send_command('<Configure parameter="Store Results">Yes</Configure>')
def configure_store_results_disable(self):
self.send_command('<Configure parameter="Store Results">No</Configure>')
def configure_store_spectra_enable(self):
self.send_command('<Configure parameter="Store Spectra">Yes</Configure>')
def configure_store_spectra_disable(self):
self.send_command('<Configure parameter="Store Spectra">No</Configure>')
def configure_reset_info_fields(self):
self.send_command('<Configure parameter="Edit Fields">Reset</Configure>')
@dataclass
class Assay:
index: str # Index num used to track order assays were taken in software. DOES NOT NECESSARILY EQUAL PDZ FILE NUMBER !!!!
date_completed: str # Date str showing date assay was completed. format YYYY/MM/DD
time_completed: str # Time str showing time assay was completed. format HH:mm:ss
time_elapsed: str # Actual elapsed time for Assay (finish time minus start time). from Start pressed to assay completed. typically = (time_total_set + 5n), where n is number of phases
time_total_set: int # Total num seconds set for the analysis, i.e. sum of all set phase lengths. (e.g. for 3-phase analysis set to 20s per phase, would equal 60)
cal_application: (
str # Calibration Application used (e.g. GeoExploration, REE_IDX, etc)
)
cal_method: str # Method of the calibration application (e.g. Oxide3Phase for GeoExploration)
results: pd.DataFrame
spectra: list
specenergies: list
legends: list
temps: str
note: str
sanity_check_passed: str # 'PASS', 'FAIL', or 'N/A'
@dataclass
class Illumination:
name: str # aka 'ID', e.g. 'Exploration_15', 'Std Alloy Hi-Z'
voltage: int # tube voltage in kV
current: float # tube current in uA
current_isdefault: bool # current tuning status for this illumination? 'Yes' = has NOT been tuned (IS default), 'No' = has been tuned (IS NOT default)
filterposition: str # actually filter description. e.g. 'Cu 75um:Ti 25um:Al 200um'
testsample: str # sample used for autotuning illumination. typically one of 'Al 7075', 'Cu 1100', '2205 SS', etc.
countrange_min: int # min counts threshold for autotuning
countrange_max: int # max counts threshold for autotuning
actualcounts: int # actual tuned counts value at specififed current
def universalPing(host, num_tries):
"""
Returns True if host (str) responds to a ping request.
Remember that a host may not respond to a ping (ICMP) request even if the host name is valid.
"""
num_tries = str(num_tries)
# Option for the number of packets as a function of
param = "-n" if sys.platform.startswith("win") else "-c"
# Building the command. Ex: "ping -c 1 google.com"
command = ["ping", param, num_tries, host]
return subprocess.call(command) == 0
def instrument_StartAssay(
customassay: bool = False,
customassay_filter: str = None,
customassay_voltage: int = None,
customassay_current: float = None,
customassay_duration: int = None,
):
pxrf.instr_assayisrunning = True
printAndLog(f"Starting Assay # {str(pxrf.assay_catalogue_num).zfill(4)}", "INFO")
unselectAllAssays()
clearCurrentSpectra()
clearResultsfromTable()
pxrf.current_working_spectra = []
if not customassay:
# if just starting a normal (non-spectrum-only) assay
pxrf.command_assay_start()
else:
# if customassay, then make ui follow along.
applicationselected_stringvar.set("Custom Spectrum")
# clear and then fill custom assay duration box with given time (for gerda customspectra)
current_time_set = customspectrum_duration_entry.get()
for char in current_time_set:
# delete all chars, because providing last_index to the delete method doesn't delete all chars. annoying!
customspectrum_duration_entry.delete(0)
customspectrum_duration_entry.insert(0, str(customassay_duration))
_no = "No"
# custom spectrum assay start, with params. assuming:
_customassay_backscatterlimit: int = 0
# backscatter: 0 = disabled, -1 = intelligent algorithm, >1 = raw counts per second limit
_customassay_rejectpackets: int = 1
# set phase time for estimate
pxrf.assay_time_total_set_seconds = customassay_duration
# fix formatting of values
_customassay_command = f'<Command parameter="Assay"><StartParameters><Filter>{customassay_filter}</Filter><HighVoltage>{customassay_voltage:.1f}</HighVoltage><AnodeCurrent>{customassay_current:.1f}</AnodeCurrent><AssayDuration>{customassay_duration}</AssayDuration><BackScatterLimit>{_customassay_backscatterlimit}</BackScatterLimit><RejectPackets>{_customassay_rejectpackets}</RejectPackets></StartParameters></Command>'
pxrf.send_command(_customassay_command)
printAndLog(
f"Spectrum-Only Assay Started: ({customassay_voltage:.1f}kV {customassay_current:.1f}uA, {customassay_filter if customassay_filter else _no} Filter)"
)
def instrument_StopAssay():
pxrf.instr_assayrepeatsleft = 0
pxrf.instr_assayisrunning = False
pxrf.command_assay_stop()
def instrument_ConfigureSystemTime():
_currenttime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# time should be format 2015-11-02 09:02:35
_set_time_command = f'<Configure parameter="System Time">{_currenttime}</Configure>'
pxrf.send_command(_set_time_command)
def instrument_toggleProximity(prox_button_bool: bool):
if prox_button_bool:
pxrf.configure_proximity_enable()
elif not prox_button_bool:
pxrf.configure_proximity_disable()
else:
printAndLog("ERROR: Cannot toggle proximity. Toggle value invalid.")
def instrument_toggleStoreResultFiles(store_results_button_bool: bool):
if store_results_button_bool:
pxrf.configure_store_results_enable()
elif not store_results_button_bool:
pxrf.configure_store_results_disable()
else:
printAndLog("ERROR: Cannot toggle store-results. Toggle value invalid.")
def instrument_toggleStoreSpectraFiles(store_spectra_button_bool: bool):
if store_spectra_button_bool:
pxrf.configure_store_spectra_enable()
elif not store_spectra_button_bool:
pxrf.configure_store_spectra_disable()
else:
printAndLog("ERROR: Cannot toggle store-spectra. Toggle value invalid.")
def instrument_SetImportantStartupConfigurables():
# enable transmission of trigger pull, assay complete messages, etc. necessary for basic function.
pxrf.configure_transmit_status_messages_enable()
# Enable transmission of elemental results, disables transmission of grade ID / passfail results
pxrf.configure_transmit_elemental_results_enable
# Enable transmission of trigger pull/release and assay start/stop status messages
pxrf.configure_transmit_spectra_enable()
# printAndLog('Instrument Transmit settings have been configured automatically to allow program functionality.')
def printAndLog(data, logbox_colour_tag: str = "BASIC", notify_slack: bool = False):
"""prints data to UI logbox and txt log file. logbox_colour_tag can be:
'ERROR' (red), 'WARNING' (yellow/orange), 'INFO' (blue), 'GERDA' (l.blue/green) or 'BASIC' (white).
This colour selection may be overidden if the message contains 'ERROR' or 'WARNING'
"""
if logFileName != "":
# print(data)
# Check for validity of logbox colour tag value. if invalid, set to default.
if logbox_colour_tag not in ["ERROR", "WARNING", "INFO", "BASIC", "GERDA"]:
logbox_colour_tag = "BASIC"
with open(logFilePath, "a", encoding="utf-16") as logFile:
logbox_msg: str = ""
# logbox.configure(state="normal")
logFile.write(time.strftime("%H:%M:%S", time.localtime()))
logFile.write("\t")
if isinstance(data, dict):
logFile.write(json.dumps(data))
logbox_msg += json.dumps(data)
elif isinstance(data, str):
logFile.write(data)
if (
"GERDA" in data.upper()
or "CNC " in data.upper()
or "CNC:" in data.upper()
) and logbox_colour_tag == "BASIC":
logbox_colour_tag = "GERDA"
elif "WARNING" in data and logbox_colour_tag == "BASIC":
logbox_colour_tag = "WARNING"
elif "ERROR" in data and logbox_colour_tag == "BASIC":
logbox_colour_tag = "ERROR"
logbox_msg += data
elif isinstance(data, pd.DataFrame):
# Because results are printed normally to resultsbox, this should now print results table to log but NOT console.
logFile.write(data.to_string(index=False).replace("\n", "\n\t\t"))
# logbox.insert('end', data.to_string(index = False))
if "Energy (keV)" in data.columns:
# If df contains energy column (i.e. is from peak ID, not results), then print to logbox.
logbox_msg += data.to_string(index=False)
logbox_colour_tag = "INFO"
elif "Grade" in data.columns: # grade library results (*alloys etc*)
logbox_msg += data.to_string(index=False)
logbox_colour_tag = "INFO"
else: # Else, df is probably results, so don't print to logbox.
logbox_msg += "Assay Results written to log file."
elif isinstance(data, list):
listastext = ", ".join(str(e) for e in data)
logFile.write(f"[{listastext}]")
logbox_msg += f"[{listastext}]"
else:
try:
logFile.write(data)
except Exception as e:
logFile.write(
f"ERROR: Data type {type(data)} unable to be written to log file. ({e})"
)
try:
logbox.insert("end", data, logbox_colour_tag)
except Exception as e:
logbox.insert(
"end",
(
f"ERROR: Data type {type(data)} unable to be written to log box. ({repr(e)})"
),
"ERROR",
)
print(f"(Unabled to be written to log box): {data}")
logFile.write("\n")
logbox_msg += "\n"
logbox.configure(state="normal")
logbox.insert("end", logbox_msg, logbox_colour_tag)
# logbox.insert("end", "\n")
logbox.see("end")
logbox.configure(state="disabled")
if notify_slack:
notifyChannelViaWebhook_OnlyIfGerdaConnected(msg=logbox_msg)
else:
print(f"(Logfile/Logbox uninitialised) Tried to print: {data}")
def notifyChannelViaWebhook_OnlyIfGerdaConnected(msg: str) -> None:
"""Sends a message to a teams or slack Channel. This was added primarily for GeRDA monitoring purposes.
The function looks for a teams or slack webhook URL (see: https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/add-incoming-webhook and https://api.slack.com/apps/)
in a text file in the directory of the S1Control executable called 'slackwebhook.txt' (for security purposes).
the text file should contain only the webhook url.
This function really isn't *vital*, so no stress if it trys and excepts."""
global notification_webhook_url
if gerdaCNC is None:
# for our purposes, we don't need to be sending notif messages unless the gerda is
return
# only need to get webhook url first time
if notification_webhook_url is None:
try:
with open(f"{os.getcwd()}/notification-channel-webhook.txt", "r") as whfile:
notification_webhook_url = whfile.read().strip()
if "hooks.slack.com" in notification_webhook_url:
printAndLog(
f"Slack Notification Webhook set successfully: {notification_webhook_url}"
)
elif "webhook.office.com" in notification_webhook_url:
printAndLog(
f"Teams Notification Webhook set successfully: {notification_webhook_url}"
)
else:
notification_webhook_url = "INVALID"
printAndLog(
"WARNING: The provided GeRDA Notification Webhook text file appears to not contain a compatible webhook. See the readme for further info."
)
except FileNotFoundError:
notification_webhook_url = "INVALID"
printAndLog(
"Note: A GeRDA Notification Webhook text file was not found. For instructions on how to set one up, see the readme."
)
return
except Exception as e:
notification_webhook_url = "INVALID"
printAndLog(
f"WARNING: The GeRDA Notification Webhook could not be set: {e}"
)
# check for previous tests, then okay to try webhook send
if (notification_webhook_url is not None) and (
notification_webhook_url != "INVALID"
):
msg_data = {"text": msg}
try:
_req = requests.post(
notification_webhook_url,
data=json.dumps(msg_data),
headers={"Content-type": "application/json"},
timeout=0.6,
)
# print(f"slack wh sent: {req}")
except Exception as e:
printAndLog(f"May have Failed to send GeRDA Notification Webhook: {e}")
def elementZtoSymbol(Z):
"""Returns 1-2 character Element symbol as a string"""
if Z == 0:
return ""
elif Z <= 118:
return elementstr_symbolsonly[Z - 1]
else:
return "Error: Z out of range"
def elementZtoSymbolZ(Z):
"""Returns 1-2 character Element symbol formatted WITH atomic number in brackets"""
if Z <= 118:
return elementstr_symbolswithzinbrackets[Z - 1]
else:
return "Error: Z out of range"
def elementZtoName(Z):
"""Returns Element name from element Z"""
if Z <= 118:
return elementstr_namesonly[Z - 1]
else:
return "Error: Z out of range"
def elementSymboltoName(sym: str):
"""returns element name from element symbol e.g. 'He' -> 'Helium'"""
if len(sym) < 4:
try:
i = elementstr_symbolsonly.index(sym)
return elementstr_namesonly[i]
except ValueError:
print("Element symbol unrecognised")
else:
return "Error: Symbol too long"
def instrument_GetInfo():
pxrf.query_instrument_definition()
pxrf.query_all_applications()
pxrf.query_current_application_incl_methods()
pxrf.query_software_version()
def printInstrumentInfo():
printAndLog(f"Model: {pxrf.instr_model}")
printAndLog(f"Serial Number: {pxrf.instr_serialnumber}")
printAndLog(f"Build Number: {pxrf.instr_buildnumber}")
printAndLog(f"Detector: {pxrf.instr_detectormodel}")
printAndLog(
f"Detector Specs: {pxrf.instr_detectortype} - {pxrf.instr_detectorwindowthickness} {pxrf.instr_detectorwindowtype} window, {pxrf.instr_detectorresolution} resolution, operating temps {pxrf.instr_detectormaxTemp} - {pxrf.instr_detectorminTemp}"
)
printAndLog(f"Source: {pxrf.instr_sourcemanufacturer} {pxrf.instr_sourcemaxP}")
printAndLog(f"Source Target: {pxrf.instr_sourcetargetName}")
printAndLog(
f"Source Voltage Range: {pxrf.instr_sourceminV} - {pxrf.instr_sourcemaxV}"
)
printAndLog(
f"Source Current Range: {pxrf.instr_sourceminI} - {pxrf.instr_sourcemaxI}"
)
def resource_path(relative_path):
"""Get absolute path to resource, works for dev and for PyInstaller"""
base_path = getattr(sys, "_MEIPASS", os.path.dirname(os.path.abspath(__file__)))
return os.path.join(base_path, relative_path)
def notifyAllAssaysComplete(number_completed: int):
"""Send a platform-suitable notification to the system/desktop to alert the user that all assays have completed. This is in case the user is not looking at the screen or does not have the S1Control window open."""
if enableendofassaynotifications_var.get() == "on":
try:
# Set notification verbage to suit multiple assays
n_title = "All Assays Complete!"
n_message = f"All {number_completed} Assays have been completed. Instrument is now idle."
n_ticker = "All Assays Complete!"
if number_completed == 1:
# Set notification verbage to suit single assay
n_title = "Assay Complete!"
n_message = "Assay has been completed. Instrument is now idle."
n_ticker = "Assay Complete!"
plyer_notification.notify(
title=n_title,
message=n_message,
ticker=n_ticker,
app_name="S1Control",
app_icon=iconpath,
timeout=10,
)
except Exception as e:
print(
f"Assays complete notification was unable to execute. This is likely due to plyer/windows jank. ({repr(e)})"
)
def initialiseLogFile():
global logFile
global logFileArchivePath
global logFileName
global logFilePath
global driveFolderStr
global datetimeString
# Set PC user and name for log file
try:
pc_user = os.getlogin()
pc_device = os.environ["COMPUTERNAME"]
except Exception as e:
print(f"Error getting user and device IDs for log. ({repr(e)})")
pc_user = "Unkown User"
pc_device = "Unknown Device"
driveArchiveLoc = None
driveFolderStr = ""
logFileArchivePath = None
# Check for PSS Drive Paths to save backup of Log file
if os.path.exists(R"Y:/Service/pXRF/Automatic Instrument Logs (S1Control)"):
# use nas path if available
driveArchiveLoc = R"Y:/Service/pXRF/Automatic Instrument Logs (S1Control)"
elif os.path.exists(R"N:/Service/pXRF/Automatic Instrument Logs (S1Control)"):
# use alt N: nas path if available
driveArchiveLoc = R"N:/Service/pXRF/Automatic Instrument Logs (S1Control)"
# this won't work, requires mounting CIFS file share and requires nas root login :(
# elif os.path.exists(
# R"smb://pss-nas.local/nas/Service/pXRF/Automatic Instrument Logs (S1Control)"
# ):
# # otherwise, check for linux smb nas access as last resort
# driveArchiveLoc = R"smb://pss-nas.local/nas/Service/pXRF/Automatic Instrument Logs (S1Control)"
if pxrf.instr_serialnumber == "UNKNOWN":
messagebox.showwarning(
"SerialNumber Error",
"Warning: The instrument's serial number was not retrieved in time to use it in the initialisation of the log file for this session. For this reason, the log file will likely display 'UNKNOWN' as the serial number in the filename.",
)
# print("serial number lookup failed. using 'UNKNOWN'")
# Check for slightly renamed folder for this instrument in drive e.g. '800N8573 Ruffo' to use preferably
foundAlternateFolderName = False
if driveArchiveLoc is not None:
for subdir, dirs, files in os.walk(driveArchiveLoc):
for dir in dirs:
# print(os.path.join(subdir, dir))
if pxrf.instr_serialnumber in dir:
driveFolderStr = dir
foundAlternateFolderName = True
break
# Use just serial num if no renamed folder exists
if foundAlternateFolderName is False:
driveFolderStr = pxrf.instr_serialnumber
# Make folder in drive archive if doesn't already exist
if (driveArchiveLoc is not None) and not os.path.exists(
driveArchiveLoc + rf"/{driveFolderStr}"
):
os.makedirs(driveArchiveLoc + rf"/{pxrf.instr_serialnumber}")
# Standard log file location in dir of program
if not os.path.exists(rf"{os.getcwd()}/Logs"):
os.makedirs(rf"{os.getcwd()}/Logs")
# Create Log file using time/date/XRFserial
datetimeString = time.strftime("%Y%m%d-%H%M%S", time.localtime())
logFileName = f"S1Control_Log_{datetimeString}_{pxrf.instr_serialnumber}.txt"
logFilePath = rf"{os.getcwd()}/Logs/{logFileName}"
if driveArchiveLoc is not None:
logFileArchivePath = rf"{driveArchiveLoc}/{driveFolderStr}/{logFileName}"
logFileStartTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
with open(logFilePath, "x", encoding="utf-16") as logFile:
logFile.write(
f"TIMESTAMP \tLog File Created: {logFileStartTime} by {pc_device}/{pc_user}, using S1Control {__version__}.\n"
)
logFile.write(
"--------------------------------------------------------------------------------------------------------------------------------------------\n"
)
def instrument_GetStates():
pxrf.query_login_state()
pxrf.query_armed_state()
gui.after(800, getOtherStates)
def getOtherStates():
pxrf.query_proximity_required()
pxrf.query_store_results()
pxrf.query_store_spectra()
# XRF Listen Loop Functions
def xrfListenLoopThread_Start(event):
global listen_thread
listen_thread = threading.Thread(target=xrfListenLoop)
listen_thread.daemon = True
listen_thread.start()
gui.after(20, xrfListenLoopThread_Check)
def xrfListenLoopThread_Check():
global quit_requested
global listen_thread
if listen_thread.is_alive():
gui.after(500, xrfListenLoopThread_Check)
else:
if not quit_requested:
printAndLog("ERROR: XRF listen loop broke", "ERROR")
# try:
# time.sleep(2)
# xrfListenLoopThread_Start(None)
# printAndLog("XRF Listen Loop successfully restarted.")
# except Exception as e:
# print(f"Unable to restart XRF listen loop. ({repr(e)})")
# # raise SystemExit(0)
else:
onClosing(force=True)
def xrfListenLoop():
"""main listen and action loop for responding to data from instrument in realtime. to be run in own thread."""
while True:
try:
data, datatype = pxrf.receive_data()
except Exception as e:
printAndLog(repr(e))
printAndLog("XRF CONNECTION LOST", "ERROR")
onInstrDisconnect()
if thread_halt:
break
# print(data)
# 6 - STATUS CHANGE
if datatype == STATUS_CHANGE:
if "@parameter" in data["Status"]: # basic status change
statusparam = data["Status"]["@parameter"]
statustext = data["Status"]["#text"]
printAndLog(f"Status Change: {statusparam} {statustext}")
if statusparam == "Assay" and statustext == "Start":
pxrf.instr_currentphase = 0
if pxrf.instr_currentapplication != "Custom Spectrum":
# only need to calculate assay total set time if it ISN'T a custom spectrum assay. if it is, it is set in startAssay()
pxrf.instr_currentphaselength_s = int(
phasedurations[pxrf.instr_currentphase] # noqa: F821
)
pxrf.assay_time_total_set_seconds = 0
for dur in phasedurations: # noqa: F821
pxrf.assay_time_total_set_seconds += int(dur)
else:
pxrf.instr_currentphaselength_s = int(
customspectrum_duration_entry.get()
)
pxrf.assay_time_total_set_seconds = (
pxrf.instr_currentphaselength_s
)
phasedurations = ["0"]
pxrf.assay_start_time = time.time()
pxrf.instr_assayisrunning = True
pxrf.assay_phase_spectrumpacketcounter = 0
# set variables for assay
pxrf.instr_currentassayspectra = []
pxrf.instr_currentassayspecenergies = []
pxrf.instr_currentassaylegends = []
pxrf.instr_currentassayresults = default_assay_results_df
xraysonbar.start()
if doAutoPlotSpectra_var.get():
clearCurrentSpectra()
elif statusparam == "Assay" and statustext == "Complete":
pxrf.assay_end_time = time.time()
# instr_assayisrunning = False
# print(spectra)
try:
pxrf.instr_currentassayspectra.append(
pxrf.current_working_spectra[-1]
)
pxrf.instr_currentassayspecenergies.append(
pxrf.current_working_specenergies[-1]
) # noqa: F823
# legend = f"Phase {instr_currentphase+1}: {txt['sngHVADC']}kV, {round(float(txt['sngCurADC']),2)}\u03bcA"
legend = f"Phase {pxrf.instr_currentphase+1}({pxrf.instr_currentphaselength_s}s): {txt['sngHVADC']}kV, {round(float(txt['sngCurADC']),2)}\u03bcA {txt['fltDescription']}" # noqa: F821
pxrf.instr_currentassaylegends.append(legend)
# plotSpectrum(spectra[-1], specenergies[-1], plotphasecolours[instr_currentphase],legend)
except Exception as e:
printAndLog(
f"Issue with Spectra experienced after completion of Assay. {(repr(e))}",
"WARNING",
)
# REPORT TEMPS EACH ASSAY COMPLETE
assay_finaltemps = f"Detector {pxrf.instr_currentdettemp}°C, Ambient {pxrf.instr_currentambtemp}°C"
# if detector temp or ambient temp are out of range, change colour of message.
temp_msg_colour = "BASIC" # set as default
try:
if (
float(pxrf.instr_currentdettemp) > (-25)
or float(pxrf.instr_currentdettemp) < (-29)
or float(pxrf.instr_currentambtemp) > (65)
):
temp_msg_colour = "ERROR"
printAndLog(
f"ERROR: Instrument Temperatures appear to be FAR outside of the normal range! {assay_finaltemps}",
logbox_colour_tag="ERROR",
)
elif (
float(pxrf.instr_currentdettemp) > (-26)
or float(pxrf.instr_currentdettemp) < (-28)
or float(pxrf.instr_currentambtemp) > (55)
):
printAndLog(
f"WARNING: Instrument Temperatures appear to be outside of the normal range! {assay_finaltemps}",
logbox_colour_tag="WARNING",
)
else:
printAndLog(f"Temps: {assay_finaltemps}", "BASIC")
except Exception as e: # likely no spectra packets sent
print(
f"Temps check failed, likely due to no spectra packets sent. ({repr(e)})"
)
printAndLog(f"Temps: {assay_finaltemps}", temp_msg_colour)
# printAndLog(f'Amb Temp F: {instr_currentambtemp_F}°F')
# instrument_QueryNoseTemp()
# add full assay with all phases to table and catalogue. this 'assay complete' response is usually recieved at very end of assay, when all other values are in place.
if pxrf.instr_currentassayresults.equals(default_assay_results_df):
completeAssay(
pxrf.instr_currentapplication,
pxrf.instr_currentmethod,
pxrf.assay_time_total_set_seconds,
default_assay_results_df,
pxrf.instr_currentassayspectra,