-
Notifications
You must be signed in to change notification settings - Fork 4
/
iec104MM2SS.py
1846 lines (1749 loc) · 66.2 KB
/
iec104MM2SS.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 python3
#
# ******************************************************
# IEC 104 Multiple Masters to Single Slave (IEC104MM2SS)
# By M. Medhat - 1 Nov 2021 - Ver 1.0
# ******************************************************
#
# Program is playing man in the middle role to connect
# multiple IEC 104 masters to single slave.
#
# Revision history:
# python:
# iec104mm2ss.py
#
# File: iec104mm2ss.csv
# Initial file as comma separated values (csv).
#
# This file: Read and write packets.
# Handle network sockets.
# Windows GUI
# Windows service
# *****************************************************
# Imports
# ------------------------------------------------------
from getopt import getopt
from ipaddress import ip_address,ip_network
import threading
from os import remove,stat,mkdir,system,name,devnull
from datetime import datetime
from socket import socket,AF_INET,SOCK_STREAM,SOL_SOCKET,SO_REUSEADDR,SHUT_RDWR,error,timeout,SOCK_DGRAM,gaierror,setdefaulttimeout
from binascii import hexlify
from signal import signal,SIGTERM
from struct import unpack,pack
from select import select
from sys import argv,byteorder,exit,stdout
from time import time,sleep
from os.path import isfile,getsize
from csv import reader
from atexit import register
if name == 'nt':
from win32api import SetSystemTime
else:
from os import WIFEXITED,WEXITSTATUS
# ******************************************************
# Variables
# ------------------------------------------------------
PYTHONUNBUFFERED='disable python buffer'
# program argument - see below
# define help message
help1="usage iec104mm2ss [[-h][--help]] [[-i][--ini] init-file] [[-t][--ntp_update_every_sec] sec] [[-s][--ntp_server] ntpserver]\n"
help2="example1: iec104mm2ss -i iec104mm2ss.csv\n"
help3="example2: iec104mm2ss --ntp_server pool.ntp.org --ntp_server time.windows.com\n"
help4="-s or --ntp_server could be included multiple times for multiple servers.\n"
help5="\t -h or --help\t\t\t\thelp message.\n"
help6="\t -i or --ini\t\t\t\tinit file (comma separated values), default iec104mm2ss.csv.\n"
help7="\t -t or --ntp_update_every_sec\t\tNTP update interval, default=900 seconds (requires admin privilege).\n"
help8="\t -s or --ntp_server\t\t\tNTP server, could be included multiple times (requires admin privilege).\n"
help9="\t -n or --nogui\t\t\t\tstart program without GUI interface.\n"
help10="\t -c or --service\t\t\tstart program as Windows service (without GUI interface).\n"
help11="\t To install the Windows service run 'iec104mm2ss --startup auto install'.\n"
help12="\t For more details please check the help file 'iec104mm2ss.pdf'.\n"
helpmess=help1+help2+help3+help4+help5+help6+help7+help8+help9+help10+help11+help12
if name == 'nt':
dir='log\\'
initfile='iec104mm2ss.csv'
else:
dir='./log/'
initfile='./iec104mm2ss.csv'
ntpserver=[]
timeupdated=''
updatetimegui=0
timeupdateevery=900 # in seconds
exitprogram=0
mainth=[]
th=[]
indexlist=[]
csvindexlist=[]
portnolist=[]
window=0
txtbx1thid=0
txtbx2thid=0
updatetoframe1=0
updatetoframe2=0
noofsys=0
programstarted=0
nogui=0
runasservice=0
logupdateperiod=10 # in case no GUI mode then update log files every 10 seconds.
# *****************************************************
# Functions
# -----------------------------------------------------
def signal_term_handler(signal, frame):
exit()
def cleanup():
global exitprogram,mainth,th,window,nogui
exitprogram=1
fh=[]
for a in mainth:
if a:
a.dataactive=0
fh.append(a.logfhw)
fh.append(a.logfhr)
for a in th:
if a:
a.join(0.1)
for a in mainth:
if a:
if not nogui:
deletertu(a)
a.c_mmainth.acquire()
tmpmmainth = a.mmainth.copy()
a.c_mmainth.release()
for i in tmpmmainth:
if i:
if i.readpacketth:
i.readpacketth.join(0.1)
i.join(0.1)
a.join(0.1)
for a in fh:
if a:
a.close()
if not nogui and window:
window.destroy()
def deletertu(self):
global window
tab_parent.select(0)
canvas.yview_moveto('0.0')
self.lbl_seqno.destroy()
self.lbl_sys.destroy()
self.lbl_status.destroy()
self.lbl_portno.destroy()
self.lbl_rtuno.destroy()
self.lbl_connectedat.destroy()
self.cbx_connectedmasters.destroy()
#if self.logevents:
self.cbx_action.destroy()
self.btn_apply.destroy()
window.update()
def opensocket(port):
# open socket
s=socket(AF_INET, SOCK_STREAM)
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind(('', port))
s.listen(1)
return s
def closesocket(self):
try:
self.s.close()
self.s = 0
except (error, OSError, ValueError, AttributeError):
self.s = 0
return 0
def openconnClient(self):
global exitprogram
conn = 0
self.srviprotate += 1
if self.srviprotate >= len(self.srvip):
self.srviprotate = 0
for i in range(self.srviprotate,len(self.srvip)):
if exitprogram:
break
# open connection for mm2ss client to real server
conn = socket( AF_INET, SOCK_STREAM )
try:
# set timeout = 3 sec.
conn.settimeout(3.0)
self.logfhw.write(str(datetime.now()) + ' : Client - ' + self.name + '.\n')
self.logfhw.write('\t\t\t ' + 'trying to connect to ' + self.srvip[i] + ':' + self.srvport[i] + '.\n')
self.logfilechanged=1
conn.connect((self.srvip[i], int(self.srvport[i])))
#self.conn.connect((address, int(self.srvport[i])))
self.timeidle=time()
self.t3timeidle=time()
except (timeout, gaierror, ConnectionRefusedError,OSError):
conn.close()
conn=0
if conn:
self.connectedip=self.srvip[i]
#tmpname = self.name.split(':')
self.logname = 'Client ' + self.name + ': ' + self.connectedip + ':' + self.srvport[i] + ':\n'
self.logfhw.write(str(datetime.now()) + ' : ' + self.logname)
self.logfhw.write('\t\t\t ' + 'connected to ' + self.srvip[i] + ':' + self.srvport[i] + '.\n')
self.logfilechanged=1
self.conn = conn
break
return conn
def openconn(self): # self thread is for slave.
# open connection
conn = 0
if self.s:
try:
conn, addr = self.s.accept()
except (error, OSError, ValueError):
conn = 0
self.s=closesocket(self)
self.s = opensocket(self.PORT)
if conn:
conn.setblocking(False)
acceptedaddr=0
for i in self.acceptnetsys:
try:
if ip_address(addr[0]) in ip_network(i):
acceptedaddr=1
break
except (ValueError):
pass
self.c_connectedmasters.acquire()
self.c_mmainth.acquire()
tmpmmainth = self.mmainth.copy()
tmpconnectedmasters = self.connectedmasters.copy()
noofmasters = self.noofmasters
self.c_mmainth.release()
accepted = True
if str(addr[0]) in tmpconnectedmasters:
if self.keepsameipconn == 'old':
accepted = False
elif self.keepsameipconn == 'new':
noofmasters -= 1
if self.conn and accepted and noofmasters < self.maxconn and (acceptedaddr or not ''.join(self.acceptnetsys)) and self.connectedip and (self.connectedip != str(addr[0])):
# insert new master connection
if self.newmasterth in tmpmmainth and self.newmasterth.is_alive(): # valid newmasterth?
if self.keepsameipconn == 'new' and str(addr[0]) in tmpconnectedmasters: # already have connection from same ip
for a in tmpmmainth:
if a.connectedip == str(addr[0]):
a.deletemaster = 1 # close and delete the old connection.
break
self.newmasterth.connectedip=str(addr[0])
self.newmasterth.name = 'Master: ' + str(addr[0]) + ':' + str(addr[1])
self.newmasterth.conn = conn
self.logfhw.write(str(datetime.now()) + ' : ' + self.newmasterth.name + ' Connected to IP: ' + str(addr[0]) + ', Port: ' + str(addr[1]) + '\n')
self.logfilechanged=1
else:
conn=closeconn(self,0,conn)
self.newmasterth = 0
else:
conn=closeconn(self,0,conn)
if self.newmasterth and not self.newmasterth.is_alive():
self.newmasterth = 0
self.c_connectedmasters.release()
return conn
def closeconnClient(self,setdisconnect=1):
if self.conn:
self.connectedip=''
try:
self.conn.shutdown(SHUT_RDWR) # 0 = done receiving, 1 = done sending, 2 = both
self.conn.close()
self.conn = 0
except (error, OSError, ValueError, AttributeError):
self.conn = 0
incseqno(self,'I')
if setdisconnect:
self.logfhw.write(str(datetime.now()) + ' : ' + self.logname)
self.logfhw.write('\t\t\t ' + 'disconnected .. trying connection ..\n')
if self.disconnectcause:
self.logfhw.write('\t\t\t ' + self.disconnectcause + '\n')
self.disconnectcause = ''
self.logfilechanged=1
initiate(self)
self.initialize=0
closemm2ssservers(self)
return 0
def closeconn(self,setdisconnect=1,conn=0): # self is for master.
if not setdisconnect:
try:
conn.shutdown(SHUT_RDWR) # 0 = done receiving, 1 = done sending, 2 = both
conn.close()
conn = 0
except (error, OSError, ValueError, AttributeError):
conn = 0
return 0
elif self.conn:
try:
self.conn.shutdown(SHUT_RDWR) # 0 = done receiving, 1 = done sending, 2 = both
self.conn.close()
self.conn = 0
except (error, OSError, ValueError, AttributeError):
self.conn = 0
self.slaveth.logfhw.write(str(datetime.now()) + ' : ' + self.name + ':\n')
self.slaveth.logfhw.write('\t\t\t ' + 'Disconnected .. waiting for connection ..\n')
if self.disconnectcause:
self.slaveth.logfhw.write('\t\t\t ' + self.disconnectcause + '\n')
self.disconnectcause = ''
self.slaveth.logfilechanged=1
return 0
def closemm2ssservers(self):
global exitprogram
self.c_mmainth.acquire()
tmpmmainth = self.mmainth.copy()
self.c_mmainth.release()
for a in tmpmmainth:
if exitprogram:
break
a.disconnectcause = 'Disconnecting becasue server restarting.'
a.deletemaster = 1
# read data
def readdata(self):
if self.conn:
if self.order: # master?
bufsize = self.slaveth.bufsize
else:
bufsize = self.bufsize
if (self.wrpointer+1) != self.rdpointer:
try:
data = self.conn.recv(2)
if data:
dt = datetime.now()
packetlen=b'\x00' # b'\x00'
if data[0] == 104:
packetlen=data[1]
elif data[1] == 104:
packetlen=self.conn.recv(1)
if packetlen != b'\x00':
data = hexlify(self.conn.recv(packetlen))
self.databuffer[self.wrpointer + 1] = [('68' + "{:02x}".format(packetlen) + data.decode()), str(dt)]
# if I-Format or S-Format packets?
i = int(self.databuffer[self.wrpointer + 1][0][4:4+2],16)
if (i & 1) == 0 or (i & 3) == 1:
self.sentnorec=0
self.t1timeout=0
# if I-Format
if (i & 1) == 0:
if not self.recnosend:
self.t2timeidle=time()
self.recnosend += 1
self.timeidle=time()
self.t3timeidle=time()
if self.wrpointer == (bufsize - 1):
self.wrpointer=-1
else:
self.wrpointer += 1
return packetlen
except (BlockingIOError, error, OSError, ValueError):
return 0
return True
return 0
def senddata(self,data,addtime=0):
dt = datetime.now()
while (not len(self.ready_to_write)):
if not self.conn:
return str(dt)
try:
if self.order:
kpackets = self.slaveth.k
else:
kpackets = self.k
# if I-Format packet
if (int.from_bytes(data[2:3], byteorder='little') & 1) == 0:
# wait for t1 timeout if exceeded k packets send without receive.
while self.sentnorec > kpackets:
if not self.conn:
return str(dt)
dt = datetime.now()
if addtime:
# prepare CP56Time2a time
ml = int((int(dt.second) * 1000) + (int(dt.microsecond) / 1000))
min = int(dt.minute)
hrs = int(dt.hour)
day = int(((int(dt.weekday()) + 1) * 32) + int(dt.strftime("%d")))
mon = int(dt.month)
yr = int(dt.strftime("%y"))
data = data + ml.to_bytes(2,'little') + min.to_bytes(1,'little') + hrs.to_bytes(1,'little') + day.to_bytes(1,'little') + mon.to_bytes(1,'little') + yr.to_bytes(1,'little')
# add seq numbers to data packet if it is I format
data1 = data[0:2] + (self.txlsb*2).to_bytes(1,'little') + self.txmsb.to_bytes(1,'little') + (self.rxlsb*2).to_bytes(1,'little') + self.rxmsb.to_bytes(1,'little') + data[6:]
self.conn.sendall(data1)
incseqno(self,'TX')
if not self.sentnorec:
self.t1timeout = time()
self.sentnorec += 1
self.recnosend = 0
self.t3timeidle=time()
else:
self.conn.sendall(data)
dt = datetime.now()
except (error, OSError, ValueError, AttributeError):
pass
return str(dt)
def incseqno(self,txrx):
if txrx == 'I':
self.txlsb=0
self.txmsb=0
self.rxlsb=0
self.rxmsb=0
elif txrx == 'TX':
self.txlsb += 1
if self.txlsb == 128:
self.txlsb=0
self.txmsb += 1
if self.txmsb == 256:
self.txmsb=0
elif txrx == 'RX':
self.rxlsb += 1
if self.rxlsb == 128:
self.rxlsb=0
self.rxmsb += 1
if self.rxmsb == 256:
self.rxmsb=0
def initiate(self):
self.sentnorec=0
self.t1timeout=0
self.recnosend=0
timeidle=time()
if self.order: # Master entry?
self.slaveth.logfilechanged=1
i = 0
self.slaveth.c_masterdataactive.acquire()
for a in self.slaveth.masterdataactive:
if a == self.order:
self.slaveth.masterdataactive[i] = 0
break
i += 1
self.slaveth.c_masterdataactive.release()
else:
self.startdttime=0
self.statusvalue="NO"
self.statuscolor='red'
self.connectedatvalue=' '
self.updatestatusgui=1
self.logfilechanged=1
self.dataactive=0
self.rcvtfperiodmin=1000000
self.time1=0
# set initialize flag
self.initialize=1
# read packet from real server to mm2ss client.
def readpacketClient(self):
global exitprogram
# if no data for t3 seconds then send testfr packet.
if ((time() - self.t3timeidle) > self.t3) and self.conn:
# send testfr act packet
sendpacket=b'\x68\x04\x43\x00\x00\x00'
senddata(self,sendpacket)
self.t3timeidle=time()
# send S-Format packet if (received w packets and we have space in data buffer) or t2 expired.
if (self.recnosend >= self.w and (self.wrpointer+1) != self.rdpointer) or (self.recnosend and ((time() - self.t2timeidle) > self.t2)):
self.recnosend=0
sendpacket=b'\x68\x04\x01\x00' + (self.rxlsb*2).to_bytes(1,'little') + self.rxmsb.to_bytes(1,'little')
dt=senddata(self,sendpacket)
else:
if (self.wrpointer+1) == self.rdpointer:
self.logfhw.write(str(datetime.now()) + ' : ' + self.logname)
self.logfhw.write('\t\t\t ' + 'Receiving buffer is full, try to increase buffer or reduce allowed connections.\n')
self.logfilechanged=1
self.c_masterdataactive.acquire()
summasterdataactive = sum(self.masterdataactive)
self.c_masterdataactive.release()
if self.conn and not self.startdttime and not self.dataactive and summasterdataactive: # At least one master connected.
# send startdt act
sendpacket=b'\x68\x04\x07\x00\x00\x00'
dt=senddata(self,sendpacket)
self.startdttime=time()
self.logfhw.write(dt + ' : ' + self.logname)
self.logfhw.write('\t\t\t ' + 'startdt transmitted.\n')
self.logfilechanged=1
elif self.conn and not self.startdttime and self.dataactive and not summasterdataactive: # No master connected.
# send stopdt act
sendpacket=b'\x68\x04\x13\x00\x00\x00'
dt=senddata(self,sendpacket)
self.startdttime=time()
self.logfhw.write(dt + ' : ' + self.logname)
self.logfhw.write('\t\t\t ' + 'All masters down, stopdt act transmitted.\n')
self.logfilechanged=1
# read from mm2ss servers and send to real server
readmm2ssserver(self)
packet=''
# read the packet from buffer
if self.rdpointer != self.wrpointer:
packet, dt=self.databuffer[self.rdpointer+1]
self.timeidle=time()
self.t3timeidle=time()
seqnotxlsb=int(packet[4:4+2],16)
if self.rdpointer == (self.bufsize - 1):
self.rdpointer=-1
else:
self.rdpointer += 1
# decode U format packets
if packet[4:4+2] == '0b': # startdt con packet
self.startdttime=0
self.dataactive=1
self.logfhw.write(dt + ' : ' + self.logname)
self.logfhw.write('\t\t\t ' + 'startdt con received.' + '\n')
self.statusvalue="YES"
self.statuscolor='green'
self.connectedatvalue=dt
self.updatestatusgui=1
elif packet[4:4+2] == '07': # startdt act packet should not come from slave
self.startdttime=0
# send startdt con
sendpacket=b'\x68\x04\x0B\x00\x00\x00'
senddata(self,sendpacket)
self.logfhw.write(dt + ' : ' + self.logname)
self.logfhw.write('\t\t\t ' + 'startdt act received and con transmitted.' + '\n')
self.statusvalue="YES"
self.statuscolor='green'
self.connectedatvalue=dt
self.updatestatusgui=1
self.dataactive=1
elif packet[4:4+2] == '43': # testfr act packet
rcvtf=time()
rcvtfperiod=round(rcvtf - self.time1,1)
# send testfr con packet
sendpacket=b'\x68\x04\x83\x00\x00\x00'
senddata(self,sendpacket)
if rcvtfperiod < self.rcvtfperiodmin and self.time1 != 0:
self.rcvtfperiodmin=rcvtfperiod
self.logfhw.write(dt + ' : ' + self.logname)
self.logfhw.write('\t\t\t ' + 'Received testfr act minimum period: ' + "{:04.1f}".format(float(rcvtfperiod)) + ' seconds.' + '\n')
self.time1=rcvtf
elif packet[4:4+2] == '13': # stopdt act packet
# send stopdt con
sendpacket=b'\x68\x04\x23\x00\x00\x00'
senddata(self,sendpacket)
self.logfhw.write(dt + ' : ' + self.logname)
self.logfhw.write('\t\t\t ' + 'stopdt act received and con transmitted.' + '\n')
# initialize
initiate(self)
elif packet[4:4+2] == '23': # stopdt con packet
self.logfhw.write(dt + ' : ' + self.logname)
self.logfhw.write('\t\t\t ' + 'stopdt con received.' + '\n')
# initialize
initiate(self)
elif (int(packet[4:4+2],16) & 0x03) == 1: # S-format packet.
pass
# check if it is I format (bit 0=0 of 3rd byte or 4 and 5 digits of databuffer) then increase RX
elif (seqnotxlsb & 1) == 0:
incseqno(self,'RX')
# end of initialization packet received.
if packet[12:12+2] == '46':
pass
else:
# forward the packet to mm2ss server
self.c_mmainth.acquire()
tmpmmainth = self.mmainth.copy()
self.c_mmainth.release()
for a in tmpmmainth:
if exitprogram:
break
org=int(packet[18:18+2],16)
# if spi, dpi or ami or org=0 then forward to all mm2ss clients.
# forward control direction I-Frames to master with order = org address.
if int(packet[12:12+2],16) <= 40 or not org or org == a.order:
if not a.deletemaster and ((a.packet2server_wrp+1) != a.packet2server_rdp) and a.dataactive:
a.packet2server[a.packet2server_wrp+1] = bytearray.fromhex(packet)
if a.packet2server_wrp == (self.bufsize - 1):
a.packet2server_wrp=-1
else:
a.packet2server_wrp += 1
self.logfilechanged=1
# read packet from real client to mm2ss server.
def readpacket(self):
global mainth
# if no data for t3 seconds then send testfr packet.
if ((time() - self.t3timeidle) > self.slaveth.t3) and self.slaveth.conn:
# send testfr act packet
sendpacket=b'\x68\x04\x43\x00\x00\x00'
senddata(self,sendpacket)
self.t3timeidle=time()
# send S-Format packet if (received w packets and we have space in data buffer) or t2 expired.
if (self.recnosend > self.slaveth.w and (self.wrpointer+1) != self.rdpointer) or (self.recnosend and ((time() - self.t2timeidle) > self.slaveth.t2)):
self.recnosend=0
sendpacket=b'\x68\x04\x01\x00' + (self.rxlsb*2).to_bytes(1,'little') + self.rxmsb.to_bytes(1,'little')
senddata(self,sendpacket)
else:
if (self.wrpointer+1) == self.rdpointer:
self.slaveth.logfhw.write(str(datetime.now()) + ' : ' + self.name)
self.slaveth.logfhw.write('\t\t\t ' + 'Receiving buffer is full, try to increase buffer or reduce allowed connections.\n')
self.slaveth.logfilechanged=1
# read from mm2ss client and send to real client
readmm2ssclient(self)
packet=''
# read the packet from buffer
if self.rdpointer != self.wrpointer:
packet, dt=self.databuffer[self.rdpointer+1]
self.timeidle=time()
self.t3timeidle=time()
seqnotxlsb=int(packet[4:4+2],16)
if self.rdpointer == (self.slaveth.bufsize - 1):
self.rdpointer=-1
else:
self.rdpointer += 1
# decode U format packets
if packet[4:4+2] == '07': # startdt act packet
# if mm2ss client connected to real server? then we will reply for everything
# send startdt con
sendpacket=b'\x68\x04\x0B\x00\x00\x00'
senddata(self,sendpacket)
self.slaveth.logfhw.write(dt + ' : ' + self.name + ':\n')
self.slaveth.logfhw.write('\t\t\t ' + 'startdt act/con done.' + '\n')
if not self.dataactive:
self.dataactive=1
self.slaveth.c_mmainth.acquire()
tmpmmainth = self.slaveth.mmainth.copy()
self.slaveth.c_mmainth.release()
i = 0
for a in tmpmmainth:
if a == self:
self.slaveth.c_masterdataactive.acquire()
self.slaveth.masterdataactive[i] = self.order
self.slaveth.c_masterdataactive.release()
break
i += 1
# send end of initialization
sendpacket=b'\x68\x0E\x00\x00\x00\x00\x46\x01\x04\x00' + int(self.slaveth.rtuno).to_bytes(2,'little') + b'\x00\x00\x00\x00'
dt=senddata(self,sendpacket)
self.slaveth.logfhw.write(dt + ' : ' + self.name + ':\n')
self.slaveth.logfhw.write('\t\t\t ' + 'End of initialization transmitted.' + '\n')
elif packet[4:4+2] == '43': # testfr act packet
rcvtf=time()
rcvtfperiod=round(rcvtf - self.time1,1)
# send testfr con packet
sendpacket=b'\x68\x04\x83\x00\x00\x00'
senddata(self,sendpacket)
if rcvtfperiod < self.rcvtfperiodmin and self.time1 != 0:
self.rcvtfperiodmin=rcvtfperiod
self.slaveth.logfhw.write(dt + ' : ' + self.name + ':\n')
self.slaveth.logfhw.write('\t\t\t ' + 'Received testfr act minimum period: ' + "{:04.1f}".format(float(rcvtfperiod)) + ' seconds.' + '\n')
self.time1=rcvtf
elif packet[4:4+2] == '13': # stopdt act packet
# send stopdt con
sendpacket=b'\x68\x04\x23\x00\x00\x00'
senddata(self,sendpacket)
self.slaveth.logfhw.write(dt + ' : ' + self.name + ':\n')
self.slaveth.logfhw.write('\t\t\t ' + 'stopdt act/con done.' + '\n')
# initialize
initiate(self)
elif (int(packet[4:4+2],16) & 0x03) == 1: # received S-Format.
pass
# check if it is I format (bit 0=0 of 3rd byte or 4 and 5 digits of databuffer) then increase RX
elif (seqnotxlsb & 1) == 0:
incseqno(self,'RX')
# forward the packet to mm2ss client
if (self.packet2client_wrp+1) != self.packet2client_rdp:
self.packet2client[self.packet2client_wrp+1] = bytearray.fromhex(packet)
# set org address to self.order
self.packet2client[self.packet2client_wrp+1][9:9+1]=self.order.to_bytes(1,'little')
if self.packet2client_wrp == (self.slaveth.bufsize - 1):
self.packet2client_wrp = -1
else:
self.packet2client_wrp += 1
self.slaveth.logfilechanged=1
def readmm2ssclient(self):
# read from mm2ss client and send to real client
if self.packet2server_rdp != self.packet2server_wrp and self.dataactive:
packet=self.packet2server[self.packet2server_rdp+1]
if self.packet2server_rdp == (self.slaveth.bufsize - 1):
self.packet2server_rdp = -1
else:
self.packet2server_rdp += 1
packet[9:9+1]=b'\x00' # set org back to 0
senddata(self,packet)
def write2criticallists(self,op='',index=0,valuemm=0,valueconm=0,valuedatact=0):
global exitprogram
if op == 'clear': # clear lists
self.mmainth.clear()
self.connectedmasters.clear()
self.masterdataactive.clear()
elif op == 'insert': # insert new value in list
self.mmainth.insert(index,valuemm)
self.connectedmasters.insert(index,valueconm)
self.masterdataactive.insert(index,valuedatact)
elif op == 'pop': # pop index
self.mmainth.pop(index)
self.connectedmasters.pop(index)
self.masterdataactive.pop(index)
elif op == 'remove': # remove value
self.mmainth.remove(valuemm)
self.connectedmasters.remove(valueconm)
self.masterdataactive.remove(valuedatact)
elif op == 'write': # write value
self.mmainth[index] = value
self.connectedmasters[index] = valueconm
self.masterdataactive[index] = valuedatact
def readmm2ssserver(self):
global exitprogram
# read from mm2ss servers and send to real server
self.c_mmainth.acquire()
tmpmmainth = self.mmainth.copy()
self.c_mmainth.release()
for a in tmpmmainth:
if exitprogram:
break
if not a.deletemaster and a.packet2client_rdp != a.packet2client_wrp:
packet=a.packet2client[a.packet2client_rdp+1]
if a.packet2client_rdp == (self.bufsize - 1):
a.packet2client_rdp = -1
else:
a.packet2client_rdp += 1
senddata(self,packet)
def readpacketthreadClient (self):
global exitprogram
initiate(self)
while True:
if exitprogram:
break
if self.initialize:
self.logfhw.write(str(datetime.now()) + ' : ' + self.logname)
self.logfhw.write('\t\t\t ' + 'Initialized ..\n')
self.initialize=0
if self.conn:
readpacketClient(self)
def readpacketthread (self):
global exitprogram
initiate(self)
while True:
if exitprogram:
break
if self.deletemaster:
break
if self.initialize:
self.slaveth.logfhw.write(str(datetime.now()) + ' : ' + self.name + ':\n')
self.slaveth.logfhw.write('\t\t\t ' + 'Initialized ..\n')
self.initialize=0
if self.conn:
readpacket(self)
'''
Returns the epoch time fetched from the NTP server passed as argument.
Returns none if the request is timed out (5 seconds).
'''
def gettime_ntp(addr='time.nist.gov'):
# http://code.activestate.com/recipes/117211-simple-very-sntp-client/
TIME1970 = 2208988800 # Thanks to F.Lundh
client = socket( AF_INET, SOCK_DGRAM )
data = '\x1b' + 47 * '\0'
try:
# Timing out the connection after 5 seconds, if no response received
client.settimeout(5.0)
client.sendto( data.encode(), (addr, 123))
data, address = client.recvfrom( 1024 )
if data:
epoch_time = unpack( '!12I', data )[10]
epoch_time -= TIME1970
return epoch_time
except (timeout, gaierror, LookupError):
return None
def ntpthread():
global ntpserver,timeupdateevery,exitprogram,timeupdated,updatetimegui
# Iterates over every server in the list until it finds time from any one.
while True:
if exitprogram:
break
for server in ntpserver:
epoch_time = gettime_ntp(server)
if epoch_time is not None:
# Local time is obtained using fromtimestamp()
localTime = datetime.fromtimestamp(epoch_time).strftime("%Y-%m-%d %H:%M:%S")
timeupdated="Time updated at: " + localTime + " from " + server[0:0+50]
try:
if name == 'nt': # windows
# SetSystemTime takes time as argument in UTC time. UTC time is obtained using utcfromtimestamp()
utcTime = datetime.utcfromtimestamp(epoch_time)
SetSystemTime(utcTime.year, utcTime.month, utcTime.weekday(), utcTime.day, utcTime.hour, utcTime.minute, utcTime.second, 0)
else:
localTimetoset = datetime.fromtimestamp(epoch_time).strftime("%H:%M:%S")
exitcode = system('date +%T -s ' + localTimetoset)
if WIFEXITED(exitcode):
if WEXITSTATUS(exitcode):
timeupdated = "No root privilege, cannot update time."
except (IOError, BaseException ) as e:
if name == 'nt':
if e.args[0] == 1314:
timeupdated = "No admin privilege, cannot update time."
else:
if (e[0] == errno.EPERM):
timeupdated = "No root privilege, cannot update time."
break
updatetimegui=1
sleep(timeupdateevery)
def restartconnClient(self,message=''):
if message:
self.logfhw.write(str(datetime.now()) + ' : ' + message)
self.logfilechanged=1
self.conn=closeconnClient(self)
self.conn=openconnClient(self)
# define iec104 thread for mm2ss client
class iec104threadClient (threading.Thread):
global nogui
def __init__(self, threadID, name,portno,rtuno,srvipport,srvport,srvip,csvindex,logevents,bufsize):
threading.Thread.__init__(self)
self.threadID = threadID
self.mmainth=[] # list of main masters threads
self.order=0
self.name = name
self.logname = name
self.PORT = portno
self.connectedip=''
self.logfilename=''
self.logfhw=0
self.logfhr=0
self.logfilechanged=0
self.rtunohex = "{:04x}".format(int(rtuno))
self.rtunohex = self.rtunohex[2:2+2] + self.rtunohex[0:2]
self.rtuno = rtuno
self.dataactive=0
self.masterdataactive=[]
self.connectedmasters=[]
self.noofmasters=-1
self.logevents=logevents
self.initialize=0
self.rcvtfperiodmin=1000000
self.sentnorec=0
self.t1timeout=0
self.recnosend=0
self.srvip=srvip.copy()
self.srvport=srvport.copy()
self.acceptnetsys=''
self.srviprotate = -1
self.disconnectcause=''
self.restartconn=0
self.startdttime=0
self.index=0
self.csvindex=csvindex
self.maxconn=5
self.bufsize=bufsize
# threads locks
self.c_mmainth = threading.Condition()
self.c_masterdataactive = threading.Condition()
self.c_connectedmasters = threading.Condition()
self.newmasterth=0
self.keepsameipconn='all' # accept multiple master connections from same ip address
# py will write this variable when connection disconnected.
self.txlsb=0
self.txmsb=0
self.rxlsb=0
self.rxmsb=0
self.conn=0
self.s=0
self.time1=0
# timeidle > t3 (time of testfr packet). if not receiving data during timeidle then disconnect.
self.timeidle=time() # after nt3 * t3 disconnect and wait for new connection.
self.t2timeidle=time() # send S packet if t2 (10 sec) expired from last received I packet without sending I packet.
self.t3timeidle=time() # send testfr packet if t3 expired without send or receive data.
# timeidle > t3 (time of testfr packet). if not receiving data during timeidle then disconnect.
self.tdisconnect=60
# IEC 104 constants
self.t1=15 # Time-Out of send or test APDU after which we must disconnect if no ack of I-Format packets.
self.t2=10 # send S-Format if no receive I-format without sending I format for t2 seconds.
self.t3=20 # send testfr packet if no data for t3 seconds.
self.w=8
self.k=12
# fifo buffer variables used between this mm2ss client and real server
self.rdpointer=-1
self.wrpointer=-1
self.databuffer=[[0] * 2 for i in range(self.bufsize+1)]
self.ready_to_write=[]
if not nogui:
# GUI variables
self.slaveipportnet=srvipport
self.filternet=''
self.lbl_seqno=tk.Label(frame, text=self.csvindex, relief=tk.RIDGE, width=5,bg="white", fg="blue")
self.lbl_seqno.grid(row=self.threadID-1, column=0)
self.lbl_sys=tk.Label(frame, text=self.name, relief=tk.RIDGE, width=16,bg="white", fg="red")
self.lbl_sys.grid(row=self.threadID-1, column=1)
self.lbl_status=tk.Label(frame, text='NO', relief=tk.RIDGE, width=6, bg="white", fg="red")
self.lbl_status.grid(row=self.threadID-1, column=2)
self.statusvalue='NO'
self.statuscolor='red'
self.updatestatusgui=0
self.lbl_portno=tk.Label(frame, text=self.PORT, relief=tk.RIDGE, width=5, bg="white", fg="blue")
self.lbl_portno.grid(row=self.threadID-1, column=3)
self.lbl_rtuno=tk.Label(frame, text=self.rtuno, relief=tk.RIDGE, width=5, bg="white", fg="blue")
self.lbl_rtuno.grid(row=self.threadID-1, column=4)
self.lbl_connectedat=tk.Label(frame, text=' ',bg="white", relief=tk.RIDGE, width=26, fg="green")
self.lbl_connectedat.grid(row=self.threadID-1, column=5)
self.connectedatvalue=' '
self.cbx_connectedmasters=ttk.Combobox(frame, width=24,values=[""])
self.cbx_connectedmasters.grid(row=self.threadID-1, column=6)
CreateToolTip(self.cbx_connectedmasters,"Currently connected masters to this client.")
#if self.logevents:
self.cbx_action=ttk.Combobox(frame, width=21,
values=[
"Open log file",
"Show log in Tab2-Text1",
"Show log in Tab2-Text2"])
self.cbx_action.grid(row=self.threadID-1, column=7)
CreateToolTip(self.cbx_action,"Select action to be applied/executed for Client.")
self.btn_apply=tk.Button(master=frame, text="Apply", command=lambda: applyaction(self))
self.btn_apply.grid(row=self.threadID-1, column=8)
CreateToolTip(self.btn_apply,"Apply action selected in combo box to Client.")
def run(self):
global exitprogram,programstarted
ready_to_read=[]
message=''
# wait until starting all threads.
while not programstarted:
pass
cleanuptimeout = time()
while True:
if exitprogram:
# close conn
if self.conn:
self.disconnectcause = 'Exiting program.'
self.conn=closeconnClient(self)
if self.s:
self.s = closesocket(self)
break
# cleanup deleted masters every 1 second.
if (time() - cleanuptimeout) > 1:
tmpth = 0
# create new thread
if not self.newmasterth:
tmpth = iec104thread('New master', self)
tmpth.daemon = True
# generate rest of the threads
tmpth1 = threading.Thread(target=readpacketthread,args=(tmpth,), daemon=True)
tmpth.readpacketth = tmpth1
self.c_mmainth.acquire()
self.c_connectedmasters.acquire()
self.c_masterdataactive.acquire()
tmpmmainth = self.mmainth.copy()
i = 0;j = 0;tmpconnectedmasters = 0
for a in tmpmmainth:
if tmpth and not tmpth.order and (a.order - 1) != i: # we can insert new master here.
tmpth.order = (i - j) + 1
if a.deletemaster:
write2criticallists(self,op='pop',index=(i-j))
j += 1
a.readpacketth.join(0.1)
a.join(0.1)
elif 'New master' not in a.name:
if self.connectedmasters[i-j] != a.connectedip:
self.connectedmasters[i-j] = a.connectedip
self.updatestatusgui = 1
tmpconnectedmasters += 1
i += 1
if tmpth and not tmpth.order:
tmpth.order = (i -j) + 1
if tmpth and tmpth.order:
# append entry in critical lists at once
write2criticallists(self,op='insert',index=(tmpth.order-1),valuemm=tmpth,valueconm='0',valuedatact=0)
tmpth.threadID = int(str(self.threadID) + str(tmpth.order))
self.c_mmainth.release()
self.c_masterdataactive.release()
if self.noofmasters != tmpconnectedmasters:
self.noofmasters = tmpconnectedmasters
self.logfhw.write(str(datetime.now()) + ' : ' + self.name + '\n')
self.logfhw.write('\t\t\t ' + 'No. of connected masters: ' + str(tmpconnectedmasters) + '\n')
self.logfilechanged=1
if tmpth and tmpth.order:
# allow to open new connection
tmpth.start()
tmpth1.start()
self.newmasterth = tmpth
self.c_connectedmasters.release()
cleanuptimeout = time()
# if I-frame timed out?
if (self.t1timeout and (time() - self.t1timeout) > self.t1):
self.disconnectcause = 'Client disconnecting becasue t1 expired before receiving I-Frame ack..'
self.sentnorec = 0
self.t1timeout = 0
self.restartconn=1
# if not received startdt con after t1 timeout then disconnect
if self.conn and self.startdttime and ((time() - self.startdttime) > self.t1):
if self.dataactive:
message = 'Client - stopdt con not received for ' + str(self.t1) + ' seconds .. disconnecting ..\n'
else:
message = 'Client - startdt con not received for ' + str(self.t1) + ' seconds .. disconnecting ..\n'
self.restartconn=1
self.startdttime=0
# timeidle > tdisconnect. if not receiving data during timeidle then disconnect.
if ((time() - self.timeidle) > self.tdisconnect) and self.conn:
message = 'Client - No received data for ' + str(self.tdisconnect) + ' seconds .. disconnecting ..\n'
self.timeidle = time()
self.restartconn=1
if self.restartconn:
self.restartconn=0
restartconnClient(self,message)