Exemplo n.º 1
0
int main(int argc, char **argv) {
	fprintf(stderr, "util:: test\n");

	uint8_t msg[] = {0x08, 0x0a, 0xe8, 0x80};

	fprintf(stderr, "util::crc8(): odd parity:  %02X\n", crc8(msg, 3, 0x80));
	fprintf(stderr, "util::crc8(): even parity: %02X\n", crc8(msg, 4, 0x80));

	return 0;
}
uint8_t receiveMedtronicMessage( uint8_t *message, uint16_t *length ) {
	uint16_t i = 0;
	uint8_t calcCRC = 0;
	uint16_t calcCRC16 = 0;

	RFST = RFST_SIDLE;
	RFST = RFST_SRX;

	PKTLEN = 0xFF;
	lastData = 0xFF;
	for( i = 0; i < 500 && lastData != 0x00; i++ ) {
		while( !RFTXRXIF ) {
			// TODO Add generic rx/tx uart code
			//usbUartProcess( );
			//usbReceiveData( );
		}
		rfMessage[i] = RFD;
		lastData = rfMessage[i];
		TCON &= ~0x02;
	}
	rfLength = i - 1;
	RFST = RFST_SIDLE;

	decode4b6b( rfMessage, rfLength, message, length );
	calcCRC = crc8( message, (*length) - 1 );

	if( calcCRC == message[(*length) - 1] ) {
		return 0;
	}

	calcCRC16 = crc16( message, (*length) - 2 );
	if( ((uint8_t)(calcCRC16 & 0x00FFu) == message[(*length) - 1]) &&
		((uint8_t)((calcCRC16 >> 8) & 0x00FFu) == message[(*length) - 2]) ) {
		return 0;
	}

	calcCRC = crc8( message, (*length) - 2 );

	if( calcCRC == message[(*length) - 2] ) {
		(*length) = (*length) - 1;
		return 0;
	}

	calcCRC16 = crc16( message, (*length) - 3 );
	if( ((uint8_t)(calcCRC16 & 0x00FFu) == message[(*length) - 2]) &&
		((uint8_t)((calcCRC16 >> 8) & 0x00FFu) == message[(*length) - 3]) ) {
		(*length) = (*length) - 1;
		return 0;
	}

	crc16Init( );
	return 1;
}
Exemplo n.º 3
0
Arquivo: nvram.c Projeto: janfj/dd-wrt
/* Regenerate NVRAM. Should be locked. */
int _nvram_commit(struct nvram_header *header)
{
//      char *init, *config, *refresh, *ncdl;
	char *ptr, *end;
	int i;
	struct nvram_tuple *t;
	struct nvram_header tmp;
	uint8 crc;

	/* Regenerate header */
	header->magic = NVRAM_MAGIC;
	header->crc_ver_init = NVRAM_DEFAULT << NVRAM_OPT_SHIFT | NVRAM_VERSION << NVRAM_VER_SHIFT;

	/* Clear data area */
	ptr = (char *)header + sizeof(struct nvram_header);
	bzero(ptr, NVRAM_SPACE - sizeof(struct nvram_header));

	/* Leave space for a double NUL at the end */
	end = (char *)header + NVRAM_SPACE - 2;

	/* Write out all tuples */
	for (i = 0; i < ARRAYSIZE(nvram_hash); i++) {
		for (t = nvram_hash[i]; t; t = t->next) {
			if ((ptr + strlen(t->name) + 1 + strlen(t->value) + 1) > end)
				break;
			ptr += sprintf(ptr, "%s=%s", t->name, t->value) + 1;
		}
	}

	/* End with a double NUL */
	ptr += 2;

	/* Set new length */
	header->len = ROUNDUP(ptr - (char *)header, 4);

	/* Little-endian CRC8 over the last 11 bytes of the header */
	tmp.crc_ver_init = htol32(header->crc_ver_init);
	tmp.config_refresh = htol32(header->config_refresh);
	tmp.config_ncdl = htol32(header->config_ncdl);
	crc = crc8((char *)&tmp + 12, sizeof(struct nvram_header) - 12, CRC8_INIT_VALUE);

	/* Continue CRC8 over data bytes */
	crc = crc8((char *)&header[1], header->len - sizeof(struct nvram_header), crc);

	/* Set new CRC8 */
	header->crc_ver_init |= crc;

	/* Reinitialize hash table */
	return nvram_rehash(header);
}
//-------------------------------------------------------
bool t_tera_ranger_one_controller::check_echo(void)
{
    if (trigger_started) {
        if (Wire.available() == 3) {
            byte buf[3];
            buf[0] = Wire.read();
            buf[1] = Wire.read();
            buf[2] = Wire.read();

            int distance = (buf[0] << 8) + buf[1]; // Calculate distance in mm

            int crc = crc8(buf, 2);                // Calculate checksum

            if ((crc - buf[2]) == 0)
                last_read_distance = distance;
            else
                last_read_distance = -1;

            trigger_started = false;
            return true;
        }
        else
            return false;
    }
    else
        return false;
}
void
ccodelte_encode (int32_t numbits,
                 uint8_t add_crc,
                 uint8_t *inPtr,
                 uint8_t *outPtr,
                 uint16_t rnti)
{
  uint32_t             state;

  uint8_t              c, out, first_bit;
  int8_t shiftbit=0;
  uint16_t c16;
  uint16_t next_last_byte=0;
  uint32_t crc=0;

#ifdef DEBUG_CCODE
  uint32_t  dummy=0;
#endif //DEBUG_CCODE

  /* The input bit is shifted in position 8 of the state.
     Shiftbit will take values between 1 and 8 */
  state = 0;

  if (add_crc == 1) {
    crc = crc8(inPtr,numbits);
    first_bit      = 2;
    c = (uint8_t)(crc>>24);
  } else if (add_crc == 2) {
Exemplo n.º 6
0
void ErrorControl::re_transmit(int promptFactor)
{
	for( char f = send_head; f != send_tail; inc_frame_id(f) )
	{
		if( !are_all_acked(f) && need_re_send(f, promptFactor) )
		{
			// count no. of remote player to re_send
			int resendSuccess = 0;
			int resendFail = 0;
			char *ecMsg = send_queue[f].queue_buf;
			DWORD ecMsgLen = send_queue[f].length();

			for( char ecPlayerId = 1; ecPlayerId <= MAX_PLAYER; ++ecPlayerId )
			{
				// resend to specific remote player
				if( dp_id[ecPlayerId-1] && !ack_flag[f][ecPlayerId-1] )
				{
#if (defined(DEBUG) && DEBUG_LOG_LEVEL >= 2)
					debugStr = "ec.remote : time-out retransmit frame ";
					debugStr += f;
					debugStr += " to ";
					debugStr += ecPlayerId;
					DEBUG_LOG(debugStr);
#endif
					if(  mp_ptr->send(dp_id[ecPlayerId-1], ecMsg, ecMsgLen))
						resendSuccess++;
					else
						resendFail++;
				}

				if( resendSuccess > 0)
				{
					if( resendFail > 0)
					{
						// some resend fail, mark short resend time
						mark_send_time(f, SHORT_TIME_OUT);
					}
					else
					{
						// all resend success, mark longer resend time
						mark_send_time(f, TIME_OUT );
					}

					// mark the func_id of the message RE_SEND
					((EcMsgHeader *)ecMsg)->func_id = RE_SEND;

					// recalculate CRC
					*((CRC_TYPE *) (ecMsg + ecMsgLen - CRC_LEN )) = crc8((unsigned char *)ecMsg, ecMsgLen - CRC_LEN);

				}
				else if( resendFail > 0)
				{
					// all fail, mark a shorter time
					// mark send time, mark a shorter time
					mark_send_time(f, SHORT_TIME_OUT);
				}
			}
		}
	}
}
Exemplo n.º 7
0
bool Keys::isCRCOK()
{
    uint8_t crc = crc8( (uint8_t*)data, sizeof(KeysCRCed), CRC8INIT );
    Serial.println (data->crc8); // added by eqiglii
    Serial.println (crc);
    return (crc == data->crc8);
}
Exemplo n.º 8
0
/*==============================================
 *
 * 函数名称:static void occ_read_device_info_cmd(void)
 * 函数功能:
 * 入口参数:
 * 出口参数:
 * 修改日期:2015-12-08
 * 修改作者:zhuchengzhi
 * 
 * ============================================*/
static void occ_read_device_info_cmd(void)
{
	int uuid_fd = 0,cfg_fd = 0,size = 0;
	
	uuid_fd = open("/yaffs/uuid.bin",O_RDONLY);
	if(uuid_fd < 0){
		printf("open file error \n");
	}
	size = read(uuid_fd,board_info.uuid,16);
	close(uuid_fd);

	cfg_fd = open("/yaffs/dev_config.bin",O_RDONLY);
	if(cfg_fd < 0){
		printf("open file error \n");
	}
	size = read(cfg_fd,board_info.name,104);
	close(cfg_fd);


	memcpy(&uart485_data.uartx_txbuf[5],&board_info.uuid[0],16);
	memcpy(&uart485_data.uartx_txbuf[21],&board_info.name[1],103);

	uart485_data.uartx_txbuf[0] = 0x7E;
	uart485_data.uartx_txbuf[1] = 0x00;
	uart485_data.uartx_txbuf[2] = 0x7C;
	uart485_data.uartx_txbuf[3] = 0x01;
	uart485_data.uartx_txbuf[4] = board_info.name[0];
	uart485_data.uartx_txbuf[124] = crc8(uart485_data.uartx_txbuf,(uart485_data.uartx_txbuf[1] << 8) | uart485_data.uartx_txbuf[2]);
	uart485_data.uartx_txbuf[125] = 0x5A;
	send_data_tty(com1_fd,uart485_data.uartx_txbuf,(((uart485_data.uartx_txbuf[1] << 8) | uart485_data.uartx_txbuf[2]) + 2));
}
Exemplo n.º 9
0
/*==============================================
 *
 * 函数名称:static void occ_write_device_uuid_info(uint8_t *src)
 * 函数功能:
 * 入口参数:
 * 出口参数:
 * 修改日期:2015-12-04
 * 修改作者:zhuchengzhi
 * 
 * ============================================*/
static void occ_write_device_uuid_info(uint8_t *src)
{
	int uuid_fd = 0 ,size = 0,ret = 0;
	uint8_t  buffer[80];
	
	uuid_fd = open("/yaffs/uuid.bin",O_RDWR | O_CREAT);
	if(uuid_fd < 0){
		printf("open file error \n");
	}
	write(uuid_fd,&src[4],16);
	close(uuid_fd);

	uuid_fd = open("/yaffs/uuid.bin",O_RDONLY);
	if(uuid_fd < 0){
		printf("open file error \n");
	}
	size = read(uuid_fd,buffer,sizeof(buffer));
	close(uuid_fd);


	ret = memcmp(buffer,&src[4],16);
	if(!ret){
		uart485_data.uartx_txbuf[4]  = 0x00;
	}else{
		uart485_data.uartx_txbuf[4]  = 0x01;
	}
	uart485_data.uartx_txbuf[0]  = 0x7E;
	uart485_data.uartx_txbuf[1]  = 0x00;
	uart485_data.uartx_txbuf[2]  = 0x05;
	uart485_data.uartx_txbuf[3]  = 0x14;
	uart485_data.uartx_txbuf[5] = crc8(uart485_data.uartx_txbuf,(((uart485_data.uartx_txbuf[1] << 8) | uart485_data.uartx_txbuf[2])));
	uart485_data.uartx_txbuf[6]  = 0x5A;
	send_data_tty(com1_fd,uart485_data.uartx_txbuf,(((uart485_data.uartx_txbuf[1] << 8) | uart485_data.uartx_txbuf[2]) + 2));
}
Exemplo n.º 10
0
uint8_t ds18x20_read_temp(int16_t *t, int8_t *e) 
{
	uint8_t i;

	if(ow_command(COMMAND_CONVERT_T,NULL) == RES_FAULT) return RES_FAULT;

	//ow_strong_pullup_line();
	_delay_ms(200); //
	//ow_normal_line();

	if(ow_command(COMMAND_READ_SP,NULL) == RES_FAULT) return RES_FAULT;

	for (i=0; i<9; i++)	
		ds18x20_sp[i] = ow_byte_read();

	if(crc8(ds18x20_sp,9) == CRC_OK)
	{
		*t = ((ds18x20_sp[1] << 8) | (ds18x20_sp[0])) / 16;
		*e = ((ds18x20_sp[0] & M00001111) * 10) / 16;
		return RES_OK;
	}
	else
	{
		//*t = 127;
		//*e = 0;
		return RES_FAULT;
	}
}
Exemplo n.º 11
0
int to_alpus_dec(const struct tag *tag, char *output)
{
	uint8_t cust_id = mirror_nibbles(tag->cust_id);
	uint32_t data = mirror_nibbles(tag->data);
	uint64_t code = ((uint64_t)cust_id << 8 * sizeof(data)) | data;

	// Collect ID from data by bytes and conv them to DEC
	uint8_t *code_bytes = (uint8_t*)&code;
	char data_str[20 + 1] = "";
	for (int i = 4; i >= 0; i--)
	{
		char byte[4 + 1];
		snprintf(byte, 4 + 1, "%i:", code_bytes[i]);
		strncat(data_str, byte, 4 + 1);
	}

	// Compute parity nibble and CRC byte
	uint8_t parity = comp_parity(code);
	uint8_t crc = crc8(code, parity);

	// Print result
	snprintf(output, OUTPUT_MAX_LEN, "255:%i:%s%i", 0xF0 + parity, data_str, crc);

	return 0;
}
Exemplo n.º 12
0
void sendTagCellShield(char *mem, const char* tag, const char* data)
{
    long int tsize = strlen(tag);
    long int dsize = strlen(data);
    unsigned char checksum = crc8(tag, 0);
    checksum = crc8(data, checksum);
    //Get hex of checksum
    char hex1 = getHexOfNibble(checksum >> 4);
    char hex2 = getHexOfNibble(checksum);
    memcpy(mem, tag, strlen(tag));
    mem[tsize] = '^';
    memcpy(mem + tsize + 1, data, dsize);
    mem[tsize + 1 + dsize] = ':';
    mem[tsize + 2 + dsize] = hex1;
    mem[tsize + 3 + dsize] = hex2;
}
Exemplo n.º 13
0
/*
 * Read in and validate sprom.
 * Return 0 on success, nonzero on error.
 */
static int
sprom_read_pci(uint16 *sprom, uint byteoff, uint16 *buf, uint nbytes, bool check_crc)
{
	int off, nw;
	uint8 chk8;
	int i;

	off = byteoff / 2;
	nw = ROUNDUP(nbytes, 2) / 2;

	/* read the sprom */
	for (i = 0; i < nw; i++)
		buf[i] = R_REG(&sprom[off + i]);

	if (check_crc) {
		/* fixup the endianness so crc8 will pass */
		htol16_buf(buf, nw * 2);
		if ((chk8 = crc8((uchar*)buf, nbytes, CRC8_INIT_VALUE)) != CRC8_GOOD_VALUE)
			return (1);
		/* now correct the endianness of the byte array */
		ltoh16_buf(buf, nw * 2);
	}

	return (0);
}
Exemplo n.º 14
0
ICACHE_FLASH_ATTR
static void ds_read_temp(uint8_t *addr) {
	uint8_t data[12];

	ds_reset();
	select(addr);
	write( DS1820_READ_SCRATCHPAD, 0);

	uint8_t i;
	for (i = 0; i < 9; i++) {
		data[i] = read();
	}

	if(data[8] != crc8(data, 8)) {
		os_printf("ERROR - DS18B20 - CRC mismatch\n");
        mqttPublishError(&mqttClient, "CRC mismatch");
//		return;
	}

// float arithmetic isn't really necessary, tVal and tFract are in 1/10 �C
	uint16_t tVal, tFract;
	char tSign;

	tVal = (data[1] << 8) | data[0];
	if (tVal & 0x8000) {
		tVal = (tVal ^ 0xffff) + 1;				// 2's complement
		tSign = '-';
	} else
		tSign = ' ';

// datasize differs between DS18S20 and DS18B20 - 9bit vs 12bit
	if (addr[0] == DS18S20) {
		tFract = (tVal & 0x01) ? 50 : 0;		// 1bit Fract for DS18S20
		tVal >>= 1;
	} else {
Exemplo n.º 15
0
uint8_t *
extract_master_key(const char *s, int len)
{
    uint8_t *mkey = NULL; /** Master key. */
    int res;
    uint8_t crc;

    mkey = malloc(33);
    if (mkey == NULL)
        return NULL;

    res = pem64_decode_bytes(s, len, mkey);
    if (res == 33) {
        /* 33 bytes in pem - last byte should be crc8 checksum */
        crc = crc8(mkey, 32);
        if (crc != mkey[32]) {
            fprintf(stderr,
                    "The provided master key's check digit is incorrect.\n"
		    "Please check for typing errors and character substitution.\n");
            free(mkey);
            return NULL;
        }
    } else if (res != 32) {
        fprintf(stderr,
                "The key given did not decode to the correct length. (%d/32)\n",
                res);
        free(mkey);
        return NULL;
    }
    return mkey;
}
Exemplo n.º 16
0
void DS1820::setScratchpad(QByteArray data)
{
    scratchpad = data;
    scratchpad[SCRATCHPAD_CRC] = crc8((uint8_t *)scratchpad.data(), SCRATCHPAD_COUNT - 1);

    emit scratchpadChanged(scratchpad);
}
Exemplo n.º 17
0
void ParsePacket()
{
  if (crc8(XBusBuffer, nXBusIndex-1) == XBusBuffer[nXBusIndex-1])
  {
	  if (XBusBuffer[0] == 0xA4)
	  {
		  ExtractChannels();
	  }
          if (XBusBuffer[0] == 0xD1)
          {
            ExtractDMX();
          }
	  if (XBusBuffer[0] == 0x20)
	  {
		  PerformCommand(XBusBuffer);
	  }
	  if (XBusBuffer[0] == 0x21)
	  {
		  PerformStatus(XBusBuffer);
	  }
  }
  memset(XBusBuffer, 0, sizeof(XBusBuffer));
  nXBusIndex = 0;
  nNewPacket = 0;
}
Exemplo n.º 18
0
static void build_data_packet_1way()
{
    packet[0] = 0x0e;
    packet[1] = fixed_id & 0xff;
    packet[2] = fixed_id >> 8;
    packet[3] = seed & 0xff;
    packet[4] = seed >> 8;
    if (state == FRSKY_DATA1 || state == FRSKY_DATA3)
        packet[5] = 0x0f;
    else if(state == FRSKY_DATA2 || state == FRSKY_DATA4)
        packet[5] = 0xf0;
    else
        packet[5] = 0x00;
    int idx = 0; //= (state == FRSKY_DATA1) ? 4 : 0;
    for(int i = 0; i < 4; i++) {
        if(idx + i >= Model.num_channels) {
            packet[2*i + 6] = 0xc8;
            packet[2*i + 7] = 0x08;
        } else {
            s32 value = (s32)Channels[i + idx + 6] * 0x600 / CHAN_MAX_VALUE + 0x8c8;
            packet[2*i + 6] = value & 0xff;
            packet[2*i + 7] = value >> 8;
        }
    }
    packet[14] = crc8(0xa6, packet, 14);
//for(int i = 0; i < 15; i++) printf("%02x ", packet[i]); printf("\n");
}
//------------------------------------------
// Function to initialize DS18X20 sensors
void DS18B20Bus::SetupTempSensors() {

  byte i, j;
  byte addr[8];
  byte data[9];
  boolean scratchPadReaded;

  //while we find some devices
  while (search(addr)) {

    //if ROM received is incorrect or not a DS1822 or DS18B20 THEN continue to next device
    if ((crc8(addr, 7) != addr[7]) || (addr[0] != 0x22 && addr[0] != 0x28)) continue;

    scratchPadReaded = ReadScratchPad(addr, data);
    //if scratchPad read failed then continue to next 1-Wire device
    if (!scratchPadReaded) continue;

    //if config is not correct
    if (data[2] != 0x50 || data[3] != 0x00 || data[4] != 0x5F) {

      //write ScratchPad with Th=80°C, Tl=0°C, Config 11bit resolution
      WriteScratchPad(addr, 0x50, 0x00, 0x5F);

      scratchPadReaded = ReadScratchPad(addr, data);
      //if scratchPad read failed then continue to next 1-Wire device
      if (!scratchPadReaded) continue;

      //so we finally can copy scratchpad to memory
      CopyScratchPad(addr);
    }
  }
}
//------------------------------------------
// List DS18X20 sensor ROMCode and return it in JSON list
String DS18B20Bus::GetRomCodeListJSON() {

  bool first = true;
  uint8_t romCode[8];

  //prepare JSON structure
  String grclJSON(F("{\"TemperatureSensorList\": [\r\n"));

  reset_search();

  while (search(romCode)) {

    //if ROM received is incorrect or not a Temperature sensor THEN continue to next device
    if ((crc8(romCode, 7) != romCode[7]) || (romCode[0] != 0x10 && romCode[0] != 0x22 && romCode[0] != 0x28)) continue;

    //increase grclJSON size to limit heap fragment
    grclJSON.reserve(grclJSON.length() + 22);

    //populate JSON answer with romCode found
    if (!first) grclJSON += F(",\r\n");
    else first = false;
    grclJSON += '"';
    for (byte i = 0; i < 8; i++) {
      if (romCode[i] < 16)grclJSON += '0';
      grclJSON += String(romCode[i], HEX);
    }
    grclJSON += '"';
  }
  //Finalize JSON structure
  grclJSON += F("\r\n]}");

  return grclJSON;
}
Exemplo n.º 21
0
int from_alpus(const char *input, struct tag *tag)
{
	if (strlen(input) != 18)
		return 1;

	for (unsigned i = 0; i < strlen(input); i++)
	{
		switch (i)
		{
		case 0:
		case 1:
		case 3:
			if (input[i] != 'F')
				return 2;
			break;
		case 2:
			if (input[i] != '-')
				return 2;
			break;
		case 15:
			if (input[i] != '*')
				return 2;
			break;
		default:
			if (!isxdigit(input[i]))
				return 2;
			break;
		}
	}

	// Cut prefix, parity and crc
	char *code_str = substring(input, 5, 10);
	uint64_t code = strtoll(code_str, NULL, 16);

	// Parse data
	tag->has_cust_id = true;

	uint8_t cust_id = extract_bytes(code_str, 0, 2);
	tag->cust_id = mirror_nibbles(cust_id);

	uint32_t data = extract_bytes(code_str, 2, 8);
	tag->data = mirror_nibbles(data);

	free(code_str);

	// Check parity
	uint8_t parity = comp_parity(code);
	uint8_t input_parity = extract_bytes(input, 4, 1);
	if (parity != input_parity)
		return 3;

	// Check CRC
	uint8_t crc = crc8(code, parity);
	uint8_t input_crc = extract_bytes(input, 16, 2);
	if (crc != input_crc)
		return 4;

	return 0;
}
Exemplo n.º 22
0
/* Incremental CRC8 over count bytes in the array pointed to by p */
static u8 i2c_smbus_pec(u8 crc, u8 *p, size_t count)
{
	int i;

	for (i = 0; i < count; i++)
		crc = crc8((crc ^ p[i]) << 8);
	return crc;
}
Exemplo n.º 23
0
Arquivo: am.c Projeto: flyhorsegit/am
frame *encapsulate(char * data, size_t len) {
    frame *frm = calloc(sizeof(char), sizeof(frame));
    frm->start[0] = 0xBE;
    frm->start[1] = 0xEF;
    memcpy(frm->data, data, (len < (FRAME_SIZE - 3)) ? len : (FRAME_SIZE - 3));
    frm->crc = crc8(frm->data, FRAME_SIZE - 3);
    return frm;
}
Exemplo n.º 24
0
void send(Manchester* man, uint8_t to, uint8_t* data, uint8_t length){
  uint8_t buffer[BUFFER_SIZE];
  buffer[0] = to;
  buffer[1] = man->addr;
  buffer[3] = length;
  memcpy( buffer+4, data, length );
  buffer[length+4] = crc8(data, length);
  transmitArray(man, length + 5, buffer);
}
Exemplo n.º 25
0
static bool checkPacket(Packet_t* packet)
{
    if (crc8(packet, packet->header.packetLen) == 0){
        return true;
    }
    else{
        return true;
    }
}
Exemplo n.º 26
0
Arquivo: am.c Projeto: flyhorsegit/am
int chk_frm(frame *frm) {
    if (frm->start[0] != (char) 0xBE)
        return 0;
    if (frm->start[1] != (char) 0xEF)
        return 0;
    if (crc8(frm->data, FRAME_SIZE - 3) != frm->crc)
        return 0;
    return 1;
}
Exemplo n.º 27
0
/**
 * @fn                  :tc_libc_misc_crc8
 * @brief               :Return a 8-bit CRC of the contents of the 'src_arr' buffer, length 'len' using a
 *                       CRC with the polynomial x^8+x^6+x^3+x^2+1
 * @scenario            :Return a 8-bit CRC of the contents of the 'src_arr' buffer, length 'len' using a
 *                       CRC with the polynomial x^8+x^6+x^3+x^2+1
 * @API's covered       :crc8
 * @Preconditions       :None
 * @Postconditions      :None
 * @Return              :void
 */
static void tc_libc_misc_crc8(void)
{
	uint8_t ret_chk;
	uint8_t src_arr[1] = { VAL_100 };
	size_t length = 1;

	/* Return value should be 213 as calculated by crc8 */

	ret_chk = crc8(src_arr, length);
	TC_ASSERT_EQ("crc8", ret_chk, VAL_213);

	/* Return value should be 71 as calculated by crc8 */

	src_arr[0] = VAL_50;
	ret_chk = crc8(src_arr, length);
	TC_ASSERT_EQ("crc8", ret_chk, VAL_71);

	TC_SUCCESS_RESULT();
}
Exemplo n.º 28
0
__inline uint8_t CRCCheck (void)
{
  if(CommandToSend.ReadStartByte != OW_NO_READ)
    if(crc8(CommandToSend.DataForRead,CommandToSend.NumByteForRead))
    {
      printf("CRC Wrong!\n\r");
      return OW_ERROR;
    }
   return OW_OK;
}
Exemplo n.º 29
0
int
TRONE::collect()
{
	int ret = -EIO;

	/* read from the sensor */
	uint8_t val[3] = {0, 0, 0};

	perf_begin(_sample_perf);

	ret = transfer(nullptr, 0, &val[0], 3);

	if (ret < 0) {
		DEVICE_LOG("error reading from sensor: %d", ret);
		perf_count(_comms_errors);
		perf_end(_sample_perf);
		return ret;
	}

	uint16_t distance_mm = (val[0] << 8) | val[1];
	float distance_m = float(distance_mm) *  1e-3f;
	struct distance_sensor_s report;

	report.timestamp = hrt_absolute_time();
	/* there is no enum item for a combined LASER and ULTRASOUND which it should be */
	report.type = distance_sensor_s::MAV_DISTANCE_SENSOR_LASER;
	report.orientation = 8;
	report.current_distance = distance_m;
	report.min_distance = get_minimum_distance();
	report.max_distance = get_maximum_distance();
	report.covariance = 0.0f;
	/* TODO: set proper ID */
	report.id = 0;

	// This validation check can be used later
	_valid = crc8(val, 2) == val[2] && (float)report.current_distance > report.min_distance
		 && (float)report.current_distance < report.max_distance ? 1 : 0;

	/* publish it, if we are the primary */
	if (_distance_sensor_topic != nullptr) {
		orb_publish(ORB_ID(distance_sensor), _distance_sensor_topic, &report);
	}

	if (_reports->force(&report)) {
		perf_count(_buffer_overflows);
	}

	/* notify anyone waiting for data */
	poll_notify(POLLIN);

	ret = OK;

	perf_end(_sample_perf);
	return ret;
}
Exemplo n.º 30
0
void up_load_alarm_to_mobile(void)
{
	unsigned char i = 0;	 // 48行
	unsigned char j = 0;	 // 14列
	unsigned char frame = 0; // 框号
	unsigned char tray = 0;  // 盘号
	unsigned char port = 0;  // 端口号
	unsigned char vstat = 0; // 状态


	for(i=0;i<48;i++){
		for(j=0;j<14;j++){
			if(alarm_buf[i][j] != 0){
				frame = ((i/6)+1);
				tray  = ((i%6)+1);
				port  = (j+1);
				vstat = alarm_buf[i][j];

				up_alarm[22 +(4*alarm_num)] = frame;
				if(port == 13){
					up_alarm[23 +(4*alarm_num)] = tray;
					up_alarm[24 +(4*alarm_num)] = 0x00;
				}else if(port == 14){
					up_alarm[23 +(4*alarm_num)] = 0x00;
					up_alarm[24 +(4*alarm_num)] = 0x00;
				}else{
					up_alarm[23 +(4*alarm_num)] = tray;
					up_alarm[24 +(4*alarm_num)] = port;
				}
				up_alarm[25 +(4*alarm_num)] = vstat;
				alarm_num += 1;
				up_alarm[4] = alarm_num;
				//return 1;//至少有一条
			}
		}
	}

	if(alarm_num == 0){
	
	}else{
		printf("alarm_num = %d \n",alarm_num);
		up_alarm[1] = (22 + (4*alarm_num))/256;
		up_alarm[2] = (22 + (4*alarm_num))%256;
		up_alarm[22 + (4*alarm_num)] = crc8(up_alarm,((up_alarm[1]<<8)|up_alarm[2]));
		up_alarm[23 + (4*alarm_num)] = 0x5a;
			
		if((order_val.resource_start == 0) && (other_thing_now == 0)){
			send_data_tty(com1_fd,up_alarm,(((up_alarm[1] << 8) | up_alarm[2]) + 2));
		}
	//	sleep(1);
		clean_alarm_buf();
		alarm_num = 0;
	}
//	return 0;//没有一个告警
}