-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpyfopidopt.py
960 lines (836 loc) · 40.8 KB
/
pyfopidopt.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
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from addict import Dict
import socket
import time, traceback
import fofopdtpidTuner as fofopdtTune
from pyGui.fomconoptimizegui import *
#gui
from pyGui import fopidoptgui, createnewfofopdtgui
#Constants
fofopdtModel = dict(K = 66.16, L = 1.93, T = 12.72, alpha = 0.5)
oustaloopModel = dict(wb = 0.0001,wh = 10000, N = 5,)
ALPHA_MIN,ALPHA_MAX,MAX_LAMBDA,MIN_COEF,MAX_COEF = 0.001,2,5,float('-inf'),float('inf')
MIN_EXPO,MAX_EXPO,MAX_ITER,MAX_DT,MIN_DT = 0.0001,5,50,0.99, 0.01
MAX_GAINMARGIN,MAX_PHASEMARGIN,MAX_SIM_TIME,STATUSBAR_TIME = 20,359,3600,7000
MIN_PORT,MAX_PORT = 1081, 65535
class fofopdtguiclass(QMainWindow, fopidoptgui.Ui_FOPIDOPT):
def __init__(self,guilock=None):
QMainWindow.__init__(self)
fopidoptgui.Ui_FOPIDOPT.__init__(self)
self.setupUi(self)
self.setWindowIcon(QIcon('index.png'))
self.comboBoxFOFOPDTSYS.currentIndexChanged.connect(self._comboBoxFOFOPDTSYSEmpty)
self.lineEdit_StartFreq.textChanged.connect(self._OustaStartFreqChanged)
self.lineEdit_StopFreq.textChanged.connect(self._OustaStopFreqChanged)
self.lineEditOrder.textChanged.connect(self._OustaOrderChanged)
self.pushButtonAddData.clicked.connect(self._addData)
self.pushButtonEditData.clicked.connect(self._edit)
self.pushButtonDeleteData.clicked.connect(self._deleteData)
self.pushButtonTune.clicked.connect(self._tune)
self.comboBoxTuneOption.currentIndexChanged.connect(self._TuneOptionChanged)
# self.lineEdit_Kp.event.connect(self._KpChanged)
self.lineEdit_Kp.textChanged.connect(self._KpChanged)
self.lineEditConstMinKp.textChanged.connect(self._KpChanged)
self.lineEditConstMaxKp.textChanged.connect(self._KpChanged)
self.lineEdit_Ki.textChanged.connect(self._KiChanged)
self.lineEditConstMinKi.textChanged.connect(self._KiChanged)
self.lineEditConstMaxKi.textChanged.connect(self._KiChanged)
self.lineEdit_Kd.textChanged.connect(self._KdChanged)
self.lineEditConstMinKd.textChanged.connect(self._KdChanged)
self.lineEditConstMaxKd.textChanged.connect(self._KdChanged)
self.lineEdit_Lam.textChanged.connect(self._LamdaChanged)
self.lineEditConstMinlam.textChanged.connect(self._LamdaChanged)
self.lineEditConstMaxlam.textChanged.connect(self._LamdaChanged)
self.lineEdit_Mu.textChanged.connect(self._MuChanged)
self.lineEditConstMinMu.textChanged.connect(self._MuChanged)
self.lineEditConstMaxMu.textChanged.connect(self._MuChanged)
self.pushButtonSetParams.clicked.connect(self._setParams)
self.lineEditParamsValue.textChanged.connect(self._paramValueChanged)
self.lineEditIter.textChanged.connect(self._iterChanged)
self.lineEditDt.textChanged.connect(self._dtChanged)
self.lineEditTankSimTime.textChanged.connect(self._simTimeChanged)
self.lineEditCritFrequency.textChanged.connect(self._criticalFrequencyChanged)
self.lineEditPhaseMargin.textChanged.connect(self._phaseMargChanged)
self._isLamdaOk=self._isMuOk = self._isKdOk = self._isKiOk = self._isKpOk = True
self._isOustaStartFreq = self._isOustaStopFreqOK = self._isOustaOrderOk =True
self._isIterOk = self._isDtOk = self._isCriticalFreqOk = self._isPhaseMargOk = self._isSimeTimeOk = True
self.comboFOFOPDTOk = False
#TankControl Checkers and Buttons
self.pushButtonTestControl.clicked.connect(self._TestControl)
self.pushButtonStartCom.clicked.connect(self.startNetContrl)
self.pushButtonStopCom.clicked.connect(self.stopNetContrl)
self.pushButtonUpdateTime.clicked.connect(self.updateTime)
self.lineEditRecieveIP.textChanged.connect(self._ipRecChanged)
self.lineEditRecievePort.textChanged.connect(self._recPortChanged)
self.lineEditSendIP.textChanged.connect(self._ipSendChanged)
self.lineEditSendPort.textChanged.connect(self._ipSendChanged)
self.pushButtonToServer.clicked.connect(self._updateFOPIDServer)
self.lineEditSendIPFOPIDContr.textChanged.connect(self._ipControlChanged)
self.lineEditSendPortFOPIDContr.textChanged.connect(self._recvPortControlChanged)
self.pushButtonExitServer.clicked.connect(self._exitServer)
self._isPortRecvOk = self._isPortSendOk = self._isIPRecOk = \
self._isIPSendOk = self._isIPControlOk = self._isPortControlOk =True
self._reloadAllFOTransFunc()
self.lock = guilock
self.show()
#region Initialization Functions
def _reloadAllFOTransFunc(self):
# Startup Config
fix = { 'Gains': [self.lineEdit_Kp, self.lineEdit_Ki, self.lineEdit_Kd]}
#,'Exponenets': [self.lineEdit_Lam, self.lineEdit_Mu]
#,'Gains & Expo': [self.lineEdit_Kp, self.lineEdit_Ki, self.lineEdit_Kd, self.lineEdit_Lam, self.lineEdit_Mu]}
algo = {"Tune Coefficient": optFix.Exp}#, "Tune All Parameters": optFix.Free, "Tune Exponents": optFix.Coeff}
# method = {"Grunwald Letnikov": simMethod.grunwaldLetnikov, "Oustaloop": simMethod.oustaloop}
method = {"Oustaloop": simMethod.oustaloop}
for i in fix:
self.comboBoxParamSetOption.addItem(i, fix[i])
for i in algo:
self.comboBoxTuneOption.addItem(i, algo[i])
for i in method:
self.comboBoxApproxFilter.addItem(i, method[i])
self.comboBoxParamSetOption.setCurrentIndex(0)
self.groupBoxFOPIDParams.setChecked(False)
self.groupBoxSimParams.setChecked(False)
self.groupBoxGainPhaseMargin.setChecked(False)
self.groupBoxTankControl.setChecked(False)
#endregion
#region Exception Handling, See fotf.py and pyfomcon.py for example
def _ShowError(self, message, obj=None, obj2=None):
try:
if self.isDialogActive is False:
self.isDialogActive = True
if obj is not None:
obj.setCursorPosition(0)
obj.setSelection(0, len(obj.text()))
self.statusbar.showMessage('Error: ' + message, STATUSBAR_TIME)
raise ValueError(
QMessageBox.question(QWidget, 'Error', message, QMessageBox.StandardButtons(QMessageBox.Ok)))
except Exception as excep:
self.isDialogActive = False
print("\nError occured @ fofopdtguiclass._ShowError\n")
print(type(excep))
#region Button Checks
def _OustaStartFreqChanged(self):
try:
x = int(self.lineEdit_StartFreq.text())
if x < 0:
self._isOustaStartFreq = True
else:
self._isOustaStartFreq = False
self._ok2Tune()
except:
self._isOustaStartFreq = False
def _OustaStopFreqChanged(self):
try:
x = int(self.lineEdit_StopFreq.text())
if x > 0:
self._isOustaStopFreqOK = True
else:
self._isOustaStopFreqOK = False
self._ok2Tune()
except:
self._isOustaStopFreqOK = False
def _OustaOrderChanged(self):
try:
x = int(self.lineEditOrder.text())
if 0 < x < fofopdtTune.NMAX:
self._isOustaOrderOk = True
else:
self._isOustaOrderOk = False
self._ok2Tune()
except:
self._isOustaOrderOk = False
def _paramValueChanged(self):
try:
x = self.lineEditParamsValue.text()
if ALPHA_MIN <= float(x) <= ALPHA_MAX and self.groupBoxFOPIDParams.isChecked():
self.pushButtonSetParams.setEnabled(True)
else:
self.pushButtonSetParams.setEnabled(False)
self.statusbar.showMessage('{2} is out of range range: {0} <= x <= {1}'.format(ALPHA_MIN,ALPHA_MAX, x), STATUSBAR_TIME)
print('{2} is out of range range: {0} <= x <= {1}'.format(ALPHA_MIN,ALPHA_MAX, x))
except:
self.pushButtonSetParams.setEnabled(False)
self.statusbar.showMessage('fofopdtguiclass._qChanged:{2} is out of range range: {0} <= x <= {1}'.format(ALPHA_MIN, ALPHA_MAX, x), STATUSBAR_TIME)
print('fofopdtguiclass._qChanged:{2} is out of range range: {0} <= x <= {1}'.format(ALPHA_MIN,ALPHA_MAX, x))
def _TuneOptionChanged(self):
currentTuneSettings = self.comboBoxTuneOption.currentData()
if currentTuneSettings is optFix.Exp :
self.lineEdit_Kp.setEnabled(True)
self.lineEditConstMinKp.setEnabled(True)
self.lineEditConstMaxKp.setEnabled(True)
self.lineEdit_Ki.setEnabled(True)
self.lineEditConstMinKi.setEnabled(True)
self.lineEditConstMaxKi.setEnabled(True)
self.lineEdit_Kd.setEnabled(True)
self.lineEditConstMinKd.setEnabled(True)
self.lineEditConstMaxKd.setEnabled(True)
self.lineEdit_Lam.setEnabled(True)
self.lineEditConstMinlam.setEnabled(True)
self.lineEditConstMaxlam.setEnabled(True)
self.lineEdit_Mu.setEnabled(True)
self.lineEditConstMinMu.setEnabled(True)
self.lineEditConstMaxMu.setEnabled(True)
elif currentTuneSettings is optFix.Coeff:
self.lineEdit_Kp.setEnabled(True)
self.lineEditConstMinKp.setEnabled(True)
self.lineEditConstMaxKp.setEnabled(True)
self.lineEdit_Ki.setEnabled(True)
self.lineEditConstMinKi.setEnabled(True)
self.lineEditConstMaxKi.setEnabled(True)
self.lineEdit_Kd.setEnabled(True)
self.lineEditConstMinKd.setEnabled(True)
self.lineEditConstMaxKd.setEnabled(True)
self.lineEdit_Lam.setEnabled(True)
self.lineEditConstMinlam.setEnabled(True)
self.lineEditConstMaxlam.setEnabled(True)
self.lineEdit_Mu.setEnabled(True)
self.lineEditConstMinMu.setEnabled(True)
self.lineEditConstMaxMu.setEnabled(True)
elif currentTuneSettings is optFix.Free:
self.lineEdit_Kp.setEnabled(True)
self.lineEditConstMinKp.setEnabled(True)
self.lineEditConstMaxKp.setEnabled(True)
self.lineEdit_Ki.setEnabled(True)
self.lineEditConstMinKi.setEnabled(True)
self.lineEditConstMaxKi.setEnabled(True)
self.lineEdit_Kd.setEnabled(True)
self.lineEditConstMinKd.setEnabled(True)
self.lineEditConstMaxKd.setEnabled(False)
self.lineEdit_Lam.setEnabled(True)
self.lineEditConstMinlam.setEnabled(True)
self.lineEditConstMaxlam.setEnabled(True)
self.lineEdit_Mu.setEnabled(True)
self.lineEditConstMinMu.setEnabled(True)
self.lineEditConstMaxMu.setEnabled(True)
def _KpChanged(self):
try:
x = float(self.lineEdit_Kp.text())
kpmin = float(self.lineEditConstMinKp.text())
kpmax = float(self.lineEditConstMaxKp.text())
if MIN_COEF <= kpmin <= x <= kpmax <= MAX_COEF:
self._isKpOk = True
else:
self._isKpOk = False
except:
self._isKpOk = False
finally:
self._ok2Tune()
def _KiChanged(self):
try:
x = float(self.lineEdit_Ki.text())
kimin = float(self.lineEditConstMinKi.text())
kimax = float(self.lineEditConstMaxKi.text())
if MIN_COEF <= kimin <= x <= kimax <= MAX_COEF:
self._isKiOk = True
else:
self._isKiOk = False
except:
self._isKiOk = False
finally:
self._ok2Tune()
def _KdChanged(self):
try:
x = float(self.lineEdit_Kd.text())
kdmin = float(self.lineEditConstMinKd.text())
kdmax = float(self.lineEditConstMaxKd.text())
if MIN_COEF <= kdmin <= x <= kdmax <= MAX_COEF:
self._isKdOk = True
else:
self._isKdOk = False
except:
self._isKdOk = False
finally:
self._ok2Tune()
def _LamdaChanged(self):
try:
x = float(self.lineEdit_Lam.text())
lammin = float(self.lineEditConstMinlam.text())
lammax = float(self.lineEditConstMaxlam.text())
if MIN_EXPO <= lammin <= x <= lammax <= MAX_EXPO:
self._isLamdaOk = True
else:
self._isLamdaOk = False
except:
self._isLamdaOk = False
finally:
self._ok2Tune()
def _MuChanged(self):
try:
x = float(self.lineEdit_Mu.text())
mumin = float(self.lineEditConstMinMu.text())
mumax = float(self.lineEditConstMaxMu.text())
if MIN_EXPO <= mumin <= x <= mumax <= MAX_EXPO:
self._isMuOk = True
else:
self._isMuOk = False
except:
self._isMuOk = False
finally:
self._ok2Tune()
def _ok2Tune(self):
try:
if self._isKpOk and self._isKiOk and self._isKdOk and self._isLamdaOk and self._isMuOk and self.groupBoxSimParams.isChecked() \
and self.comboFOFOPDTOk and self._isOustaStartFreq and self._isOustaStopFreqOK and self._isOustaOrderOk \
and self._isIterOk and self._isDtOk and self.groupBoxSimParams.isChecked() \
and self._isCriticalFreqOk and self._isPhaseMargOk and self.groupBoxGainPhaseMargin.isChecked() \
and self._isIPControlOk and self._isPortControlOk and self._isSimeTimeOk \
and self.pushButtonTestControl.isEnabled()==False and self.groupBoxTankControl.isChecked():
self.pushButtonTune.setEnabled(True)
self.pushButtonToServer.setEnabled(True)
self.pushButtonUpdateTime.setEnabled(True)
else:
self.pushButtonTune.setEnabled(False)
self.pushButtonToServer.setEnabled(False)
self.pushButtonUpdateTime.setEnabled(False)
except:
self.pushButtonTune.setEnabled(False)
self.pushButtonToServer.setEnabled(False)
self.pushButtonUpdateTime.setEnabled(False)
def _iterChanged(self):
iter = self.lineEditIter.text()
try:
if 1 <= int(iter) <= MAX_ITER:
self._isIterOk = True
else:
self._isIterOk = False
print("No. of Iteration: {0} is out of range. [{1} <= 'No. of Iteration' <= {2}]".format(iter,1,MAX_ITER))
self.statusbar.showMessage("No. of Iteration: {0} is out of range. [{1} <= 'No. of Iteration' <= {2}]".format(iter,1,MAX_ITER), STATUSBAR_TIME)
except:
self._isIterOk = False
print("ERROR!, 'No. of Iteration' Must be an integer")
self.statusbar.showMessage("ERROR!, 'No. of Iteration' Must be an integer", STATUSBAR_TIME)
finally:
self._ok2Tune()
def _dtChanged(self):
step = self.lineEditDt.text()
try:
if MIN_DT <= float(step) <= MAX_DT:
self._isDtOk = True
else:
self._isDtOk = False
print("Step :{0}s is out of range. [{1} <= 'Step' <= {2}]".format(step,MIN_DT, MAX_DT))
self.statusbar.showMessage("Step :{0}s is out of range. [{1} <= 'Step' <= {2}]".format(step,MIN_DT, MAX_DT), STATUSBAR_TIME)
except:
self._isDtOk = False
print("ERROR!. Step :{0}s is NOT VALID".format(step))
self.statusbar.showMessage("ERROR!. Step :{0}s is NOT VALID".format(step), STATUSBAR_TIME)
finally:
self._ok2Tune()
def _criticalFrequencyChanged(self):
criticalFrequency = self.lineEditCritFrequency.text()
try:
if 0 < float(criticalFrequency) <= MAX_GAINMARGIN:
self._isCriticalFreqOk = True
else:
self._isCriticalFreqOk = False
print("Gain Margin: {0} dB, is out of range. [{1} < 'Gain margin[dB]' <= {2}]".format(criticalFrequency, 0, MAX_GAINMARGIN))
self.statusbar.showMessage("Gain Margin: {0} dB, is out of range. [{1} < 'Gain margin[dB]' <= {2}]".format(criticalFrequency, 0, MAX_GAINMARGIN), STATUSBAR_TIME)
except:
self._isCriticalFreqOk = False
print("ERROR! Gain Margin: '{0}' dB is NOT VALID".format(criticalFrequency))
self.statusbar.showMessage("ERROR! Gain Margin: '{0}' dB is NOT VALID".format(criticalFrequency), STATUSBAR_TIME)
finally:
self._ok2Tune()
def _simTimeChanged(self):
simtime = self.lineEditTankSimTime.text()
try:
if 0 < float(simtime) <= MAX_SIM_TIME and not self.pushButtonTestControl.isEnabled():
self._isSimeTimeOk = True
else:
self._isSimeTimeOk = False
print("Sim Time:{0}s is out of range. [{1} < 'Sim Time[s]' <= {2}]".format(simtime,0,MAX_SIM_TIME))
self.statusbar.showMessage("Sim Time:{0}s is out of range. [{1} < 'Sim Time[s]' <= {2}]".format(simtime,0,MAX_SIM_TIME), STATUSBAR_TIME)
except:
self._isSimeTimeOk = False
print("ERROR! Sim Time: '{0}'s is NOT VALID".format(simtime))
self.statusbar.showMessage("ERROR! Sim Time: '{0}'s is NOT VALID".format(simtime), STATUSBAR_TIME)
finally:
self._ok2Tune()
def _phaseMargChanged(self):
phasemargin = self.lineEditPhaseMargin.text()
try:
if 1 <= float(phasemargin) <= MAX_PHASEMARGIN:
self._isPhaseMargOk = True
else:
self._isPhaseMargOk = False
print("Phase Margin:{0}[deg] is out opf range [{1} <= Phase margin[deg] <= {2}]".format(phasemargin,1, MAX_PHASEMARGIN))
self.statusbar.showMessage("Phase Margin:{0}[deg] is out of range [{1} < Phase margin[deg] <= {2}]".format(phasemargin,1, MAX_PHASEMARGIN), STATUSBAR_TIME)
except:
self._isPhaseMargOk = False
print("ERROR! 'Phase Margin':{0}[deg] is NOT VALID".format(phasemargin))
self.statusbar.showMessage("ERROR! 'Phase Margin':{0}[deg] is NOT VALID".format(phasemargin), STATUSBAR_TIME)
finally:
self._ok2Tune()
def _ok2TestCon(self):
if self._isIPRecOk and self._isIPSendOk and self._isPortRecvOk and self._isPortSendOk and self.comboFOFOPDTOk \
and self.groupBoxTankControl.isChecked() and self.groupBoxFOPIDParams.isChecked() \
and self.lineEditRecieveIP.isEnabled() and self.lineEditSendIP.isEnabled()\
and self.lineEditRecievePort.isEnabled() and self.lineEditSendPort.isEnabled() and not self.pushButtonTestControl.isEnabled() :
self.pushButtonStartCom.setEnabled(True)
else:
self.pushButtonStartCom.setEnabled(False)
#region IP LINE EDIT CHECKERS
def _ipRecChanged(self):
ipaddress = self.lineEditRecieveIP.text().strip(" ").split(".")
try:
if len(ipaddress) == 4:
for a in ipaddress:
if 0 <= int(a) < 255:
pass
else:
self._isIPRecOk = False
print("{0} is Invalid in the IP address".format(a))
self.statusbar.showMessage("{0} is Invalid in the IP address".format(a), STATUSBAR_TIME)
self._isIPRecOk = True
print("'{0}' VALID IP Address format".format(ipaddress))
self.statusbar.showMessage("'{0}' VALID IP Address format".format(ipaddress), STATUSBAR_TIME)
else:
self._isIPRecOk = False
print("'{0}' needs to be formated with 3 '.'s i.e 'X.X.X.X'".format(ipaddress))
except:
traceback.format_stack()
self._isIPRecOk = False
print("{0} is NOT an IP Address".format(ipaddress))
self.statusbar.showMessage("{0} is NOT an IP Address".format(ipaddress), STATUSBAR_TIME)
finally:
self._ok2TestCon()
def _ipSendChanged(self):
ipaddress = self.lineEditSendIP.text().strip(" ").split(".")
try:
if len(ipaddress) == 4:
for a in ipaddress:
if 0 <= int(a) < 255:
pass
else:
self._isIPSendOk = False
print("{0} is Invalid in the IP address".format(a))
self.statusbar.showMessage("{0} is Invalid in the IP address".format(a), STATUSBAR_TIME)
self._isIPSendOk = True
print("'{0}' VALID IP Address format".format(ipaddress))
self.statusbar.showMessage("'{0}' VALID IP Address format".format(ipaddress), STATUSBAR_TIME)
else:
self._isIPSendOk = False
print("'{0}' needs to be formated with 3 '.'s i.e 'X.X.X.X'".format(ipaddress))
except Exception as exce:
traceback.format_stack()
self._isIPSendOk = False
print("{0} NOT an IP Address".format(ipaddress))
self.statusbar.showMessage("{0} is NOT an IP Address".format(ipaddress), STATUSBAR_TIME)
finally:
self._ok2TestCon()
def _ipControlChanged(self):
ipaddress = self.lineEditSendIPFOPIDContr.text().strip(" ").split(".")
try:
if len(ipaddress) == 4:
for a in ipaddress:
if 0 <= int(a) < 255:
pass
else:
self._isIPControlOk = False
print("{0} is Invalid in the IP address".format(a))
self.statusbar.showMessage("{0} is Invalid in the IP address".format(a), STATUSBAR_TIME)
self._isIPControlOk = True
print("'{0}' VALID IP Address format".format(ipaddress))
self.statusbar.showMessage("'{0}' VALID IP Address format".format(ipaddress), STATUSBAR_TIME)
else:
self._isIPControlOk = False
print("'{0}' needs to be formated with 3 '.'s i.e 'X.X.X.X'".format(ipaddress))
except Exception as exce:
traceback.format_stack()
self._isIPControlOk = False
print("{0} NOT an IP Address".format(ipaddress))
self.statusbar.showMessage("{0} is NOT an IP Address".format(ipaddress), STATUSBAR_TIME)
finally:
self._ok2Tune()
#endregion
#region PORT LINE EDIT CHECKER
def _recPortChanged(self):
portnum = self.lineEditRecievePort.text()
try:
if MIN_PORT <= int(portnum) <= MAX_PORT:
self._isPortRecvOk = True
else:
self._isPortRecvOk = False
print("Port:{0} is out of range. '{1} <= port <= {2}'".format(portnum,MIN_PORT, MAX_PORT))
self.statusbar.showMessage(
"Port:{0} is out of range. '{1} <= port <= {2}'".format(portnum,MIN_PORT, MAX_PORT), STATUSBAR_TIME)
except:
self._isPortRecvOk = False
print("ERROR: {0} is NOT an integer".format(portnum))
self.statusbar.showMessage("ERROR: {0} is NOT an integer".format(portnum), STATUSBAR_TIME)
finally:
self._ok2TestCon()
def _sendPortChanged(self):
portnum = self.lineEditSendPort.text()
try:
if MIN_PORT <= int(portnum) <= MAX_PORT:
self._isPortSendOk = True
else:
self._isPortSendOk = False
print("Port:{0} is out of range. '{1} <= port <= {2}'".format(portnum, MIN_PORT, MAX_PORT))
self.statusbar.showMessage(
"Port:{0} is out of range. '{1} <= port <= {2}'".format(portnum, MIN_PORT, MAX_PORT), STATUSBAR_TIME)
except:
self._isPortSendOk = False
print("ERROR: {0} is NOT an integer".format(portnum))
self.statusbar.showMessage("ERROR: {0} is NOT an integer".format(portnum), STATUSBAR_TIME)
finally:
self._ok2TestCon()
def _recvPortControlChanged(self):
portnum = self.lineEditSendPortFOPIDContr.text()
try:
if MIN_PORT <= int(portnum) <= MAX_PORT:
self._isPortControlOk = True
else:
self._isPortControlOk = False
print("Port:{0} is out of range. '{1} <= port <= {2}'".format(portnum, MIN_PORT, MAX_PORT))
self.statusbar.showMessage(
"Port:{0} is out of range. '{1} <= port <= {2}'".format(portnum, MIN_PORT, MAX_PORT),
STATUSBAR_TIME)
except:
self._isPortControlOk = False
print("ERROR: {0} is NOT an integer".format(portnum))
self.statusbar.showMessage("ERROR: {0} is NOT an integer".format(portnum), STATUSBAR_TIME)
finally:
self._ok2Tune()
#endregion
#endregion
#region Button Clicked Functions
def _addData(self):
_loadData = newfofopdtguiclass()
# _loadData.setFocus()
# _loadData.foregroundRole()
_loadData.exec_()
try:
_sysname = _loadData.lineEditSysName.text()
_pandasData = Dict(fofopdtModel)
_pandasData.K = float(_loadData.lineEdit_GainK.text())
_pandasData.L = float(_loadData.lineEdit_DelayText.text())
_pandasData.T = float(_loadData.lineEdit_TimeConstant.text())
_pandasData.alpha = float(_loadData.lineEdit_OrderAlpha.text())
if _sysname:
self.comboBoxFOFOPDTSYS.addItem(_sysname, _pandasData)
self.comboBoxFOFOPDTSYS.setCurrentIndex(int(self.comboBoxFOFOPDTSYS.count()) - 1)
except:
self.statusbar.showMessage('fofopdtguiclass._addData: FOFOPDT Addition Failed', STATUSBAR_TIME)
print('\nfofopdtguiclass._addData: FOFOPDT Addition Failed\n')
def _deleteData(self):
self.comboBoxFOFOPDTSYS.removeItem(self.comboBoxFOFOPDTSYS.currentIndex())
def _comboBoxFOFOPDTSYSEmpty(self):
if self.comboBoxFOFOPDTSYS.count() == 0:
self.pushButtonDeleteData.setEnabled(False)
self.pushButtonEditData.setEnabled(False)
self.pushButtonTune.setEnabled(False)
self.comboFOFOPDTOk = False
else:
currentFOFOPDT = self.comboBoxFOFOPDTSYS.currentData()
T_c = currentFOFOPDT.L/(currentFOFOPDT.L + currentFOFOPDT.T)
if T_c >= 0.6:
self.lineEdit_Lam.setText("1.1")
elif 0.4<=T_c<0.6:
self.lineEdit_Lam.setText("1.0")
elif 0.1<=T_c<0.4:
self.lineEdit_Lam.setText("0.9")
elif T_c < 0.1:
self.lineEdit_Lam.setText("0.7")
self.lineEditConstMaxMu.setText(str(currentFOFOPDT.alpha))
self.comboFOFOPDTOk = True
self.pushButtonDeleteData.setEnabled(True)
self.pushButtonEditData.setEnabled(True)
self._ok2Tune()
self._ok2TestCon()
def _tune(self):
try:
fofopdtTune.ACTIVATETUNING = True
x = time.time()
fofopdtTune.DT = float(self.lineEditDt.text()) #very important to be first
# fofopdtTune.NMAX = int(self.lineEditIter.text()) #Max allowed N for oustaloop approximation
fofopdtTune.OPT_MAX_ITER = int(self.lineEditIter.text()) #Max iteration during tuning
#get oustaloop model
oustalModel = Dict(dict(wb=10**float(self.lineEdit_StartFreq.text()), wh=10**float(self.lineEdit_StopFreq.text()),
N=int(self.lineEditOrder.text()), Ts= float(self.lineEditDt.text()))) #step = 1/samplerate
#get fopidGuessModel
fopidGuessModel = Dict(dict(Kp = float(self.lineEdit_Kp.text()), Ki = float(self.lineEdit_Ki.text()),
Kd = float(self.lineEdit_Kd.text()), lam = float(self.lineEdit_Lam.text()),
mu = float(self.lineEdit_Mu.text())))
#get tuning/design parameter
tunninParams = Dict(dict(wc = float(self.lineEditCritFrequency.text()), pm = float(self.lineEditPhaseMargin.text()), optnorm = fofopdtTune.OPT_NORM))
#get Current FOFOPDT Model
currentModel = self.comboBoxFOFOPDTSYS.currentData()
#initialize the tuningProcess #TODO: if possible in another thread os as a task
fofopdtTune.mainFOFOPIDOPT(currentModel, fopidGuessModel, oustalModel, tunninParams)
print("Tuning Time for '{0}': {1:.3f}s".format(self.comboBoxFOFOPDTSYS.currentText(),time.time()-x))
self.lineEdit_Kp.setText(str(fofopdtTune.und_fopid.Kp))
self.lineEdit_Ki.setText(str(fofopdtTune.und_fopid.Ki))
self.lineEdit_Kd.setText(str(fofopdtTune.und_fopid.Kd))
self.lineEdit_Lam.setText(str(fofopdtTune.und_fopid.lam))
self.lineEdit_Mu.setText(str(fofopdtTune.und_fopid.mu))
self._ok2TestCon()
fofopdtTune.ACTIVATETUNING = False
except Exception as e:
self._ok2TestCon()
print("An exception occurred. Try using another limit/ initial guess settings")
traceback.print_exc()
self.statusbar.showMessage("An exception occurred. Try using another limit/ initial guess settings", STATUSBAR_TIME)
def _updateFOPIDServer(self):
try:
confs = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Set the parameters here to test and send them using the socket
Kp = self.lineEdit_Kp.text()
Ki = self.lineEdit_Ki.text()
Kd = self.lineEdit_Kd.text()
lam =self.lineEdit_Lam.text()
mu = self.lineEdit_Mu.text()
fopid = dict(Kp=Kp, Ki=Ki, Kd=Kd, lam=lam, mu=mu)
controlfopid = dict(control = fopid)
confs.sendto(bytes(repr(controlfopid),'utf-8'), (self.UDP_IP, self.UDP_PORT_CTRL))
except Exception as e:
traceback.print_exc()
def startNetContrl(self):
try:
confs = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
recvIp = self.lineEditRecieveIP.text()
recvPort = self.lineEditRecievePort.text()
sendPort = self.lineEditSendPort.text()
sendIp = self.lineEditSendIP.text()
simuTyme = self.lineEditTankSimTime.text()
serverSettings = dict(recvIP=recvIp, recvPORT=recvPort, sendIP=sendIp, sendPORT=sendPort, time2Run=simuTyme)
startControl = dict(start=serverSettings)
if not self.isIPandPortExist(recvIp, recvPort):
confs.sendto(bytes(repr(startControl), 'utf-8'), (self.UDP_IP, self.UDP_PORT_CTRL))
self.pushButtonStartCom.setEnabled(False)
self.pushButtonStopCom.setEnabled(True)
self.pushButtonExitServer.setEnabled(True)
else:
confs.sendto(bytes(repr(startControl), 'utf-8'), (self.UDP_IP, self.UDP_PORT_CTRL))
self.pushButtonStartCom.setEnabled(False)
self.pushButtonStopCom.setEnabled(True)
self.pushButtonExitServer.setEnabled(True)
# print("Controller START Completed: Simulaion Time Set to {0}s",simuTyme)
except Exception as e:
traceback.print_exc()
self.pushButtonStartCom.setEnabled(False)
self.pushButtonStopCom.setEnabled(True)
self.pushButtonExitServer.setEnabled(False)
def stopNetContrl(self):
try:
confs = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Set the parameters here to test and send them using the socket
stopControl = dict(stop = "")
# NB! Parameter order is important! "s" means change start FOPID controller server parameters
confs.sendto(bytes(repr(stopControl), 'utf-8'), (self.UDP_IP, self.UDP_PORT_CTRL))
except Exception as e:
traceback.print_exc()
self.pushButtonStartCom.setEnabled(True)
self.pushButtonStopCom.setEnabled(False)
def _exitServer(self):
try:
confs = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Set the parameters here to test and send them using the socket
exitServer = dict(exit = "")
# NB! Parameter order is important! "s" means change start FOPID controller server parameters
confs.sendto(bytes(repr(exitServer), 'utf-8'), (self.UDP_IP, self.UDP_PORT_CTRL))
self.pushButtonStartCom.setEnabled(False)
self.pushButtonStopCom.setEnabled(False)
self.pushButtonTestControl.setEnabled(True)
self.pushButtonExitServer.setEnabled(False)
self.pushButtonToServer.setEnabled(False)
except Exception as e:
traceback.print_exc()
def _TestControl(self):
contrlPort = int(self.lineEditSendPortFOPIDContr.text())
controlIP = self.lineEditSendIPFOPIDContr.text()
try:
if self.isIPandPortExist(controlIP,contrlPort):
self.UDP_IP = self.lineEditSendIPFOPIDContr.text()
self.UDP_PORT_CTRL = int(self.lineEditSendPortFOPIDContr.text())
self.lineEditSendPortFOPIDContr.setEnabled(False)
self.pushButtonTestControl.setEnabled(False)
# self.lock.acquire()
# print("Controller IP and Port Matched. Server FOUND")
# self.lock.release()
else:
self.UDP_IP = 0
self.UDP_PORT_CTRL = 0
self.lineEditSendPortFOPIDContr.setEnabled(True)
self.pushButtonTestControl.setEnabled(True)
# self.lock.acquire()
# print("ERROR!: Controller IP and Port Not Found. Run controlServer.py First")
# self.lock.release()
except Exception as e:
traceback.print_exc()
self.lineEditSendPortFOPIDContr.setEnabled(True)
self.pushButtonTestControl.setEnabled(True)
finally:
self._ok2Tune()
def updateTime(self):
try:
confs = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Set the parameters here to test and send them using the socket
updatetimett = dict(time= dict(time2Run = self.lineEditTankSimTime.text()))
# NB! Parameter order is important! "s" means change start FOPID controller server parameters
confs.sendto(bytes(repr(updatetimett), 'utf-8'), (self.UDP_IP, self.UDP_PORT_CTRL))
except:
pass
def _edit(self):
# read current name and Data
currentText = self.comboBoxFOFOPDTSYS.currentText()
currentData = self.comboBoxFOFOPDTSYS.currentData()
# get datavalues for u,t,y
K = currentData.K
L = currentData.L
T = currentData.T
alpha = currentData.alpha
# create trim data class
_trista = newfofopdtguiclass()
_trista.lineEditSysName.setText(currentText)
_trista.lineEdit_GainK.setText(str(K))
_trista.lineEdit_DelayText.setText(str(L))
_trista.lineEdit_TimeConstant.setText(str(T))
_trista.lineEdit_OrderAlpha.setText(str(alpha))
# exec the trimdata classs
_trista.setFocus()
_trista.exec_()
# now trimdata is exited get new values
try:
_sysname = _trista.lineEditSysName.text()
_pandasData = Dict(fofopdtModel)
_pandasData.K = float(_trista.lineEdit_GainK.text())
_pandasData.L = float(_trista.lineEdit_DelayText.text())
_pandasData.T = float(_trista.lineEdit_TimeConstant.text())
_pandasData.alpha = float(_trista.lineEdit_OrderAlpha.text())
if _sysname:
self.comboBoxFOFOPDTSYS.addItem(_sysname, _pandasData)
self.comboBoxFOFOPDTSYS.setCurrentIndex(int(self.comboBoxFOFOPDTSYS.count()) - 1)
except:
self.statusbar.showMessage('fofopdtguiclass._edit: FOFOPDT Addition Failed', STATUSBAR_TIME)
print('\nfofopdtguiclass.edit: FOFOPDT Addition Failed\n')
def _setParams(self):
data = self.comboBoxParamSetOption.currentData()
[z.setText(self.lineEditParamsValue.text()) for z in data]
self._KpChanged()
self._KiChanged()
self._KdChanged()
self._LamdaChanged()
self._MuChanged()
def closeEvent(self, event):
reply = QMessageBox.question(self, "Exit?",
"Are you sure you would like to 'Exit' this form?",
QMessageBox.Yes | QMessageBox.No)
if reply == QMessageBox.Yes:
event.accept()
else:
event.ignore()
def isIPandPortExist(self, ip, port):
contrlPort = int(port)
controlIP = str(ip)
open = None
try:
addressinfo = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
addressinfo.bind((controlIP, contrlPort))
addressinfo.shutdown(socket.SHUT_RDWR)
addressinfo.close()
return False
except:
return True
#endregion
class newfofopdtguiclass(QDialog, createnewfofopdtgui.Ui_dialogCreateNewFOTF):
def __init__(self):
QDialog.__init__(self)
createnewfofopdtgui.Ui_dialogCreateNewFOTF.__init__(self)
self.setWindowIcon(QIcon('index.png'))
self.setupUi(self)
self.lineEditSysName.textChanged.connect(self._checkSysName)
self.lineEdit_GainK.textChanged.connect(self._checkGain)
self.lineEdit_DelayText.textChanged.connect(self._checkDelay)
self.lineEdit_TimeConstant.textChanged.connect(self._checkTimeConstant)
self.lineEdit_OrderAlpha.textChanged.connect(self._checkAlpha)
self.pushButtonOK.clicked.connect(self.close)
self.pushButtonCancel.clicked.connect(self.close)
self.sysnamecheck = self.gaincheck = self.delaycheck = self.timeconstantcheck = self.alphacheck = False
self.lineEditSysName.setFocus()
self.show()
#region Button OK Check
def _checkOkButton(self):
if self.sysnamecheck and self.gaincheck and self.delaycheck and self.timeconstantcheck and self.alphacheck:
self.pushButtonOK.setEnabled(True)
else:
self.pushButtonOK.setEnabled(False)
#endregion
#region lineEdit Values Check
def _checkSysName(self):
try:
self.sysnamecheck = len(self.lineEditSysName.text().strip(" ")) >= 1
self._checkOkButton()
except:
self.sysnamecheck = False
self._checkOkButton()
def _checkGain(self):
try:
self.gaincheck = isinstance(float(self.lineEdit_GainK.text()), float)
self._checkOkButton()
except:
self.gaincheck = False
self._checkOkButton()
def _checkDelay(self):
try:
self.delaycheck = float(self.lineEdit_DelayText.text()) >= 0
self._checkOkButton()
except:
self.delaycheck = False
self._checkOkButton()
def _checkTimeConstant(self):
try:
self.timeconstantcheck = isinstance(float(self.lineEdit_TimeConstant.text()),float)
self._checkOkButton()
except:
self.timeconstantcheck = False
self._checkOkButton()
def _checkAlpha(self):
try:
self.alphacheck = ALPHA_MIN < float(self.lineEdit_OrderAlpha.text()) < ALPHA_MAX
self._checkOkButton()
except:
self.alphacheck = False
self._checkOkButton()
#endregion
def closeEvent(self, event):
sender = self.sender().text()
close = QMessageBox.question(self, "{0}?".format(sender),
"Are you sure you would like to '{0}' this form?".format(sender),
QMessageBox.Yes | QMessageBox.No)
if close == QMessageBox.Yes:
if sender == "OK":
pass
else:
self.lineEditSysName.clear()
self.lineEdit_GainK.clear()
self.lineEdit_DelayText.clear()
self.lineEdit_TimeConstant.clear()
self.lineEdit_OrderAlpha.clear()
event.accept()
else:
event.ignore()
# def fopidgui(lcok):
# app = QApplication(sys.argv)
# shareMem = fofopdtguiclass(lcok)
# app.exec_()
# if __name__ == "__main__":
# lock = Lock()
# server = Process(target=controlServer.controlServerAutoStart, name="FOPIDServer", args = (controlServer.DURATION, lock,))
# gui = Process(target= fopidgui, name="FOPIDGui", args= (lock,))
#
# server.start()
# gui.start()
#
# server.join()
# gui.join()
#
# print("Gui and Server were 'Exited'")
if __name__ == "__main__":
app = QApplication(sys.argv)
shareMem = fofopdtguiclass()
app.exec_()