• Python_Example_CAN转RS-485实现程序


    2018-09-12

    Author: 楚格

    IDE: Pycharm2018.02   Python 3.7   

    KeyWord :  CAN模块

    Explain:

    多级选择,后续待优化

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

    --

    __all__ = []
    
    import sys
    import os
    
    import re
    import string
    import binascii
    import array
    import signal
    from time import sleep
    
    import serial
    import time
    import pprint
    from collections import OrderedDict  # 字典元素有序排列
    
    # =========================================
    
    
    
    '''
    # ------------------------------------------
    # 导入:本文件夹中 .py 模块
    # 直接引用模块名称
    # ------------------------------------------
    '''
    #preject module
    from Testing_CRC import *
    
    
    '''
    # ======================================
    # 串口读取
    # ======================================
    '''
    
    global MAX_LOOP_NUM
    global newCmd
    MAX_LOOP_NUM = 0
    
    
    #========================================================
    '''
    # ======================================
    # 输入函数  函数
    # ======================================
    '''
    # def Input_AT_CMD(AT_CMD):
    #     print('输入函数  Input_AT_CMD')
    #
    #     print('AT_CMD :', len(AT_CMD), type(AT_CMD), AT_CMD)
    #     AT_CMD_Handle = AT_CMD
    #
    #     result = AT_CMD_Handle
    #
    #     return AT_CMD_Handle
    
    
    
    '''
    # ======================================
    # 校验函数  函数
    # ======================================
    '''
    def Modbus_CRC():
        print('校验函数 Modbus CRC')
    
        global crc_value
    
        # ========================================================
        # 输入列表值 字节  临时
    
        Local_AT = 2
    
        if   Local_AT == 1 :
            # 测试
            crc_value = [0x01, 0x04, 0x13, 0x87, 0x00, 0x30]
    
        elif Local_AT == 2 :
            # SN
            crc_value = [0x01, 0x04, 0x13, 0x7e, 0x00, 0x0A]
    
        else:
            print('AT指令超出范围')
    
        # crc_value = AT_crc
    
            # CRC 校验 添加校验码
        crc_transformation = CalCRC16(crc_value, len(crc_value))      # 核心步骤
        print('crc_transformation: ',crc_transformation, type(crc_transformation)) # Int没有Len
    
        crc_calculation = hex(crc_transformation)
        print('crc_calculation   : ',crc_calculation, type(crc_calculation))
    
            # 注意添加先后顺序 先低 后高
        crc_value.append(int(hex(crc_transformation        & 0xFF), 16))
        crc_value.append(int(hex((crc_transformation >> 8) & 0xFF), 16))
        print('crc_value         : ',len(crc_value), type(crc_value), crc_value)  # calculation value   CRC
    
        '''
        # 本区域是上述语句的分解
        # tasd = [0x00, 0x00]     # 申明 初始化变量
        # tasd[0] =  crc_transformation       & 0xFF
        # tasd[1] = (crc_transformation >> 8) & 0xFF
        # H = hex(tasd[0])
        # L = hex(tasd[1])
        # H_value = int(H, 16)
        # L_value = int(L, 16)
        # crc_value.append(H_value)
        # crc_value.append(L_value)
        '''
        print('
    ')
        # ========================================================
        # CRC 校验再次检查
        CRC_Check = CheckCRC(crc_value, len(crc_value),0)
    
        if CRC_Check == 1:
            print('Result    :', CRC_Check)  # check calculation value
            print('CRC_Check : Right')
        else:
            print('Result    :', CRC_Check)  # check calculation value
            print('CRC_Check : wrong')
    
        print('
    ')
        # ========================================================
        # 返回添加后的CRC值
        return crc_value
    
        # ========================================================
    
    '''
    # ======================================
    # 串口设置  函数
    # ======================================
    '''
    def Serial_info():
        print('串口初始化  Serial_info')
        #-----------------------------
    
        global ser, band
    
        Local_func =True
        while Local_func:
            print("默认请输入:1  
    重新输入为:2")
            default = input('您的请选择:  ')
    
            if default == "1":
                ser = serial.Serial(port="COM5", baudrate=115200, timeout=1)  # 端口控制
                Local_func = False  # 结束执行
    
            elif default == "2":
                port = input('串口号(数字): ', ) # 查看端口号
    
                Local_xuhao = True
    
                while Local_xuhao:
                    print('可选波特率:1 = 9600 
    		 2 = 115200')
                    band = input('波特率序号: ')
    
                    if band == "1":
                        band = 9600
                        Local_xuhao = False
                    elif band == "2":
                        band = 115200
                        Local_xuhao = False
                    else:
                        print('超出范围:请重新选择波特率!')
                        Local_xuhao = True
                    # 组装成串口初设信息
                ser = serial.Serial(port="COM" + port, baudrate=band, timeout=1)  # 端口控制
                Local_func = False  # 结束执行
            else:
                print('超出选择范围,请重新选择序号!')
                Local_func = True #返回继续执行
    
        # AT = 'Slave:GetConfig'
        # AT = bytearray([0x01,0x04,0x13,0x87,0x00,0x30,0x44,0xB3])
        # AT = bytes([0x01,0x04,0x13,0x87,0x00,0x30,0x44,0xB3])
        # AT  = bytearray(crc_value)
    
        AT  = bytes(crc_value)
    
        sendAT_Cmd(ser, AT, 1)
    
    '''
    # ======================================
    # 发送指令 函数
    # ======================================
    '''
    def sendAT_Cmd(serInstance, atCmdStr, waitforOk):
        print('发送指令函数  send_cmd')
        #---------------------------
        # print("Instance: %s" % serInstance) # 打开串口的信息
        print("Command : %s" % atCmdStr)    # 发送的指令
        print("Port    :",ser.port)         # 端口号
    
            #  判断是字符串还是字节
            #  or define b'string',bytes should be used not str
        # serInstance.write(atCmdStr.encode('utf-8'))
    
        # in_bytes = atCmdStr.encode(atCmdStr)
        serInstance.write(atCmdStr)
    
    
    
        if (waitforOk == 1):
            waitForCmdOKRsp()
        # else:
        #     waitForCmdRsp()
    
    
    '''
    # ======================================
    # 等待回复  函数
    # ======================================
    '''
    def waitForCmdOKRsp():
        print('等待回复函数  waitForCmdOKRsp')
        #----------------------------------
        maxloopNum = 0
        global Reveice_Value
    
        while True:
            line = ser.readline()   # 读取全部内容
            print("Len     :", len(line)," Type :", type(line),"   Rsponse : %s" % line)
    
            aa = line.hex()         # 字节变成字符串
            print("Len     :",len(aa),type(aa),aa)
    
            az = aa.split(" ")      # 字符串变成列表元素
            print("Len     :",len(az),type(az),az)
    
    
    
            print('
    ')
    
            # try:
            #     # print("Rsponse : %s" % line)     # 字节
            # except:
            #     print('出现异常')
    
            #=======  选择接受次数  =========
            # maxloopNum = maxloopNum + 1
            # if (re.search(b'OK', line)):
            #     break
            # elif (maxloopNum > MAX_LOOP_NUM):
            #     sys.exit(0)
            # ============================
    
            Reveice_Value = aa
    
            Handle_Reveice()
            # result = Reveice_Value
            # return Reveice_Value
    
    
    '''
    # ======================================
    # 等待回复  函数
    # ======================================
    '''
    
    def Handle_Reveice():
        print('Handle_Reveice')
    
        print(Reveice_Value[:10],Reveice_Value[10:18],Reveice_Value[18:34],Reveice_Value[34:48],)
    
        # print(Reveice_Value[16:18])
        if Reveice_Value[17:18] == '2' :
            print('ID: %s'% Reveice_Value[10:18])
    
            AT = bytes(crc_value)
            sendAT_Cmd(ser, AT, 1)
    
    # ========================================================
    
    
    
    
    '''
      Frame head          |   Data   |  CRC
     Address  | function  |   Ntype  |  2Type
    
      - - - - - - - - - - - - - - - - - - - -  
      1.获取ID 设备地址,并保存
      2.确实发送的功能码
      3.读取寄存器地址和数量
      4.CRC校验
    
      - - - - - - - - - - - - - - - - - - - - 
      
    1.获取设备地址
    0xff, 0x03, 0x75, 0x52, 0x00, 0x01, 0xff, 0xff
    
    '''
    
    
    
    # ===============================================================
    
    
    # ===============================================================
    
    '''
    #===============================================================
    #   测试专用
    #===============================================================
    '''
    if __name__ == '__main__':
    
    
        print('-------------------------------------')
        print('=		 欢迎进入   测试环境  			=')
        print('-------------------------------------
    ')
        #
        # 语句
        # AT_CMD = [0x01, 0x04, 0x13, 0x7e, 0x00, 0x0A]
        # Input_AT_CMD(AT_CMD)
        #
        Modbus_CRC()
    
        Serial_info()
    
    
        sur.colse()
    
            
        # ===============================================================

    __all__ = ["CalCRC16","CheckCRC"]
    
    # ===============================================================
    import crcmod
    
    
    
    # ===============================================================
    '''
    # ======================================
    # 校验函数  函数
    # ======================================
    '''
    def CalCRC16(data, length):
        print(' 校验函数     CalCRC16')
        print('显示输入参数:',data,'	', length)
    
        crc=0xFFFF      # 初始值 变量申明
        if length == 0:
            length = 1
        ## for j in data:
        ##     crc ^= j
    
        j = 0
        while length != 0:
            crc ^= list.__getitem__(data, j)
            #print('j=0x%02x, length=0x%02x, crc=0x%04x' %(j,length,crc))
            for i in range(0,8):
                if crc & 1:
                    crc >>= 1
                    crc ^= 0xA001
                else:
                    crc >>= 1
            length -= 1
            j += 1
            ##if length == 0:
            ##         break
    
        return crc
    
    # ===============================================================
    def CheckCRC(data, length, crctype):
        print('校验CRC  CheckCRC')
        print('Length | Type | Data : ',length, type(data), data)
    
        if length < 3:
            print('The data len(%d) is less than 3!!!', length)
            return 0
    
        crc_res = 0
        tmp=[0,0,0,0]
    
        if crctype == 0:
            crc_res = CalCRC16(data, length-2)
            tmp[0] = crc_res & 0xFF
            tmp[1] = (crc_res >> 8) & 0xFF
    
            if data[length-2] == tmp[0] and data[length-1] == tmp[1]:
                return 1
        elif crctype == 1:
            print('CRC32 is not support...')
    
        return 0
    # ===============================================================
    
    
    
    
    
    # ===============================================================
    '''
    #===============================================================
    #   测试专用
    #===============================================================
    '''
    if __name__ == '__main__':
    
        ## Name Identifier-name, Poly  Reverse Init-value XOR-out Check
        ## ['modbus','CrcModbus',0x18005,REVERSE,0xFFFF,0x0000,0x4B37]
        ## crc16 = crcmod.mkCrcFun(0x18005, rev=True, initCrc=0xFFFF,  xorOut=0x0000) # rev=True,False
    
        crc16 = crcmod.mkCrcFun(0x18005,  initCrc=0xFFFF,rev=True,  xorOut=0x0000) # rev=True,False
        crc_array = b'0xFE 0xFD'
        crc_calc = crc16(crc_array) #计算得到的CRC
        a=hex(crc_calc)
        print(crc_calc,a)
        print('
    ')
    
        # =========================================
        crc_value = [0x01, 0x04, 0x13, 0x87, 0x00, 0x30]
        crc_transformation = CalCRC16(crc_value,len(crc_value))
        crc_calculation    = hex(crc_transformation)
        # print('crc_calculation:',crc_calculation)
        tasd = [0x00,0x00]
        tasd[0]  = crc_transformation & 0xFF
        tasd[1] = (crc_transformation >> 8) & 0xFF
        H =hex(tasd[0])
        L =hex(tasd[1])
        H_value = int(H,16)
        L_value = int(L,16)
        crc_value.append(H_value)
        crc_value.append(L_value)
        print(crc_value)          # calculation value   CRC
    
        # ========================================================
        print('
    ')
        # crc_value2 = [0x01, 0x04, 0x13, 0x87, 0x00, 0x30,0x44,0xB3]
        # print('crc_value2:',crc_value2)
        # crc_cheak=CheckCRC(crc_value2,len(crc_value2),0)
    
        crc_check=CheckCRC(crc_value,len(crc_value),0)
        if crc_check == 1:
            print('Right')
        else:
            print('wrong')
    
        print(crc_check)    # check calculation value

    --

    RUN Result

    --

    -------------------------------------
    =		 欢迎进入   测试环境  			=
    -------------------------------------
    
    校验函数 Modbus CRC
     校验函数     CalCRC16
    显示输入参数: [1, 4, 19, 126, 0, 10] 	 6
    crc_transformation:  37140 <class 'int'>
    crc_calculation   :  0x9114 <class 'str'>
    crc_value         :  8 <class 'list'> [1, 4, 19, 126, 0, 10, 20, 145]
    
    
    校验CRC  CheckCRC
    Length | Type | Data :  8 <class 'list'> [1, 4, 19, 126, 0, 10, 20, 145]
     校验函数     CalCRC16
    显示输入参数: [1, 4, 19, 126, 0, 10, 20, 145] 	 6
    Result    : 1
    CRC_Check : Right
    
    
    串口初始化  Serial_info
    默认请输入:1  
    重新输入为:2
    您的请选择:  1
    发送指令函数  send_cmd
    Command : b'x01x04x13~x00
    x14x91'
    Port    : COM5
    等待回复函数  waitForCmdOKRsp
    Len     : 19  Type : <class 'bytes'>    Rsponse : b'x00x00x00x02x02x04	xc3x00Rx82dx00x00x00x02x02x04
    '
    Len     : 38 <class 'str'> 00000002020409c3005282640000000202040a
    Len     : 1 <class 'list'> ['00000002020409c3005282640000000202040a']
    
    
    Handle_Reveice
    0000000202 0409c300 5282640000000202 040a
    Len     : 24  Type : <class 'bytes'>    Rsponse : b'x15x00<xe24x00x00x00x02x02x04	xc3x00Rx82dx00x00x00x02x02x04
    '
    Len     : 48 <class 'str'> 15003ce23400000002020409c3005282640000000202040a
    Len     : 1 <class 'list'> ['15003ce23400000002020409c3005282640000000202040a']
    
    
    Handle_Reveice
    15003ce234 00000002 020409c300528264 0000000202040a
    ID: 00000002
    发送指令函数  send_cmd
    Command : b'x01x04x13~x00
    x14x91'
    Port    : COM5
    等待回复函数  waitForCmdOKRsp
    Len     : 24  Type : <class 'bytes'>    Rsponse : b'x15x00<xe24x00x00x00x02x02x04	xc3x00Rx82dx00x00x00x02x02x04
    '
    Len     : 48 <class 'str'> 15003ce23400000002020409c3005282640000000202040a
    Len     : 1 <class 'list'> ['15003ce23400000002020409c3005282640000000202040a']
    
    
    Handle_Reveice
    15003ce234 00000002 020409c300528264 0000000202040a
    ID: 00000002
    发送指令函数  send_cmd
    Command : b'x01x04x13~x00
    x14x91'
    Port    : COM5
    等待回复函数  waitForCmdOKRsp
    Len     : 24  Type : <class 'bytes'>    Rsponse : b'x15x00<xe24x00x00x00x01x01x04	xc3x00Rx82Wx00x00x00x01x01x04
    '
    Len     : 48 <class 'str'> 15003ce23400000001010409c3005282570000000101040a
    Len     : 1 <class 'list'> ['15003ce23400000001010409c3005282570000000101040a']
    
    
    Handle_Reveice
    15003ce234 00000001 010409c300528257 0000000101040a
    Len     : 24  Type : <class 'bytes'>    Rsponse : b'x15x00<xe2x07x00x00x00x01x01x04	xc3x00Rx82Wx00x00x00x01x01x04
    '
    Len     : 48 <class 'str'> 15003ce20700000001010409c3005282570000000101040a
    Len     : 1 <class 'list'> ['15003ce20700000001010409c3005282570000000101040a']
    
    
    Handle_Reveice
    15003ce207 00000001 010409c300528257 0000000101040a
    Len     : 24  Type : <class 'bytes'>    Rsponse : b'x15x00<xe2x07x00x00x00x01x01x04	xc3x00Rx82Wx00x00x00x01x01x04
    '
    Len     : 48 <class 'str'> 15003ce20700000001010409c3005282570000000101040a
    Len     : 1 <class 'list'> ['15003ce20700000001010409c3005282570000000101040a']
    
    
    Handle_Reveice
    15003ce207 00000001 010409c300528257 0000000101040a
    Len     : 24  Type : <class 'bytes'>    Rsponse : b'x15x00<xe2x07x00x00x00x02x02x04	xc3x00Rx82dx00x00x00x02x02x04
    '
    Len     : 48 <class 'str'> 15003ce20700000002020409c3005282640000000202040a
    Len     : 1 <class 'list'> ['15003ce20700000002020409c3005282640000000202040a']
    
    
    Handle_Reveice
    15003ce207 00000002 020409c300528264 0000000202040a
    ID: 00000002
    发送指令函数  send_cmd
    Command : b'x01x04x13~x00
    x14x91'
    Port    : COM5
    等待回复函数  waitForCmdOKRsp
    Len     : 24  Type : <class 'bytes'>    Rsponse : b'x15x00<xe24x00x00x00x02x02x04	xc3x00Rx82dx00x00x00x02x02x04
    '
    Len     : 48 <class 'str'> 15003ce23400000002020409c3005282640000000202040a
    Len     : 1 <class 'list'> ['15003ce23400000002020409c3005282640000000202040a']
    
    
    Handle_Reveice
    15003ce234 00000002 020409c300528264 0000000202040a
    ID: 00000002
    发送指令函数  send_cmd
    Command : b'x01x04x13~x00
    x14x91'
    Port    : COM5
    等待回复函数  waitForCmdOKRsp
    
    Process finished with exit code -1
    

      

  • 相关阅读:
    12.python中的列表
    11.python中的元组
    10.python中的序列
    9.python的布尔类型与流程控制
    8.python中的数字
    7.python字符串-内置方法分析
    Boost--lexical_cast 一个方便安全高效的string转换库
    STL进阶--vector vs deque
    STL进阶--删除元素
    STL进阶--相等 vs 等价 (Equality vs Equivalence)
  • 原文地址:https://www.cnblogs.com/caochucheng/p/9636801.html
Copyright © 2020-2023  润新知