利用Python简单实现环保212协议客户端【HJ212_2017协议的封包发送】

1、文件组成:

config.json——配置信息
HJ212_2017_Helper.py——功能函数
HJ212_2017_CLIENT.py——客户端发送

2、配置文件(JSON格式)

{
     
	"server":{
     
		"ip":"127.0.0.1", 
		"port":8640
	}, 
	"data":{
     
		"ST":"21", 
		"CN":"2011",
		"PW":"123456",
		"MN":"010000A8900016F000169DC0", 
		"Flag":"4"		 				 		
	}
}

3、功能函数(利用Python字典结构做协议封包)

#!/usr/bin/python3

import time

'''
    crc16效验

'''
def crc16(text):
    data = bytearray(text, encoding='utf-8')
    crc = 0xffff
    dxs = 0xa001
    for i in range(len(data)):
        hibyte = crc >> 8
        crc = hibyte ^ data[i]
        for j in range(8):
            sbit = crc & 0x0001
            crc = crc >> 1
            if sbit == 1:
                crc ^= dxs
    return hex(crc)[2:]


'''
    QN=年月日时分秒毫秒
'''
def get_time_stamp():
    timestamp=time.time()
    local_time = time.localtime(timestamp)
    data_head = time.strftime("%Y%m%d%H%M%S", local_time)
    data_secs = (timestamp - int(timestamp)) * 1000
    dt_ms = "%s%03d" % (data_head, data_secs)
    # print(dt_ms)
    return dt_ms

'''
    由配置信息生成数据字典
'''
def make_dic(config):
    DIC_HJ212_2017={
     }            
    DIC_HJ212_2017['QN']=get_time_stamp()
    DIC_HJ212_2017['ST']=config['data']['ST']
    DIC_HJ212_2017['CN']=config['data']['CN']
    DIC_HJ212_2017['PW']=config['data']['PW']
    DIC_HJ212_2017['MN']=config['data']['MN']
    DIC_HJ212_2017['Flag']=config['data']['Flag']
        
    DIC_HJ212_2017['CP']={
     }
    DIC_HJ212_2017['CP']['DataTime']=DIC_HJ212_2017['QN'][0:14]

    return DIC_HJ212_2017


'''
    由数据字典生成 HJ212_2017 协议字符串
'''
def make_str(DIC_HJ212_2017):
    _data=''
    for key,value in DIC_HJ212_2017.items():
        if(key=='CP'):
            _data+='CP=&&'                            
            for cp_key,cp_value in DIC_HJ212_2017[key].items():
                _data+=cp_key+'='+str(cp_value)+';'
            _data=_data[0:-1]                    
            _data+='&&'                        
        else:        
            _data+=key+'='+str(value)+';'


    _head='##'
    _length=len(_data)
        
    STR_HJ212_2017=''
    STR_HJ212_2017+=_head
    STR_HJ212_2017+=str(_length).zfill(4)
    STR_HJ212_2017+=_data
    STR_HJ212_2017+=str(crc16(_data)).zfill(4).upper();
    STR_HJ212_2017+='\r\n'
    return STR_HJ212_2017 

#自我测试    
if __name__ == "__main__":
    print(get_time_stamp())
    print(crc16(''))

4、采集报送

#!/usr/bin/python3

from socket import *
import threading
import time
import json
import os
import HJ212_2017_Helper as hj212

'''
发送数据
'''
def send_msg(tcp_socket):
    global config
    while True:
        DIC_HJ212_2017=hj212.make_dic(config)
		'''		
		数据采集过程
		将采集的结果填充到数据字段 CP, 
		'''		
        DIC_HJ212_2017['CP']['a01002-Rtd']='12.69'
        DIC_HJ212_2017['CP']['a01002-Flag']='N'
		'''
		按需求自行填写
		'''
        STR_HJ212_2017=hj212.make_str(DIC_HJ212_2017)       
        
        '''
        回显待发送数据,【调试用】
        '''
        print (STR_HJ212_2017)    

		'''
		报送数据
		'''
        tcp_socket.send(STR_HJ212_2017.encode('utf8'))
        '''
        recv_msg= tcp_socket.recv(1024).decode("utf8")
        print('接收到的信息为:%s\n'% recv_msg)
        接收平台返回数据,做远程反控
        '''
        
        time.sleep(5) 



#读本地配置文件 config.json
with open(os.path.join(os.getcwd(),'config.json'),'r',encoding='utf-8') as f:
    content=f.read()
config=json.loads(content)

tcp_socket=socket(AF_INET, SOCK_STREAM)

#连接平台服务器
tcp_socket.connect((config['server']['ip'], config['server']['port']))

#开启采集——>发送线程
threading.Thread(target=send_msg,args=(tcp_socket,)).start()

5、运行调试

利用Python简单实现环保212协议客户端【HJ212_2017协议的封包发送】_第1张图片
利用Python简单实现环保212协议客户端【HJ212_2017协议的封包发送】_第2张图片

你可能感兴趣的:(HJ212-2017,环保212协议,python,网络协议)