Calculating FCS(CRC) for HDLC frame

后端 未结 3 1013
北海茫月
北海茫月 2021-02-04 21:22

I have the following frame:

7e  01 00  00  01  00  18  ef  00  00  00   b5   20 c1 05 10 02 71 2e 1a c2 05 10 01 71 00 6e 87 02 00 01 42 71 2e 1a 01 96 27 be 27          


        
3条回答
  •  猫巷女王i
    2021-02-04 21:45

    This is simple Python script for HDLC CRC calculation. You can use it for DLMS

    def byte_mirror(c):
    
        c = (c & 0xF0) >> 4 | (c & 0x0F) << 4
        c = (c & 0xCC) >> 2 | (c & 0x33) << 2
        c = (c & 0xAA) >> 1 | (c & 0x55) << 1
    
        return c
    
    CRC_INIT=0xffff
    POLYNOMIAL=0x1021
    DATA_VALUE=0xA0
    
    SNRM_request=[ 0x7E, 0xA0, 0x08, 0x03, 0x02, 0xFF, 0x93, 0xCA, 0xE4, 0x7E]
    
    print("sent>>", end=" ")
    
    for x in SNRM_request:
      if x>15:
           print(hex(x), end=" ")
      else:
           a=str(hex(x))
           a = a[:2] + "0" + a[2:]
           print(a, end=" ")
    
    lenn=len(SNRM_request)
    print(" ")
    
    crc = CRC_INIT
    
    
    
    for i in range(lenn):
    
        if( (i!=0) and (i!=(lenn-1)) and (i!=(lenn-2)) and (i!=(lenn-3)) ):
    
            print("i>>",i)
    
            c=SNRM_request[i]
            c=byte_mirror(c)
            c = c << 8
        
            print(hex(c))
    
            for j in range(8):
      
                print(hex(c))
                print("CRC",hex(crc))
    
                if (crc ^ c) & 0x8000:
                    crc = (crc << 1) ^ POLYNOMIAL
                else:
                    crc = crc << 1
    
                c = c << 1   
                crc=crc%65536
                c  =c%65536
    
    
    print("CRC-CALC",hex(crc))
    
    crc=0xFFFF-crc          
    print("CRC- NOT",hex(crc))
    
    crc_HI=crc//256
    crc_LO=crc%256
    
    print("CRC-HI",hex(crc_HI))
    print("CRC-LO",hex(crc_LO))
    
    crc_HI=byte_mirror(crc_HI)
    crc_LO=byte_mirror(crc_LO)
    
    print("CRC-HI-zrc",hex(crc_HI))
    print("CRC-LO-zrc",hex(crc_LO))
    
    crc=256*crc_HI+crc_LO
    print("CRC-END",hex(crc))
    

提交回复
热议问题