Python_Example_modbus串口_完成模拟DSP通信_实现程序

2018-09-20

 

Author: 楚格

IDE: Pycharm2018.02   Python 3.7   

KeyWord :  Excel display

Explain:  

 思路:

 

 

1------------------------------------------------------------------------------------------------------------------

--

 

  1 __all__ = ['Function_Serial_Info','Function_Receive_Data',
  2            'Function_Receive_Data','Function_Send_Data',
  3            'Function_Handle_Receive','Function_Modbus_CRC',
  4            'Function_HexString_Trans',]
  5 
  6 import sys
  7 import os
  8 
  9 import re
 10 import string
 11 import binascii
 12 import array
 13 import signal
 14 import serial
 15 import time
 16 from time import sleep
 17 
 18 import logging
 19 import unittest
 20 # =========================================
 21 
 22 '''
 23 # ------------------------------------------
 24 # 导入:外文件夹中 .py 模块
 25 # 先导入路径,后引用模块
 26 # ------------------------------------------
 27 '''
 28 # 1 D:\Auto_Testing_Pycharm\Log_Run
 29 sys.path.insert(0,"./Log_Run")
 30 from Testing_Log import *
 31 
 32 
 33 '''
 34 # ------------------------------------------
 35 # 导入:本文件夹中 .py 模块
 36 # 直接引用模块名称
 37 # ------------------------------------------
 38 '''
 39 # preject module
 40 from Testing_CRC import *
 41 
 42 
 43 # ============================================================================
 44 '''
 45 # ============================================================================
 46 # Function:   串口设置  函数
 47 # Explain : 
 48 #         :
 49 # ============================================================================
 50 '''
 51 def Function_Serial_Info():
 52     print('串口初始化  Function_Serial_Info')
 53     # -----------------------------
 54 
 55     global global_var_serial_init
 56     global global_var_serial_band
 57 
 58     # 必须设置串口
 59     local_var_serial_func = True
 60 
 61     while local_var_serial_func:
 62 
 63         print("默认请输入:1  \n重新输入为:2")
 64 
 65         # default = input('您的请选择:  ')
 66         default = "1"     # debug
 67 
 68         if default == "1":
 69 
 70             global_var_serial_init = serial.Serial(port="COM5", baudrate=115200, timeout=0.05)  # 端口控制
 71             local_var_serial_func = False     # 结束执行
 72 
 73         elif default == "2":
 74             port = input('串口号(数字): ', )   # 端口号
 75 
 76             local_var_serial_nunber = True
 77 
 78             while local_var_serial_nunber:
 79                 print('可选波特率:1 = 9600 \n\t\t 2 = 115200')
 80                 global_var_serial_band = input('波特率序号: ')
 81 
 82                 if global_var_serial_band == "1":
 83                     global_var_serial_band = 9600
 84                     local_var_serial_nunber = False
 85 
 86                 elif global_var_serial_band == "2":
 87                     global_var_serial_band = 115200
 88                     local_var_serial_nunber = False
 89 
 90                 else:
 91                     print('超出范围:请重新选择波特率!')
 92                     local_var_serial_nunber = True
 93 
 94                 # 组装成串口初设信息
 95             global_var_serial_init = serial.Serial(port="COM" + port, baudrate=global_var_serial_band, timeout=1)  # 端口控制
 96 
 97             local_var_serial_func = False  # 结束执行
 98 
 99         else:
