-
Notifications
You must be signed in to change notification settings - Fork 2
/
iec104rs.py
1869 lines (1779 loc) · 80.9 KB
/
iec104rs.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 RTU simulator
# By M. Medhat - 7 Feb 2021 - Ver 1.0
# ******************************************************
# Revision history:
# Ver 0.0 - Tested startdt, GI and dummy dpi.
# Ver 0.1 - spi, dpi, NVA meas., SVA meas., time tag.
# Ver 0.2 - FLT meas., sco and dco simulation,
# millisec to time stamp, time sync.
# Ver 0.3 - Performance enhancements.
# Ver 0.4 - rco simulation.
# Logging for all signals.
# Signals attributes such as:
# Command select/execute.
# Command pulse information.
# Time saving.
# Fixing bugs related to:
# - Commands.
# - Time sync.
# Ver 0.5 - re-write socket, ieee754, microseconds
# in python
# Ver 0.6 - Parallel operation, now can send GI, DPI,
# SPI, AMI, receive commands, time sync,
# etc. simultaneously.
# - Fixing some bugs related to network socket.
# Ver 1.0 - Windows GUI, myltithreading operation.
# local clock time update via NTP server(s).
# RTU can have unique accepted net/hosts.
# Support for unlimited number of RTUs.
# RTUs may have same RTU no. but unique port.
# RTUs can share same iodata.csv file or have
# separated file for each RTU.
#
# python:
# iec104rs.py - socket, ieee754, microseconds
#
# File: iodata.csv
# IO database as comma separated values (csv).
# all RTUs can share same iodata.csv file or have
# separated file for each RTU.
#
# This file: Read and write packets.
# Handle network sockets.
# Calculate Ieee 754 float points.
# Add microseconds to timetag.
# Windows GUI
# *****************************************************
# Imports
# ------------------------------------------------------
import tkinter as tk
from tkinter import ttk
from tkinter.font import Font
from tkinter import messagebox
from getopt import getopt
from ipaddress import ip_address,ip_network
import threading
from os import remove,stat,mkdir,system,name
from datetime import datetime
from socket import socket,AF_INET,SOCK_STREAM,SOL_SOCKET,SO_REUSEADDR,SHUT_RDWR,error,timeout,SOCK_DGRAM,gaierror,IPPROTO_TCP,TCP_NODELAY
from binascii import hexlify
from signal import signal,SIGTERM
from struct import unpack,pack
from select import select
from sys import argv,byteorder,exit
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
#import ctypes
# ******************************************************
# Variables
# ------------------------------------------------------
PYTHONUNBUFFERED='disable python buffer'
# program argument - see below
# define help message
help1="usage iec104rs [[-h][--help]] [[-i][--ini] init-file] [[-t][--ntp_update_every_sec seconds] sec] [[-s][--ntp_server ntpserver] server]\n"
help2="example1: iec104rs -i iec104rs1.csv\n"
help3="example2: iec104rs --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 iec104rs.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"
helpmess=help1+help2+help3+help4+help5+help6+help7+help8
if name == 'nt':
dir='log\\'
datadir='data\\'
initfile='iec104rs.csv'
else:
dir='./log/'
datadir='./data/'
initfile='./iec104rs.csv'
ntpserver=[]
timeupdated=''
updatetimegui=0
timeupdateevery=900 # in seconds
exitprogram=0
pulsemess='No pulseShort Long Persist '
valuemess='OFFON '
regmess='DECREMENTINCREMENT'
'''
if name == 'nt':
is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0
else:
is_admin = 2 # not windows so no need for NTP updates.
'''
# cmd program files
cmdtime=0
cmdvalue=0
cmdtype=0
ioacmdv=0
cmdrtuno=0
# index program files
indextime=0
indexvalue=0
repeattimeindex=0 # repeat sending index for number of seconds (7 digits).
stopsendindex=0
# iec 104 supported types for index send
types = [1,3,9,11,13,30,31,34,35,36]
bufsize=100
mainth=[]
th=[]
portnolist=[]
window=0
txtbx1thid=0
txtbx2thid=0
updatetoframe1=0
updatetoframe2=0
noofrtu=0
programstarted=0
# *****************************************************
# Functions
# -----------------------------------------------------
def signal_term_handler(signal, frame):
exit()
def cleanup():
global exitprogram,mainth,th,window
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:
deletertu(a)
a.join(0.1)
for a in fh:
if a:
a.close()
if window:
window.destroy()
def deletertu(self):
tab_parent.select(0)
canvas.yview_moveto('0.0')
self.lbl_seqno.destroy()
self.lbl_sys.destroy()
self.lbl_status.destroy()
self.lbl_rtuno.destroy()
self.lbl_portno.destroy()
self.lbl_gi.destroy()
self.lbl_index.destroy()
self.lbl_connectedat.destroy()
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.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1)
s.bind(('', port))
s.listen(1)
return s
def closesocket(s):
try:
s.close()
except (error, OSError, ValueError):
pass
return 0
def openconn(self):
# open connection
if self.s:
try:
self.conn, addr = self.s.accept()
self.timeidle=time()
except (error, OSError, ValueError):
self.conn = 0
if self.conn:
self.conn.setblocking(False)
self.s=closesocket(self.s)
acceptedaddr=0
for i in self.acceptnetsys:
try:
if ip_address(addr[0]) in ip_network(i):
acceptedaddr=1
break
except (ValueError):
pass
if acceptedaddr or not ''.join(self.acceptnetsys):
self.logfhw.write(str(datetime.now()) + ' : Connected to IP: ' + str(addr[0]) + ', Port: ' + str(addr[1]) + '\n')
self.logfilechanged=1
else:
self.conn=closeconn(self,0)
self.s=opensocket(self.PORT)
return self.conn
def closeconn(self,setdisconnet=1):
if self.conn:
try:
self.conn.shutdown(SHUT_RDWR) # 0 = done receiving, 1 = done sending, 2 = both
self.conn.close()
except (error, OSError, ValueError):
pass
incseqno(self,'I')
if setdisconnet:
self.disconnected=1
return 0
# read data
def readdata(self):
global bufsize
if self.conn:
if (self.wrpointer+1) != self.rdpointer:
try:
data = self.conn.recv(2)
if data:
dt = datetime.now()
packetlen=b'0'
if data[0] == 104:
packetlen=data[1]
elif data[1] == 104:
packetlen=self.conn.recv(1)
if packetlen != b'0':
data = hexlify(self.conn.recv(packetlen))
self.databuffer[self.wrpointer + 1] = [data.decode(), str(dt)]
self.c_sentnorec.acquire()
self.sentnorec=0
self.c_sentnorec.release()
self.timeidle=time()
if self.wrpointer == (bufsize - 1):
self.wrpointer=-1
else:
self.wrpointer += 1
return packetlen
except (BlockingIOError, error, OSError, ValueError):
pass
def senddata(self,data,addtime=0):
while not len(self.ready_to_write):
pass
self.c_senddata.acquire()
#while self.insenddata:
# pass
#self.insenddata=1
# wait if exceeded k packets send without receive.
oktosend = 0
while True:
self.c_sentnorec.acquire()
if self.sentnorec < self.kpackets:
oktosend = 1
self.c_sentnorec.release()
if oktosend:
break
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')
try:
# add seq numbers to data packet if it is I format
if (int.from_bytes(data[2:3], byteorder='little') & 1) == 0:
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')
self.c_sentnorec.acquire()
self.sentnorec += 1
self.c_sentnorec.release()
else:
self.conn.sendall(data)
except (error, OSError, ValueError, AttributeError):
pass
self.timeidle=time()
#self.insenddata=0
self.c_senddata.release()
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.dataactive=0
self.statusvalue="NO"
self.statuscolor='red'
self.connectedatvalue=' '
self.updatestatusgui=1
self.c_sentnorec.acquire()
self.sentnorec=0
self.c_sentnorec.release()
self.rcvtfperiodmin=1000000
self.time1=0
# set initialize flag
self.initialize=1
self.logfilechanged=1
def isfloat(i):
try:
float(i)
except ValueError:
return False
return ('nan' not in i.lower())
#return i.replace('+','',1).replace('-','',1).replace('.','',1).isdigit()
def readpacket(self):
global ioacmdv,cmdtype,cmdvalue,cmdtime,cmdrtuno,bufsize,pulsemess,regmess,valuemess
packet=''
# read the packet from buffer
if self.rdpointer != self.wrpointer:
packet, dt=self.databuffer[self.rdpointer+1]
seqnotxlsb=int(packet[0:2],16)
if self.rdpointer == (bufsize - 1):
self.rdpointer=-1
else:
self.rdpointer += 1
# decode U format packets
if packet[0:2] == '07': # startdt act packet
# send startdt con
sendpacket=b'\x68\x04\x0B\x00\x00\x00'
senddata(self,sendpacket)
self.logfhw.write(dt + ' : startdt act/con done.' + '\n')
if not self.dataactive:
# send end of initialization
sendpacket=b'\x68\x0E\x00\x00\x00\x00\x46\x01\x04\x00' + int(self.rtuno).to_bytes(2,'little') + b'\x00\x00\x00\x00'
senddata(self,sendpacket)
self.logfhw.write(dt + ' : End of initialization transmitted.' + '\n')
self.dataactive=1
self.statusvalue="YES"
self.statuscolor='green'
self.connectedatvalue=dt
self.updatestatusgui=1
elif packet[0: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 + ' : Received testfr act minimum period: ' + "{:04.1f}".format(float(rcvtfperiod)) + ' seconds.' + '\n')
self.time1=rcvtf
elif packet[0:2] == '13': # stopdt act packet
# send stopdt con
sendpacket=b'\x68\x04\x23\x00\x00\x00'
senddata(self,sendpacket)
self.logfhw.write(dt + ' : stopdt act/con done.' + '\n')
# initialize
initiate(self)
# check if it is I format (bit 0=0 of 3rd byte or 4 and 5 digits of databuffer) then increase RX
if (seqnotxlsb & 1) == 0:
incseqno(self,'RX')
self.org = packet[14:14+2] # get org. address
# check if required to check filter on same type id and same ioa and same value
if len(packet) >= 28:
ioacmd=bytearray.fromhex(packet[20:20+6])
if self.checkfilter and ((not self.filtertypid.isdigit()) or int(self.filtertypid) == int(packet[8:8+2],16)) and ((not self.filterioa.isdigit()) or (self.filterioa == str(int.from_bytes(ioacmd,'little')))) and ((not self.filtervalue.isdigit()) or (int(self.filtervalue) == int(packet[26:26+2],16) & 0x03)):
self.checkfilter=''
# decode I format packets
if packet[8:8+2] == '64' and (packet[16:16+4] == self.rtunohex or packet[16:16+4] == 'ffff'): # GI act packet
# check if required to check filter on type id GI
if self.checkfilter and self.filtertypid == '100':
self.checkfilter=''
sendpacket=b'\x68\x0E\x00\x00\x00\x00\x64\x01\x07' + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + b'\x00\x00\x00\x14'
senddata(self,sendpacket)
self.logfhw.write(dt + ' : GI received.' + '\n')
f=open(self.logfilenamegi,"a")
f.write(dt + ' : GI received.' + '\n')
f.close()
self.sendgi += 1
elif packet[8:8+2] == '67' and (packet[16:16+4] == self.rtunohex or packet[16:16+4] == 'ffff'): # Time sync act packet
# check if required to check filter on type id time sync
if self.checkfilter and self.filtertypid == '103':
self.checkfilter=''
sendpacket=b'\x68\x14\x00\x00\x00\x00\x67\x01\x07' + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + b'\x00\x00\x00'
senddata(self,sendpacket,addtime=1)
ts=((int(packet[32:32+2],16) & 0x80)>>7)*3
ms=packet[28:28+2] + packet[26:26+2]
self.logfhw.write(dt + ' : Time sync. received with date (dd-mm-yy): ' + "{:02d}".format(int(packet[34:34+2],16)&0x1f) + '-' + "{:02d}".format(int(packet[36:36+2],16)&0x0f) + '-' + "{:02d}".format(int(packet[38:38+2],16)&0x7f) + ',\n\t\t\t time (HH:MM:SS.ms): ' + "{:02d}".format(int(packet[32:32+2],16)&0x1f) + ':' + "{:02d}".format(int(packet[30:30+2],16)&0x3f) + ':' + "{:09.6f}".format(float(int(ms,16))/1000) + ', Time saving ' + valuemess[ts:ts+3] + '\n')
elif packet[8:8+2] == '2d' and packet[16:16+4] == self.rtunohex: # sco command without time tag.
pulse=((int(packet[26:26+2],16) & 0x7c)>>2)*8
valuem=(int(packet[26:26+2],16) & 0x03)*3
# if select? then acknowledge only otherwise ack and term then prepare for sending back the status
if (int(packet[26:26+2],16) & 0x80) != 0: # check select bit 1000 0000
# send cmd ack
sendpacket=b'\x68\x0e\x00\x00\x00\x00' + int(packet[8:8+2],16).to_bytes(1,'little') + b'\x01\x07' + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + ioacmd + int(packet[26:26+2],16).to_bytes(1,'little')
senddata(self,sendpacket)
logmess=dt + ' : SCO without time tag received, IOA=' + str(int.from_bytes(ioacmd,'little')) + ', Select set, Pulse=' + pulsemess[pulse:pulse+8] + ', Val=' + valuemess[valuem:valuem+3]
else:
# send actconf.
sendpacket=b'\x68\x0e\x00\x00\x00\x00' + int(packet[8:8+2],16).to_bytes(1,'little') + b'\x01\x07' + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + ioacmd + int(packet[26:26+2],16).to_bytes(1,'little')
senddata(self,sendpacket)
# send actterm.
sendpacket=b'\x68\x0e\x00\x00\x00\x00' + int(packet[8:8+2],16).to_bytes(1,'little') + b'\x01\x0a' + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + ioacmd + int(packet[26:26+2],16).to_bytes(1,'little')
senddata(self,sendpacket)
ioacmdv=str(int.from_bytes(ioacmd,'little'))
cmdvalue=(int(packet[26:26+2],16) & 0x03)
cmdtype=1 # sco - cmdtype=${packet:8:2}
logmess=dt + ' : SCO without time tag received, IOA=' + ioacmdv + ', Execute set, Pulse=' + pulsemess[pulse:pulse+8] + ', Val=' + valuemess[valuem:valuem+3]
cmdrtuno=self.rtuno
cmdtime=time()
self.logfhw.write(logmess + '\n')
elif packet[8:8+2] == '2e' and packet[16:16+4] == self.rtunohex: # dco command without time tag.
pulse=((int(packet[26:26+2],16) & 0x7c)>>2)*8
valuem=((int(packet[26:26+2],16) & 0x03)-1)*3
# if select? then acknowledge only otherwise ack and term then prepare for sending back the status
if (int(packet[26:26+2],16) & 0x80) != 0: # check select bit 1000 0000
# send cmd ack
sendpacket=b'\x68\x0e\x00\x00\x00\x00' + int(packet[8:8+2],16).to_bytes(1,'little') + b'\x01\x07' + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + ioacmd + int(packet[26:26+2],16).to_bytes(1,'little')
senddata(self,sendpacket)
logmess=dt + ' : DCO without time tag received, IOA=' + str(int.from_bytes(ioacmd,'little')) + ', Select set, Pulse=' + pulsemess[pulse:pulse+8] + ', Val=' + valuemess[valuem:valuem+3]
else:
# send actconf.
sendpacket=b'\x68\x0e\x00\x00\x00\x00' + int(packet[8:8+2],16).to_bytes(1,'little') + b'\x01\x07' + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + ioacmd + int(packet[26:26+2],16).to_bytes(1,'little')
senddata(self,sendpacket)
# send actterm.
sendpacket=b'\x68\x0e\x00\x00\x00\x00' + int(packet[8:8+2],16).to_bytes(1,'little') + b'\x01\x0a' + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + ioacmd + int(packet[26:26+2],16).to_bytes(1,'little')
senddata(self,sendpacket)
ioacmdv=str(int.from_bytes(ioacmd,'little'))
cmdvalue=(int(packet[26:26+2],16) & 0x03)
cmdtype=2 # dco - cmdtype=${packet:8:2}
logmess=dt + ' : DCO without time tag received, IOA=' + ioacmdv + ', Execute set, Pulse=' + pulsemess[pulse:pulse+8] + ', Val=' + valuemess[valuem:valuem+3]
cmdrtuno=self.rtuno
cmdtime=time()
self.logfhw.write(logmess + '\n')
elif packet[8:8+2] == '2f' and packet[16:16+4] == self.rtunohex: # rco command without time tag.
pulse=((int(packet[26:26+2],16) & 0x7c)>>2)*8
valuem=((int(packet[26:26+2],16) & 0x03)-1)*9
# if select? then acknowledge only otherwise ack and term then prepare for sending back the status
if (int(packet[26:26+2],16) & 0x80) != 0: # check select bit 1000 0000
# send cmd ack
sendpacket=b'\x68\x0e\x00\x00\x00\x00' + int(packet[8:8+2],16).to_bytes(1,'little') + b'\x01\x07' + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + ioacmd + int(packet[26:26+2],16).to_bytes(1,'little')
senddata(self,sendpacket)
logmess=dt + ' : RCO without time tag received, IOA=' + str(int.from_bytes(ioacmd,'little')) + ', Select set, Pulse=' + pulsemess[pulse:pulse+8] + ', Val=' + regmess[valuem:valuem+9]
else:
# send actconf.
sendpacket=b'\x68\x0e\x00\x00\x00\x00' + int(packet[8:8+2],16).to_bytes(1,'little') + b'\x01\x07' + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + ioacmd + int(packet[26:26+2],16).to_bytes(1,'little')
senddata(self,sendpacket)
# send actterm.
sendpacket=b'\x68\x0e\x00\x00\x00\x00' + int(packet[8:8+2],16).to_bytes(1,'little') + b'\x01\x0a' + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + ioacmd + int(packet[26:26+2],16).to_bytes(1,'little')
senddata(self,sendpacket)
ioacmdv=str(int.from_bytes(ioacmd,'little'))
cmdvalue=(int(packet[26:26+2],16) & 0x03)
cmdtype=2 # rco - cmdtype=${packet:8:2}
logmess=dt + ' : RCO without time tag received, IOA=' + ioacmdv + ', Execute set, Pulse=' + pulsemess[pulse:pulse+8] + ', Val=' + regmess[valuem:valuem+9]
cmdrtuno=self.rtuno
cmdtime=time()
self.logfhw.write(logmess + '\n')
elif packet[8:8+2] == '3a' and packet[16:16+4] == self.rtunohex: # sco command with time tag.
pulse=((int(packet[26:26+2],16) & 0x7c)>>2)*8
valuem=(int(packet[26:26+2],16) & 0x03)*3
ts=((int(packet[34:34+2],16) & 0x80)>>7)*3
ms=packet[30:30+2] + packet[28:28+2]
logtime='with date (dd-mm-yy): ' + "{:02d}".format(int(packet[36:36+2],16)&0x1f) + '-' + "{:02d}".format(int(packet[38:38+2],16)&0x0f) + '-' + "{:02d}".format(int(packet[40:40+2],16)&0x7f) + ' & time (HH:MM:SS.ms): ' + "{:02d}".format(int(packet[34:34+2],16)&0x1f) + ':' + "{:02d}".format(int(packet[32:32+2],16)&0x3f) + ':' + "{:09.6f}".format(float(int(ms,16))/1000) + ', Time saving ' + valuemess[ts:ts+3]
# if select? then acknowledge only otherwise ack and term then prepare for sending back the status
if (int(packet[26:26+2],16) & 0x80) != 0: # check select bit 1000 0000
# send cmd ack
sendpacket=b'\x68\x15\x00\x00\x00\x00' + int(packet[8:8+2],16).to_bytes(1,'little') + b'\x01\x07' + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + ioacmd + int(packet[26:26+2],16).to_bytes(1,'little')
senddata(self,sendpacket,addtime=1)
logmess=dt + ' : SCO with time tag received, IOA=' + str(int.from_bytes(ioacmd,'little')) + ', Select set, Pulse=' + pulsemess[pulse:pulse+8] + ', Val=' + valuemess[valuem:valuem+3]
else:
# send actconf.
sendpacket=b'\x68\x15\x00\x00\x00\x00' + int(packet[8:8+2],16).to_bytes(1,'little') + b'\x01\x07' + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + ioacmd + int(packet[26:26+2],16).to_bytes(1,'little')
senddata(self,sendpacket,addtime=1)
# send actterm.
sendpacket=b'\x68\x15\x00\x00\x00\x00' + int(packet[8:8+2],16).to_bytes(1,'little') + b'\x01\x0a' + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + ioacmd + int(packet[26:26+2],16).to_bytes(1,'little')
senddata(self,sendpacket,addtime=1)
ioacmdv=str(int.from_bytes(ioacmd,'little'))
cmdvalue=(int(packet[26:26+2],16) & 0x03)
cmdtype=1 # sco - cmdtype=${packet:8:2}
logmess=dt + ' : SCO with time tag received, IOA=' + ioacmdv + ', Execute set, Pulse=' + pulsemess[pulse:pulse+8] + ', Val=' + valuemess[valuem:valuem+3]
cmdrtuno=self.rtuno
cmdtime=time()
self.logfhw.write(logmess + '\n\t\t\t ' + logtime + '\n')
elif packet[8:8+2] == '3b' and packet[16:16+4] == self.rtunohex: # dco command with time tag.
pulse=((int(packet[26:26+2],16) & 0x7c)>>2)*8
valuem=((int(packet[26:26+2],16) & 0x03)-1)*3
ts=((int(packet[34:34+2],16) & 0x80)>>7)*3
ms=packet[30:30+2] + packet[28:28+2]
logtime='with date (dd-mm-yy): ' + "{:02d}".format(int(packet[36:36+2],16)&0x1f) + '-' + "{:02d}".format(int(packet[38:38+2],16)&0x0f) + '-' + "{:02d}".format(int(packet[40:40+2],16)&0x7f) + ' & time (HH:MM:SS.ms): ' + "{:02d}".format(int(packet[34:34+2],16)&0x1f) + ':' + "{:02d}".format(int(packet[32:32+2],16)&0x3f) + ':' + "{:09.6f}".format(float(int(ms,16))/1000) + ', Time saving ' + valuemess[ts:ts+3]
# if select? then acknowledge only otherwise ack and term then prepare for sending back the status
if (int(packet[26:26+2],16) & 0x80) != 0: # check select bit 1000 0000
# send cmd ack
sendpacket=b'\x68\x15\x00\x00\x00\x00' + int(packet[8:8+2],16).to_bytes(1,'little') + b'\x01\x07' + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + ioacmd + int(packet[26:26+2],16).to_bytes(1,'little')
senddata(self,sendpacket,addtime=1)
logmess=dt + ' : DCO with time tag received, IOA=' + str(int.from_bytes(ioacmd,'little')) + ', Select set, Pulse=' + pulsemess[pulse:pulse+8] + ', Val=' + valuemess[valuem:valuem+3]
else:
# send actconf.
sendpacket=b'\x68\x15\x00\x00\x00\x00' + int(packet[8:8+2],16).to_bytes(1,'little') + b'\x01\x07' + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + ioacmd + int(packet[26:26+2],16).to_bytes(1,'little')
senddata(self,sendpacket,addtime=1)
# send actterm.
sendpacket=b'\x68\x15\x00\x00\x00\x00' + int(packet[8:8+2],16).to_bytes(1,'little') + b'\x01\x0a' + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + ioacmd + int(packet[26:26+2],16).to_bytes(1,'little')
senddata(self,sendpacket,addtime=1)
ioacmdv=str(int.from_bytes(ioacmd,'little'))
cmdvalue=(int(packet[26:26+2],16) & 0x03)
cmdtype=2 # dco - cmdtype=${packet:8:2}
logmess=dt + ' : DCO with time tag received, IOA=' + ioacmdv + ', Execute set, Pulse=' + pulsemess[pulse:pulse+8] + ', Val=' + valuemess[valuem:valuem+3]
cmdrtuno=self.rtuno
cmdtime=time()
self.logfhw.write(logmess + '\n\t\t\t ' + logtime + '\n')
elif packet[8:8+2] == '3c' and packet[16:16+4] == self.rtunohex: # rco command with time tag.
pulse=((int(packet[26:26+2],16) & 0x7c)>>2)*8
valuem=((int(packet[26:26+2],16) & 0x03)-1)*9
ts=((int(packet[34:34+2],16) & 0x80)>>7)*3
ms=packet[30:30+2] + packet[28:28+2]
logtime='with date (dd-mm-yy): ' + "{:02d}".format(int(packet[36:36+2],16)&0x1f) + '-' + "{:02d}".format(int(packet[38:38+2],16)&0x0f) + '-' + "{:02d}".format(int(packet[40:40+2],16)&0x7f) + ' & time (HH:MM:SS.ms): ' + "{:02d}".format(int(packet[34:34+2],16)&0x1f) + ':' + "{:02d}".format(int(packet[32:32+2],16)&0x3f) + ':' + "{:09.6f}".format(float(int(ms,16))/1000) + ', Time saving ' + valuemess[ts:ts+3]
# if select? then acknowledge only otherwise ack and term then prepare for sending back the status
if (int(packet[26:26+2],16) & 0x80) != 0: # check select bit 1000 0000
# send cmd ack
sendpacket=b'\x68\x15\x00\x00\x00\x00' + int(packet[8:8+2],16).to_bytes(1,'little') + b'\x01\x07' + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + ioacmd + int(packet[26:26+2],16).to_bytes(1,'little')
senddata(self,sendpacket,addtime=1)
logmess=dt + ' : RCO with time tag received, IOA=' + str(int.from_bytes(ioacmd,'little')) + ', Select set, Pulse=' + pulsemess[pulse:pulse+8] + ', Val=' + regmess[valuem:valuem+9]
else:
# send actconf.
sendpacket=b'\x68\x15\x00\x00\x00\x00' + int(packet[8:8+2],16).to_bytes(1,'little') + b'\x01\x07' + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + ioacmd + int(packet[26:26+2],16).to_bytes(1,'little')
senddata(self,sendpacket,addtime=1)
# send actterm.
sendpacket=b'\x68\x15\x00\x00\x00\x00' + int(packet[8:8+2],16).to_bytes(1,'little') + b'\x01\x0a' + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + ioacmd + int(packet[26:26+2],16).to_bytes(1,'little')
senddata(self,sendpacket,addtime=1)
ioacmdv=str(int.from_bytes(ioacmd,'little'))
cmdvalue=(int(packet[26:26+2],16) & 0x03)
cmdtype=2 # rco - cmdtype=${packet:8:2}
logmess=dt + ' : RCO with time tag received, IOA=' + ioacmdv + ', Execute set, Pulse=' + pulsemess[pulse:pulse+8] + ', Val=' + regmess[valuem:valuem+9]
cmdrtuno=self.rtuno
cmdtime=time()
self.logfhw.write(logmess + '\n\t\t\t ' + logtime + '\n')
else: # if not implemented I-Format then just ack by sending S-Format
sendpacket=b'\x68\x04\x01\x00' + (self.rxlsb*2).to_bytes(1,'little') + self.rxmsb.to_bytes(1,'little')
senddata(self,sendpacket)
self.logfhw.write(dt + ' : Acknowledged TypeID: ' + str(int(packet[8:8+2],16)) + ' without further action\n')
if packet[16:16+4] != self.rtunohex:
self.logfhw.write('\t\t\t Wrong RTU no. received.\n')
self.logfilechanged=1
def sendtelegramind (self,row):
global valuemess
telegram=''
if not self.dataactive:
return
cot=3 # spont.
objno=1
# GI typeid IOA Value wait(sec) filterrtu filtertypid filterioa filtervalue Comment
# decode io signals
if row[2] == '1' or row[2] == '3': # spi or dpi without time tag
# length = 4 control fields + ASDU
len=14
packet = b'\x68' + len.to_bytes(1,'little') + b'\x00\x00\x00\x00' + int(row[2]).to_bytes(1,'little') + objno.to_bytes(1,'little') + cot.to_bytes(1,'little') + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + int(row[3]).to_bytes(3,'little') + int(row[4]).to_bytes(1,'little')
dt = senddata(self,packet)
if row[2] == '1':
v=int(row[4]) * 3
self.logfhw.write(dt + ' : SPI, IOA=' + row[3][0:12] + ', Val=' + valuemess[v:v+3] + ' ' + row[10][0:53] + '\n')
else:
v=(int(row[4]) - 1) * 3
self.logfhw.write(dt + ' : DPI, IOA=' + row[3][0:12] + ', Val=' + valuemess[v:v+3] + ' ' + row[10][0:53] + '\n')
elif row[2] == '30' or row[2] == '31': # spi or dpi with time tag
# length = 4 control fields + ASDU
len=21
if row[2] == '30':
v=int(row[4]) * 3
packet = b'\x68' + len.to_bytes(1,'little') + b'\x00\x00\x00\x00' + int(row[2]).to_bytes(1,'little') + objno.to_bytes(1,'little') + cot.to_bytes(1,'little') + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + int(row[3]).to_bytes(3,'little') + int(row[4]).to_bytes(1,'little')
dt = senddata(self,packet,addtime=1)
self.logfhw.write(dt + ' : SPI, IOA=' + row[3][0:12] + ', Val=' + valuemess[v:v+3] + ' ' + row[10][0:53])
else:
v=(int(row[4]) - 1) * 3
packet = b'\x68' + len.to_bytes(1,'little') + b'\x00\x00\x00\x00' + int(row[2]).to_bytes(1,'little') + objno.to_bytes(1,'little') + cot.to_bytes(1,'little') + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + int(row[3]).to_bytes(3,'little') + int(row[4]).to_bytes(1,'little')
dt = senddata(self,packet,addtime=1)
self.logfhw.write(dt + ' : DPI, IOA=' + row[3][0:12] + ', Val=' + valuemess[v:v+3] + ' ' + row[10][0:53])
# write date in log file.
self.logfhw.write('\n\t\t\t with date&time tag: ' + dt + ', Time saving OFF\n')
elif row[2] == '9': # meas. normalized without time tag
len=16
qds=0
v=int(float(row[4])*32767)
packet = b'\x68' + len.to_bytes(1,'little') + b'\x00\x00\x00\x00' + int(row[2]).to_bytes(1,'little') + objno.to_bytes(1,'little') + cot.to_bytes(1,'little') + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + int(row[3]).to_bytes(3,'little') + v.to_bytes(2,'little', signed=True) + qds.to_bytes(1,'little')
dt = senddata(self,packet)
self.logfhw.write(dt + ' : NORM AMI, IOA=' + row[3][0:12] + ', Val=' + row[4][0:12] + ' ' + row[10][0:53] + '\n')
elif row[2] == '34': # meas. normalized with time tag
len=23
qds=0
v=int(float(row[4])*32767)
packet = b'\x68' + len.to_bytes(1,'little') + b'\x00\x00\x00\x00' + int(row[2]).to_bytes(1,'little') + objno.to_bytes(1,'little') + cot.to_bytes(1,'little') + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + int(row[3]).to_bytes(3,'little') + v.to_bytes(2,'little', signed=True) + qds.to_bytes(1,'little')
dt = senddata(self,packet,addtime=1)
self.logfhw.write(dt + ' : NORM AMI, IOA=' + row[3][0:12] + ', Val=' + row[4][0:12] + ' ' + row[10][0:53])
self.logfhw.write('\n\t\t\t with date&time tag: ' + dt + ', Time saving OFF\n')
elif row[2] == '11': # meas. scaled without time tag
len=16
qds=0
v=int(row[4])
packet = b'\x68' + len.to_bytes(1,'little') + b'\x00\x00\x00\x00' + int(row[2]).to_bytes(1,'little') + objno.to_bytes(1,'little') + cot.to_bytes(1,'little') + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + int(row[3]).to_bytes(3,'little') + v.to_bytes(2,'little', signed=True) + qds.to_bytes(1,'little')
dt = senddata(self,packet)
self.logfhw.write(dt + ' : SCAL AMI, IOA=' + row[3][0:12] + ', Val=' + row[4][0:12] + ' ' + row[10][0:53] + '\n')
elif row[2] == '35': # meas. scaled with time tag
len=23
qds=0
v=int(row[4])
packet = b'\x68' + len.to_bytes(1,'little') + b'\x00\x00\x00\x00' + int(row[2]).to_bytes(1,'little') + objno.to_bytes(1,'little') + cot.to_bytes(1,'little') + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + int(row[3]).to_bytes(3,'little') + v.to_bytes(2,'little', signed=True) + qds.to_bytes(1,'little')
dt = senddata(self,packet,addtime=1)
self.logfhw.write(dt + ' : SCAL AMI, IOA=' + row[3][0:12] + ', Val=' + row[4][0:12] + ' ' + row[10][0:53])
self.logfhw.write('\n\t\t\t with date&time tag: ' + dt + ', Time saving OFF\n')
elif row[2] == '13': # meas. float without time tag
len=18
qds=0
v = int(unpack("I", pack("f", float (row[4])))[0])
packet = b'\x68' + len.to_bytes(1,'little') + b'\x00\x00\x00\x00' + int(row[2]).to_bytes(1,'little') + objno.to_bytes(1,'little') + cot.to_bytes(1,'little') + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + int(row[3]).to_bytes(3,'little') + v.to_bytes(4,'little') + qds.to_bytes(1,'little')
dt = senddata(self,packet)
self.logfhw.write(dt + ' : FLT AMI, IOA=' + row[3][0:12] + ', Val=' + row[4][0:12] + ' ' + row[10][0:53] + '\n')
elif row[2] == '36': # meas. float with time tag
len=25
qds=0
v = int(unpack("I", pack("f", float (row[4])))[0])
packet = b'\x68' + len.to_bytes(1,'little') + b'\x00\x00\x00\x00' + int(row[2]).to_bytes(1,'little') + objno.to_bytes(1,'little') + cot.to_bytes(1,'little') + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + int(row[3]).to_bytes(3,'little') + v.to_bytes(4,'little') + qds.to_bytes(1,'little')
dt = senddata(self,packet,addtime=1)
self.logfhw.write(dt + ' : FLT AMI, IOA=' + row[3][0:12] + ', Val=' + row[4][0:12] + ' ' + row[10][0:53])
self.logfhw.write('\n\t\t\t with date&time tag: ' + dt + ', Time saving OFF\n')
def sendtelegramgi (self,row,f):
global valuemess
telegram=''
if not self.dataactive:
return
cot=20 # GI
objno=1
# GI typeid IOA Value wait(sec) filterrtu filtertypid filterioa filtervalue Comment
# decode io signals
if row[2] == '1' or row[2] == '3' or row[2] == '30' or row[2] == '31': # spi or dpi /with/without time tag
# length = 4 control fields + ASDU
len=14
if row[2] == '1' or row[2] == '30':
v=int(row[4]) * 3
typeid=1
packet = b'\x68' + len.to_bytes(1,'little') + b'\x00\x00\x00\x00' + typeid.to_bytes(1,'little') + objno.to_bytes(1,'little') + cot.to_bytes(1,'little') + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + int(row[3]).to_bytes(3,'little') + int(row[4]).to_bytes(1,'little')
dt = senddata(self,packet)
f.write(dt + ' : SPI, IOA=' + row[3][0:12] + ', Val=' + valuemess[v:v+3] + ' ' + row[10][0:53] + '\n')
else:
v=(int(row[4]) - 1) * 3
typeid=3
packet = b'\x68' + len.to_bytes(1,'little') + b'\x00\x00\x00\x00' + typeid.to_bytes(1,'little') + objno.to_bytes(1,'little') + cot.to_bytes(1,'little') + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + int(row[3]).to_bytes(3,'little') + int(row[4]).to_bytes(1,'little')
dt = senddata(self,packet)
f.write(dt + ' : DPI, IOA=' + row[3][0:12] + ', Val=' + valuemess[v:v+3] + ' ' + row[10][0:53] + '\n')
elif row[2] == '9' or row[2] == '34': # meas. normalized without time tag
len=16
qds=0
typeid=9
v=int(float(row[4])*32767)
packet = b'\x68' + len.to_bytes(1,'little') + b'\x00\x00\x00\x00' + typeid.to_bytes(1,'little') + objno.to_bytes(1,'little') + cot.to_bytes(1,'little') + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + int(row[3]).to_bytes(3,'little') + v.to_bytes(2,'little', signed=True) + qds.to_bytes(1,'little')
dt = senddata(self,packet)
f.write(dt + ' : NORM AMI, IOA=' + row[3][0:12] + ', Val=' + row[4][0:12] + ' ' + row[10][0:53] + '\n')
elif row[2] == '11' or row[2] == '35': # meas. scaled without time tag
len=16
qds=0
typeid=11
v=int(row[4])
packet = b'\x68' + len.to_bytes(1,'little') + b'\x00\x00\x00\x00' + typeid.to_bytes(1,'little') + objno.to_bytes(1,'little') + cot.to_bytes(1,'little') + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + int(row[3]).to_bytes(3,'little') + v.to_bytes(2,'little', signed=True) + qds.to_bytes(1,'little')
dt = senddata(self,packet)
f.write(dt + ' : SCAL AMI, IOA=' + row[3][0:12] + ', Val=' + row[4][0:12] + ' ' + row[10][0:53] + '\n')
elif row[2] == '13' or row[2] == '36': # meas. float without time tag
len=18
qds=0
typeid=13
v = int(unpack("I", pack("f", float (row[4])))[0])
packet = b'\x68' + len.to_bytes(1,'little') + b'\x00\x00\x00\x00' + typeid.to_bytes(1,'little') + objno.to_bytes(1,'little') + cot.to_bytes(1,'little') + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + int(row[3]).to_bytes(3,'little') + v.to_bytes(4,'little') + qds.to_bytes(1,'little')
dt = senddata(self,packet)
f.write(dt + ' : FLT AMI, IOA=' + row[3][0:12] + ', Val=' + row[4][0:12] + ' ' + row[10][0:53] + '\n')
def sendtelegramcmd (self,row):
global valuemess
telegram=''
if not self.dataactive:
self.cmdvalue=0
self.cmdtype=0
return
self.sendingcmd=1
cot=3 # spont.
objno=1
# GI typeid IOA Value wait(sec) filterrtu filtertypid filterioa filtervalue Comment
# decode io signals
if row[2] == '1' or row[2] == '3': # spi or dpi without time tag
# length = 4 control fields + ASDU
len=14
if row[2] == '1' and self.cmdtype == 2: #spi but cmd was dco; adjust value
self.cmdvalue -= 1
if row[2] == '3' and self.cmdtype == 1: # dpi but cmd was sco; adjust value
self.cmdvalue += 1
v=self.cmdvalue
if row[2] == '1':
v *= 3
typeid=1
packet = b'\x68' + len.to_bytes(1,'little') + b'\x00\x00\x00\x00' + typeid.to_bytes(1,'little') + objno.to_bytes(1,'little') + cot.to_bytes(1,'little') + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + int(row[3]).to_bytes(3,'little') + v.to_bytes(1,'little')
dt = senddata(self,packet)
self.logfhw.write(dt + ' : SPI, IOA=' + row[3][0:12] + ', Val=' + valuemess[v:v+3] + ' ' + row[10][0:53] + '\n')
else:
v = (v - 1) * 3
typeid=3
packet = b'\x68' + len.to_bytes(1,'little') + b'\x00\x00\x00\x00' + typeid.to_bytes(1,'little') + objno.to_bytes(1,'little') + cot.to_bytes(1,'little') + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + int(row[3]).to_bytes(3,'little') + v.to_bytes(1,'little')
dt = senddata(self,packet)
self.logfhw.write(dt + ' : DPI, IOA=' + row[3][0:12] + ', Val=' + valuemess[v:v+3] + ' ' + row[10][0:53] + '\n')
if row[2] == '30' or row[2] == '31': # spi or dpi with time tag
# length = 4 control fields + ASDU
len=21
if row[2] == '30' and self.cmdtype == 2: #spi but cmd was dco; adjust value
self.cmdvalue -= 1
if row[2] == '31' and self.cmdtype == 1: # dpi but cmd was sco; adjust value
self.cmdvalue += 1
value=self.cmdvalue
if row[2] == '30':
v = value * 3
typeid=30
packet = b'\x68' + len.to_bytes(1,'little') + b'\x00\x00\x00\x00' + typeid.to_bytes(1,'little') + objno.to_bytes(1,'little') + cot.to_bytes(1,'little') + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + int(row[3]).to_bytes(3,'little') + value.to_bytes(1,'little')
dt = senddata(self,packet,addtime=1)
self.logfhw.write(dt + ' : SPI, IOA=' + row[3][0:12] + ', Val=' + valuemess[v:v+3] + ' ' + row[10][0:53])
else:
v=(value - 1) * 3
typeid=31
packet = b'\x68' + len.to_bytes(1,'little') + b'\x00\x00\x00\x00' + typeid.to_bytes(1,'little') + objno.to_bytes(1,'little') + cot.to_bytes(1,'little') + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + int(row[3]).to_bytes(3,'little') + value.to_bytes(1,'little')
dt = senddata(self,packet,addtime=1)
self.logfhw.write(dt + ' : DPI, IOA=' + row[3][0:12] + ', Val=' + valuemess[v:v+3] + ' ' + row[10][0:53])
# write date in log file.
self.logfhw.write('\n\t\t\t with date&time tag: ' + dt + ', Time saving OFF\n')
if row[2] == '9': # meas. normalized without time tag
len=16
qds=0
v=int(float(row[4])*32767)
packet = b'\x68' + len.to_bytes(1,'little') + b'\x00\x00\x00\x00' + int(row[2]).to_bytes(1,'little') + objno.to_bytes(1,'little') + cot.to_bytes(1,'little') + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + int(row[3]).to_bytes(3,'little') + v.to_bytes(2,'little', signed=True) + qds.to_bytes(1,'little')
dt = senddata(self,packet)
self.logfhw.write(dt + ' : NORM AMI, IOA=' + row[3][0:12] + ', Val=' + row[4][0:12] + ' ' + row[10][0:53] + '\n')
if row[2] == '34': # meas. normalized with time tag
len=23
qds=0
v=int(float(row[4])*32767)
packet = b'\x68' + len.to_bytes(1,'little') + b'\x00\x00\x00\x00' + int(row[2]).to_bytes(1,'little') + objno.to_bytes(1,'little') + cot.to_bytes(1,'little') + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + int(row[3]).to_bytes(3,'little') + v.to_bytes(2,'little', signed=True) + qds.to_bytes(1,'little')
dt = senddata(self,packet,addtime=1)
self.logfhw.write(dt + ' : NORM AMI, IOA=' + row[3][0:12] + ', Val=' + row[4][0:12] + ' ' + row[10][0:53])
self.logfhw.write('\n\t\t\t with date&time tag: ' + dt + ', Time saving OFF\n')
if row[2] == '11': # meas. scaled without time tag
len=16
qds=0
v=int(row[4])
packet = b'\x68' + len.to_bytes(1,'little') + b'\x00\x00\x00\x00' + int(row[2]).to_bytes(1,'little') + objno.to_bytes(1,'little') + cot.to_bytes(1,'little') + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + int(row[3]).to_bytes(3,'little') + v.to_bytes(2,'little', signed=True) + qds.to_bytes(1,'little')
dt = senddata(self,packet)
self.logfhw.write(dt + ' : SCAL AMI, IOA=' + row[3][0:12] + ', Val=' + row[4][0:12] + ' ' + row[10][0:53] + '\n')
if row[2] == '35': # meas. scaled with time tag
len=23
qds=0
v=int(row[4])
packet = b'\x68' + len.to_bytes(1,'little') + b'\x00\x00\x00\x00' + int(row[2]).to_bytes(1,'little') + objno.to_bytes(1,'little') + cot.to_bytes(1,'little') + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + int(row[3]).to_bytes(3,'little') + v.to_bytes(2,'little', signed=True) + qds.to_bytes(1,'little')
dt = senddata(self,packet,addtime=1)
self.logfhw.write(dt + ' : SCAL AMI, IOA=' + row[3][0:12] + ', Val=' + row[4][0:12] + ' ' + row[10][0:53])
self.logfhw.write('\n\t\t\t with date&time tag: ' + dt + ', Time saving OFF\n')
if row[2] == '13': # meas. float without time tag
len=18
qds=0
v = int(unpack("I", pack("f", float (row[4])))[0])
packet = b'\x68' + len.to_bytes(1,'little') + b'\x00\x00\x00\x00' + int(row[2]).to_bytes(1,'little') + objno.to_bytes(1,'little') + cot.to_bytes(1,'little') + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + int(row[3]).to_bytes(3,'little') + v.to_bytes(4,'little') + qds.to_bytes(1,'little')
dt = senddata(self,packet)
self.logfhw.write(dt + ' : FLT AMI, IOA=' + row[3][0:12] + ', Val=' + row[4][0:12] + ' ' + row[10][0:53] + '\n')
if row[2] == '36': # meas. float with time tag
len=25
qds=0
v = int(unpack("I", pack("f", float (row[4])))[0])
packet = b'\x68' + len.to_bytes(1,'little') + b'\x00\x00\x00\x00' + int(row[2]).to_bytes(1,'little') + objno.to_bytes(1,'little') + cot.to_bytes(1,'little') + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + int(row[3]).to_bytes(3,'little') + v.to_bytes(4,'little') + qds.to_bytes(1,'little')
dt = senddata(self,packet,addtime=1)
self.logfhw.write(dt + ' : FLT AMI, IOA=' + row[3][0:12] + ', Val=' + row[4][0:12] + ' ' + row[10][0:53])
self.logfhw.write('\n\t\t\t with date&time tag: ' + dt + ', Time saving OFF\n')
self.cmdvalue=0
self.cmdtype=0
self.sendingcmd=0
def indexthread (self):
global indextime,indexvalue,repeattimeindex,stopsendindex,exitprogram
while True:
if exitprogram:
break
if self.indextime != indextime:
self.indextime=indextime
if not self.dataactive:
continue
ioindex=indexvalue
indexfound=0
self.indexvalue=f'Sending {ioindex}'
self.updateindexgui=1
timetorepeatindex=time()
while True:
with open(self.iodata) as csv_file:
# GI typeid IOA Value wait(sec) filterrtu filtertypid filterioa filtervalue Comment
self.sendingind=1
csv_reader = reader(csv_file, delimiter=',')
for row in csv_reader:
if not self.dataactive:
break
if not row[0].isdigit() or not row[2].isdigit() or not row[3].isdigit() or not row[4] or (row[6].isdigit() and row[6] != self.rtuno):
continue
if (row[0] == ioindex or int(ioindex) == 0) and int(row[2]) in types:
indexfound=1
# check filter and wait to receive it.
if not isfloat(row[5]): # if delay is empty or not float then put it as zero seconds.
row[5] = '0'
if not isfloat(row[10]): # if filter timeout is empty or not float then put it as zero sec.
row[10] = '0'
self.filtertypid=row[7]
self.filterioa=row[8]
self.filtervalue=row[9]
self.checkfilter = row[7] or row[8] or row[9]
filtertimeout=time()
while self.checkfilter and ((time() - filtertimeout) < float(row[10])):
if stopsendindex:
break
if (not self.checkfilter):
for l in range(11,len(row)):
row[10] += ' ' + row[l]
sendtelegramind(self,row)
else:
self.logfhw.write(str(datetime.now()) + ' : IOA:' + row[3] + ' not submitted; did not receive filter condition(s):\n\t\t\t RTU:' + row[6] + ', ID:' + row[7] + ', IOA:' + row[8] + ', Val:' + row[9] + '\n')
# wait for row[5] seconds
filtertimeout=time()
while (time() - filtertimeout) < float(row[5]):
if stopsendindex:
break
# if repeat time finished then exit.
if (time() - timetorepeatindex) >= repeattimeindex:
break
#while not self.indrun:
# pass
self.sendingind=0
if indexfound:
self.indexvalue=f'{ioindex}'
else:
self.indexvalue=f'Missing {ioindex}'
self.updateindexgui=1
self.logfilechanged=1
def githread (self):
global exitprogram
while True:
if exitprogram:
break
if not self.dataactive:
self.sendgi=0
if self.sendgi:
self.givalue='RUN'
self.updategigui=1
f=open(self.logfilenamegi,"a")
with open(self.iodata) as csv_file:
# GI typeid IOA Value wait(sec) filterrtu filtertypid filterioa filtervalue Comment
csv_reader = reader(csv_file, delimiter=',')
for row in csv_reader:
if not row:
pass
elif row[0][0:1] == '!' or not self.dataactive:
break
elif not row[0].isdigit() or not row[2].isdigit() or not row[3].isdigit() or not row[4]:
continue
elif row[1] == 'Y':
for l in range(11,len(row)):
row[10] += ' ' + row[l]
sendtelegramgi(self,row,f)
# send end of GI if not interrupted
if self.dataactive:
xlen=14
packet = b'\x68' + xlen.to_bytes(1,'little') + b'\x00\x00\x00\x00' + b'\x64\x01\x0a' + int(self.org,16).to_bytes(1,'little') + int(self.rtuno).to_bytes(2,'little') + b'\x00\x00\x00\x14'
dt = senddata(self,packet)
self.logfhw.write(dt + ' : GI finished.\n')
f.write(dt + ' : GI finished.\n')
else:
self.logfhw.write(str(datetime.now()) + ' : GI interrupted due to disconnection.\n')
f.write(str(datetime.now()) + ' : GI interrupted due to disconnection.\n')
f.close()
self.givalue=' '
self.updategigui=1
#while self.updategigui:
# pass
self.sendgi -= 1
self.logfilechanged=1
def cmdthread (self):
global ioacmdv,cmdtype,cmdvalue,cmdtime,cmdrtuno,exitprogram
while True:
if exitprogram:
break
if not self.dataactive:
self.cmdvalue=0
self.cmdtype=0
if self.cmdtime != cmdtime:
self.cmdtime=cmdtime
if self.rtuno != cmdrtuno:
break
cmdioa=ioacmdv
self.cmdvalue=cmdvalue
self.cmdtype=cmdtype
with open(self.iodata) as csv_file:
# GI typeid IOA Value wait(sec) filterrtu filtertypid filterioa filtervalue Comment
csv_reader = reader(csv_file, delimiter=',')
for row in csv_reader:
if not self.dataactive:
self.cmdvalue=0
self.cmdtype=0
break
if not row[0].isdigit() or not row[2].isdigit() or not row[3].isdigit() or not row[4]:
continue
if row[3] == cmdioa:
objaddress=row[4]
break
for row in csv_reader:
if not self.dataactive:
self.cmdvalue=0
self.cmdtype=0
break
if not row[0].isdigit() or not row[2].isdigit() or not row[3].isdigit() or not row[4]:
continue
if row[3] == objaddress:
for l in range(11,len(row)):
row[10] += ' ' + row[l]
sendtelegramcmd(self,row)
break
self.logfilechanged=1
def readpacketthread (self):
global exitprogram
initiate(self)
while True:
if exitprogram:
break
if self.initialize:
self.logfhw.write(str(datetime.now()) + ' : Initialized ..\n')
self.initialize=0
if self.disconnected:
self.logfhw.write(str(datetime.now()) + ' : Disconnected .. waiting for connection ..\n')
initiate(self)
self.initialize=0
self.disconnected=0
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 )