int protocol_get_buffer(char *dst, int max_len) { uint16_t crc16; uint16_t packet_crc16; int cpy_len = protocol_buffer_p; if (cpy_len>max_len) cpy_len = max_len; if (!cpy_len) return 0; /*crc takes 2 bytes*/ if (cpy_len<2) return ERR_BAD_LEN; crc16 = crc16_calc (protocol_buffer,cpy_len-2 ); packet_crc16 = protocol_buffer[cpy_len-2]; packet_crc16 = packet_crc16<<8; packet_crc16 |= protocol_buffer[cpy_len-1]; /* 0xBEEF is used for DEBUG CRC*/ if (packet_crc16!=0xBEEF && (packet_crc16!=crc16)) { protocol_buffer_clr(); return ERR_BAD_CRC; } memcpy(dst,protocol_buffer,cpy_len-2); protocol_buffer_clr(); return cpy_len-2; }
// <0 for failure, 1 for file done, 0 for OK to send _xmodem_debug int _assemble_packet( xbee_xmodem_state_t *xbxm, uint16_t block_size) { int err; uint8_t packet_num; uint16_t checksum; int ch; uint16_t i; char FAR *p; // Assemble a packet to send -- 3-byte header; 64, 128 or 1K xmodem // block from source file; and then 1-byte checksum or 2-byte CRC. xbxm->tries = 3; xbxm->buffer[0] = (xbxm->flags & XBEE_XMODEM_FLAG_1K) ? XMODEM_STX : XMODEM_SOH; packet_num = (uint8_t) xbxm->packet_num; xbxm->buffer[1] = packet_num; xbxm->buffer[2] = ~packet_num; err = xbxm->file.read( xbxm->file.context, &xbxm->buffer[3], block_size); if (err == -ENODATA || err == 0) { #ifdef XBEE_XMODEM_VERBOSE printf( "%s: reached end of file\n", __FUNCTION__); #endif xbxm->state = XBEE_XMODEM_STATE_EOF; return 1; } else if (err < 0) { #ifdef XBEE_XMODEM_VERBOSE printf( "%s: error %d reading file\n", __FUNCTION__, err); #endif return err; } else if (err < block_size) { // if necessary, we could wrap this all up into a while loop that // uses multiple reads, if necessary, to fill xbxm->buffer. if (xbxm->file.read( xbxm->file.context, &ch, 1) == 1) { #ifdef XBEE_XMODEM_VERBOSE printf( "%s: short read of %d bytes\n", __FUNCTION__, err); #endif return -EIO; } // short read, but it's the last block from the file -- set // remaining bytes to 0xFF _f_memset( &xbxm->buffer[3 + err], 0xFF, block_size - err); } if (xbxm->flags & XBEE_XMODEM_FLAG_CRC) { checksum = crc16_calc( &xbxm->buffer[3], block_size, 0); // append 16-bit CRC, MSB-first xbxm->buffer[3 + block_size] = checksum >> 8; xbxm->buffer[4 + block_size] = checksum & 0x00FF; }
void protocol_send_buffer(unsigned char *src, int len) { uint16_t crc16; crc16 = crc16_calc(src,len); uart1_putchar(STX); while(len--) protocol_send_char(*src++); protocol_send_char(crc16>>8); protocol_send_char(crc16&0xff); uart1_putchar(ETX); }
uint16_t crc16_ccitt(uint8_t *message, int nBytes) { return crc16_calc(message, nBytes, POLYNOMIAL_CRC15_CCIT); }
uint16_t crc16_ansi(uint8_t *message, int nBytes) { return crc16_calc(message, nBytes, POLYNOMIAL_CRC15_ANSI); }