This repository has been archived by the owner on May 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplctag_gui.py
1562 lines (1294 loc) · 68.4 KB
/
plctag_gui.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
'''
Create a simple Tkinter window to display fetched tags and selected tag value(s).
Tkinter doesn't come preinstalled on all Linux distributions, so you may need to install it.
For Ubuntu: sudo apt-get install python-tk
Tkinter vs tkinter
Reference: https://stackoverflow.com/questions/17843596/difference-between-tkinter-and-tkinter
Window/widget resizing
Reference: https://stackoverflow.com/questions/22835289/how-to-get-tkinter-canvas-to-dynamically-resize-to-window-width
'''
import threading
import platform
import time
import math
import re as regexp # regular expressions
from libplctag import *
try:
# Python 2
from Tkinter import *
except ImportError:
# Python 3
from tkinter import *
import tkinter.font as tkfont
pythonVersion = platform.python_version()
# if setting myTag for startup then also set the correct value of myTagDataType
currentPLC = 'controllogix'
ipAddress = '192.168.1.15'
path = '1,3'
myTag = 'CT_BOOLArray_1[0]{5}'
myTagDataType = 'bool array'
timeout = 10000
ab_plc_type = ['controllogix', 'micrologix', 'logixpccc', 'micro800', 'slc500', 'plc5', 'njnx']
ab_data_type = ['int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64', 'float32', 'float64', 'bool', 'bool array', 'string', 'custom string', 'timer', 'counter', 'control']
ab_mlgx_data_type = ['int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64', 'float32', 'float64', 'string', 'timer', 'counter', 'control', 'pid']
ab_slcplc5_data_type = ['int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64','float32', 'float64', 'string', 'timer', 'counter', 'control']
timer_bits_words = ['None', 'EN', 'TT', 'DN', 'PRE', 'ACC']
counter_bits_words = ['None', 'CU', 'CD', 'DN', 'OV', 'UN', 'UA', 'PRE', 'ACC']
control_bits_words = ['None', 'EN', 'EU', 'DN', 'EM', 'ER', 'UL', 'IN', 'FD', 'LEN', 'POS']
pid_bits_words = ['None', 'TM', 'AM', 'CM', 'OL', 'RG', 'SC', 'TF', 'DA', 'DB', 'UL', 'LL', 'SP', 'PV', 'DN', 'EN', 'SPS', 'KC', 'Ti', 'TD', 'MAXS', 'MINS', 'ZCD', 'CVH', 'CVL', 'LUT', 'SPV', 'CVP']
bits_8bit = ['None', '0', '1', '2', '3', '4', '5', '6', '7']
bits_16bit = ['None', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15']
bits_32bit = ['None', '0', '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']
bits_64bit = ['None', '0', '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']
string_length = ['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']
bool_display = ['T : F', '1 : 0', 'On : Off']
# width wise resizing of the label displaying tag value (window)
class LabelResizing(Label):
def __init__(self,parent,**kwargs):
Label.__init__(self,parent,**kwargs)
self.bind("<Configure>", self.on_resize)
self.width = self.winfo_reqwidth()
def on_resize(self,event):
if self.width > 0:
self.width = int(event.width)
self.config(width=self.width, wraplength=self.width)
# width wise resizing of the tag entry box (window)
class EntryResizing(Entry):
def __init__(self,parent,**kwargs):
Entry.__init__(self,parent,**kwargs)
self.bind("<Configure>", self.on_resize)
self.width = self.winfo_reqwidth()
def on_resize(self,event):
if self.width > 0:
self.width = int(event.width)
self.config(width=self.width)
class connection_thread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
comm_check()
class get_tags_thread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
getTags()
class update_thread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
start_update_value()
plctagVersion = ''
def main():
'''
Create our window and comm driver
'''
global root
global tagID
global currentTag
global stringTag
global tagValue
global realElementCount
global selectedPath
global selectedIPAddress
global selectedPLC
global selectedDataType
global selectedPID
global selectedTCC
global selectedBit
global selectedStringLength
global selectedTag
global selectedBoolDisplay
global selectedProgramName
global updateRunning
global connectionInProgress
global connected
global bitIndex
global pidElement
global tccElement
global tccType
global plctagVersion
global offset
global lblTagStatus
global btnStart
global btnStop
global btnGetTags
global lbPLC
global lbDataType
global lbPID
global lbTCC
global lbBit
global lbStringLength
global lbBoolDisplay
global lbTags
global tbPLC
global tbDataType
global tbPID
global tbBit
global tbStringLength
global tbIPAddress
global tbPath
global tbTag
global tbProgramName
global popup_menu_tbIPAddress
global popup_menu_tbPath
global popup_menu_tbTag
global popup_menu_tbProgramName
root = Tk()
root.config(background='#837DFF')
root.title('Plctag GUI - Connection/Read Tester (Python v' + pythonVersion + ')')
root.geometry('800x600')
connected, connectionInProgress, updateRunning = False, False, True
currentTag, tccType, tccElement, pidElement, plctagVersion = myTag, '', 'None', 'None', ''
bitIndex, tagID, realElementCount = -1, -1, 0
#-------------------------------------------------------------------------------------------
# add a frame to hold top widgets
frame1 = Frame(root, background='#837DFF')
frame1.pack(fill=X)
# add listboxes for PLCs, DataTypes, PID, Timer/Counter/Control, Bits, Custom String Length, Bool Display and Tags
lbPLC = Listbox(frame1, height=11, width=12, bg='lightblue')
lbDataType = Listbox(frame1, height=11, width=13, bg='lightblue')
lbPID = Listbox(frame1, height=11, width=6, bg='lightblue')
lbTCC = Listbox(frame1, height=11, width=6, bg='lightblue')
lbBit = Listbox(frame1, height=11, width=6, bg='lightblue')
lbStringLength = Listbox(frame1, height=11, width=5, bg='lightblue')
lbBoolDisplay = Listbox(frame1, height=11, width=9, bg='lightblue')
lbTags = Listbox(frame1, height=11, width=50, bg='lightgreen')
lbPLC.insert(1, '~ PLC')
i = 2
for plc in ab_plc_type:
lbPLC.insert(i, plc)
i = i + 1
lbPLC.pack(anchor='n', side='left', padx=2, pady=3)
# select PLC on the mouse double-click
lbPLC.bind('<Double-Button-1>', lambda event: plc_select())
lbDataType.insert(1, '~ Data Type')
i = 2
for dataType in ab_data_type:
lbDataType.insert(i, dataType)
i = i + 1
lbDataType.pack(anchor='n', side='left', padx=2, pady=3)
# select Data Type on the mouse double-click
lbDataType.bind('<Double-Button-1>', lambda event: data_type_select())
# add scrollbar for the DataTypes list box
scrollbarDataTypes = Scrollbar(frame1, orient='vertical', width=12, command=lbDataType.yview)
scrollbarDataTypes.pack(anchor='n', side='left', pady=3, ipady=65)
lbDataType.config(yscrollcommand = scrollbarDataTypes.set)
# conditional addition of MicroLogix PID list box, for plctag library version lower than 2.2.0
if plc_tag_check_lib_version(2, 2, 0) != 0:
lbPID.insert(1, '~ PID')
i = 2
for pid in pid_bits_words:
lbPID.insert(i, pid)
i = i + 1
lbPID.pack(anchor='n', side='left', padx=3, pady=3)
if myTagDataType == 'pid':
lbPID['state'] = 'normal'
else:
lbPID['state'] = 'disabled'
# select PID on the mouse double-click
lbPID.bind('<Double-Button-1>', lambda event: pid_select())
# add scrollbar for the PID list box
scrollbarPID = Scrollbar(frame1, orient='vertical', width=12, command=lbPID.yview)
scrollbarPID.pack(anchor='n', side='left', pady=3, ipady=65)
lbPID.config(yscrollcommand = scrollbarPID.set)
lbTCC.insert(1, '~ TCC')
i = 2
for tccELMNT in timer_bits_words:
lbTCC.insert(i, tccELMNT)
i = i + 1
lbTCC.pack(anchor='n', side='left', padx=2, pady=3)
if myTagDataType == 'timer' or myTagDataType == 'counter' or myTagDataType == 'control':
lbTCC['state'] = 'normal'
else:
lbTCC['state'] = 'disabled'
# select TCC element on the mouse double-click
lbTCC.bind('<Double-Button-1>', lambda event: tcc_select())
# add scrollbar for the TCC list box
scrollbarTCC = Scrollbar(frame1, orient='vertical', width=12, command=lbTCC.yview)
scrollbarTCC.pack(anchor='n', side='left', pady=3, ipady=65)
lbTCC.config(yscrollcommand = scrollbarTCC.set)
lbBit.insert(1, '~ Bit')
i = 2
for bit in bits_8bit:
lbBit.insert(i, bit)
i = i + 1
lbBit.pack(anchor='n', side='left', padx=3, pady=3)
if regexp.match('.int.+', myTagDataType) or regexp.match('int.+', myTagDataType) or regexp.match('float.+', myTagDataType):
lbBit['state'] = 'normal'
else:
lbBit['state'] = 'disabled'
# select Bit on the mouse double-click
lbBit.bind('<Double-Button-1>', lambda event: bit_select())
# add scrollbar for the Bit list box
scrollbarBit = Scrollbar(frame1, orient='vertical', width=12, command=lbBit.yview)
scrollbarBit.pack(anchor='n', side='left', pady=3, ipady=65)
lbBit.config(yscrollcommand = scrollbarBit.set)
lbStringLength.insert(1, '~ Str')
i = 2
for strLength in string_length:
lbStringLength.insert(i, strLength)
i = i + 1
lbStringLength.pack(anchor='n', side='left', padx=3, pady=3)
if myTagDataType == 'custom string':
lbStringLength['state'] = 'normal'
else:
lbStringLength['state'] = 'disabled'
# select string length on the mouse double-click
lbStringLength.bind('<Double-Button-1>', lambda event: string_length_select())
# add scrollbar for the string length listbox
scrollbarStringLength = Scrollbar(frame1, orient='vertical', width=12, command=lbStringLength.yview)
scrollbarStringLength.pack(anchor='n', side='left', pady=3, ipady=65)
lbStringLength.config(yscrollcommand = scrollbarStringLength.set)
lbBoolDisplay.insert(1, '~ Bool')
i = 2
for boolDisplay in bool_display:
lbBoolDisplay.insert(i, boolDisplay)
i = i + 1
lbBoolDisplay.pack(anchor='n', side='left', padx=3, pady=3)
# select boolean display format on the mouse double-click
lbBoolDisplay.bind('<Double-Button-1>', lambda event: bool_display_select())
# add scrollbar for the Tags list box
scrollbarTags = Scrollbar(frame1, orient='vertical', width=12, command=lbTags.yview)
scrollbarTags.pack(anchor='n', side='right', padx=3, pady=3, ipady=65)
lbTags.config(yscrollcommand = scrollbarTags.set)
# copy selected tag to the clipboard on the mouse double-click
lbTags.bind('<Double-Button-1>', lambda event: tag_copy())
lbTags.pack(anchor='n', side='right', pady=3)
#-------------------------------------------------------------------------------------------
# add a frame to hold labels, Program Name entry box and Get Tags button
frame2 = Frame(root, background='#837DFF')
frame2.pack(fill=X)
# add text boxes to serve as labels showing currently selected PLC, DataType, PID, Bit, StringLength and BoolDisplay
selectedPLC = StringVar()
tbPLC = Entry(frame2, justify='center', textvariable=selectedPLC, width=12, fg='blue', state='readonly')
selectedPLC.set(currentPLC)
tbPLC.pack(side='left', padx=2, pady=1)
selectedDataType = StringVar()
tbDataType = Entry(frame2, justify='center', textvariable=selectedDataType, width=13, fg='blue', state='readonly')
if myTagDataType == '':
selectedDataType.set('int8')
else:
selectedDataType.set(myTagDataType)
tbDataType.pack(side='left', padx=2, pady=1)
# offsets used for positioning TCC, Bit, String Length and Bool Display list boxes (when PID list box is not included)
offsetTCCBox = 9
offsetBitBox = -7
offsetStringLengthBox = 5
offsetBoolBox = -4
# conditional addition of the PID list box, for plctag library version lower than 2.2.0
if plc_tag_check_lib_version(2, 2, 0) != 0:
selectedPID = StringVar()
tbPID = Entry(frame2, justify='center', textvariable=selectedPID, width=6, fg='blue', state='readonly')
selectedPID.set('None')
tbPID.pack(side='left', padx=14, pady=1)
offsetTCCBox = 0
offsetBitBox = 0
offsetStringLengthBox = 0
offsetBoolBox = 0
selectedTCC = StringVar()
tbTCC = Entry(frame2, justify='center', textvariable=selectedTCC, width=6, fg='blue', state='readonly')
selectedTCC.set('None')
tbTCC.pack(side='left', padx=4 + offsetTCCBox, pady=1)
selectedBit = StringVar()
tbBit = Entry(frame2, justify='center', textvariable=selectedBit, width=6, fg='blue', state='readonly')
selectedBit.set('None')
tbBit.pack(side='left', padx=12 + offsetBitBox, pady=1)
selectedStringLength = StringVar()
tbStringLength = Entry(frame2, justify='center', textvariable=selectedStringLength, width=5, fg='blue', state='readonly')
selectedStringLength.set('1')
tbStringLength.pack(side='left', padx=7 + offsetStringLengthBox, pady=1)
selectedBoolDisplay = StringVar()
tbBoolDisplay = Entry(frame2, justify='center', textvariable=selectedBoolDisplay, width=9, fg='blue', state='readonly')
selectedBoolDisplay.set('T : F')
tbBoolDisplay.pack(side='left', padx=10 + offsetBoolBox, pady=1)
# add Get Tags button
btnGetTags = Button(frame2, text = 'Get Tags', fg ='brown', height=1, width=8, relief='raised', command=start_get_tags)
btnGetTags.pack(side='right', padx=3, pady=1)
# add an entry box for the Program Name
selectedProgramName = StringVar()
tbProgramName = Entry(frame2, justify='center', textvariable=selectedProgramName, font='Helvetica 9', relief='raised')
selectedProgramName.set('MainProgram')
# add the 'Paste' menu on the mouse right-click
popup_menu_tbProgramName = Menu(tbProgramName, tearoff=0)
popup_menu_tbProgramName.add_command(label='Paste', command=program_name_paste)
tbProgramName.bind('<Button-3>', lambda event: program_name_menu(event, tbProgramName))
tbProgramName.pack(side='right', padx=20, pady=1)
#-------------------------------------------------------------------------------------------
# add frames to hold bottom widgets
frame5 = Frame(root, background='#837DFF')
frame5.pack(side='bottom', fill=X)
frame6 = Frame(root, background='#837DFF')
frame6.pack(side='bottom', fill=X)
# create a label and an entry box for the IPAddress
lblIPAddress = Label(frame6, text='IP Address', fg='black', bg='#837DFF', font='Helvetica 9')
lblIPAddress.pack(side='left', padx=45)
selectedIPAddress = StringVar()
tbIPAddress = Entry(frame5, justify='center', textvariable=selectedIPAddress, font='Helvetica 9', relief='raised')
selectedIPAddress.set(ipAddress)
# add the 'Paste' menu on the mouse right-click
popup_menu_tbIPAddress = Menu(tbIPAddress, tearoff=0)
popup_menu_tbIPAddress.add_command(label='Paste', command=ip_paste)
tbIPAddress.bind('<Button-3>', lambda event: ip_menu(event, tbIPAddress))
tbIPAddress.pack(side='left', padx=3, pady=3)
# create a label for tag status
lblTagStatus = Label(frame5, text=' tag status ', fg='black', bg='red', font='Helvetica 9')
lblTagStatus.pack(side='left', padx=5)
# create a label and an entry box for the Path
lblPath = Label(frame6, text='Path', fg='black', bg='#837DFF', font='Helvetica 9')
lblPath.pack(side='right', padx=60)
selectedPath = StringVar()
tbPath = Entry(frame5, justify='center', textvariable=selectedPath, font='Helvetica 9', relief='raised')
selectedPath.set(path)
# add the 'Paste' menu on the mouse right-click
popup_menu_tbPath = Menu(tbPath, tearoff=0)
popup_menu_tbPath.add_command(label='Paste', command=path_paste)
tbPath.bind('<Button-3>', lambda event: path_menu(event, tbPath))
tbPath.pack(side='right', padx=3, pady=3)
if int(pythonVersion[0]) >= 3:
plctagVersion = str(plc_tag_get_int_attribute(0, ('version_major').encode('utf-8'), 0)) + '.' + str(plc_tag_get_int_attribute(0, ('version_minor').encode('utf-8'), 0)) + '.' + str(plc_tag_get_int_attribute(0, ('version_patch').encode('utf-8'), 0))
else:
plctagVersion = str(plc_tag_get_int_attribute(0, 'version_major', 0)) + '.' + str(plc_tag_get_int_attribute(0, 'version_minor', 0)) + '.' + str(plc_tag_get_int_attribute(0, 'version_patch', 0))
# create a label for the plctag library version
lblLibraryVersion = Label(frame5, text=' libplctag ' + plctagVersion + ' ', fg='black', bg='#837DFF', font='Helvetica 9')
lblLibraryVersion.pack(side='right', padx=5)
#-------------------------------------------------------------------------------------------
# add a frame to hold center widgets
frame3 = Frame(root, background='#837DFF')
frame3.pack(fill=X)
# create a label for the Tag entry
lblTag = Label(frame3, text='Tag to Read (optional applicable # elements as {x})', fg='black', bg='#837DFF', font='Helvetica 8 italic')
lblTag.pack(anchor='center', pady=10)
# add a button to start updating tag value
btnStart = Button(frame3, text = 'Start Update', state='disabled', bg='lightgrey', fg ='blue', height=1, width=10, relief='raised', command=start_update)
btnStart.pack(side='left', padx=3, pady=1)
# add a button to stop updating tag value
btnStop = Button(frame3, text = 'Stop Update', state='disabled', bg='lightgrey', fg ='blue', height=1, width=10, relief='raised', command=stop_update_value)
btnStop.pack(side='right', padx=3, pady=1)
# create a text box for the Tag entry
char_width = 5
if int(pythonVersion[0]) >= 3:
fnt = tkfont.Font(family="Helvetica", size=11, weight="normal")
char_width = fnt.measure("0")
selectedTag = StringVar()
tbTag = EntryResizing(frame3, justify='center', textvariable=selectedTag, font='Helvetica 11', width=(int(800 / char_width) - 22), relief='raised')
selectedTag.set(myTag)
# add the 'Paste' menu on the mouse right-click
popup_menu_tbTag = Menu(tbTag, tearoff=0)
popup_menu_tbTag.add_command(label='Paste', command=tag_paste)
tbTag.bind('<Button-3>', lambda event: tag_menu(event, tbTag))
tbTag.pack(side='left', fill=X)
#-------------------------------------------------------------------------------------------
# add a frame to hold the label displaying the tag value
frame4 = Frame(root, background='#837DFF')
frame4.pack(fill=X)
# create a label to display the received tag value
if int(pythonVersion[0]) >= 3:
fnt = tkfont.Font(family="Helvetica", size=18, weight="normal")
char_width = fnt.measure("0")
tagValue = LabelResizing(frame4, text='~', fg='yellow', bg='navy', font='Helvetica 18', width=(int(800 / char_width - 4.5)), wraplength=800, relief='sunken')
tagValue.pack(anchor='center', pady=5)
#-------------------------------------------------------------------------------------------
# add unframed Exit button (relatively positioned on the bottom)
btnExit = Button(root, text = 'E x i t', fg ='red', height=1, width=8, relief='raised', command=root.destroy)
btnExit.place(anchor='center', relx=0.5, rely=0.97)
#-------------------------------------------------------------------------------------------
# set the minimum window size to the current size
root.update()
root.minsize(root.winfo_width(), root.winfo_height())
start_connection()
root.mainloop()
try:
if not tagID is None:
if tagID > 0:
plc_tag_destroy(tagID)
except:
pass
def start_connection():
try:
thread1 = connection_thread()
thread1.setDaemon(True)
thread1.start()
except Exception as e:
print('unable to start thread1 - connection_thread, ' + str(e))
def start_get_tags():
try:
thread2 = get_tags_thread()
thread2.setDaemon(True)
thread2.start()
except Exception as e:
print('unable to start thread2 - get_tags_thread, ' + str(e))
def start_update():
try:
thread3 = update_thread()
thread3.setDaemon(True)
thread3.start()
except Exception as e:
print('unable to start thread3 - update_thread, ' + str(e))
def get_bit(int, n):
return ((int >> n & 1) != 0)
def getTags():
try:
cpu = selectedPLC.get()
ipAddress = selectedIPAddress.get()
pth = (selectedPath.get()).replace(' ', '')
if cpu == 'controllogix':
controllerTags = []
j = 1
lbTags.delete(0, 'end')
stringTag = 'protocol=ab_eip&gateway=' + ipAddress + '&path=' + pth + '&cpu=' + cpu + '&name=@tags'
if int(pythonVersion[0]) >= 3:
tagC = plc_tag_create(stringTag.encode('utf-8'), timeout)
else:
tagC = plc_tag_create(stringTag, timeout)
while plc_tag_status(tagC) == 1:
time.sleep(0.01)
if plc_tag_status(tagC) < 0:
plc_tag_destroy(tagC)
lbTags.insert(j, 'Failed to fetch Controller Tags')
j += 1
else:
tagSize = plc_tag_get_size(tagC)
offset = 0
while offset < tagSize:
# tagId, tagLength and IsStructure variables can be calculated if needed.
# They can also be diplayed by following the comments further below.
# tagId = plc_tag_get_uint32(tagC, offset)
tagType = plc_tag_get_uint16(tagC, offset + 4)
# tagLength = plc_tag_get_uint16(tagC, offset + 6)
systemBit = get_bit(tagType, 12) # bit 12
if systemBit is False:
# IsStructure = get_bit(tagType, 15) # bit 15
x = int(plc_tag_get_uint32(tagC, offset + 8))
y = int(plc_tag_get_uint32(tagC, offset + 12))
z = int(plc_tag_get_uint32(tagC, offset + 16))
dimensions = ''
if (x != 0 and y != 0 and z != 0):
dimensions = '[' + str(x) + ', ' + str(y) + ', ' + str(z) + ']'
elif (x != 0 and y != 0):
dimensions = '[' + str(x) + ', ' + str(y) + ']'
elif (x != 0):
if (tagType == 8403 or tagType == 211):
dimensions = '[' + str(x * 32) + ']'
else:
dimensions = '[' + str(x) + ']'
offset += 20
tagNameLength = plc_tag_get_uint16(tagC, offset)
tagNameBytes = bytearray(tagNameLength)
offset += 2
i = 0
while i < tagNameLength:
tagNameBytes[i] = plc_tag_get_uint8(tagC, offset + i)
i += 1
tagName = tagNameBytes.decode('utf-8')
# skip all module tags by checking for ':'
if ':' not in tagName:
# display tag name and its dimensions only
controllerTags.append(tagName + dimensions)
# display tag name, dimensions, tagType, IsStructure, tagLength and tagId (comment and uncomment appropriate lines above and below)
# controllerTags.append(tagName + dimensions + '; Type=' + str(tagType) + '; IsStructure=' + IsStructure + '; Length=' + str(tagLength) + 'bytes; Id=' + str(tagId))
offset += tagNameLength
else:
offset += 20
tagNameLength = plc_tag_get_uint16(tagC, offset)
offset += (2 + tagNameLength)
for t in controllerTags:
lbTags.insert(j, t)
j += 1
plc_tag_destroy(tagC)
programName = selectedProgramName.get()
programTags = []
if programName != '':
stringTag = 'protocol=ab_eip&gateway=' + ipAddress + '&path=' + path + '&cpu=' + cpu + '&name=Program:' + programName + '.@tags'
if int(pythonVersion[0]) >= 3:
tagP = plc_tag_create(stringTag.encode('utf-8'), timeout)
else:
tagP = plc_tag_create(stringTag, timeout)
while plc_tag_status(tagP) == 1:
time.sleep(0.01)
if plc_tag_status(tagP) < 0:
plc_tag_destroy(tagP)
lbTags.insert(j, 'Failed to fetch ' + programName + ' Tags')
else:
tagSize = plc_tag_get_size(tagP)
offset = 0
while offset < tagSize:
# tagId, tagLength and IsStructure variables can be calculated if needed.
# They can also be diplayed by following the comments further below.
# tagId = plc_tag_get_uint32(tagP, offset)
tagType = plc_tag_get_uint16(tagP, offset + 4)
# tagLength = plc_tag_get_uint16(tagP, offset + 6)
systemBit = get_bit(tagType, 12) # bit 12
if systemBit is False:
# IsStructure = get_bit(tagType, 15) # bit 15
x = int(plc_tag_get_uint32(tagP, offset + 8))
y = int(plc_tag_get_uint32(tagP, offset + 12))
z = int(plc_tag_get_uint32(tagP, offset + 16))
dimensions = ''
if (x != 0 and y != 0 and z != 0):
dimensions = '[' + str(x) + ', ' + str(y) + ', ' + str(z) + ']'
elif (x != 0 and y != 0):
dimensions = '[' + str(x) + ', ' + str(y) + ']'
elif (x != 0):
if (tagType == 8403):
dimensions = '[' + str(x * 32) + ']'
else:
dimensions = '[' + str(x) + ']'
offset += 20
tagNameLength = plc_tag_get_uint16(tagP, offset)
tagNameBytes = bytearray(tagNameLength)
offset += 2
i = 0
while i < tagNameLength:
tagNameBytes[i] = plc_tag_get_uint8(tagP, offset + i)
i += 1
tagName = tagNameBytes.decode('utf-8')
# display tag name and its dimensions only
programTags.append('Program:' + programName + '.' + tagName + dimensions)
# display tag name, dimensions, tagType, IsStructure, tagLength and tagId (comment and uncomment appropriate lines above and below)
# programTags.append('Program:' + programName + '.' + tagName + dimensions + '; Type=' + str(tagType) + '; IsStructure=' + IsStructure + '; Length=' + str(tagLength) + 'bytes; Id=' + str(tagId))
offset += tagNameLength
else:
offset += 20
tagNameLength = plc_tag_get_uint16(tagP, offset)
offset += (2 + tagNameLength)
for t in programTags:
lbTags.insert(j, t)
j += 1
plc_tag_destroy(tagP)
else:
lbTags.insert(j, 'No Program Tags Retrieved (missing program name)')
else:
lbTags.insert(1, 'No Tags Retrieved (incorrect PLC type selected)')
except:
pass
def comm_check():
global currentPLC
global path
global ipAddress
global lblTagStatus
global currentTag
global myTag
global tagID
global elem_size
global elem_count
global bitIndex
global realElementCount
global pidElement
global tccElement
global tccType
global connectionInProgress
global connected
try:
cpu = selectedPLC.get()
ip = selectedIPAddress.get()
pth = selectedPath.get()
tag = selectedTag.get()
bitIndex = -1
realElementCount = 0
pidElement = 'None'
tccElement = 'None'
tccType = ''
connectionInProgress = True
if tag != '':
if (not connected or tagID < 0 or currentPLC != cpu or ipAddress != ip or path != pth or myTag != tag):
lblTagStatus['bg'] = 'red'
btnStart['state'] = 'disabled'
currentPLC = cpu
ipAddress = ip
path = pth.replace(' ', '')
myTag = tag
currentTag = myTag
elem_count = 1
elem_size = 1
if not tagID is None:
if tagID > 0:
plc_tag_destroy(tagID)
if (myTag.endswith('}')) and ('{' in myTag):
elem_count = int(myTag[myTag.index('{') + 1:myTag.index('}')])
myTag = myTag[:myTag.index('{')]
if '/' in myTag:
bitIndex = int(myTag[myTag.index('/') + 1:])
if bitIndex < lbBit.size() - 2:
selectedBit.set(bitIndex)
else:
selectedBit.set('None')
myTag = myTag[:myTag.index('/')]
dt = selectedDataType.get()
if dt == 'bool':
elem_size = 1
elif dt == 'int8' or dt == 'uint8':
elem_size = 1
elif dt == 'int16' or dt == 'uint16':
elem_size = 2
elif dt == 'int32' or dt == 'uint32' or dt == 'float32':
elem_size = 4
elif dt == 'bool array':
elem_size = 4
if ((myTag.endswith(']')) and ('[' in myTag)):
if not (',' in myTag):
bitIndex = int(myTag[(myTag.index('[') + 1):myTag.index(']')])
if bitIndex > -1:
realElementCount = int(math.ceil(float(bitIndex + elem_count) / float(elem_size * 8)))
myTag = myTag[:myTag.index('[')] + '[0]' # Workaround
elif dt == 'int64' or dt == 'uint64' or dt == 'float64':
elem_size = 8
elif dt == 'custom string':
elem_size = int(math.ceil(int(selectedStringLength.get()) / 8)) * 8
elif dt == 'string':
if cpu == 'micro800':
elem_size = 256
elif cpu == 'controllogix':
elem_size = 88
else:
elem_size = 84
elif dt == 'timer' or dt == 'counter' or dt == 'control':
if cpu == 'controllogix' or cpu == 'micro800':
if myTag.endswith('.PRE') or myTag.endswith('.ACC') or myTag.endswith('.LEN') or myTag.endswith('.POS'):
elem_size = 4
tccType = 'int32'
elif myTag.endswith('.EN') or myTag.endswith('.TT') or myTag.endswith('.DN') or myTag.endswith('.CU') or myTag.endswith('.CD') or myTag.endswith('.OV') or myTag.endswith('.UN') or myTag.endswith('.UA') or myTag.endswith('.EU') or myTag.endswith('.EM') or myTag.endswith('.ER') or myTag.endswith('.UL') or myTag.endswith('.IN') or myTag.endswith('.FD'):
elem_size = 1
tccType = 'bool'
else:
elem_size = 12
else:
elem_size = 6
if '.' in myTag:
tccElement = myTag[myTag.index('.') + 1:]
myTag = myTag[:myTag.index('.')]
else:
tccElement = 'None'
else: # pid
elem_size = 46
if '.' in myTag:
pidElement = myTag[myTag.index('.') + 1:]
myTag = myTag[:myTag.index('.')]
# example addressing:
# 'protocol=ab_eip&gateway=192.168.1.10&cpu=mlgx&elem_size=4&elem_count=1&name=F8:0&debug=1'
# 'protocol=ab-eip&gateway=192.168.1.24&path=1,3&cpu=lgx&name=@tags'
# 'protocol=ab-eip&gateway=192.168.0.100&path=1,3&cpu=lgx&name=Program:MainProgram.@tags'
if '/' in currentTag and elem_count > 1:
stringTag = 'protocol=ab_eip&gateway=' + ipAddress + '&path=' + path + '&cpu=' + currentPLC + '&elem_size=' + str(elem_size) + '&elem_count=1&name=' + myTag
else:
if realElementCount > 0:
stringTag = 'protocol=ab_eip&gateway=' + ipAddress + '&path=' + path + '&cpu=' + currentPLC + '&elem_size=' + str(elem_size) + '&elem_count=' + str(realElementCount) + '&name=' + myTag
else:
stringTag = 'protocol=ab_eip&gateway=' + ipAddress + '&path=' + path + '&cpu=' + currentPLC + '&elem_size=' + str(elem_size) + '&elem_count=' + str(elem_count) + '&name=' + myTag
if int(pythonVersion[0]) >= 3:
tagID = plc_tag_create(stringTag.encode('utf-8'), timeout)
else:
tagID = plc_tag_create(stringTag, timeout)
# tag creation pending
while plc_tag_status(tagID) == 1:
time.sleep(0.01)
# handle the (un)successful tag creation
if plc_tag_status(tagID) < 0:
plc_tag_destroy(tagID)
connected = False
if btnStop['state'] == 'disabled':
btnStart['state'] = 'disabled'
btnStart['bg'] = 'lightgrey'
root.after(5000, start_connection)
else:
connected = True
connectionInProgress = False
lblTagStatus['bg'] = 'lightgreen'
if btnStop['state'] == 'disabled':
btnStart['state'] = 'normal'
btnStart['bg'] = 'lightgreen'
updateRunning = True
else:
start_update()
else:
lblTagStatus['bg'] = 'red'
tagValue['text'] = '~'
root.after(10000, start_connection)
except:
pass
def start_update_value():
global currentPLC
global path
global ipAddress
global myTag
global tagID
global currentTag
global connected
global updateRunning
'''
Call ourself to update the screen
'''
try:
cpu = selectedPLC.get()
ip = selectedIPAddress.get()
pth = selectedPath.get()
tag = selectedTag.get()
if tag != '':
if not connected or currentTag != tag or currentPLC != cpu or ipAddress != ip or path != pth:
currentTag = tag
currentPLC = cpu
ipAddress = ip
path = pth
if not connectionInProgress:
if btnStart['state'] != 'disabled':
btnStart['state'] = 'disabled'
btnStart['bg'] = 'lightgrey'
btnStop['state'] = 'normal'
btnStop['bg'] = 'lightgreen'
lbPLC['state'] = 'disabled'
lbDataType['state'] = 'disabled'
lbPID['state'] = 'disabled'
lbBit['state'] = 'disabled'
tbIPAddress['state'] = 'disabled'
tbPath['state'] = 'disabled'
tbTag['state'] = 'disabled'
connected = False
start_connection()
else:
if not updateRunning:
updateRunning = True
else:
if btnStart['state'] != 'disabled':
btnStart['state'] = 'disabled'
btnStart['bg'] = 'lightgrey'
btnStop['state'] = 'normal'
btnStop['bg'] = 'lightgreen'
lbPLC['state'] = 'disabled'
lbDataType['state'] = 'disabled'
lbPID['state'] = 'disabled'
lbBit['state'] = 'disabled'
tbIPAddress['state'] = 'disabled'
tbPath['state'] = 'disabled'
tbTag['state'] = 'disabled'
if tagID > 0:
try:
plc_tag_read(tagID, timeout)
if plc_tag_status(tagID) == 1 or plc_tag_status(tagID) < 0:
plc_tag_destroy(tagID)
connected = False
tagValue['text'] = 'not connected'
start_connection()
else:
dt = selectedDataType.get()
if dt == 'timer' or dt == 'counter' or dt == 'control':
if tccType != '':
dt = tccType
z = 0
strValues = ''
if dt == 'bool':
tagValue['text'] = set_bool_display(plc_tag_get_bit(tagID, 0))
elif (dt == 'bool array') or (bitIndex > -1):
while z < elem_count:
strValues += set_bool_display(plc_tag_get_bit(tagID, bitIndex + z)) + ', '
z += 1
tagValue['text'] = strValues[:-2]
elif dt == 'int8':
while z < elem_count:
strValues += str(plc_tag_get_int8(tagID, z * elem_size)) + ', '
z += 1
tagValue['text'] = strValues[:-2]
elif dt == 'uint8':
while z < elem_count:
strValues += str(plc_tag_get_uint8(tagID, z * elem_size)) + ', '
z += 1
tagValue['text'] = strValues[:-2]
elif dt == 'int16':
while z < elem_count:
strValues += str(plc_tag_get_int16(tagID, z * elem_size)) + ', '
z += 1
tagValue['text'] = strValues[:-2]
elif dt == 'uint16':
while z < elem_count:
strValues += str(plc_tag_get_uint16(tagID, z * elem_size)) + ', '
z += 1
tagValue['text'] = strValues[:-2]
elif dt == 'int32':
while z < elem_count:
strValues += str(plc_tag_get_int32(tagID, z * elem_size)) + ', '
z += 1
tagValue['text'] = strValues[:-2]