zoukankan      html  css  js  c++  java
  • python串口通信

    1 编码:

    def bytes(dataDict):
            strBody = json.dumps(dataDict)  # 将dict 数据妆化为字符串
            sendBuf = bytearray()  
            sendBuf += ('%04X' % len(strBody)).encode()  
            sendBuf += strBody.encode()   # 将字符串转化为字节数组
            crcVal = CRC16Kermit().calculate(str(strBody)) sendBuf += crcVal.encode() return sendBuf

    2 解码:

     msg = json.loads(body.decode('utf-8'))  # 先将字节数组解码为字符串 , JSON编码的字符串转换回一个Python数据结构

    3 crc16:

    from ctypes import c_ushort
    
    class CRC16Kermit(object):
        crc16kermit_tab = []
    
        crc16Kermit_constant = 0x8408
    
        def __init__(self):
            if not len(self.crc16kermit_tab): self.init_crc16kermit()  # initialize the precalculated tables
    
        def calculate(self, string=''):
            try:
                if not isinstance(string, str): raise Exception("Please provide a string as argument for calculation.")
                if not string: return 0
    
                crcValue = 0x0000
    
                for c in string:
                    tmp = crcValue ^ ord(c)
                    crcValue = c_ushort(crcValue >> 8).value ^ int(self.crc16kermit_tab[(tmp & 0x00ff)], 0)
    
                # After processing, the one's complement of the CRC is calcluated and the 
                # two bytes of the CRC are swapped.
                low_byte = (crcValue & 0xff00) >> 8
                high_byte = (crcValue & 0x00ff) << 8
                crcValue = low_byte | high_byte
                return "%04X" % crcValue
    
            except:
                print("calculate fail")
      
    
        def init_crc16kermit(self):
            '''The algorithm use tables with precalculated values'''
            for i in range(0, 256):
    
                crc = c_ushort(i).value
                for j in range(0, 8):
                    if (crc & 0x0001):
                        crc = c_ushort(crc >> 1).value ^ self.crc16Kermit_constant
                    else:
                        crc = c_ushort(crc >> 1).value
                self.crc16kermit_tab.append(hex(crc))

      

  • 相关阅读:
    Java基础--阻塞队列ArrayBlockingQueue
    Java基础--反射Reflection
    Java基础--对象克隆
    Java基础--HashCode
    Java基础--序列化Serializable
    OpenCV 绘制图像直方图
    PHP isset, array_key_exists配合使用, 并解决效率问题
    安装XDEBUG步骤及问题
    设计模式例子
    适配器模式例子
  • 原文地址:https://www.cnblogs.com/countryboy666/p/14418030.html
Copyright © 2011-2022 走看看