100             print('超出选择范围,请重新选择序号!')
101             local_var_serial_func = True  # 返回继续执行
102 
103     # ------------------------------------------------------
104 
105 '''
106 # ============================================================================
107 # Function:   接受数据  函数
108 # Explain :   接受串口收到的数据
109 #         :
110 # ============================================================================
111 '''
112 def Function_Receive_Data():
113     # print('Function_Receive_Data :')
114     # logging.debug('Function_Receive_Data')
115     # ======================================
116     global global_var_receive_string  # 作为获取到的数据
117 
118     # 接收单次数据,外部进行处理 SINGLE    #循环接收数据,内部进行处理 LOOP
119     FREQUENCY = True
120     SINGLE    = False
121     LOOP      = True
122 
123     if FREQUENCY == SINGLE:
124         print(SINGLE)
125         # 待开发模块
126 
127     elif FREQUENCY ==LOOP:
128         # logging.debug('LOOP:')
129         # ------------------------------------------------------
130         # line = global_var_serial_init.readline()  # 读取全部内容
131         line = global_var_serial_init.read(100)  # 读取全部内容
132         # print("Len     :", len(line), " Type :", type(line), "    readline : %s" % line)
133         # logging.debug(line)
134 
135         # 字节变成字符串,目的是方便处理数据
136         types_transform_string = line.hex()  # 字节变成字符串
137         # print("Len     :", len(types_transform_string), type(types_transform_string), types_transform_string)
138         # logging.debug(types_transform_string)
139 
140         # ------------------------------------------------------
141         # 数据名称变换 目的是作为全局变量
142         global_var_receive_string = types_transform_string
143 
144     else:
145         pass
146     # ------------------------------------------------------
147 
148 '''
149 # ============================================================================
150 # Function:  发送数据  函数
151 # Explain :  发送数据到串口 
152 #          golal_var_result_send_data
153 # ============================================================================
154 '''
155 def Function_Send_Data(send_data):
156     # print('发送指令函数  Function_Send_Data')
157     # ---------------------------
158     # print('''
159     #         ---- Info of Send Data Parameter ----
160     #             Send   data    : %s
161     #             Serial Port    : %s
162     #         ''' % ( send_data,global_var_serial_init.port)
163     #       )
164 
165     local_var_send_data_buff =send_data
166     #--------------------------------------
167     # 发送函数 核心语句 输出接口
168     global_var_serial_init.write(local_var_send_data_buff)
169     #--------------------------------------
170 
171     # global_var_serial_init.close() # 关闭串口
172     # global_var_serial_init.open()  # 打开端口
173     # global_var_serial_init.isOpen() #串口是否被打开
174 # ---------------------------------------------------------
175 '''
176 # ============================================================================
177 # Function: 数据处理   函数
178 # Explain:  接收数据进行处理
179 #           global_var_receive_string
180 # ============================================================================
181 '''
182 def Function_Handle_Receive():
183     # ======================================
184     global global_var_crc_value
185 
186     local_var_handle_data = global_var_receive_string
187     # global_var_receive_string.reset_input_buffer() #清除输入缓存
188     print('local_var_handle_data: < %s >'%local_var_handle_data)
189 
190     logging.debug(local_var_handle_data)
191     # logging.getLogger('Function_Handle_Receive')
192 
193     # # 字符串重新规整 剪断拼接字符串
194     # DIVISION = 24
195     # local_var_handle_data = local_var_handle_data[10:] +local_var_handle_data[:10]
196     # local_var_Temp_1 =local_var_handle_data[ :DIVISION]        # 新划分的数据 local_var_Temp_1
197     # local_var_Temp_2 =local_var_handle_data[DIVISION: ]        # 新划分的数据 local_var_Temp_2
198     # print('24',time.time())
199     # logging.debug(local_var_Temp_1)
200     # logging.debug(local_var_Temp_2)
201     # print('25',time.time())
202     local_var_Temp_1 =local_var_handle_data        # 新划分的数据 local_var_Temp_1
203 
204 
205     # 结果存留区
206     # request data format
207 
208     L_DIVI = 0
209     result_CAN_ID_1         = local_var_Temp_1[(L_DIVI +  0):(L_DIVI +  8)]
210     result_slave_address_1  = local_var_Temp_1[(L_DIVI +  8):(L_DIVI + 10)]
211     result_slave_function_1 = local_var_Temp_1[(L_DIVI + 10):(L_DIVI + 12)]
212     result_slave_register_1 = local_var_Temp_1[(L_DIVI + 12):(L_DIVI + 16)]
213     result_slave_number_1   = local_var_Temp_1[(L_DIVI + 16):(L_DIVI + 20)]
214     # 根据不同 result_CAN_ID 进行处理,包括组包  response data
215     # 调用函数
216     Function_Handle_Judge(result_CAN_ID_1,
217                           result_slave_address_1,
218                           result_slave_function_1,
219                           result_slave_register_1,
220                           result_slave_number_1)
221         #--------------------------------------------------
222 
223 
224 # ---------------------------------------------------------
225 '''
226 # ============================================================================
227 # Function: 判断 
228 # Explain:  输入参数  CAN_ID,slave_address,slave_function,slave_register,slave_number
229 #           输出参数      
230 # ============================================================================
231 '''
232 def Function_Handle_Judge(result_CAN_ID,result_slave_address,
233                           result_slave_function,result_slave_register,result_slave_number):
234     #------------------------------------------
235     # 形参名称变换
236     Local_var_CAN_ID         = result_CAN_ID
237     Local_var_slave_address  = result_slave_address
238     Local_var_slave_function = result_slave_function
239     Local_var_slave_register = result_slave_register
240     Local_var_slave_number   = result_slave_number
241     Local_var_slave_RegNum   = result_slave_register \
242                                + result_slave_number
243     # --------------------------------------------
244 
245     # 常量声明
246     SLAVE_CAN_ID_1 = '00000001'
247     SLAVE_CAN_ID_2 = '00000002'
248     # 功能码
249     SLAVE_FUNCTION_RO = '04'
250     SLAVE_FUNCTION_SG = '06'
251     SLAVE_FUNCTION_MU = '10'
252 
253     # 此处来自协议文本 此处复制 后期拓展
254     #------------------------
255     #协议取值 临时
256     #------------------------
257     RESISTER_C_1 = '09c3'
258     NUMBER_C_1   = '0052'
259     RESISTER_C_2 = '0a15'
260     NUMBER_C_2   = '003c'
261     RESISTER_C_3 = '137c'
262     NUMBER_C_3   = '000f'
263     RESISTER_C_4 = '138f'
264     NUMBER_C_4   = '0039'
265     RESISTER_C_5 = '13d8'
266     NUMBER_C_5   = '001b'
267 
268 
269     #-----------------------
270     # logging.debug(Local_var_CAN_ID)
271     # ID='00000001'
272     if (Local_var_CAN_ID == SLAVE_CAN_ID_1) :
273         # print(Local_var_CAN_ID,Local_var_slave_address,Local_var_slave_function,Local_var_slave_register,Local_var_slave_number)
274 
275         if Local_var_slave_function == SLAVE_FUNCTION_RO :
276 
277             if (Local_var_slave_register == RESISTER_C_1) and (Local_var_slave_number == NUMBER_C_1 ):
278                 Local_temp_value   = Function_Response_Data_1()  # 回填数据
279                 Function_Handle_AddCRC_Send(Local_var_CAN_ID,Local_var_slave_address, Local_var_slave_function, Local_temp_value)
280 
281             elif (Local_var_slave_register == RESISTER_C_2) and (Local_var_slave_number == NUMBER_C_2 ):
282                 Local_temp_value = Function_Response_Data_2()   # 回填数据
283                 Function_Handle_AddCRC_Send(Local_var_CAN_ID, Local_var_slave_address, Local_var_slave_function,Local_temp_value)
284 
285             elif (Local_var_slave_register == RESISTER_C_3) and (Local_var_slave_number == NUMBER_C_3 ):
286                 Local_temp_value = Function_Response_Data_3()   # 回填数据
287                 Function_Handle_AddCRC_Send(Local_var_CAN_ID, Local_var_slave_address, Local_var_slave_function,Local_temp_value)
288 
289             elif (Local_var_slave_register == RESISTER_C_4) and (Local_var_slave_number == NUMBER_C_4 ):
290                 Local_temp_value = Function_Response_Data_4()   # 回填数据
291                 Function_Handle_AddCRC_Send(Local_var_CAN_ID, Local_var_slave_address, Local_var_slave_function,Local_temp_value)
292 
293             elif (Local_var_slave_register == RESISTER_C_5) and (Local_var_slave_number == NUMBER_C_5 ):
294                 Local_temp_value = Function_Response_Data_5()   # 回填数据
295                 Function_Handle_AddCRC_Send(Local_var_CAN_ID, Local_var_slave_address, Local_var_slave_function,Local_temp_value)
296 
297 
298             else:
299                 print('未知。。。register or number')
300 
301         elif Local_var_slave_function == SLAVE_FUNCTION_SG:
302             print('-06')
303             Function_Handle_AddCRC_Send(Local_var_CAN_ID, Local_var_slave_address, Local_var_slave_function,
304                                         Local_var_slave_RegNum)
305 
306 
307         elif Local_var_slave_function == SLAVE_FUNCTION_MU:
308             print('10')
309             Function_Handle_AddCRC_Send(Local_var_CAN_ID, Local_var_slave_address, Local_var_slave_function,
310                                         Local_var_slave_RegNum)
311 
312 
313         else:
314             print('未知... function code 功能码')
315 
316 
317         #  # ID='00000002'
318     elif Local_var_CAN_ID == SLAVE_CAN_ID_2:
319         # print(Local_var_CAN_ID,Local_var_slave_address,Local_var_slave_function,Local_var_slave_register,Local_var_slave_number)
320         print('暂时忽略')
321 
322     else:
323         print('未知。。。 CAN_ID')
324 
325 
326 # ---------------------------------------------------------
327 '''
328 # ============================================================================
329 # Function: 添加CRC && send
330 # Explain:  输入参数  CAN_ID,slave_address,slave_function,slave_register,slave_number
331 #           输出参数  
332 #               
333 #           
334 # ============================================================================
335 '''
336 def Function_Handle_AddCRC_Send(result_CAN_ID,result_slave_address,result_slave_function,result_temp_value):
337     # print('Function_Handle_AddCRC_Send: ')
338     # ------------------------------------------
339     # 形参名称变换
340     Local_var_CAN_ID         = result_CAN_ID
341     Local_var_slave_address  = result_slave_address
342     Local_var_slave_function = result_slave_function
343     Local_var_temp_value     = result_temp_value
344     # --------------------------------------------
345 
346     # --------------------
347     # 预处理目的:添加 CRC码
348     local_var_modbus_data = Local_var_slave_address + Local_var_slave_function + Local_var_temp_value
349     Pack_modbus_data = Function_HexString_Trans(local_var_modbus_data)
350     Pack_Buff_modbus_data = Function_Modbus_CRC(Pack_modbus_data, 0)
351 
352     Pack_Buff_CAN_data = Local_var_CAN_ID  # 作为格式对称保留
353 
354     local_var_result_send_data = Function_HexString_Trans(Pack_Buff_CAN_data) + Pack_Buff_modbus_data
355 
356     logging.debug(local_var_result_send_data)
357     print(local_var_result_send_data)
358     # --------------------------
359     # handle data finish got together package
360     # 这是处理完成后,组包发送给串口
361     # -------------------------------------------------------------------
362     Function_Send_Data(local_var_result_send_data)  # 核心 函数
363     # -------------------------------------------------------------------
364 
365 
366 
367 # ---------------------------------------------------------
368 
369 '''
370 # ============================================================================
371 # Function: Modbus CRC 校验   函数
372 # Explain:  输入参数  列表 [1, 4, 8, 1, 2, 3, 4, 5, 6, 7, 8          ]
373 #           输出参数  列表 [1, 4, 8, 1, 2, 3, 4, 5, 6, 7, 8, 212, 201]
374 #           check    right: 1   wrong: 0
375 #           
376 # ============================================================================
377 '''
378 def Function_Modbus_CRC(Pack_modbus_data,test_type):
379     # print('Function_Modbus_CRC : ',)
380     #------------------------------------
381     global global_var_modbus_data_buff
382     global global_var_modbus_check
383 
384     if test_type == 0 :
385         # # CRC 校验 添加校验码
386         temp_crc_translate = CalCRC16(Pack_modbus_data, len(Pack_modbus_data))  # 核心步骤
387         # -------------------------
388         # # 注意添加先后顺序 先低 后高
389         Pack_modbus_data.append(int(hex(temp_crc_translate & 0xFF), 16))
390         Pack_modbus_data.append(int(hex((temp_crc_translate >> 8) & 0xFF), 16))
391         # print('Pack_Buff_modbus_data : ', len(Pack_modbus_data), type(Pack_modbus_data),Pack_modbus_data)  # calculation value   CRC
392         # -------------------------
393         global_var_modbus_data_buff = Pack_modbus_data  # 重新命名
394 
395         return global_var_modbus_data_buff
396 
397     # ---------------------------------------------------------
398     # CRC 校验检查 check
399     elif test_type == 1 :
400 
401         temp_CRC_check = CheckCRC(Pack_modbus_data, len(Pack_modbus_data), 0)
402 
403         if temp_CRC_check == 1:
404             print('Result    :', temp_CRC_check)  # check calculation value
405             print('CRC_Check : Right')
406             global_var_modbus_check = temp_CRC_check    # 重新命名
407 
408             return global_var_modbus_check
409 
410         else:
411             print('Result    :', temp_CRC_check)  # check calculation value
412             print('CRC_Check : wrong')
413             global_var_modbus_check = temp_CRC_check    # 重新命名
414 
415             return global_var_modbus_check
416 
417     # ---------------------------------------------------------
418 # ---------------------------------------------------------
419 '''
420 # ============================================================================
421 #   函数    数据转换
422 # Explain: 输入参数:data_trans
423 #          输出参数:global_var_trans_data
424 #   功能  :hex string转换为整形列表
425 # example: AT = '01F2AA0405'
426 #          SEND_AT = Function_HexString_Trans(AT)
427 #          print(SEND_AT)
428 #          Function_Send_Data(SEND_AT)
429 #          time.sleep(2)
430 # ============================================================================
431 '''
432 
433 def Function_HexString_Trans(data_trans):
434     # print('Function_HexString_Trans : ',)
435     #------------------------------------
436     global global_var_trans_data
437 
438     temp = bytearray.fromhex(data_trans)
439     global_var_trans_data= list(temp)
440     # print(global_var_trans_data)
441 
442     return global_var_trans_data
443 
444     # --------------------------------------------
445 
446 '''
447 # ============================================================================
448 # Function: 
449 # Explain:  
450 #          
451 #           
452 # ============================================================================
453 '''
454 def Function_Response_Data_1():
455     global temp_data
456 
457     temp_data =   'A420010000010001000258303000000000000000000000000000000000000001' \
458                   '0F534736304B544C0000000000000000005631310000000000000000000000' \
459                   '0000000000002064010101000100000000FF00000000303030303030303030' \
460                   '303030300121020330010002' \
461                   '00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FF00000000' \
462                   '00000000000000000000000000000000000000000000000000000002'
463 
464     return temp_data
465 
466 def Function_Response_Data_2():
467     global temp_data
468 
469     temp_data =   '784D4453505F534736304B544C5F5631315F56315F5300000000000000000053' \
470                   '4736304B544C5F43504C445F5631315F430000000000000000000000003030' \
471                   '00000000000000000000000000000000000000000000000000000000303000' \
472                   '000000000000000000000000000000000000000000000000000000'
473 
474     return temp_data
475 
476 def Function_Response_Data_3():
477     global temp_data
478 
479     temp_data =   '1E00000000000000410011004100320000000007000100010F02580001012C'
480 
481     return temp_data
482 
483 
484 def Function_Response_Data_4():
485     global temp_data
486     # 13 8F 00 39
487     temp_data =   '72013E00000000000000000000000000010000000000000000000000000000' \
488                   '00000000000000000000000000000000000000000000000000000000000000' \
489                   '00000000000000000000005500000000000000000000550001FFFF00000100' \
490                   '000000000000000000000001000000030000FFFF0000'
491 
492     return temp_data
493 
494 def Function_Response_Data_5():
495     global temp_data
496     # 13 D8 00 1B
497     temp_data =   '36FFFC000000000000000000000000000100000000000000770086009E0000' \
498                   '00000000000005140514051400000000157C000400640300'
499 
500     return temp_data
501 
502 
503 
504 # def Function_Response_Data_8():
505 #     global temp_data
506 #
507 #     temp_data =   ''
508 #
509 #     return temp_data
510 
511 # ============================================================================
512 
513 
514 '''
515 # ============================================================================
516 #   测试专用
517 # ============================================================================
518 '''
519 if __name__ == '__main__':
520     print('-------------------------------------')
521     print('=\t\t 欢迎进入   测试环境  \t\t\t=')
522     print('-------------------------------------\n')
523 
524     Function_Serial_Info()  # 打开串口
525     # 需要关闭窗口
526     # global_var_serial_init.close() # 关闭串口
527     # global_var_serial_init.open()  # 打开端口
528     print(global_var_serial_init.isOpen())
529 
530 
531     TEST_RUN   = True   # 测试层演示
532     USER_DEBUD = True   # 用户层调试 False
533     BOOT_DEBUG = True   # 开发层调试 False
534 
535     # 一直收到数据
536     while True:
537         # print('1', time.time())
538         Function_Receive_Data()     # 接收函数
539         # print('2', time.time())
540         Function_Handle_Receive()   # 处理函数
541         # print('3', time.time())
542 
543 
544         # if TEST_RUN:
545         #     print('USER_DEBUD')
546         #     # --------------------------
547         # else:
548         #     pass
549 
550     # global_var_serial_init.colse()
551     # ===============================================================

 

--

run result

--

无:内容涉及协议

--

 

posted @ 2018-09-20 11:04  楚格  阅读(927)  评论(0编辑  收藏  举报