forked from machoe/HART-IP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhartip.py
199 lines (159 loc) · 7.41 KB
/
hartip.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
import struct
from hartcommand import *
Length = {'Total':8,'VerLen':1,'MesTypeLen':1,'MesIDLen':1,'StatusCodeLen':1,'SeqNumLen':2,'ByteCountLen':2}
Version = 1
MessageType = {'Request':0,'Response':1,'Pub_Noti':12,'Nak':15}
MessageID = {'SessionInitiate':0,'SesstionClose':1,'KeepAlive':2,'TPPDU':3,'Discovery':128}
StatusCode = ''
SequenceNumber = ''
ByteCount = ''
def ReceiveFromSocket(data,client):
#Calculate the data length from the socket received
RecLength = len(data)
RecFmt = str(RecLength)+'B'
print struct.unpack(RecFmt,data)
Header = ProcessHeader(data[0:8])
if Header['Status'] == True:
MesHeader = Header['RecHeader']
if MesHeader['RecMesType'] == 0: #Request
if MesHeader['RecMesID'] == 0: #Session Initiate
print 'Session initiate'
SessionReq = {'MasterType':'','InactivityCloseTime':''}
ResData =''
RC = 0
if MesHeader['RecVersion'] != Version:
RC = 14
if MesHeader['RecByteCount'] < 13:
RC = 6
else:
SessionReq['MasterType'] = struct.unpack('B',data[8])[0]
SessionReq['InactivityCloseTime'] = struct.unpack('!I',data[9:13])[0] #Milliseconeds
if SessionReq['MasterType'] != 1:
RC = 2
if SessionReq['InactivityCloseTime'] <= 100000:
SessionReq['InactivityCloseTime'] = 100000
RC = 8
client.settimeout(SessionReq['InactivityCloseTime']/1000)
print 'sesstion timeout is:',SessionReq['InactivityCloseTime']
#response to initiate
if RC==0:
ResData += struct.pack('B',SessionReq['MasterType'])
ResData += struct.pack('!I',SessionReq['InactivityCloseTime'])
client.send(ResponseToRequest(Version,0,RC,MesHeader['RecSecNum'],ResData))
elif MesHeader['RecMesID'] == 1: #Session Close
print 'Session Close'
elif MesHeader['RecMesID'] == 2: #Keep Alive
print 'Keep Alive'
client.send(ResponseToRequest(Version,2,0,MesHeader['RecSecNum'],''))
elif MesHeader['RecMesID'] == 3: #Token-Passing PDU
print 'Token-Passing PDU'
TPLength = MesHeader['RecByteCount'] - 8
try:
RC,resBinary = ProcessTPPDURequest(data[8:RecLength],client)
except Exception as e:
RC = False
if RC == True:
client.send(ResponseToRequest(Version,3,0,MesHeader['RecSecNum'],resBinary))
elif MesHeader['RecMesID'] == 128: #Discovery
print 'Discovery'
else: #Error occur
print 'err message type :'+ MesHeader['RecMesID']
elif MesHeader['RecMesType'] == 1: #Response
pass
elif MesHeader['RecMesType'] == 2: #Publish/Notification
pass
elif MesHeader['RecMesType'] == 15: #NAK
pass
else: #Error occur
print 'err message type :'+ MesHeader['RecMesType']
def ProcessHeader(data):
RecHeader = {'RecVersion':'','RecMesType':'','RecMesID':'','RecStatusCode':'','RecSecNum':'','RecByteCount':''}
Res = {'Status':'False','RecHeader':RecHeader}
if len(data) != 8:
return Res
try:
RecHeader['RecVersion'] = struct.unpack('B',data[0])[0]
RecHeader['RecMesType'] = struct.unpack('B',data[1])[0]
RecHeader['RecMesID'] = struct.unpack('B',data[2])[0]
RecHeader['RecStatusCode'] = struct.unpack('B',data[3])[0]
RecHeader['RecSecNum'] = struct.unpack('!H',data[4:6])[0]
RecHeader['RecByteCount'] = struct.unpack('!H',data[6:8])[0]
Res['Status'] = True
except Exception as E:
print E
return Res
def ResponseToRequest(ver,MesID,Status,SeqNum,data):
return AssemblePacket(ver, MessageType['Response'], MesID, Status, SeqNum, data)
def AssemblePacket(ver,Mestype,MesID,Status,SeqNum,data):
frame = ''
length = 8
newdata = []
datalength = len(data)
length += datalength
try:
frame+=struct.pack('B',ver)
frame+=struct.pack('B',Mestype)
frame+=struct.pack('B',MesID)
frame+=struct.pack('B',Status)
frame+=struct.pack('!H',SeqNum)
frame+=struct.pack('!H',length)
frame+=data
except Exception as e:
print e
return frame
def ProcessTPPDURequest(data,client):
datalist = list(struct.unpack(str(len(data))+'B',data))
recCheck = datalist.pop()
if recCheck == CheckSum(datalist):
Delimiter = datalist[0]
if Delimiter == 0x02: #Polling Request
cmdres = CommandRequest_0()
cmd0 = [0]
res = cmd0 + cmdres
resDelimiter = 0x06
addr = [128]
resList = [resDelimiter] + addr + res
resList.append(CheckSum(resList))
return True,ListToBinary(resList)
elif Delimiter == 0x82: #Long Address Request
addr = struct.unpack('!5B',data[1:6])
if addr == Device['Address']:
recCmdID = datalist[6]
recCmdLength = datalist[7]
try:
if HARTCommandRequestFunction.has_key(str(recCmdID)):
print 'Command' , recCmdID
if recCmdLength == 0:
resCommand = HARTCommandRequestFunction[str(recCmdID)]()
else:
resCommand = HARTCommandRequestFunction[str(recCmdID)](datalist[7:])
else:
print 'No this command',recCmdID
resCommand = [64] # Response Code, No payloads
except Exception as e:
resCommand = [64] # problem occur
res = [recCmdID] + resCommand
resDelimiter = 0x86
addr = [166,78,0,0,240]
resList = [resDelimiter] + addr + res
resList.append(CheckSum(resList))
return True,ListToBinary(resList)
else:
print 'Delimiter is error'
return
else: #checksum is error
print checksum is error
return
else:
print 'wrong request is receive' + Delimiter
return
def ListToBinary(InputList):
str = ''
for i in range(len(InputList)):
str += struct.pack('B',InputList[i])
return str
def CheckSum(InputList):
Check = InputList[0]
for i in range(1,len(InputList)):
Check ^= InputList[i]
return Check