CRC16 检验
        - 启用``use_byte`` 则返回 bytes 类型.

    :param cmd: 无crc检验的指令
    :type cmd:
    :param use_byte: 是否返回byte类型
    :type use_byte:
    :return: 返回crc值
    :rtype:
966229
def crc16(cmd, use_byte=False):
    
    crc = 0xFFFF

    # crc16 计算方法, 需要使用 byte
    if hasattr(cmd, 'encode'):
        cmd = bytes.fromhex(cmd)

    for _ in cmd:
        c = _ & 0x00FF
        crc ^= c
        for i in range(8):
            if crc & 0x0001 > 0:
                crc >>= 1
                crc ^= 0xA001
            else:
                crc >>= 1

    # modbus crc16计算时,需要高/低位倒置
    t = [(crc & 0x00FF), (crc >> 8 & 0xFF)]
    crc = '%02X%02X' % (t[0], t[1])
    if use_byte:
        crc = bytes.fromhex(crc)
    return crc
296016
function serializeCommand(self, command, callback) {
  const originalCommandBuffer = command.toBin();

  // Check whether we and the server have agreed to use a compressor
  const shouldCompress = !!self.options.agreedCompressor;
  if (!shouldCompress || !canCompress(command)) {
    return callback(null, originalCommandBuffer);
  }

  // Transform originalCommandBuffer into OP_COMPRESSED
  const concatenatedOriginalCommandBuffer = Buffer.concat(originalCommandBuffer);
  const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE);

  // Extract information needed for OP_COMPRESSED from the uncompressed message
  const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12);

  // Compress the message body
  compress(self, messageToBeCompressed, function(err, compressedMessage) {
    if (err) return callback(err, null);

    // Create the msgHeader of OP_COMPRESSED
    const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE);
    msgHeader.writeInt32LE(
      MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length,
      0
    ); // messageLength
    msgHeader.writeInt32LE(command.requestId, 4); // requestID
    msgHeader.writeInt32LE(0, 8); // responseTo (zero)
    msgHeader.writeInt32LE(opcodes.OP_COMPRESSED, 12); // opCode

    // Create the compression details of OP_COMPRESSED
    const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE);
    compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode
    compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader
    compressionDetails.writeUInt8(compressorIDs[self.options.agreedCompressor], 8); // compressorID

    return callback(null, [msgHeader, compressionDetails, compressedMessage]);
  });
}
798626
def _calculateCrcString(inputstring):
    
    _checkString(inputstring, description='input CRC string')
 
    # Preload a 16-bit register with ones
    register = 0xFFFF

    for char in inputstring:
        register = (register >> 8) ^ _CRC16TABLE[(register ^ ord(char)) & 0xFF]
 
    return _numToTwoByteString(register, LsbFirst=True)
556647
def compute_crc(data):
    """"""
    crc16 = crcmod.predefined.Crc('modbus')
    crc16.update(data)
    return int(crc16.hexdigest(), 16)
1169321
def recv(self, stream, crc_mode=1, retry=16, timeout=60, delay=1, quiet=0):
        '''
        
        '''

        # initiate protocol
        error_count = 0
        char = 0
        cancel = 0
        while True:
            # first try CRC mode, if this fails,
            # fall back to checksum mode
            if error_count >= retry:
                self.abort(timeout=timeout)
                return None
            elif crc_mode and error_count < (retry / 2):
                if not self.putc(CRC):
                    time.sleep(delay)
                    error_count += 1
            else:
                crc_mode = 0
                if not self.putc(NAK):
                    time.sleep(delay)
                    error_count += 1

            char = self.getc(1, timeout)
            if not char:
                error_count += 1
                continue
            elif char == SOH:
                #crc_mode = 0
                break
            elif char == STX:
                break
            elif char == CAN:
                if cancel:
                    return None
                else:
                    cancel = 1
            else:
                error_count += 1

        # read data
        error_count = 0
        income_size = 0
        packet_size = 128
        sequence = 1
        cancel = 0
        while True:
            while True:
                if char == SOH:
                    packet_size = 128
                    break
                elif char == STX:
                    packet_size = 1024
                    break
                elif char == EOT:
                    # We received an EOT, so send an ACK and return the received
                    # data length
                    self.putc(ACK)
                    return income_size
                elif char == CAN:
                    # cancel at two consecutive cancels
                    if cancel:
                        return None
                    else:
                        cancel = 1
                else:
                    if not quiet:
                        print >> sys.stderr, \
                            'recv ERROR expected SOH/EOT, got', ord(char)
                    error_count += 1
                    if error_count >= retry:
                        self.abort()
                        return None
            # read sequence
            error_count = 0
            cancel = 0
            seq1 = ord(self.getc(1))
            seq2 = 0xff - ord(self.getc(1))
            if seq1 == sequence and seq2 == sequence:
                # sequence is ok, read packet
                # packet_size + checksum
                data = self.getc(packet_size + 1 + crc_mode, timeout)
                if crc_mode:
                    csum = (ord(data[-2]) << 8) + ord(data[-1])
                    data = data[:-2]
                    log.debug('CRC (%04x <> %04x)' % \
                        (csum, self.calc_crc(data)))
                    valid = csum == self.calc_crc(data)
                else:
                    csum = data[-1]
                    data = data[:-1]
                    log.debug('checksum (checksum(%02x <> %02x)' % \
                        (ord(csum), self.calc_checksum(data)))
                    valid = ord(csum) == self.calc_checksum(data)

                # valid data, append chunk
                if valid:
                    income_size += len(data)
                    stream.write(data)
                    self.putc(ACK)
                    sequence = (sequence + 1) % 0x100
                    char = self.getc(1, timeout)
                    continue
            else:
                # consume data
                self.getc(packet_size + 1 + crc_mode)
                self.debug('expecting sequence %d, got %d/%d' % \
                    (sequence, seq1, seq2))

            # something went wrong, request retransmission
            self.putc(NAK)
