-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSoftC10TL27_V2.py
3175 lines (2836 loc) · 188 KB
/
SoftC10TL27_V2.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/env python
# -*- encoding: utf-8 -*-
### Opérations sur les fichiers
import os
from os import path
from json import *
from turtle import done
import pandas
### Interface graphique
from tkinter import *
from tkinter import ttk
# from tkinter import tix # Obsolète, à remplacer
from tkinter.messagebox import *
from tkinter.filedialog import *
from screeninfo import get_monitors
### Création de PDF
import PIL
# from Pillow import Image
from reportlab.pdfgen import canvas as cvpdf
from reportlab.lib.pagesizes import A4
from win32com.client import Dispatch # pip install pywin32
import excel2img
from openpyxl import load_workbook
from openpyxl_image_loader import SheetImageLoader
from PIL import ImageGrab, Image
### Imports pour CRAPPy
import crappy
import customblocks
import custom_generator
import custom_pid
import custom_dashboard
from test_RAZ import remise_a_zero
# import custom_multiplex
import custom_grapher
import custom_recorder
### Divers
from numpy import pi
import time
import datetime
import re
from threading import Event, Thread
### Debug
import sys
import random
### Potentiellement à virer. À vérifer
import xlsxwriter
# Coefficients de changement d'unité
COEF_VOLTS_TO_MILLIMETERS = 200
COEF_MILLIMETERS_TO_VOLTS = 1 / COEF_VOLTS_TO_MILLIMETERS
COEF_VOLTS_TO_TONS = 2
COEF_TONS_TO_VOLTS = 1 / COEF_VOLTS_TO_TONS
# Les trois constantes suivantes sont pour verrou_production
ON = 1
OFF = 0
RESTART = 3
verrou_production = OFF
# Constantes pour les choix de consignes
NOMBRE_DE_CONSIGNES_MAXIMAL = 1000
TYPES_DE_CONSIGNE = {"constant" : "palier",
"ramp" : "rampe",
"cyclic" : "cycle de paliers",
"cyclic_ramp" : "cycle de rampes",
"sine" : "sinus"}
LABEL_SORTIE_EN_CHARGE = "sortie_charge_transformee"
LABEL_SORTIE_EN_POSITION = "sortie_position_transformee"
DEBUT_CONDITION_TEMPS = len("delay=")
DEBUT_CONDITION_CHARGE = len(LABEL_SORTIE_EN_CHARGE) + 1
DEBUT_CONDITION_POSITION = len(LABEL_SORTIE_EN_POSITION) + 1
# Types d'asservissement
ASSERVISSEMENT_EN_CHARGE = 1
ASSERVISSEMENT_EN_DEPLACEMENT = 2
def lecture_donnee(file_name):
"""FR : Renvoie la dernière entrée du fichier texte indiqué. Les fichiers utilisant
cette fonction ne doivent être modifiés que par les fonctions de cette application.
EN : Returns the last entry in the indicated text file. Files using this function musn't
be modified except by functions of this application."""
with open(file_name,'r') as f :
lines=f.readlines()
data=lines[-1][11:-1] # Datas are formated as "yyyy-mm-dd <data>\n".
return data
#V
# Chemins des fichiers
SEPARATEUR = "\\" # "\\" for windows, "/" for linux
DOSSIER_CONFIG_ET_CONSIGNES = lecture_donnee("dossier_config_et_consignes.txt") + SEPARATEUR
DOSSIER_ENREGISTREMENTS = lecture_donnee("dossier_enregistrements.txt") + SEPARATEUR
# print (DOSSIER_ENREGISTREMENTS)
liste_des_blocs_crappy_utilises = []
launch_crappy_event = Event()
start_generator = False
# stop_crappy_event = Event()
enregistrement_effectue = False
charge_max = -10
position_min = 2000
position_max = -10
# tonnage_limite = 20
alphabet=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
next_available_letter=0
def etalonnage_des_coefficients_de_transformation():
"""FR : Étalonne les coefficient de la fonction de passage de volts à tonnes.
EN : Calibrates the function passing from volts to tons coefficients."""
#fonction calculant la valeur de charge réelle lue.
#Prend en x la tension délivrée par l'Indi-Paxs.
#Sort la tension correspondant à la charge réelle.
global etalonnage_a, etalonnage_b, etalonnage_c
etalonnage_a = float(lecture_donnee(DOSSIER_CONFIG_ET_CONSIGNES + 'etal_a.txt'))
etalonnage_b = float(lecture_donnee(DOSSIER_CONFIG_ET_CONSIGNES + 'etal_b.txt'))
etalonnage_c = float(lecture_donnee(DOSSIER_CONFIG_ET_CONSIGNES + 'etal_c.txt'))
#V
etalonnage_a, etalonnage_b, etalonnage_c = 0, 0, 0
etalonnage_des_coefficients_de_transformation()
def RTM_protocol():
"""FR : Ouvre le manuel du banc.
EN : Opens the bench's manual."""
os.startfile(lecture_donnee(DOSSIER_CONFIG_ET_CONSIGNES + 'chemin_manuel.txt') + SEPARATEUR + lecture_donnee(DOSSIER_CONFIG_ET_CONSIGNES + 'nom_manuel.txt'))
return 0
#V
def ecriture_donnee(file_name, data) :
"""FR : Écrit la donnée précédée de la date dans le fichier texte indiqué. Les
fichiers utilisant cette fonction ne doivent être modifiés que par les fonctions
de cette application.
EN : Writes the data preceded by the date in the indicated text file. Files using this function musn't
be modified except by functions of this application."""
with open(file_name,'a') as f :
# Les 11 premiers caractères sont la date au format "2022-07-04 ".
f.write(str(datetime.datetime.now())[:11] + ' ' + data + "\n")
#V
def suppression_d_un_fichier(file_name) :
"""FR : Supprime ce fichier.
EN : Deletes that file."""
try :
os.remove(file_name)
except FileNotFoundError :
showwarning("Attention", "Fichier " + file_name + " non trouvé")
#V
### Fonctions de conversions d'unité
def volts_to_tons(volts) :
"""FR : Convertit des volts en tonnes.
EN : Converts volts in tons."""
return 2 * volts
#V
def tons_to_volts(tons) :
"""FR : Convertit des tonnes en volts.
EN : Converts tons in volts."""
return round(tons/2, 2)
#V
### Fonctions de vérification des entrées des utilisateurs
def _check_entree_float(new_value):
"""FR : Empêche l'utilisateur d'entrer des valeurs incorrectes.
EN : Prevent the user from entering incorrect values."""
if new_value == "" :
return True
if re.match("^[0-9]+\.?[0-9]*$", new_value) is None and re.match("^[0-9]*\.?[0-9]+$", new_value) is None :
return False
return True
#V
def _check_entree_charge(new_value):
"""FR : Empêche l'utilisateur d'entrer des valeurs incorrectes.
EN : Prevent the user from entering incorrect values."""
if new_value == "" :
return True
if re.match("^[0-9]+\.?[0-9]*$", new_value) is None and re.match("^[0-9]*\.?[0-9]+$", new_value) is None :
return False
new_value = float(new_value)
return new_value >= 0.0 and new_value <= 20.0
#V
def _check_entree_charge_prod(new_value):
"""FR : Empêche l'utilisateur d'entrer des valeurs incorrectes.
EN : Prevent the user from entering incorrect values."""
if new_value == "" :
return True
if re.match("^[0-9]+\.?[0-9]*$", new_value) is None and re.match("^[0-9]*\.?[0-9]+$", new_value) is None :
return False
new_value = float(new_value)
return new_value >= 0.0 and new_value <= 10.0
#V
def _check_entree_position(new_value):
"""FR : Empêche l'utilisateur d'entrer des valeurs incorrectes.
EN : Prevent the user from entering incorrect values."""
if new_value == "" :
return True
if re.match("^[0-9]+\.?[0-9]*$", new_value) is None and re.match("^[0-9]*\.?[0-9]+$", new_value) is None :
return False
new_value = float(new_value)
return new_value >= 0.0 and new_value <= 2000.0
#V
def _check_entree_longueur(new_value):
"""FR : Empêche l'utilisateur d'entrer des valeurs incorrectes.
EN : Prevent the user from entering incorrect values."""
if new_value == "" :
return True
if re.match("^[0-9]+\.?[0-9]*$", new_value) is None and re.match("^[0-9]*\.?[0-9]+$", new_value) is None :
return False
new_value = float(new_value)
return new_value >= 0.0 and new_value <= 26.0
#V
def _check_entree_vitesse_charge(new_value):
"""FR : Empêche l'utilisateur d'entrer des valeurs incorrectes.
EN : Prevent the user from entering incorrect values."""
if new_value == "" or new_value == '-' :
return True
if re.match("^-?[0-9]+\.?[0-9]*$", new_value) is None and re.match("^-?[0-9]*\.?[0-9]+$", new_value) is None :
return False
new_value = float(new_value)
return new_value >= -20.0 and new_value <= 20.0
#V
def _check_entree_vitesse_position(new_value):
"""FR : Empêche l'utilisateur d'entrer des valeurs incorrectes.
EN : Prevent the user from entering incorrect values."""
if new_value == "" or new_value == '-' :
return True
if re.match("^-?[0-9]+\.?[0-9]*$", new_value) is None and re.match("^-?[0-9]*\.?[0-9]+$", new_value) is None :
return False
new_value = float(new_value)
return new_value >= -2000.0 and new_value <= 2000.0
#V
def _check_entree_temps(new_value):
"""FR : Empêche l'utilisateur d'entrer des valeurs incorrectes.
EN : Prevent the user from entering incorrect values."""
if new_value == "" :
return True
if re.match("^[0-9]+\.?[0-9]*$", new_value) is None and re.match("^[0-9]*\.?[0-9]+$", new_value) is None :
return False
new_value = float(new_value)
return new_value >= 0.0
#V
def _check_entree_cycles(new_value):
"""FR : Empêche l'utilisateur d'entrer des valeurs incorrectes.
EN : Prevent the user from entering incorrect values."""
if new_value == "" :
return True
if re.match("^[0-9]*$", new_value) is None :
return False
new_value = int(new_value)
return new_value > 0
#V
def _check_entree_string(new_value):
"""FR : Empêche l'utilisateur d'entrer des valeurs incorrectes.
EN : Prevent the user from entering incorrect values."""
if new_value == "" :
return True
if re.match("^[-A-Za-z0-9éèêëàùôÎïÉÈÊËÀÙÔÏ_ ]*$", new_value) is None :
return False
return True
#V
### Fonctions gérant le défilement
def _bound_to_mousewheel(widget, event):
"""FR : Lie le défilement de la fenêtre à la molette de la souris lorsque le curseur est sur
cette fenêtre.
EN : Binds the window's scrolling to the mousewheel when the cursor is over that window."""
widget.bind_all("<MouseWheel>", lambda e : _on_mousewheel(widget, e))
#V
def _unbound_to_mousewheel(widget, event):
"""FR : Délie le défilement de la fenêtre à la molette de la souris lorsque le curseur sort
de cette fenêtre.
EN : Binds the window's scrolling to the mousewheel when the cursor leaves that window."""
widget.unbind_all("<MouseWheel>")
#V
def _on_mousewheel(widget, event):
"""FR : Fait défiler la fenêtre avec la molette.
EN : Scrolls the window with the mousewheel."""
widget.yview_scroll(int(-1*(event.delta/80)), "units")
#V
### Fonctions servant de modificateurs aux liens CRAPPy
#TODO : variables d'étalonnage plutôt que constantes
# préciser les unités et d'autres trucs
def _card_to_pid_and_generator(dic):
"""FR : Étalonne la tension renvoyée par le capteur d'efforts.
EN : Calibrates the voltage fed back by the effort sensor."""
# global start_generator
# if start_generator :
# return
if "sortie_charge_brute" not in dic.keys() or "sortie_position_brute" not in dic.keys() :
dic["t(s)"] = time.time()
dic ["sortie_charge_brute"] = 0.0
dic["sortie_position_brute"] = 0.0
return dic
x = 2 * dic["sortie_charge_brute"]
dic[LABEL_SORTIE_EN_CHARGE] = float(etalonnage_a*(x**2) + etalonnage_b * x + etalonnage_c) / 2.0
dic[LABEL_SORTIE_EN_POSITION] = float(transformation_capteur_de_position(dic["sortie_position_brute"]))
# if dic[LABEL_SORTIE_EN_CHARGE] > (20 * COEF_TONS_TO_VOLTS) and (2 * COEF_MILLIMETERS_TO_VOLTS) < dic[LABEL_SORTIE_EN_POSITION] < (1900 * COEF_MILLIMETERS_TO_VOLTS) :
# stop_crappy()
return dic
def _gen_to_graph_charge(dic = {}):
if "consigne" not in dic.keys() :
dic["t(s)"] = time.time()
dic["consigne"] = 0.0
dic ["Consigne (T)"] = 0.0
return dic
dic["Consigne (T)"] = COEF_VOLTS_TO_TONS * dic["consigne"]
#TODO : fonction inverse de l'étalonnage
return dic
def _gen_to_graph_position(dic = {}):
if "consigne" not in dic.keys() :
dic["t(s)"] = time.time()
dic["consigne"] = 0.0
dic ["Consigne (mm)"] = 0.0
return dic
dic["Consigne (mm)"] = COEF_VOLTS_TO_MILLIMETERS * dic["consigne"]
#TODO : fonction inverse de l'étalonnage
return dic
def _card_to_recorder_and_graph(dic) :
dic = _card_to_pid_and_generator(dic)
dic["Temps (s)"] = dic["t(s)"]
dic["Charge (T)"] = 2 * dic[LABEL_SORTIE_EN_CHARGE]
dic["Position (mm)"] = COEF_VOLTS_TO_MILLIMETERS * dic[LABEL_SORTIE_EN_POSITION]
dic["Position (dm)"] = dic["Position (mm)"] /100
return dic
def _pid_to_card_charge(dic) :
if 0.03 < dic["entree_charge"] :
dic["entree_charge"] += 0.03 #0.458
else :
dic["entree_charge"] = 0
return dic
def _pid_to_card_decharge(dic) :
if -0.03 > dic["entree_decharge"] :
dic["entree_decharge"] -= 1.11 #0.525
else :
dic["entree_decharge"] = 0
dic["entree_decharge"] *= -1
return dic
def _gen_to_dashboard_charge(dic) :
if "consigne" not in dic.keys() :
dic["t(s)"] = time.time()
dic ["Consigne (T)"] = 0.0
return dic
dic["Consigne (T)"] = COEF_VOLTS_TO_TONS * dic["consigne"]
return dic
def _gen_to_dashboard_position(dic) :
if "consigne" not in dic.keys() :
dic["t(s)"] = time.time()
dic ["Consigne (mm)"] = 0.0
return dic
dic["Consigne (mm)"] = COEF_VOLTS_TO_MILLIMETERS * dic["consigne"]
return dic
def _card_to_dashboard(dic) :
global charge_max, position_max, position_min
dic = _card_to_recorder_and_graph(dic)
if dic["Charge (T)"] > charge_max :
charge_max = dic["Charge (T)"]
dic["Charge max (T)"] = charge_max
sortie_position_en_mm = dic["Position (mm)"]
if sortie_position_en_mm > position_max :
position_max = sortie_position_en_mm
dic["Position max (mm)"] = position_max
if sortie_position_en_mm < position_min :
position_min = sortie_position_en_mm
dic["Position min (mm)"] = position_min
return dic
def gen_to_multiplex(dic = None):
if "consigne" not in dic.keys() :
dic["t(s)"] = str(time.time())
dic["consigne"] = str(0.0)
return dic
### Fonctions de démarrage de Crappy
def demarrage_de_crappy_charge(consignes_generateur = None, fichier_d_enregistrement = None,
parametres_du_test = [], labels_a_enregistrer = None):
"""TODO"""
gen = crappy.blocks.Generator(path = consignes_generateur,
cmd_label = 'consigne',
spam = True,
freq = 50)
liste_des_blocs_crappy_utilises.append(gen)
carte_NI = crappy.blocks.IOBlock(name = "Nidaqmx",
labels = ["t(s)", "sortie_charge_brute",
"sortie_position_brute"],
cmd_labels = ["entree_decharge", "entree_charge"],
initial_cmd = [0.0, 0.0],
exit_values = [0.0, 0.0],
channels=[{'name': 'Dev3/ao0'},
{'name': 'Dev3/ao1'},
{'name': 'Dev3/ai6'},
{'name': 'Dev3/ai7'}],
spam=True,
freq = 50)
liste_des_blocs_crappy_utilises.append(carte_NI)
pid_charge = custom_pid.PID(kp=1,
ki=0.01,
kd=0.1,
out_max=5,
out_min=-5,
i_limit=0.5,
input_label = LABEL_SORTIE_EN_CHARGE,
target_label = 'consigne',
labels = ["t(s)", 'entree_charge'],
freq = 50)
liste_des_blocs_crappy_utilises.append(pid_charge)
pid_decharge = custom_pid.PID(kp=0.3,
ki=0.01,
kd=0.1,
out_max=5,
out_min=-5,
i_limit=0.5,
target_label = 'consigne',
labels = ["t(s)", 'entree_decharge'],
input_label = LABEL_SORTIE_EN_CHARGE,
freq = 50)
liste_des_blocs_crappy_utilises.append(pid_decharge)
y_charge = crappy.blocks.Multiplex(freq = 50)
liste_des_blocs_crappy_utilises.append(y_charge)
y_decharge = crappy.blocks.Multiplex(freq = 50)
liste_des_blocs_crappy_utilises.append(y_decharge)
graphe = custom_grapher.EmbeddedGrapher(("Temps (s)", "Consigne (T)"),
("Temps (s)", "Charge (T)"),
("Temps (s)", "Position (dm)"),
freq = 3)
liste_des_blocs_crappy_utilises.append(graphe)
y_record = crappy.blocks.Multiplex(freq = 50)
liste_des_blocs_crappy_utilises.append(y_record)
y_dashboard = crappy.blocks.Multiplex(freq = 50)
liste_des_blocs_crappy_utilises.append(y_dashboard)
pancarte = custom_dashboard.Dashboard(labels = ["Temps (s)", "Consigne (T)", "Position (mm)",
"Charge (T)", "Charge max (T)",
"Position min (mm)", "Position max (mm)"],
freq = 5)
liste_des_blocs_crappy_utilises.append(pancarte)
affichage_secondaire = custom_dashboard.Dashboard(labels = ["Temps (s)", "Consigne (T)", "Position (mm)",
"Charge (T)", "Charge max (T)",
"Position min (mm)", "Position max (mm)"],
is_primary = False,
freq = 5)
liste_des_blocs_crappy_utilises.append(affichage_secondaire)
if fichier_d_enregistrement is not None :
record = custom_recorder.CustomRecorder(filename = fichier_d_enregistrement,
labels = labels_a_enregistrer,
parametres_a_inscrire = parametres_du_test)
liste_des_blocs_crappy_utilises.append(record)
crappy.link(gen, y_charge, modifier = gen_to_multiplex)
crappy.link(gen, y_decharge, modifier = gen_to_multiplex)
crappy.link(carte_NI, y_charge, modifier=_card_to_pid_and_generator)
crappy.link(carte_NI, y_decharge, modifier=_card_to_pid_and_generator)
crappy.link(y_charge, pid_charge)
crappy.link(y_decharge, pid_decharge)
crappy.link(pid_charge, carte_NI, modifier=_pid_to_card_charge)
crappy.link(pid_decharge, carte_NI, modifier=_pid_to_card_decharge)
crappy.link(carte_NI, gen, modifier=_card_to_pid_and_generator)
crappy.link(gen, y_record, modifier = _gen_to_graph_charge)
crappy.link(pid_charge, y_record, modifier=_pid_to_card_charge)
crappy.link(pid_decharge, y_record, modifier=_pid_to_card_decharge)
crappy.link(carte_NI, y_record, modifier = _card_to_recorder_and_graph)
# [_card_to_recorder_and_graph,
# crappy.modifier.Diff(label = LABEL_SORTIE_EN_CHARGE,
# out_label = "derivee_voltage")])
if fichier_d_enregistrement is not None :
crappy.link(y_record, record)
crappy.link(carte_NI, graphe, modifier=_card_to_recorder_and_graph)
crappy.link(gen, graphe, modifier=_gen_to_graph_charge)
crappy.link(gen, y_dashboard, modifier = _gen_to_dashboard_charge)
crappy.link(carte_NI, y_dashboard, modifier = _card_to_dashboard)
crappy.link(y_dashboard, pancarte)
crappy.link(y_dashboard, affichage_secondaire)
crappy.start()
crappy.reset()
def demarrage_de_crappy_deplacement(consignes_generateur = None, fichier_d_enregistrement = None,
parametres_du_test = [], labels_a_enregistrer = None):
"""TODO"""
gen = crappy.blocks.Generator(path = consignes_generateur,
cmd_label = 'consigne',
spam = True,
freq = 50)
liste_des_blocs_crappy_utilises.append(gen)
carte_NI = crappy.blocks.IOBlock(name = "Nidaqmx",
labels = ["t(s)", "sortie_charge_brute",
"sortie_position_brute"],
cmd_labels = ["entree_decharge", "entree_charge"],
initial_cmd = [0.0, 0.0],
exit_values = [0.0, 0.0],
channels = [{'name': 'Dev3/ao0'},
{'name': 'Dev3/ao1'},
{'name': 'Dev3/ai6'},
{'name': 'Dev3/ai7'}],
spam = True,
freq = 50)
liste_des_blocs_crappy_utilises.append(carte_NI)
pid_charge = custom_pid.PID(kp=1,
ki=0.01,
kd=0.01,
out_max=5,
out_min=-5,
i_limit=0.5,
input_label = LABEL_SORTIE_EN_POSITION,
target_label = 'consigne',
labels = ["t(s)", 'entree_charge'],
freq = 50)
liste_des_blocs_crappy_utilises.append(pid_charge)
pid_decharge = custom_pid.PID(kp=0.5,
ki=0.0,
kd=0.0,
out_max=5,
out_min=-5,
i_limit=0.5,
target_label = 'consigne',
labels = ["t(s)", 'entree_decharge'],
input_label = LABEL_SORTIE_EN_POSITION,
freq = 50)
liste_des_blocs_crappy_utilises.append(pid_decharge)
y_charge = crappy.blocks.Multiplex(freq = 50)
# y_charge = customblocks.YBlock(out_labels = ["t(s)", "consigne", LABEL_SORTIE_EN_POSITION],
# freq = 50)
liste_des_blocs_crappy_utilises.append(y_charge)
y_decharge = crappy.blocks.Multiplex(freq = 50)
# y_decharge = customblocks.YBlock(out_labels = ["t(s)", "consigne", LABEL_SORTIE_EN_POSITION],
# freq = 50)
liste_des_blocs_crappy_utilises.append(y_decharge)
graphe = custom_grapher.EmbeddedGrapher(("Temps (s)", "consigne"),
("Temps (s)", "Charge (T)"),
("Temps (s)", "Position (dm)"),
freq = 3)
liste_des_blocs_crappy_utilises.append(graphe)
y_record = crappy.blocks.Multiplex(freq = 50)
liste_des_blocs_crappy_utilises.append(y_record)
y_dashboard = crappy.blocks.Multiplex(freq = 50)
liste_des_blocs_crappy_utilises.append(y_record)
pancarte = custom_dashboard.Dashboard(labels = ["Temps (s)", "Consigne (mm)", "Position (mm)",
"Charge (T)", "Charge max (T)",
"Position min (mm)", "Position max (mm)"],
freq = 5)
liste_des_blocs_crappy_utilises.append(pancarte)
affichage_secondaire = custom_dashboard.Dashboard(labels = ["Temps (s)", "Consigne (mm)", "Position (mm)",
"Charge (T)", "Charge max (T)",
"Position min (mm)", "Position max (mm)"],
is_primary = False,
freq = 5)
liste_des_blocs_crappy_utilises.append(affichage_secondaire)
if fichier_d_enregistrement is not None :
record = custom_recorder.CustomRecorder(filename = fichier_d_enregistrement,
labels = labels_a_enregistrer,
parametres_a_inscrire = parametres_du_test)
liste_des_blocs_crappy_utilises.append(record)
crappy.link(gen, y_charge)
crappy.link(gen, y_decharge)
crappy.link(carte_NI, y_charge, modifier=_card_to_pid_and_generator)
crappy.link(carte_NI, y_decharge, modifier=_card_to_pid_and_generator)
crappy.link(y_charge, pid_charge)
crappy.link(y_decharge, pid_decharge)
crappy.link(pid_charge, carte_NI, modifier=_pid_to_card_charge)
crappy.link(pid_decharge, carte_NI, modifier=_pid_to_card_decharge)
crappy.link(carte_NI, gen, modifier=_card_to_pid_and_generator)
crappy.link(gen, y_record, modifier = _gen_to_graph_position) #
crappy.link(pid_charge, y_record, modifier=_pid_to_card_charge)
crappy.link(pid_decharge, y_record, modifier=_pid_to_card_decharge)
crappy.link(carte_NI, y_record, modifier = _card_to_recorder_and_graph) #
# [_card_to_recorder_and_graph,
# crappy.modifier.Diff(label = LABEL_SORTIE_EN_POSITION,
# out_label = "derivee_voltage")])
if fichier_d_enregistrement is not None :
crappy.link(y_record, record)
crappy.link(carte_NI, graphe, modifier=_card_to_recorder_and_graph)
crappy.link(gen, graphe, modifier=_gen_to_graph_position)
crappy.link(gen, y_dashboard, modifier = _gen_to_dashboard_position) #
crappy.link(carte_NI, y_dashboard, modifier = _card_to_dashboard) #
crappy.link(y_dashboard, pancarte)
crappy.link(y_dashboard, affichage_secondaire)
crappy.start()
crappy.reset()
def gen_to_card_RaZ_et_MeT(dic):
dic["entree_decharge"] = -dic["consigne"] if dic["consigne"] < 0 else 0
dic["entree_charge"] = dic["consigne"] if dic["consigne"] > 0 else 0
return dic
### Fake_machine
def carte_to_gen(dic):
dic[LABEL_SORTIE_EN_POSITION] = 2 * dic["F(N)"] / 9.807 / 1000
# if dic[LABEL_SORTIE_EN_POSITION] > 2 :
# stop_crappy()
# dic[LABEL_SORTIE_EN_POSITION] = "safeguard"
return dic
def carte_to_pid(dic):
dic[LABEL_SORTIE_EN_POSITION] = dic["F(N)"] / 9.807 / 1000
# print(dic[LABEL_SORTIE_EN_POSITION])
return dic
def plastic(v: float, yield_strain: float = .005, rate: float = .02) -> float:
if v > yield_strain:
return ((v - yield_strain) ** 2 + rate ** 2) ** .5 - rate
return 0
def demarrage_de_crappy_fake_machine(consignes_generateur = None, fichier_d_enregistrement = None,
parametres_du_test = [], labels_a_enregistrer = None):
carte_NI = crappy.blocks.Fake_machine(k = 10000*450,
l0 = 4000,
maxstrain = 7,
nu = 0.5,
max_speed = 100,
mode = 'speed',
cmd_label = "entree_charge",
plastic_law = plastic)
liste_des_blocs_crappy_utilises.append(carte_NI)
pid_charge = custom_pid.PID(kp=1,
ki=0.0,
kd=0.0,
out_max=5,
out_min=-5,
i_limit=0.5,
target_label = "consigne",
labels = ["t(s)", 'entree_charge'],
input_label = LABEL_SORTIE_EN_POSITION,
freq = 50)
liste_des_blocs_crappy_utilises.append(pid_charge)
graphe = custom_grapher.EmbeddedGrapher(("t(s)", "consigne"),
("t(s)", LABEL_SORTIE_EN_POSITION),
freq = 3)
liste_des_blocs_crappy_utilises.append(graphe)
y_charge = crappy.blocks.Multiplex(freq = 50)
liste_des_blocs_crappy_utilises.append(y_charge)
y_record = crappy.blocks.Multiplex(freq = 50)
liste_des_blocs_crappy_utilises.append(y_record)
if fichier_d_enregistrement is not None :
record = custom_recorder.CustomRecorder(filename = fichier_d_enregistrement,
labels = ["t(s)",
"x(mm)",
"F(N)",
"entree_charge"],
parametres_a_inscrire = parametres_du_test)
liste_des_blocs_crappy_utilises.append(record)
pancarte = custom_dashboard.Dashboard(labels = ["t(s)", "F(N)", LABEL_SORTIE_EN_POSITION],
is_primary = False,
freq = 5)
liste_des_blocs_crappy_utilises.append(pancarte)
gen = crappy.blocks.Generator(path = consignes_generateur,
cmd_label = 'consigne',
spam = True,
freq = 50)
liste_des_blocs_crappy_utilises.append(gen)
crappy.link(gen, y_charge)
crappy.link(carte_NI, y_charge, modifier = carte_to_gen)
crappy.link(y_charge, pid_charge)
crappy.link(pid_charge, carte_NI)
crappy.link(carte_NI, gen, modifier = carte_to_gen)
crappy.link(pid_charge, y_record)
crappy.link(carte_NI, y_record)
if fichier_d_enregistrement is not None :
crappy.link(y_record, record)
crappy.link(carte_NI, graphe, modifier = carte_to_pid)
crappy.link(gen, graphe)
crappy.link(y_record, pancarte)
crappy.start()
crappy.reset()
def transformation_capteur_de_position(x):
#TODO : constantes WTF
#convertion tension lue par le capteur ultrason -> tension étalonnée pour ne pas dépasser les valeurs limites en distance
return (x-2.18)*5/4.08
def desactiver_bouton(btn):
"""FR : Désactive le bouton.
EN : Deactivate the button."""
btn["state"] = "disabled"
#V
def activer_bouton(btn):
"""FR : Active le bouton.
EN : Activate the button."""
btn["state"] = "normal"
#V
def modification_du_mot_de_passe(parent):
"""FR : Fenêtre de changement du mot de passe.
EN : Password change window."""
def enregistrer_mot_de_passe():
"""FR : Enregistre le nouveau mot de passe dans un fichier de config prédéfini.
EN : Saves the new password in a predefined config file."""
ecriture_donnee('mdp_liste.txt', mdp_val.get())
fen_mdp.destroy()
fen_mdp=Toplevel(parent)
fen_mdp.lift()
mdp_val=StringVar()
Label(fen_mdp, text="Choisissez le nouveau mot de passe").grid(row=1,column=0,padx =10, pady =10)
password_entry = Entry(fen_mdp, textvariable=mdp_val, width=30)
password_entry.grid(row=1,column=1,padx =10, pady =10)
password_entry.focus()
Button(fen_mdp, text='Retour', command=fen_mdp.destroy).grid(row=4,column=0,padx =10, pady =10)
Button(fen_mdp, text='Enregistrer', command=enregistrer_mot_de_passe).grid(row=4,column=1,padx =10, pady =10)
#V
def modification_des_chemins_d_acces(parent):
"""FR : Fenêtre de choix du dossier d'enregistrement et du chemin d'accès au
manuel du banc.
EN : Saved files' directory and bench's manual access path choice window."""
def chemin_suivant() :
"""FR : Enregistre les chemins dans un fichier de config prédéfini.
EN : Saves the paths in a predefined config file."""
ecriture_donnee('chemin_enre.txt', chemin_enre.get())
ecriture_donnee('chemin_manuel.txt', chemin_aide.get())
ecriture_donnee('nom_manuel.txt', nom_manuel.get())
fen_chem.destroy()
fen_chem=Toplevel(parent)
chemin_enre=StringVar()
chemin_aide=StringVar()
nom_manuel=StringVar()
chemin_enre.set(lecture_donnee(DOSSIER_CONFIG_ET_CONSIGNES + 'chemin_enre.txt'))
chemin_aide.set(lecture_donnee(DOSSIER_CONFIG_ET_CONSIGNES + 'chemin_manuel.txt'))
nom_manuel.set(lecture_donnee(DOSSIER_CONFIG_ET_CONSIGNES + 'nom_manuel.txt'))
Label(fen_chem, text="Choisissez le chemin des documents enregistrés").grid(row=1,column=0,padx =10, pady =10)
Entry(fen_chem, textvariable=chemin_enre, width=100).grid(row=1,column=1,padx =10, pady =10)
Label(fen_chem, text="Choisissez le chemin du manuel d'aide").grid(row=2,column=0,padx =10, pady =10)
Entry(fen_chem, textvariable=chemin_aide, width=100).grid(row=2,column=1,padx =10, pady =10)
Label(fen_chem, text="Choisissez le nom du manuel d'aide (ne pas oublier le .docx ou le .pdf)").grid(row=3,column=0,padx =10, pady =10)
Entry(fen_chem, textvariable=nom_manuel, width=100).grid(row=3,column=1,padx =10, pady =10)
Button(fen_chem, text='Retour',command=fen_chem.destroy).grid(row=4,column=0,padx =10, pady =10)
Button(fen_chem, text='Enregistrer',command=chemin_suivant).grid(row=4,column=1,padx =10, pady =10)
#V
def modification_des_PID(parent):
"""FR : Fenêtre de choix des valeurs PID.
EN : PID's values' choice window."""
def validation_des_nouveaux_PID():
"""FR : Enregistre les valeurs des PID dans un fichier de config prédéfini.
EN : Saves the PID's values in a predefined config file."""
dic_PID ={}
dic_PID["charge_P"] = charge_P.get()
dic_PID["charge_I"] = charge_I.get()
dic_PID["charge_D"] = charge_D.get()
dic_PID["decharge_P"] = decharge_P.get()
dic_PID["decharge_I"] = decharge_I.get()
dic_PID["decharge_D"] = decharge_D.get()
if type_de_materiau.get() == 0 :
fichier_des_PID = DOSSIER_CONFIG_ET_CONSIGNES + "pid_mou.json"
else :
fichier_des_PID = DOSSIER_CONFIG_ET_CONSIGNES + "pid_rigide.json"
with open(fichier_des_PID, 'w') as f :
dump(dic_PID, f)
fenetre_de_modification_des_PID.destroy()
#V
def valeurs_actuelles_des_PID():
"""FR : Affiche les valeurs de PID correspondantes au type de matériau choisi.
EN : Prints the PID's values corresponding to the chosen material's type."""
if type_de_materiau.get() == 0 :
with open(DOSSIER_CONFIG_ET_CONSIGNES + "pid_mou.json", 'r') as fichier_PID :
dic_PID = load (fichier_PID)
else :
with open(DOSSIER_CONFIG_ET_CONSIGNES + "pid_rigide.json", 'r') as fichier_PID :
dic_PID = load (fichier_PID)
charge_P.set(dic_PID["charge_P"])
charge_I.set(dic_PID["charge_I"])
charge_D.set(dic_PID["charge_D"])
decharge_P.set(dic_PID["decharge_P"])
decharge_I.set(dic_PID["decharge_I"])
decharge_D.set(dic_PID["decharge_D"])
#V
fenetre_de_modification_des_PID = Toplevel(parent)
type_de_materiau = IntVar()
charge_P = DoubleVar()
charge_I = DoubleVar()
charge_D = DoubleVar()
decharge_P = DoubleVar()
decharge_I = DoubleVar()
decharge_D = DoubleVar()
dic_PID = {}
with open(DOSSIER_CONFIG_ET_CONSIGNES + "pid_mou.json", 'r') as fichier_PID :
dic_PID = load (fichier_PID)
charge_P.set(dic_PID["charge_P"])
charge_I.set(dic_PID["charge_I"])
charge_D.set(dic_PID["charge_D"])
decharge_P.set(dic_PID["decharge_P"])
decharge_I.set(dic_PID["decharge_I"])
decharge_D.set(dic_PID["decharge_D"])
Radiobutton(fenetre_de_modification_des_PID, text = "PID des matériaux mou", variable = type_de_materiau, value = 0, command = valeurs_actuelles_des_PID).grid(row = 0, column = 0, columnspan = 6, sticky = "w", padx = 5, pady = 5)
Radiobutton(fenetre_de_modification_des_PID, text = "PID des matériaux rigide", variable = type_de_materiau, value = 1, command = valeurs_actuelles_des_PID).grid(row = 1, column = 0, columnspan = 6, sticky = "w", padx = 5, pady = 5)
Label(fenetre_de_modification_des_PID, text = "PID de charge").grid(row = 4, column = 0, padx = 5, pady = 5)
Label(fenetre_de_modification_des_PID, text = "P").grid(row = 5, column = 1, padx = 5, pady = 5)
Entry(fenetre_de_modification_des_PID, textvariable = charge_P, width = 5, validate = "key", validatecommand = (fenetre_de_modification_des_PID.register(_check_entree_float), '%P')).grid(row = 5, column = 2, padx = 5, pady = 5)
Label(fenetre_de_modification_des_PID, text = "I").grid(row = 5, column = 3, padx = 5, pady = 5)
Entry(fenetre_de_modification_des_PID, textvariable = charge_I, width = 5, validate = "key", validatecommand = (fenetre_de_modification_des_PID.register(_check_entree_float), '%P')).grid(row = 5, column = 4, padx = 5, pady = 5)
Label(fenetre_de_modification_des_PID, text = "D").grid(row = 5, column = 5, padx = 5, pady = 5)
Entry(fenetre_de_modification_des_PID, textvariable = charge_D, width = 5, validate = "key", validatecommand = (fenetre_de_modification_des_PID.register(_check_entree_float), '%P')).grid(row = 5, column = 6, padx = 5, pady = 5)
Label(fenetre_de_modification_des_PID, text = "PID de charge").grid(row = 6, column = 0, padx = 5, pady = 5)
Label(fenetre_de_modification_des_PID, text = "P").grid(row = 7, column = 1, padx = 5, pady = 5)
Entry(fenetre_de_modification_des_PID, textvariable = decharge_P, width = 5, validate = "key", validatecommand = (fenetre_de_modification_des_PID.register(_check_entree_float), '%P')).grid(row = 7, column = 2, padx = 5, pady = 5)
Label(fenetre_de_modification_des_PID, text = "I").grid(row = 7, column = 3, padx = 5, pady = 5)
Entry(fenetre_de_modification_des_PID, textvariable = decharge_I, width = 5, validate = "key", validatecommand = (fenetre_de_modification_des_PID.register(_check_entree_float), '%P')).grid(row = 7, column = 4, padx = 5, pady = 5)
Label(fenetre_de_modification_des_PID, text = "D").grid(row = 7, column = 5, padx = 5, pady = 5)
Entry(fenetre_de_modification_des_PID, textvariable = decharge_D, width = 5, validate = "key", validatecommand = (fenetre_de_modification_des_PID.register(_check_entree_float), '%P')).grid(row = 7, column = 6, padx = 5, pady = 5)
Button(fenetre_de_modification_des_PID, text = "Retour", command = fenetre_de_modification_des_PID.destroy).grid(row = 8, column = 0, columnspan = 3, padx = 5, pady = 5)
Button(fenetre_de_modification_des_PID, text = "Valider", command = validation_des_nouveaux_PID).grid(row = 8, column = 4, columnspan = 3, padx = 5, pady = 5)
with open(DOSSIER_CONFIG_ET_CONSIGNES + "pid_personnalise.json", 'r') as fichier_PID :
dic_PID = load (fichier_PID)
#V
def demarrage_du_programme() :
"""FR : Fenêtre de choix du mode. Est lancée au début du programme.
EN : Mode choice window. Is launched at the start of the program."""
def utilisation_pour_R_et_D():
#TODO : lock buttons from fenetre1 at creation and unlock them when this window
# is closed through any mean other than the validation of the password.
# IDEA : use withdraw on the first window.
"""FR: Lance le mode R&D protégé par un mot de passe.
EN : Launches the R&D mode protected by a password."""
def verification_mot_de_passe ():
"""FR : Vérifie le mot de passe.
EN : Verifies the password."""
global verrou_production
verrou_production = OFF
if mot_de_passe.get() == lecture_donnee(DOSSIER_CONFIG_ET_CONSIGNES + 'mdp_liste.txt') :
fenetre1.destroy()
return fonction_principale()
else :
showinfo(title='Échec', message='Mot de passe incorrect')
mot_de_passe = StringVar()
fenetre_mdp=Toplevel(fenetre1)
Label(fenetre_mdp, text = 'mot de passe').grid(row=0, column=0, padx =20, pady =10)
entree_mot_de_passe = Entry(fenetre_mdp,textvariable=mot_de_passe,show='*', width=30)
entree_mot_de_passe.grid(row=0, column=1, padx =20, pady =10)
entree_mot_de_passe.focus_force()
Button(fenetre_mdp,text="Valider",command=verification_mot_de_passe).grid(row=1, column=1,padx =0, pady =10)
Button(fenetre_mdp,text='Quitter', command=fenetre_mdp.destroy).grid(row=1, column=0,padx =0, pady =10)
#PV facultatif
def utilisation_pour_production():
"""FR : Lance le mode Production.
EN : Launches the Production mode."""
global verrou_production
verrou_production = ON
fenetre1.destroy()
return fonction_principale()
#V
fenetre1 = Tk()
fenetre1.title("Sélection du mode")
Label(fenetre1, text = "Veuillez sélectionner le mode d'utilisation",justify = CENTER).grid(row=0, column=0, padx =20, pady =10,columnspan=2)
R_et_D_btn=Button(fenetre1,text="R&D",command=utilisation_pour_R_et_D)
prod_btn=Button(fenetre1, text='Production', command=utilisation_pour_production)
#TODO : tooltips. Tix has been deprecated for years.
# bal = tix.Balloon(fenetre1)
# bal.bind_widget(R_et_D_btn, msg="Cliquez ici pour effectuer tous types de tests (Attention : les sécurités sont désactivées)")
# bal.bind_widget(prod_btn, msg="Cliquez ici pour effectuer un préétirage")
R_et_D_btn.grid(row=1, column=0,padx =0, pady =10 )
prod_btn.grid(row=1, column=1,padx =0, pady =10 )
#TODO : tearoff's removal should be globalized
menubar = Menu(fenetre1)
aide= Menu(menubar, tearoff=0)
aide.add_command(label="Afficher la documentation",command=RTM_protocol)
menubar.add_cascade(label="Aide", menu=aide)
fenetre1.configure(menu=menubar)
fenetre1.mainloop()
#PV obligatoire (tix)
def configuration_initiale (init_titre, init_nom,
init_materiau, init_lg_banc, init_charge_rupt, init_diam_a_vide,
init_accroche, init_epissage, init_cabestan, init_lg_utile, init_type_d_asservissement) :
"""FR : Fenêtre de configuration des valeurs initiales de l'essai.
EN : Test's initial values configuration window."""
def retour_au_choix_de_mode():
"""FR : Retourne à la fenêtre du choix de mode.
EN : Gets back to the mode choice window."""
global verrou_production
fenetre_des_entrees.destroy()
verrou_production = RESTART
#V
def validation_des_entrees() :
nonlocal dic_PID
if choix_PID.get() == 2 :
with open(DOSSIER_CONFIG_ET_CONSIGNES + "pid_personalise.json", 'w') as fichier_PID_perso :
dump (dic_PID, fichier_PID_perso)
fenetre_des_entrees.destroy()
def diam_cabestan(afficher):
###affiche la valeur du diamètre de cabestan si la case est cochée
if afficher :
Label(cadre_choix_type_d_accroche,text="Diamètre cabestan (mm)").grid(row=15,column=0,padx =10, pady =10)
Entry(cadre_choix_type_d_accroche, textvariable=diametre_du_cabestan, width=10).grid(row=15,column=1,padx =10, pady =10)
else :
for widget in cadre_choix_type_d_accroche.winfo_children()[-2:] :
widget.destroy()
#PV facultatif
def iso_quai():
# Is okay
""" """
if is_test_iso.get() :
Label( cordage_label, text = "Cordage épissé").grid(row = 1, column = 0, padx =10, pady =10)
Radiobutton(cordage_label, text="Oui", variable=est_episse, value=True).grid(row = 1, column = 1, padx = 5, pady = 5)
Radiobutton(cordage_label, text="Non", variable=est_episse, value=False).grid(row = 1, column = 2,padx = 5, pady = 5)
Label(cordage_label, text = "Numéro de référence").grid(row = 3, column = 0, padx = 5, pady = 5)
Entry(cordage_label, textvariable=diametre_a_vide, width=10).grid(row = 3, column = 2 ,padx = 5, pady = 5)
else :
for widget in cordage_label.winfo_children()[1:] :
widget.destroy()
#PV facultatif