|
1.此程序主要用来进行报文翻译;
2.参考文献:http://blog.csdn.net/w83761456/article/details/21171085;
3.
"""
作者:桑文超
功能:解析昌盛集控报文
版本:V1.0
日期:2017-12-26
"""
from struct import unpack
import datetime
print('***************************************************')
author = '桑文超'
software_function = '解析昌盛集控报文'
version = 'V1.0'
date = '2017-12-26'
a = datetime.datetime.now()
print('作者:{}\n\n软件功能:{}\n\n版本:{}\n\n日期:{}\n'.format(author,software_function,version,date))
print('当前时间:{}'.format(a))
print('***************************************************')
def main():
#输入报文,去除空格
message_str = input('请输入:')
while message_str != 'Q' :
nospace_message_str = message_str.replace(' ','')
#计算包长度
pack_length_str = nospace_message_str[4:8]
pack_length = unpack('<h',bytes.fromhex(pack_length_str))[0]
print('包长度:{}'.format(pack_length))
#计算厂站号
station_no_str = nospace_message_str[8:12]
station_no = unpack('<h', bytes.fromhex(station_no_str))[0]
print('厂站号:{}'.format(station_no))
#计算采集仪地址
collect_adr_str = nospace_message_str[12:16]
collect_adr = unpack('<h', bytes.fromhex(collect_adr_str))[0]
print('采集仪地址:{}'.format(collect_adr))
#计算帧长度
frame_str = nospace_message_str[16:18]
frame = int(frame_str,16)
print('帧长度:{}'.format(frame))
#计算功能码,并判断是遥信还是遥测
function_code_str = nospace_message_str[18:20]
function_code = int(function_code_str, 16)
if function_code == 7 :
code1 = '主动上送遥测'
print('功能码:{},功能:{}'.format(function_code,code1))
else:
code2 = '主动上送遥信'
print('功能码:{},功能:{}'.format(function_code, code2))
#计算设备类型标识,因都是00故没做判断
equipment_str = nospace_message_str[20:22]
equipment = int(equipment_str, 16)
print('设备类型标识:{}'.format(equipment))
#计算信息体地址
information_adr_str = nospace_message_str[22:28]
information_adr = unpack('<hb', bytes.fromhex(information_adr_str))[0]
print('信息体地址:{}'.format(information_adr))
#计算点值
value_str = nospace_message_str[28:-4]
i = 0
s = ''
while i < len(value_str):
s += value_str[i]
i += 1
if i % 8 == 0 :
b = unpack('<f',bytes.fromhex(s))[0]
substation_adr = information_adr-16385
print('集控点号:{},子站点号:{},值为:{}'.format(information_adr,substation_adr,b))
s = ''
information_adr += 1
substation_adr += 1
else:
continue
message_str = input('请输入:')
if __name__ == '__main__':
main()
information_adr = unpack('<hb', bytes.fromhex(information_adr_str))[0]
bytes.fromhex(str) 用来将字符串转换为
unpack()结果为一个元组,所以输出的时候在后面会添加[0]代表输出元组中0号位的元素
‘<hb’ 要参考下表:



因我取出的数据为 ‘094700’,只占用3个字节,实际使用应该是004709,所以我用'<',代表使用小端法,作用是将094700转换为004709,而‘hb’是用来存储3个字节的
详细内容可参考:https://docs.python.org/3.5/library/struct.html?highlight=struct#module-struct
|