245210
def get_bytes(self, bridge):
        
        if not bridge.is_ready:
            raise Exception('The bridge has to be ready to construct command.')

        wb1 = bridge.wb1
        wb2 = bridge.wb2
        sn = bridge.sn

        preamble = [0x80, 0x00, 0x00, 0x00, 0x11, wb1, wb2, 0x00, sn, 0x00]
        cmd = [0x31, self.PASSWORD_BYTE1, self.PASSWORD_BYTE2,
               self._remote_style, self._cmd_1,
               self._cmd_2, self._cmd_2, self._cmd_2, self._cmd_2]
        zone_selector = [self._group_number, 0x00]
        checksum = sum(cmd + zone_selector) & 0xFF

        return bytearray(preamble + cmd + zone_selector + [checksum])
277529
def write_byte(self, cmd, value):
        
        self.bus.write_byte_data(self.address, cmd, value)
        self.log.debug(
            "write_byte: Wrote 0x%02X to command register 0x%02X" % (
                value, cmd
            )
        )
438873
def calc_crc(self, data, crc=0):
        '''
        

        '''
        for char in data:
            crc = (crc << 8) ^ self.crctable[((crc >> 8) ^ ord(char)) & 0xff]
        return crc & 0xffff
304028
def _CSI(self, cmd):
        
        sys.stdout.write('\x1b[')
        sys.stdout.write(cmd)
692903
def _cmd(self, endpoint, cmd):
        
        cmdbuf = "%s\n" % (cmd)
        # some cmds have large outputs and ZK closes the connection as soon as it
        # finishes writing. so read in huge chunks.
        recvsize = 1 << 20
        replies = []
        host, port = endpoint

        ips = get_ips(host, port)

        if len(ips) == 0:
            raise self.CmdFailed("Failed to resolve: %s" % (host))

        for ip in ips:
            try:
                with connected_socket((ip, port)) as sock:
                    sock.send(cmdbuf.encode())
                    while True:
                        buf = sock.recv(recvsize).decode("utf-8")
                        if buf == "":
                            break
                        replies.append(buf)
            except socket.error as ex:
                # if there's only 1 record, give up.
                # if there's more, keep trying.
                if len(ips) == 1:
                    raise self.CmdFailed("Error(%s): %s" % (ip, ex))

        return "".join(replies)
1042600
def crc16jit(buf, offset, crc, length):
  """"""
  for index in range(offset, offset + length):
    data = buf[index]
    lookup = crc16_tab[((nb.u2(crc) >> 8) & nb.u2(0xFF)) ^ (data & nb.u2(0xFF))]
    crc = ((nb.u2(crc) << nb.u2(8)) & nb.u2(0xFFFF)) ^ lookup
    crc = nb.u2(crc) & nb.u2(0xFFFF)
  return crc
641448
def crc16_nojit(s, crc=0):
  """"""
  for ch in bytearray(s):  # bytearray's elements are integers in both python 2 and 3
    crc = ((crc << 8) & 0xFFFF) ^ _crc16_tab[((crc >> 8) & 0xFF) ^ (ch & 0xFF)]
    crc &= 0xFFFF
  return crc
299525
function lockCrc(inputStr){

		res = 0xff;
		inputHex = new Buffer(inputStr,'hex');

		//start from the second byte 
		for (i = 1; i<= inputHex.length; i++) {
			res = res ^ inputHex[i];
		}
		//add padding
		reshex = (res+0x100).toString(16).substr(-2);
//		console.log(reshex);

		return(inputStr+reshex);
}
851931
def write_block_data(self, cmd, block):
        
        self.bus.write_i2c_block_data(self.address, cmd, block)
        self.log.debug(
            "write_block_data: Wrote [%s] to command register 0x%02X" % (
                ', '.join(['0x%02X' % x for x in block]),
                cmd
            )
        )
1265819
def crc16(data):
    
    m_crc = 0xffff
    for this in data:
        m_crc ^= ord_byte(this)
        for _ in range(8):
            j = m_crc & 1
            m_crc >>= 1
            if j:
                m_crc ^= 0x8408
    return m_crc
382682
public static long calculateCRC32(byte[] buffer, int offset, int length)
	{
		if (!init_done)
		{
			initialize();
		}
		for (int i = offset; i < offset + length; i++)
		{
			long tmp1 = (crc >>> 8) & 0x00FFFFFFL;
			long tmp2 = values[(int) ((crc ^ Character.toUpperCase((char) buffer[i])) & 0xff)];
			crc = tmp1 ^ tmp2;
			// System.out.println("CRC:   "+crc);
		}
		return crc;
	}
1235534
def crc8(data):
        
        crc = 0

        for byte in data:
            crc ^= byte
            for _ in range(8):
                if crc & 0x01:
                    crc = (crc >> 1) ^ 0x8C
                else:
                    crc >>= 1
                crc &= 0xFF
        return crc