예제 #1
0
static int gpt_check_hdr_crc(const struct disk_info * const diskinfo, struct disk_gpt_header **_gh)
{
    struct disk_gpt_header *gh = *_gh;
    uint64_t lba_alt;
    uint32_t hold_crc32;

    hold_crc32 = gh->chksum;
    gh->chksum = 0;
    if (check_crc(hold_crc32, (const uint8_t *)gh, gh->hdr_size)) {
	error("WARNING: Primary GPT header checksum invalid.\n");
	/* retry with backup */
	lba_alt = gh->lba_alt;
	free(gh);
	if (!(gh = *_gh = disk_read_sectors(diskinfo, lba_alt, 1))) {
	    error("Couldn't read backup GPT header.\n");
	    return -1;
	}
	hold_crc32 = gh->chksum;
	gh->chksum = 0;
	if (check_crc(hold_crc32, (const uint8_t *)gh, gh->hdr_size)) {
	    error("Secondary GPT header checksum invalid.\n");
	    return -1;
	}
    }
    /* restore old checksum */
    gh->chksum = hold_crc32;

    return 0;
}
예제 #2
0
/* Detect a crc32 compensation attack on a packet */
int
detect_attack(u_char *buf, u_int32_t len)
{
	static u_int16_t *h = (u_int16_t *) NULL;
	static u_int32_t n = HASH_MINSIZE / HASH_ENTRYSIZE;
	u_int32_t i, j;
	u_int32_t l, same;
	u_char *c;
	u_char *d;

	if (len > (SSH_MAXBLOCKS * SSH_BLOCKSIZE) ||
	    len % SSH_BLOCKSIZE != 0) {
		fatal("detect_attack: bad length %d", len);
	}
	for (l = n; l < HASH_FACTOR(len / SSH_BLOCKSIZE); l = l << 2)
		;

	if (h == NULL) {
		debug("Installing crc compensation attack detector.");
		h = (u_int16_t *) xcalloc(l, HASH_ENTRYSIZE);
		n = l;
	} else {
		if (l > n) {
			h = (u_int16_t *)xrealloc(h, l, HASH_ENTRYSIZE);
			n = l;
		}
	}

	if (len <= HASH_MINBLOCKS) {
		for (c = buf; c < buf + len; c += SSH_BLOCKSIZE) {
			for (d = buf; d < c; d += SSH_BLOCKSIZE) {
				if (!CMP(c, d)) {
					if ((check_crc(c, buf, len)))
						return (DEATTACK_DETECTED);
					else
						break;
				}
			}
		}
		return (DEATTACK_OK);
	}
	memset(h, HASH_UNUSEDCHAR, n * HASH_ENTRYSIZE);

	for (c = buf, same = j = 0; c < (buf + len); c += SSH_BLOCKSIZE, j++) {
		for (i = HASH(c) & (n - 1); h[i] != HASH_UNUSED;
		    i = (i + 1) & (n - 1)) {
			if (!CMP(c, buf + h[i] * SSH_BLOCKSIZE)) {
				if (++same > MAX_IDENTICAL)
					return (DEATTACK_DOS_DETECTED);
				if (check_crc(c, buf, len))
					return (DEATTACK_DETECTED);
				else
					break;
			}
		}
		h[i] = j;
	}
	return (DEATTACK_OK);
}
예제 #3
0
/* Detect a crc32 compensation attack on a packet */
int
detect_attack(struct deattack_ctx *dctx, const u_char *buf, u_int32_t len)
{
	u_int32_t i, j, l, same;
	const u_char *c, *d;

	if (len > (SSH_MAXBLOCKS * SSH_BLOCKSIZE) ||
	    len % SSH_BLOCKSIZE != 0)
		return DEATTACK_ERROR;
	for (l = dctx->n; l < HASH_FACTOR(len / SSH_BLOCKSIZE); l = l << 2)
		;

	if (dctx->h == NULL) {
		if ((dctx->h = calloc(l, HASH_ENTRYSIZE)) == NULL)
			return DEATTACK_ERROR;
		dctx->n = l;
	} else {
		if (l > dctx->n) {
			if (reallocn((void **)&dctx->h, l, HASH_ENTRYSIZE) != 0) {
				free(dctx->h);
				dctx->h = NULL;
				return DEATTACK_ERROR;
			}
			dctx->n = l;
		}
	}

	if (len <= HASH_MINBLOCKS) {
		for (c = buf; c < buf + len; c += SSH_BLOCKSIZE) {
			for (d = buf; d < c; d += SSH_BLOCKSIZE) {
				if (!CMP(c, d)) {
					if ((check_crc(c, buf, len)))
						return DEATTACK_DETECTED;
					else
						break;
				}
			}
		}
		return DEATTACK_OK;
	}
	memset(dctx->h, HASH_UNUSEDCHAR, dctx->n * HASH_ENTRYSIZE);

	for (c = buf, same = j = 0; c < (buf + len); c += SSH_BLOCKSIZE, j++) {
		for (i = HASH(c) & (dctx->n - 1); dctx->h[i] != HASH_UNUSED;
		    i = (i + 1) & (dctx->n - 1)) {
			if (!CMP(c, buf + dctx->h[i] * SSH_BLOCKSIZE)) {
				if (++same > MAX_IDENTICAL)
					return DEATTACK_DOS_DETECTED;
				if (check_crc(c, buf, len))
					return DEATTACK_DETECTED;
				else
					break;
			}
		}
		dctx->h[i] = j;
	}
	return DEATTACK_OK;
}
예제 #4
0
Int32 sbr_crc_check(BIT_BUFFER * hBitBuf, UInt32 NrBits)
{
    Int32 crcResult = 1;
    BIT_BUFFER BitBufferCRC;
    UInt32 NrCrcBits;

    UInt32 crcCheckSum;

    Int32 i;
    CRC_BUFFER CrcBuf;
    UInt32 bValue;
    Int32 CrcStep;
    Int32 CrcNrBitsRest;

    crcCheckSum = buf_getbits(hBitBuf, SI_SBR_CRC_BITS);


    /*
     *    Copy Bit buffer State
     */

    BitBufferCRC.char_ptr       = hBitBuf->char_ptr;
    BitBufferCRC.buffer_word    = hBitBuf->buffer_word;
    BitBufferCRC.buffered_bits  = hBitBuf->buffered_bits;
    BitBufferCRC.nrBitsRead     = hBitBuf->nrBitsRead;
    BitBufferCRC.bufferLen      = hBitBuf->bufferLen;


    NrCrcBits = min(NrBits, BitBufferCRC.bufferLen - BitBufferCRC.nrBitsRead);


    CrcStep = NrCrcBits / MAXCRCSTEP;
    CrcNrBitsRest = (NrCrcBits - CrcStep * MAXCRCSTEP);

    CrcBuf.crcState = CRCSTART;
    CrcBuf.crcMask  = CRCMASK;
    CrcBuf.crcPoly  = CRCPOLY;

    for (i = 0; i < CrcStep; i++)
    {
        bValue = buf_getbits(&BitBufferCRC, MAXCRCSTEP);
        check_crc(&CrcBuf, bValue, MAXCRCSTEP);
    }

    bValue = buf_getbits(&BitBufferCRC, CrcNrBitsRest);
    check_crc(&CrcBuf, bValue, CrcNrBitsRest);

    if ((UInt32)(CrcBuf.crcState & CRCRANGE) != crcCheckSum)
    {
        crcResult = 0;
    }

    return (crcResult);
}
예제 #5
0
//format: ID+len+flag('c'=check crc, else ignore crc)
static void cmd_handle_collect()
{
  u32 len, crc = 0;
  s32 ret = -1;

  ret = flash_mapping_type_test();
  if(-1 == ret)
  {
    cmd_response(CMD_ERROR, P2P_CMD_COLLECT, CMD_COLLECT_DMH_ERR);
    return;
  }
  else if(-3 == ret)
  {
    cmd_response(CMD_ERROR, P2P_CMD_COLLECT, CMD_COLLECT_FALSH_READ_ERR);
    return;
  }

  if('C' == cmd_buff[2])
  {
    ret = check_crc();

    if(-1 == ret)
    {
      cmd_response(CMD_ERROR, P2P_CMD_COLLECT, CMD_COLLECT_DMH_ERR);
      return;
    }
    else if(-2 == ret)
    {
      cmd_response(CMD_ERROR, P2P_CMD_COLLECT, CMD_COLLECT_CRC_ERR);
      return;
    }
    else if(-3 == ret)
    {
      cmd_response(CMD_ERROR, P2P_CMD_COLLECT, CMD_COLLECT_FALSH_READ_ERR);
      return;
    }
  }

  ret = get_info(&slave_info);

  if(-1 == ret)
  {
    cmd_response(CMD_ERROR, P2P_CMD_COLLECT, CMD_COLLECT_DMH_ERR);
    return;
  }
  else if(-3 == ret)
  {
    cmd_response(CMD_ERROR, P2P_CMD_COLLECT, CMD_COLLECT_FALSH_READ_ERR);
    return;
  }

  cmd_response(CMD_OK, 0, 0);

  len = slave_info.bh_size * slave_info.block_num + fieldoffset(upg_slave_info, blocks);
  crc = crc_fast_calculate(CRC_MODE, CRC_INIT, (u8 *)&slave_info, len);

  send_data((u8 *)&len, 4);            //send length
  send_data((u8 *)&slave_info, len);   //send info
  send_data((u8 *)&crc, 4);            //send crc
}
예제 #6
0
static KSensorStatus read_value(uint8_t cmd, int * raw)
{
    uint8_t buffer[3];
    int bit0, bit1;
    memset(buffer, '\0', 3);
    if (raw == NULL)
    {
        return SENSOR_ERROR;
    }
    if (k_i2c_write(I2C_BUS, SENSOR_ADDR, &cmd, 1) != I2C_OK)
    {
        return SENSOR_WRITE_ERROR;
    }
    vTaskDelay(30);
    if (k_i2c_read(I2C_BUS, SENSOR_ADDR, buffer, 3) != I2C_OK)
    {
        return SENSOR_READ_ERROR;
    }

    bit0 = (int)buffer[0];
    bit1 = (int)buffer[1];
    *raw = (bit0 << 8) | bit1;

    if (check_crc(*raw, (int)buffer[2]) != 0)
    {
        return SENSOR_ERROR;
    }
    return SENSOR_OK;
}
예제 #7
0
unsigned int HTU21D::read_value(byte cmd)
{
	//Request a humidity reading
	Wire.beginTransmission(HTDU21D_ADDRESS);
	Wire.write(cmd); //Measure value (prefer no hold!)
	Wire.endTransmission();

	//Hang out while measurement is taken. datasheet says 50ms, practice may call for more
        byte num_read;
        byte counter;
        for (counter = 0, num_read = 0; counter < MAX_COUNTER && num_read != 3; counter++) {
	        delay(DELAY_INTERVAL);

                //Comes back in three bytes, data(MSB) / data(LSB) / Checksum
                num_read = Wire.requestFrom(HTDU21D_ADDRESS, 3);
        }

        if (counter == MAX_COUNTER) return 998; //Error out

	byte msb, lsb, checksum;
	msb = Wire.read();
	lsb = Wire.read();
	checksum = Wire.read();

	unsigned int raw_value = ((unsigned int) msb << 8) | (unsigned int) lsb;

	if(check_crc(raw_value, checksum) != 0) return(999); //Error out

    return raw_value & 0xFFFC; // Zero out the status bits
}
예제 #8
0
파일: i2c.c 프로젝트: Chong-Li/cse522
static int microread_i2c_read(struct microread_i2c_phy *phy,
			      struct sk_buff **skb)
{
	int r;
	u8 len;
	u8 tmp[MICROREAD_I2C_LLC_MAX_SIZE - 1];
	struct i2c_client *client = phy->i2c_dev;

	r = i2c_master_recv(client, &len, 1);
	if (r != 1) {
		nfc_err(&client->dev, "cannot read len byte\n");
		return -EREMOTEIO;
	}

	if ((len < MICROREAD_I2C_LLC_MIN_SIZE) ||
	    (len > MICROREAD_I2C_LLC_MAX_SIZE)) {
		nfc_err(&client->dev, "invalid len byte\n");
		r = -EBADMSG;
		goto flush;
	}

	*skb = alloc_skb(1 + len, GFP_KERNEL);
	if (*skb == NULL) {
		r = -ENOMEM;
		goto flush;
	}

	*skb_put(*skb, 1) = len;

	r = i2c_master_recv(client, skb_put(*skb, len), len);
	if (r != len) {
		kfree_skb(*skb);
		return -EREMOTEIO;
	}

	I2C_DUMP_SKB("cc frame read", *skb);

	r = check_crc(*skb);
	if (r != 0) {
		kfree_skb(*skb);
		r = -EBADMSG;
		goto flush;
	}

	skb_pull(*skb, 1);
	skb_trim(*skb, (*skb)->len - MICROREAD_I2C_FRAME_TAILROOM);

	usleep_range(3000, 6000);

	return 0;

flush:
	if (i2c_master_recv(client, tmp, sizeof(tmp)) < 0)
		r = -EREMOTEIO;

	usleep_range(3000, 6000);

	return r;
}
예제 #9
0
파일: env.c 프로젝트: qgp/armboot
/* 
 * try to read env character at offset #index
 * 
 * called before the environment is copied to ram
 * returns -1 on error, 0 if ok
 */
uchar *board_env_getaddr(bd_t * bd, int index)
{
    env_t *env = (env_t *)CFG_ENV_ADDR; 
   
    /* check environment crc */
    if (index < sizeof(env->data) && check_crc(bd))
      return &env->data[index];
   
    return 0;
}
예제 #10
0
//Calc temperature and return it to the user
//Returns 998 if I2C timed out
//Returns 999 if CRC is wrong
bool HTU21D::readTemperature(unsigned int *rawout, float *hrfout)
{
    //Request the temperature
    Wire.beginTransmission(HTDU21D_ADDRESS);
    Wire.write(TRIGGER_TEMP_MEASURE_NOHOLD);
    Wire.endTransmission();

    //Hang out while measurement is taken. 50mS max, page 4 of datasheet.
    delay(55);

    //Comes back in three bytes, data(MSB) / data(LSB) / Checksum
    Wire.requestFrom(HTDU21D_ADDRESS, 3);

    //Wait for data to become available
    int counter = 0;
    while(Wire.available() < 3)
    {
        counter++;
        delay(1);
        if(counter > 100) return false;                               //Error out
    }

    unsigned char msb, lsb, checksum;
    msb = Wire.read();
    lsb = Wire.read();
    checksum = Wire.read();

/* //Used for testing
    byte msb, lsb, checksum;
    msb = 0x68;
    lsb = 0x3A;
    checksum = 0x7C; */

    unsigned int rawTemperature = ((unsigned int) msb << 8) | (unsigned int) lsb;

    if (rawout != NULL) {
        *rawout = rawTemperature;
    }

    if(check_crc(rawTemperature, checksum) != 0) return false;   //Error out

    //sensorStatus = rawTemperature & 0x0003; //Grab only the right two bits
    rawTemperature &= 0xFFFC;                                   //Zero out the status bits but keep them in place

    //Given the raw temperature data, calculate the actual temperature
    float tempTemperature = rawTemperature / (float)65536;      //2^16 = 65536
    //From page 14
    float realTemperature = (float)(-46.85 + (175.72 * tempTemperature));

    if (hrfout != NULL) {
        *hrfout = realTemperature;
    }

    return true;
}
예제 #11
0
//Calc humidity and return it to the user
//Returns 998 if I2C timed out
//Returns 999 if CRC is wrong
bool HTU21D::readHumidity(unsigned int *rawout, float *hrfout)
{
    //Request a humidity reading
    Wire.beginTransmission(HTDU21D_ADDRESS);
    Wire.write(TRIGGER_HUMD_MEASURE_NOHOLD);                    //Measure humidity with no bus holding
    Wire.endTransmission();

    //Hang out while measurement is taken. 50mS max, page 4 of datasheet.
    delay(55);

    //Comes back in three bytes, data(MSB) / data(LSB) / Checksum
    Wire.requestFrom(HTDU21D_ADDRESS, 3);

    //Wait for data to become available
    int counter = 0;
    while(Wire.available() < 3)
    {
        counter++;
        delay(1);
        if(counter > 100) return false;                               //Error out
    }

    byte msb, lsb, checksum;
    msb = Wire.read();
    lsb = Wire.read();
    checksum = Wire.read();

/* //Used for testing
    byte msb, lsb, checksum;
    msb = 0x4E;
    lsb = 0x85;
    checksum = 0x6B;*/

    unsigned int rawHumidity = ((unsigned int) msb << 8) | (unsigned int) lsb;

    if (rawout != NULL) {
        *rawout = rawHumidity;
    }

    if(check_crc(rawHumidity, checksum) != 0) return false;      //Error out

    //sensorStatus = rawHumidity & 0x0003; //Grab only the right two bits
    rawHumidity &= 0xFFFC;                                      //Zero out the status bits but keep them in place

    //Given the raw humidity data, calculate the actual relative humidity
    float tempRH = rawHumidity / (float)65536;                  //2^16 = 65536
    float rh = -6 + (125 * tempRH);                             //From page 14

    if (hrfout != NULL) {
        *hrfout = rh;
    }

    return true;
}
예제 #12
0
파일: env.c 프로젝트: qgp/armboot
/*
 * copy environment to memory
 * returns -1 on error, 0 if ok
 */
int board_env_copy(bd_t *bd, env_t *data, int size)
{
    env_t *env = (env_t *)CFG_ENV_ADDR;

    if (check_crc(bd))
    {
	memcpy(data, env, sizeof(env_t));
	return 0;
    } 

    return -1;
}
예제 #13
0
/*!
  @brief Checks if packet is in buffer, loads it to p_in_buffer,
  then returns the packet type
*/
uint8_t load_packet( uint8_t* buffer )
{
  uint8_t packet_size;
   

  packet_size = find_and_escape_packet( buffer, p_in_buffer );

#ifdef PACKET_DEBUG
   {
    uint8_t tmp_count;
    printf("\nESC: ");   
    for( tmp_count = 0; tmp_count< packet_size; tmp_count++)
    {
      printf("%02x ", p_in_buffer[tmp_count]);
    }
    printf("\n");
  }
#endif
  
  if ( (packet_size > 0) && check_crc( p_in_buffer, packet_size) )
  {
 
    // Move packet to serial_buffer to align memory and get rid of start char
    memmove( p_in_buffer, ( p_in_buffer + 1 ), (packet_size - 2) );
    memcpy( (void *)(&in_packet), (void*)p_in_buffer, sizeof( in_packet ) );
  
    // move data to start of serial_buffer
    memmove( p_in_buffer, (p_in_buffer + sizeof(tos_packet_header_t)),
              in_packet.length );
    
    return in_packet.am_type;
  }
  else
  {
    printf("Bad packet - ");
    printf("CRC Match = %d\n", check_crc( p_in_buffer, packet_size));
    
    return 0;
  }
}
예제 #14
0
파일: env.c 프로젝트: qgp/armboot
/* 
 * try to read env character at offset #index
 * 
 * called before the environment is copied to ram
 * returns -1 on error, 0 if ok
 */
int board_env_getchar(bd_t * bd, int index, uchar *c)
{
    env_t *env = (env_t *)CFG_ENV_ADDR; 
   
    /* check environment crc */
    if (index < sizeof(env->data) && check_crc(bd))
    {
	*c = env->data[index];
	return 0;
    }

    return -1;
}
예제 #15
0
파일: check.c 프로젝트: bcopeland/omfsprogs
int check_inode(check_context_t *ctx)
{
	int i;
	int ret = 1;
	omfs_inode_t *inode = ctx->current_inode;

	if (test_bit(ctx->visited, ctx->block))
	{
		fix_problem(E_LOOP, ctx);
		return 0;
	}
	for (i=0; i < swap_be32(ctx->omfs_info->super->s_mirrors); i++)
		set_bit(ctx->visited, ctx->block + i);

	if (!check_sanity(ctx))
	{
		fix_problem(E_INSANE, ctx);
		return 0;
	}
	if (!check_header((u8 *)inode)) 
	{
		fix_problem(E_HEADER_XOR, ctx);
		ret = 0;
	}
	if (!check_crc((u8 *)inode)) 
	{
		fix_problem(E_HEADER_CRC, ctx);
		ret = 0;
	}
	if (swap_be64(inode->i_head.h_self) != ctx->block)
	{
		fix_problem(E_SELF_PTR, ctx);
		ret = 0;
	}
	if (swap_be64(inode->i_parent) != ctx->parent)
	{
		fix_problem(E_PARENT_PTR, ctx);
		ret = 0;
	}
	if (omfs_compute_hash(ctx->omfs_info, inode->i_name) != ctx->hash)
	{
		fix_problem(E_HASH_WRONG, ctx);
		ret = 0;
	}
	if (inode->i_type == OMFS_FILE)
	{
		visit_extents(ctx);
	}

	return ret;
}
예제 #16
0
파일: main.cpp 프로젝트: Elv1zz/engraver_fw
void loop (void) {
  unsigned char received_char, received_char_2, received_char_3, received_char_crc;

  received_char = receiveData ();
  if (received_char == 'a') {
    //digitalWrite (WARNPIN, LOW);
    received_char_2 = receiveData ();   // b1
    received_char_3 = receiveData ();   // b2 
    received_char_crc = receiveData (); // b4   (CRC)
    if (check_crc (received_char_2, received_char_3, received_char_crc)) {
      //CRC OK

      // motor X
      if ((received_char_3 & 0x03) == 0x03) {
        // negative step
        motorX.onestep (-1, INTERLEAVE);
      } else if ((received_char_3 & 0x0C) == 0x0C) {
        // positive step
        motorX.onestep (1, INTERLEAVE);
      }
      // motor Y
      if ((received_char_3 & 0x30) == 0x30) {
        // negative step
        motorY.onestep (-1, INTERLEAVE);
      } else if ((received_char_3 & 0xC0) == 0xC0) {
        // positive step
        motorY.onestep (1, INTERLEAVE);
      }
      // laser
      if ((received_char_2 & BIT_LASER) == BIT_LASER) {
        // on
        digitalWrite (LASERPIN, HIGH);
      } else {
        // off
        digitalWrite (LASERPIN, LOW);
      }
      sendData ('O');
    } else {
      sendData ('C');
      //digitalWrite (WARNPIN, HIGH);
    }
  } else if (received_char == 'r') {
    // go to (0,0):
    // - register interrupts for 0-position switches
    // - start motors
  } else {
    //digitalWrite (WARNPIN, HIGH);
    sendData ('F');
  }
}
예제 #17
0
int verify_load_firmware(uint32_t start, int size)
{
	mdev_t *fl_drv;
	struct firmware_segment segment;
	struct img_hdr ih;
	struct seg_hdr sh;

	fl_drv = flash_drv_open(FL_PART_DEV);
	if (fl_drv == NULL) {
		rf_e("Flash driver init is required before open");
		goto error;
	}

	segment.offset = start;
	segment.length = size;

	/* load and validate image header */
	read_from_seghdr(fl_drv, &segment, &ih, sizeof(ih));
	if ((ih.magic_str != FW_MAGIC_STR) ||
			(ih.magic_sig != FW_MAGIC_SIG))
		goto error;

	while (ih.seg_cnt--) {
		read_from_seghdr(fl_drv, &segment, &sh, sizeof(sh));
		sh.offset += start;

		switch (sh.type) {
		case FW_BLK_LOADABLE_SEGMENT:
			if (check_crc(fl_drv, sh.offset, sh.len, sh.crc))
				goto error;
			break;

		case FW_BLK_POKE_DATA:
		case FW_BLK_FN_CALL:
		case FW_BLK_ANCILLARY:
			/* do nothing */
			break;

		default:
			goto error;
		}
	}


	return WM_SUCCESS;
error:
	return -WM_E_RFGET_FFW_LOAD;
}
예제 #18
0
static int cont_grep(regex_t *exp, regex_t *nl_exp, int fd, pb_file *pbf, int options) {
	int retflag = TRUE;
	int i;
	int j;
	ub4 csize;
	ub4 usize;
	ub2 fnlen;
	ub2 eflen;
	ub2 flags;
	ub2 method;
	ub1 file_header[30];
	char *filename;
	char *str_stream;
	regmatch_t *match_array;
	regmatch_t *nl_offsets;

	if(pb_read(pbf, (file_header + 4), 26) != 26) {
		perror("read");
		retflag = FALSE;
   	}
	else {
		decd_siz(&csize, &usize, &fnlen, &eflen, &flags, &method, file_header);
		filename = new_filename(pbf, fnlen);
		lseek(fd, eflen, SEEK_CUR);
		if(filename[fnlen - 1] != '/') {
			str_stream = (method == 8 || (flags & 0x0008)) ? 
				(char *) inflate_string(pbf, &csize, &usize) : 
					read_string(pbf, csize);
			if(flags & 0x008) check_crc(pbf, str_stream, usize);
			mk_ascii(str_stream, usize);
			match_array = fnd_match(exp, str_stream, &i);
			if((options & JG_PRINT_LINE_NUMBER) && i) 
				nl_offsets = fnd_match(nl_exp, str_stream, &j);
			prnt_mtchs(exp, filename, str_stream, match_array, nl_offsets, i, j, options);
			if(match_array) free(match_array);
			free(str_stream);
		}
		free(filename);
		retflag = TRUE;
	}

	return retflag;
}
예제 #19
0
파일: lan.c 프로젝트: Sepharon/UPC-Projects
static void comp(void){
  /*
    1- El on_message_recived del init detecta que rebem un missatge
    2- El on_message_recived crida a la funcio comp ^
    3- La funcio comp comprova que tot funcioni be i crida a la funcio funcio()
    4- La funcio funcio() s'hagfa del on_lan_recived
    5- La funcio on_lan_recived es crida al main de l'applicacio
    6- La funcio cridada es la funcio pinta del modul aplicacio .c
  */
  // Agafem els blocks
  ether_block_get(rx);
  if (check_crc(rx)){
    // Comprovem el origen
    if(rx[1]==node_origen){
      // Fem el callback
      funcio();
    }
  }
}  
예제 #20
0
파일: yx_Oil.cpp 프로젝트: awzhang/MyWork
void COil::AnalyseComData(char *v_szBuf, int v_iLen)
{
	int iRet = 0;
	if( !v_szBuf || v_iLen <= 0 ) 
		return ;
	
	static int i7ECount = 0;
	
	for( int i = 0; i < v_iLen; i ++ )
	{
		if( 0x7e == v_szBuf[ i ] )
		{
			++ i7ECount;
			
			if( 0 == i7ECount % 2 ) // 若得到一帧
			{		
				// 反转义
				m_iComFrameLen = DetranData(m_szComFrameBuf, m_iComFrameLen);
				
				// 计算校验和,校验正确,送入接收队列
				if( check_crc((byte*)m_szComFrameBuf, m_iComFrameLen) )
				{		
					DWORD dwPacketNum = 0;
					m_objRecvMng.PushData(LV2, m_iComFrameLen-4, m_szComFrameBuf+4, dwPacketNum);					
				}
				else
				{
					PRTMSG(MSG_ERR, "Oil frame check crc err!\n");
					memset(m_szComFrameBuf, 0, m_iComFrameLen);
					m_iComFrameLen = 0;
				}
				
				//无论校验正确与否,都将缓冲区清0
				memset(m_szComFrameBuf, 0, m_iComFrameLen);
				m_iComFrameLen = 0;
			}
		}
		else
		{
			m_szComFrameBuf[m_iComFrameLen++] = v_szBuf[i];
		}
	}
}
예제 #21
0
파일: inkjar.cpp 프로젝트: Spin0za/inkscape
guint8 *JarFile::get_uncompressed_file(guint32 compressed_size, guint32 crc, 
				       guint16 eflen, guint16 flags)
{
    GByteArray *gba = g_byte_array_new();
    unsigned int out_a = 0;
    unsigned int in_a = compressed_size;
    guint8 *bytes;
    guint32 crc2 = 0;
    
    crc2 = crc32(crc2, NULL, 0);
    
    bytes = (guint8 *)g_malloc(sizeof(guint8) * RDSZ);
    while(out_a < compressed_size){
	unsigned int nbytes = (in_a > RDSZ ? RDSZ : in_a);
	
	if (!(nbytes = read(bytes, nbytes))) {
	    g_free(bytes);
	    return NULL;
	}
	
	crc2 = crc32(crc2, (Bytef*)bytes, nbytes);
	    
	g_byte_array_append (gba, bytes, nbytes);
	out_a += nbytes;
	in_a -= nbytes;
	    
#ifdef DEBUG    
	std::printf("%d bytes written\n", out_a);
#endif
    }
    lseek(fd, eflen, SEEK_CUR);
    g_free(bytes);

    if (!check_crc(crc, crc2, flags)) {
        bytes = gba->data;
        g_byte_array_free(gba, FALSE);//FALSE argument does not free actual data
	return NULL;
    }
    
    return bytes;
}
예제 #22
0
파일: clunet.c 프로젝트: dudanov/clunet
void
clunet_send(const uint8_t address, const uint8_t prio, const uint8_t command, const char* data, const uint8_t size)
{
	/* Если размер данных в пределах буфера передачи (максимально для протокола 250 байт) */
	if (size < (CLUNET_SEND_BUFFER_SIZE - CLUNET_OFFSET_DATA))
	{
		/* Прерываем текущую передачу, если есть такая */
		if (clunetSendingState)
		{
			CLUNET_DISABLE_TIMER_COMP;
			CLUNET_SEND_0;
		}

		/* Заполняем переменные */
		clunetCurrentPrio = (prio > 4) ? 4 : prio ? : 1;	// Ограничим приоритет диапазоном (1 ; 4)
		dataToSend[CLUNET_OFFSET_SRC_ADDRESS] = CLUNET_DEVICE_ID;
		dataToSend[CLUNET_OFFSET_DST_ADDRESS] = address;
		dataToSend[CLUNET_OFFSET_COMMAND] = command;
		dataToSend[CLUNET_OFFSET_SIZE] = size;
		
		/* Копируем данные в буфер */
		uint8_t i;
		for (i = 0; i < size; i++)
			dataToSend[CLUNET_OFFSET_DATA + i] = data[i];

		/* Добавляем контрольную сумму */
		dataToSend[CLUNET_OFFSET_DATA + size] = check_crc((char*)dataToSend, CLUNET_OFFSET_DATA + size);
		
		clunetSendingDataLength = size + (CLUNET_OFFSET_DATA + 1);

		// Если линия свободна, то запланируем передачу сразу
		if (!CLUNET_READING)
			clunet_start_send();
		// Иначе будем ожидать когда освободится в процедуре внешнего прерывания
		else
			clunetSendingState = CLUNET_SENDING_STATE_WAITING_LINE;

	}
}
예제 #23
0
void send_command(t_serial_request *prq, t_shared_data *pshared)
{
  char             byte;
  char             message[MAX_MSG_SIZE];
  int              sz, ctn;
  //
  enum eserial_state
    {
      ser_nothing,
      ser_waiting_response
    };
  eserial_state ser_state;

  ser_state = ser_nothing;
  switch (prq->type)
    {
    case enothing:
      break;
    case eping:
      {
	while (pshared->pserial->read_next_byte(&byte)); // Empty the buffer
	snprintf(message, MAX_MSG_SIZE, "ping\n");
	add_crc(message);
	pshared->pserial->write_serial_port(message, 1 + strlen(message));
	ser_state = ser_waiting_response;
      }
      break;
    case einformation:
      {
	while (pshared->pserial->read_next_byte(&byte)); // Empty the buffer
	snprintf(message, MAX_MSG_SIZE, "get_params\n");
	add_crc(message);
	pshared->pserial->write_serial_port(message, 1 + strlen(message));
	ser_state = ser_waiting_response;
      }
      break;
    case ereport:
      {
	while (pshared->pserial->read_next_byte(&byte)); // Empty the buffer
	snprintf(message, MAX_MSG_SIZE, "get_report\n");
	add_crc(message);
	pshared->pserial->write_serial_port(message, 1 + strlen(message));
	ser_state = ser_waiting_response;
      }
      break;
    case eprogram:
      {
	snprintf(message, MAX_MSG_SIZE, "set_param %s\n", prq->command);
	add_crc(message);
	pshared->pserial->write_serial_port(message, 1 + strlen(message));
	usleep(500000);
	ser_state = ser_nothing;
      }
      break;
    case eupdategui:
    default:
      break;
    }
  if (ser_state == ser_waiting_response)
    {
      // Get the bytes from the serial line. Wait a little if nothing is found.
      sz = 0;
      for (ctn = 0; !pshared->pserial->read_next_byte(&byte) && ctn < 10; ctn++)
	usleep(10000);
      while (sz < MAX_MSG_SIZE && byte != 0 && ctn < 10) // Is the end of the message
	{
	  message[sz++] = byte;
	  for (ctn = 0; !pshared->pserial->read_next_byte(&byte) && ctn < 10; ctn++)
	    usleep(1000);
	}
      if (byte == 0 && sz > 0)
	{
	  message[sz] = '\0';
	  if (!check_crc(message, sz))
	    {
	      printf("Wrong CRC: %x / %x.\n", calculate_CRC(message, sz - 1), message[sz - 1]);
	      return;
	    }
	  message[sz - 1] = '\0'; // Erase the CRC
	  printf("<- Received a serial message: \"%s\".\n", message);
	  LOCK;
	  // Process the shit, like if it was a sewer pipe.
	  switch (prq->type)
	    {
	    case enothing:
	      break;
	    case eping:
	      {
		strncpy(pshared->bms_version, message, MAX_MSG_SIZE);
	      }
	      break;
	    case einformation:
	      {
		strncpy(pshared->param_msg, message, MAX_MSG_SIZE);
		pshared->pBMS->parse_BMS_params_string(&pshared->pBMS->m_params, pshared->param_msg);
	      }
	      break;
	    case ereport:
	      {
		strncpy(pshared->report_msg, message, MAX_MSG_SIZE);
		pshared->pBMS->parse_BMS_report_string(&pshared->pBMS->m_report, pshared->report_msg);
	      }
	      break;
	    case eprogram:
	    case eupdategui:
	    default:
	      break;
	    }
	  // This will trigger a screen refresh
	  add_command_in_locked_area(eupdategui, " ", pshared);
	  UNLOCK;
	}
    }
}
예제 #24
0
/**
 * pi_begin() - check disk, validate, and get proper iterator
 * @di:	    diskinfo struct pointer
 *
 * This function checks the disk for GPT or legacy partition table and allocates
 * an appropriate iterator.
 **/
struct part_iter *pi_begin(const struct disk_info *di, int stepall)
{
    int setraw = 0;
    struct part_iter *iter = NULL;
    struct disk_dos_mbr *mbr = NULL;
    struct disk_gpt_header *gpth = NULL;
    struct disk_gpt_part_entry *gptl = NULL;

    /* Read MBR */
    if (!(mbr = disk_read_sectors(di, 0, 1))) {
	error("Couldn't read first disk sector.\n");
	goto bail;
    }

    setraw = -1;

    /* Check for MBR magic*/
    if (mbr->sig != disk_mbr_sig_magic) {
	error("No MBR magic.\n");
	goto bail;
    }

    /* Check for GPT protective MBR */
    if (mbr->table[0].ostype == 0xEE) {
	if (!(gpth = disk_read_sectors(di, 1, 1))) {
	    error("Couldn't read potential GPT header.\n");
	    goto bail;
	}
    }

    if (gpth && gpth->rev.uint32 == 0x00010000 &&
	    !memcmp(gpth->sig, disk_gpt_sig_magic, sizeof(disk_gpt_sig_magic))) {
	/* looks like GPT v1.0 */
	uint64_t gpt_loff;	    /* offset to GPT partition list in sectors */
	uint64_t gpt_lsiz;	    /* size of GPT partition list in bytes */
	uint64_t gpt_lcnt;	    /* size of GPT partition in sectors */
#ifdef DEBUG
	puts("Looks like a GPT v1.0 disk.");
	disk_gpt_header_dump(gpth);
#endif
	/* Verify checksum, fallback to backup, then bail if invalid */
	if (gpt_check_hdr_crc(di, &gpth))
	    goto bail;

	gpt_loff = gpth->lba_table;
	gpt_lsiz = (uint64_t)gpth->part_size * gpth->part_count;
	gpt_lcnt = (gpt_lsiz + di->bps - 1) / di->bps;

	/*
	 * disk_read_sectors allows reading of max 255 sectors, so we use
	 * it as a sanity check base. EFI doesn't specify max (AFAIK).
	 * Apart from that, some extensive sanity checks.
	 */
	if (!gpt_loff || !gpt_lsiz || gpt_lcnt > 255u ||
		gpth->lba_first_usable > gpth->lba_last_usable ||
		!sane(gpt_loff, gpt_lcnt) ||
		gpt_loff + gpt_lcnt > gpth->lba_first_usable ||
		!sane(gpth->lba_last_usable, gpt_lcnt) ||
		gpth->lba_last_usable + gpt_lcnt >= gpth->lba_alt ||
		gpth->lba_alt >= di->lbacnt ||
		gpth->part_size < sizeof(struct disk_gpt_part_entry)) {
	    error("Invalid GPT header's values.\n");
	    goto bail;
	}
	if (!(gptl = disk_read_sectors(di, gpt_loff, (uint8_t)gpt_lcnt))) {
	    error("Couldn't read GPT partition list.\n");
	    goto bail;
	}
	/* Check array checksum(s). */
	if (check_crc(gpth->table_chksum, (const uint8_t *)gptl, (unsigned int)gpt_lsiz)) {
	    error("WARNING: GPT partition list checksum invalid, trying backup.\n");
	    free(gptl);
	    /* secondary array directly precedes secondary header */
	    if (!(gptl = disk_read_sectors(di, gpth->lba_alt - gpt_lcnt, (uint8_t)gpt_lcnt))) {
		error("Couldn't read backup GPT partition list.\n");
		goto bail;
	    }
	    if (check_crc(gpth->table_chksum, (const uint8_t *)gptl, (unsigned int)gpt_lsiz)) {
		error("Backup GPT partition list checksum invalid.\n");
		goto bail;
	    }
	}
	/* allocate iterator and exit */
	iter = pi_new(typegpt, di, stepall, gpth, gptl);
    } else {
	/* looks like MBR */
	iter = pi_new(typedos, di, stepall, mbr);
    }

    setraw = 0;
bail:
    if (setraw) {
	error("WARNING: treating disk as raw.\n");
	iter = pi_new(typeraw, di, stepall);
    }
    free(mbr);
    free(gpth);
    free(gptl);

    return iter;
}
예제 #25
0
void readHumidTimerHandler(void *T)
{
	I2C001_DataType data1;
	data1.Data1.TDF_Type = I2C_TDF_MRStart;
	data1.Data1.Data = ((HTDU21D_ADDRESS << 1) | I2C_READ);
	I2C001_WriteData(&I2C001_Handle1,&data1);

	delay11(DELAY);

	if(I2C001_GetFlagStatus(&I2C001_Handle1,I2C001_FLAG_NACK_RECEIVED) == I2C001_SET)
	{
		I2C001_ClearFlag(&I2C001_Handle1,I2C001_FLAG_NACK_RECEIVED);
		errorCounter++;
	}
	else
	{
		uint8_t msb = 0x00;
		uint8_t lsb = 0x00;
		uint8_t checksum = 0x00;

		USIC_CH_TypeDef* I2CRegs = I2C001_Handle1.I2CRegs;

		I2C001_DataType data2;
		data2.Data1.TDF_Type = I2C_TDF_MRxAck0;
		data2.Data1.Data = ubyteFF;
		I2C001_WriteData(&I2C001_Handle1,&data2);

		delay11(DELAY);

		if(!USIC_ubIsRxFIFOempty(I2CRegs))
		{
			msb = (uint8_t)I2CRegs->OUTR;
			//Result = (bool)TRUE;
		}

		I2C001_DataType data3;
		data3.Data1.TDF_Type = I2C_TDF_MRxAck0;
		data3.Data1.Data = ubyteFF;
		I2C001_WriteData(&I2C001_Handle1,&data3);

		delay11(DELAY);

		if(!USIC_ubIsRxFIFOempty(I2CRegs))
		{
			lsb = (uint8_t)I2CRegs->OUTR;
			//Result = (bool)TRUE;
		}

		I2C001_DataType data4;
		data4.Data1.TDF_Type = I2C_TDF_MRxAck1;
		data4.Data1.Data = ubyteFF;
		I2C001_WriteData(&I2C001_Handle1,&data4);

		delay11(DELAY);

		I2C001_DataType data5;
		data5.Data1.TDF_Type = I2C_TDF_MStop;
		data5.Data1.Data = ubyteFF;
		I2C001_WriteData(&I2C001_Handle1,&data5);

		delay11(DELAY);



		int d = USIC_GetRxFIFOFillingLevel(I2CRegs);
		// Read receive buffer, put the data in DataReceive1


		if(!USIC_ubIsRxFIFOempty(I2CRegs))
		{
			checksum = (uint8_t)I2CRegs->OUTR;
			//Result = (bool)TRUE;
		}


		unsigned int rawHumid = ((unsigned int) msb << 8) | (unsigned int) lsb;

		if(check_crc(rawHumid, checksum) != 0)
		{
			wrong_checksum = 1;
		}

		rawHumid &= 0xFFFC; //Zero out the status bits but keep them in place

		//Given the raw temperature data, calculate the actual temperature
		float tempRH = rawHumid / (float)65536; //2^16 = 65536
		rh = -6 + (125 * tempRH); //From page 14

		readHumid = 1;
	}
}
static bool
validate (Dwfl_Module *mod, int fd, bool check, GElf_Word debuglink_crc)
{
  /* For alt debug files always check the build-id from the Dwarf and alt.  */
  if (mod->dw != NULL)
    {
      bool valid = false;
      const void *build_id;
      const char *altname;
      ssize_t build_id_len = INTUSE(dwelf_dwarf_gnu_debugaltlink) (mod->dw,
								   &altname,
								   &build_id);
      if (build_id_len > 0)
	{
	  /* We need to open an Elf handle on the file so we can check its
	     build ID note for validation.  Backdoor the handle into the
	     module data structure since we had to open it early anyway.  */
	  Dwfl_Error error = __libdw_open_file (&fd, &mod->alt_elf,
						false, false);
	  if (error != DWFL_E_NOERROR)
	    __libdwfl_seterrno (error);
	  else
	    {
	      const void *alt_build_id;
	      ssize_t alt_len = INTUSE(dwelf_elf_gnu_build_id) (mod->alt_elf,
								&alt_build_id);
	      if (alt_len > 0 && alt_len == build_id_len
		  && memcmp (build_id, alt_build_id, alt_len) == 0)
		valid = true;
	      else
		{
		  /* A mismatch!  */
		  elf_end (mod->alt_elf);
		  mod->alt_elf = NULL;
		  close (fd);
		  fd = -1;
		}
	    }
	}
      return valid;
    }

  /* If we have a build ID, check only that.  */
  if (mod->build_id_len > 0)
    {
      /* We need to open an Elf handle on the file so we can check its
	 build ID note for validation.  Backdoor the handle into the
	 module data structure since we had to open it early anyway.  */

      mod->debug.valid = false;
      Dwfl_Error error = __libdw_open_file (&fd, &mod->debug.elf, false, false);
      if (error != DWFL_E_NOERROR)
	__libdwfl_seterrno (error);
      else if (likely (__libdwfl_find_build_id (mod, false,
						mod->debug.elf) == 2))
	/* Also backdoor the gratuitous flag.  */
	mod->debug.valid = true;
      else
	{
	  /* A mismatch!  */
	  elf_end (mod->debug.elf);
	  mod->debug.elf = NULL;
	  close (fd);
	  fd = -1;
	}

      return mod->debug.valid;
    }

  return !check || check_crc (fd, debuglink_crc);
}
예제 #27
0
void UI_SCPECG2EDFwindow::SelectFileButton()
{
  FILE *inputfile=NULL;

  int i, j, k, n, hdl, chns, sf, avm, blocks, *buf, encoding, compression, offset,
      abs_val_a[256],
      abs_val_b[256],
      var_tmp;

  unsigned short sh_tmp;

  long long filesize, ll_tmp, bits;

  char input_filename[MAX_PATH_LENGTH],
       txt_string[2048],
       edf_filename[MAX_PATH_LENGTH],
       scratchpad[MAX_PATH_LENGTH],
       *block,
       ch_tmp;

  union{
         unsigned long long ll_int;
         unsigned int one[2];
         unsigned short two[4];
         unsigned char four[8];
       } var;

  pushButton1->setEnabled(false);

  for(i=0; i<256; i++)
  {
    abs_val_a[i] = 0;
    abs_val_b[i] = 0;
  }

  strcpy(input_filename, QFileDialog::getOpenFileName(0, "Select inputfile", QString::fromLocal8Bit(recent_opendir), "SCP files (*.scp *.SCP)").toLocal8Bit().data());

  if(!strcmp(input_filename, ""))
  {
    pushButton1->setEnabled(true);
    return;
  }

  get_directory_from_path(recent_opendir, input_filename, MAX_PATH_LENGTH);

  inputfile = fopeno(input_filename, "rb");
  if(inputfile==NULL)
  {
    snprintf(txt_string, 2048, "Can not open file %s for reading.\n", input_filename);
    textEdit1->append(QString::fromLocal8Bit(txt_string));
    pushButton1->setEnabled(true);
    return;
  }

  get_filename_from_path(scratchpad, input_filename, MAX_PATH_LENGTH);

  snprintf(txt_string, 2048, "Read file: %s", scratchpad);
  textEdit1->append(QString::fromLocal8Bit(txt_string));

  fseeko(inputfile, 0LL, SEEK_END);
  filesize = ftello(inputfile);
  if(filesize<126)
  {
    textEdit1->append("Error, filesize is too small.\n");
    fclose(inputfile);
    pushButton1->setEnabled(true);
    return;
  }

  ll_tmp = 0LL;

  fseeko(inputfile, 2LL, SEEK_SET);

  if(fread(&ll_tmp, 4, 1, inputfile) != 1)
  {
    textEdit1->append("A read-error occurred (1)\n");
    fclose(inputfile);
    pushButton1->setEnabled(true);
    return;
  }

  if(ll_tmp != filesize)
  {
    textEdit1->append("Error, filesize does not match with header.\n");
    fclose(inputfile);
    pushButton1->setEnabled(true);
    return;
  }

  block = (char *)malloc(SPCECGBUFSIZE);
  if(block == NULL)
  {
    textEdit1->append("Malloc error (block 1)\n");
    fclose(inputfile);
    pushButton1->setEnabled(true);
    return;
  }

  rewind(inputfile);

  if(fread(&sh_tmp, 2, 1, inputfile) != 1)
  {
    textEdit1->append("A read-error occurred (2)\n");
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

  if(check_crc(inputfile, 2LL, filesize - 2LL, sh_tmp, block))
  {
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

  memset(&sp, 0, sizeof(struct section_prop_struct[12]));

  if(read_section_header(0, inputfile, 6LL, block))
  {
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

  if(strncmp(sp[0].reserved, "SCPECG", 6))
  {
    textEdit1->append("Error, reserved field of section header 0 does not contain string \"SCPECG\".\n");
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

  sp[0].file_offset = 6LL;

// printf("\nsection ID is %i\n"
//        "section file offset is %lli\n"
//        "section CRC is 0x%04X\n"
//        "section length is %i\n"
//        "section version is %i\n"
//        "section protocol version is %i\n",
//        sp[0].section_id,
//        sp[0].file_offset,
//        (int)sp[0].crc,
//        sp[0].section_length,
//        sp[0].section_version,
//        sp[0].section_protocol_version);

  if(read_data_section_zero(inputfile, block, filesize))
  {
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

  fseeko(inputfile, sp[6].file_offset + 16LL, SEEK_SET);

  if(fread(block, 6, 1, inputfile) != 1)
  {
    textEdit1->append("A read-error occurred\n");
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

  avm = *((unsigned short *)block);

  sf = 1000000 / *((unsigned short *)(block + 2));

  encoding = *((unsigned char *)(block + 4));

  compression = *((unsigned char *)(block + 5));

  if(compression != 0)
  {
    textEdit1->append("File contains bimodal compressed data which is not supported by this converter.\n ");
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

  fseeko(inputfile, sp[3].file_offset + 16LL, SEEK_SET);

  if(fread(scratchpad, 2, 1, inputfile) != 1)
  {
    textEdit1->append("A read-error occurred (40)\n");
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

  chns = *((unsigned char *)scratchpad);

  if(chns < 1)
  {
    textEdit1->append("Error, number of signals is less than one.\n ");
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

  if(chns > 256)
  {
    textEdit1->append("Error, number of signals is more than 256.\n ");
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

  if(scratchpad[1] & 1)
  {
    textEdit1->append("Reference beat subtraction used for compression which is not supported by this converter.\n ");
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

  if(!(scratchpad[1] & 4))
  {
    textEdit1->append("Leads are not simultaneously recorded which is not supported by this converter. (1)\n ");
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

// printf("chns is %u   AVM is %u   sf is %u   encoding is %u   compression is %u\n",
//        chns, avm, sf, encoding, compression);

  memset(&lp, 0, sizeof(struct lead_prop_struct[256]));

  fseeko(inputfile, sp[3].file_offset + 18LL, SEEK_SET);

  for(i=0; i<chns; i++)
  {
    if(fread(&(lp[i].start), 4, 1, inputfile) != 1)
    {
      textEdit1->append("A read-error occurred (30)\n");
      fclose(inputfile);
      free(block);
      pushButton1->setEnabled(true);
      return;
    }

    if(fread(&(lp[i].end), 4, 1, inputfile) != 1)
    {
      textEdit1->append("A read-error occurred (31)\n");
      fclose(inputfile);
      free(block);
      pushButton1->setEnabled(true);
      return;
    }

    if(fread(&(lp[i].label), 1, 1, inputfile) != 1)
    {
      textEdit1->append("A read-error occurred (32)\n");
      fclose(inputfile);
      free(block);
      pushButton1->setEnabled(true);
      return;
    }
  }

// for(i=0; i<chns; i++)
// {
//   printf("lp[i].start is %i   lp[i].end is %i\n", lp[i].start, lp[i].end);
// }

  if(chns > 1)
  {
    for(i=1; i<chns; i++)
    {
      if(lp[i].start != lp[0].start)
      {
        textEdit1->append("Error, leads are not simultaneously recorded. (2)\n");
        fclose(inputfile);
        free(block);
        pushButton1->setEnabled(true);
        return;
      }

      if(lp[i].end != lp[0].end)
      {
        textEdit1->append("Error, leads are not simultaneously recorded. (3)\n");
        fclose(inputfile);
        free(block);
        pushButton1->setEnabled(true);
        return;
      }
    }
  }

  for(i=0; i<chns; i++)
  {
    if(lp[i].start < 1)
    {
      textEdit1->append("Error, start sample number in section 3 is less than 1.\n");
      fclose(inputfile);
      free(block);
      pushButton1->setEnabled(true);
      return;
    }

    if(lp[i].end <= lp[i].start)
    {
      textEdit1->append("Error (56) (lp[i].end <= lp[i].start)\n");
      fclose(inputfile);
      free(block);
      pushButton1->setEnabled(true);
      return;
    }

    if(lp[i].start != 1)
    {
      textEdit1->append("Error (57) (lp[i].start != 1)\n");
      fclose(inputfile);
      free(block);
      pushButton1->setEnabled(true);
      return;
    }

    lp[i].start--;

    if((lp[i].end - lp[i].start) < sf)
    {
      textEdit1->append("Error, recording length is less than one second.\n");
      fclose(inputfile);
      free(block);
      pushButton1->setEnabled(true);
      return;
    }

    lp[i].samples = lp[i].end - lp[i].start;
  }

  fseeko(inputfile, sp[6].file_offset + 22LL, SEEK_SET);

  n = 0;

  for(i=0; i<chns; i++)
  {
    if(fread(block, 2, 1, inputfile) != 1)
    {
      textEdit1->append("A read-error occurred (41)\n");
      fclose(inputfile);
      free(block);
      pushButton1->setEnabled(true);
      return;
    }

    lp[i].bytes = *((unsigned short *)block);

    n += lp[i].bytes;

// printf("lead samples is %i   bytes is %i\n", lp[i].samples, lp[i].bytes);

    if(sp[2].present != 1)  // huffmantable
    {
      if(lp[i].bytes < (lp[i].samples * 2))
      {
        textEdit1->append("Error, lead samples is less than lead bytes.\n");
        fclose(inputfile);
        free(block);
        pushButton1->setEnabled(true);
        return;
      }
    }
  }

  if(n > (sp[6].section_length - 22 - (chns * 2)))
  {
    textEdit1->append("Error, total databytes is more than section size.\n");
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

//////////////////////////////// Huffman tables ////////////////////

  if(sp[2].present == 1)  // huffmantable
  {
    fseeko(inputfile, sp[2].file_offset + 16LL, SEEK_SET);

    if(fread(block, 13, 1, inputfile) != 1)
    {
      textEdit1->append("A read-error occurred (50)\n");
      fclose(inputfile);
      free(block);
      pushButton1->setEnabled(true);
      return;
    }

    ht.h_tables_cnt = *((unsigned short *)block);
    ht.code_structs_cnt = *((unsigned short *)(block + 2));
    ht.prefix_bits = *((unsigned char *)(block + 4));
    ht.total_bits = *((unsigned char *)(block + 5));
    ht.table_mode_switch = *((unsigned char *)(block + 6));
    ht.base_value = *((unsigned short *)(block + 7));
    ht.base_code = *((unsigned int *)(block + 9));

//   printf("ht.h_tables_cnt is %i   ht.code_structs_cnt is %i   ht.prefix_bits is %i   ht.total_bits is %i\n",
//         ht.h_tables_cnt, ht.code_structs_cnt, ht.prefix_bits, ht.total_bits);

    if(ht.h_tables_cnt != 19999)
    {
      textEdit1->append("Aborted, this converter does not support customized Huffmantables.\n");
      fclose(inputfile);
      free(block);
      pushButton1->setEnabled(true);
      return;
    }
  }

//////////////////////////////// patient data ////////////////////

  memset(&pat_dat, 0, sizeof(struct patient_data_struct));

  if(get_patient_data(inputfile))
  {
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

// printf("patient ID:          %s\n"
//        "patient lastname:    %s\n"
//        "patient firstname:   %s\n"
//        "patient sex:         %i\n"
//        "startdate year:      %i\n"
//        "startdate month:     %i\n"
//        "startdate day:       %i\n"
//        "starttime hour:      %i\n"
//        "starttime minute:    %i\n"
//        "starttime second:    %i\n"
//        "birthdate year:      %i\n"
//        "birthdate month:     %i\n"
//        "birthdate day:       %i\n"
//        "device model:        %s\n"
//        "language code:       %u\n"
//        "manufacturer:        %s\n",
//        pat_dat.pat_id,
//        pat_dat.last_name,
//        pat_dat.first_name,
//        pat_dat.sex,
//        pat_dat.startdate_year,
//        pat_dat.startdate_month,
//        pat_dat.startdate_day,
//        pat_dat.starttime_hour,
//        pat_dat.starttime_minute,
//        pat_dat.starttime_second,
//        pat_dat.birthdate_year,
//        pat_dat.birthdate_month,
//        pat_dat.birthdate_day,
//        pat_dat.device_model,
//        pat_dat.lang_code,
//        pat_dat.manufacturer);

////////////////////////// start conversion ///////////////////////////////

  free(block);

  buf = (int *)malloc(((lp[0].samples / sf) + 1) * chns * sf * sizeof(int));
  if(buf == NULL)
  {
    textEdit1->append("Malloc error (buf)\n");
    fclose(inputfile);
    pushButton1->setEnabled(true);
    return;
  }

  n = 0;

  for(i=0; i<chns; i++)
  {
    n += lp[i].bytes;
  }

  block = (char *)calloc(1, n + 64);
  if(block == NULL)
  {
    textEdit1->append("Malloc error (block 3)\n");
    fclose(inputfile);
    free(buf);
    pushButton1->setEnabled(true);
    return;
  }

  fseeko(inputfile, sp[6].file_offset + 22LL + (chns * 2LL), SEEK_SET);  // rhythm data

  if(fread(block, n, 1, inputfile) != 1)
  {
    textEdit1->append("A read-error occurred during conversion (70)\n");
    fclose(inputfile);
    free(buf);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

  offset = 0;

  for(j=0; j<chns; j++)
  {
    if(j > 0)
    {
      offset += lp[j - 1].bytes;
    }

    bits = 0LL;

    for(i=0; i<lp[j].samples; i++)
    {
      if(sp[2].present == 1)  // huffmantable present
      {
        if((bits / 8LL) > lp[j].bytes)
        {
          textEdit1->append("Error, (bits / 8) >= lp[j].bytes (71)\n");
          fclose(inputfile);
          free(buf);
          free(block);
          pushButton1->setEnabled(true);
          return;
        }

        memcpy(&var, block + offset + ((int)(bits / 8LL)), 5);

        for(k=0; k<5; k++)
        {
          var.four[k] = reverse_bitorder(var.four[k]);
        }

        var.ll_int >>= (int)(bits % 8LL);

        if((var.four[0] & 1) == 0)  // b00000001
        {
          buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = 0;
          bits++;
        } else
        if((var.four[0] & 7) == 1)  // b00000111
        {
          buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = 1;
          bits += 3LL;
        } else
        if((var.four[0] & 7) == 5)  // b00000111
        {
          buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = -1;
          bits += 3LL;
        } else
        if((var.four[0] & 15) == 3)  // b00001111
        {
          buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = 2;
          bits += 4LL;
        } else
        if((var.four[0] & 15) == 11)  // b00001111
        {
          buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = -2;
          bits += 4LL;
        } else
        if((var.four[0] & 31) == 7)  // b00011111
        {
          buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = 3;
          bits += 5LL;
        } else
        if((var.four[0] & 31) == 23)  // b00011111
        {
          buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = -3;
          bits += 5LL;
        } else
        if((var.four[0] & 63) == 15)  // b00111111
        {
          buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = 4;
          bits += 6LL;
        } else
        if((var.four[0] & 63) == 47)  // b00111111
        {
          buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = -4;
          bits += 6LL;
        } else
        if((var.four[0] & 127) == 31)  // b01111111
        {
          buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = 5;
          bits += 7LL;
        } else
        if((var.four[0] & 127) == 95)  // b01111111
        {
          buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = -5;
          bits += 7LL;
        } else
        if(var.four[0] == 63)  // b11111111
        {
          buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = 6;
          bits += 8LL;
        } else
        if(var.four[0] == 191)  // b11111111
        {
          buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = -6;
          bits += 8LL;
        } else
        if(var.four[0] == 127)  // b11111111
        {
          if((var.four[1] & 1) == 0)  // b00000001
          {
            buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = 7;
            bits += 9LL;
          }
          else
          {
            buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = -7;
            bits += 9LL;
          }
        } else
        if(var.four[0] == 255)  // b11111111
        {
          if((var.four[1] & 3) == 0)  // b00000011
          {
            buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = 8;
            bits += 10LL;
          } else
          if((var.four[1] & 3) == 2)  // b00000011
          {
            buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = -8;
            bits += 10LL;
          } else
          if((var.four[1] & 3) == 1)  // b00000011
          {
            var.ll_int >>= 2;
            var.four[1] = reverse_bitorder(var.four[1]);
            buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = *((signed char *)&(var.four[1]));  // 8-bit original
            bits += 18LL;
          } else
          if((var.four[1] & 3) == 3)  // b00000011
          {
            var.ll_int >>= 10;
            ch_tmp = reverse_bitorder(var.four[0]);
            var.four[0] = reverse_bitorder(var.four[1]);
            var.four[1] = ch_tmp;
            buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = *((signed short *)&(var.two[0]));  // 16-bit original
            bits += 26LL;
          }
        }
      }
예제 #28
0
int main ( void )
{
	uint8_t     bld_status;
    uint16_t    length = 0;
    register uint8_t temp, tempSREG;
    void (*start) ( void ) = (void*) 0x0000; // function pointer to application code

    DBG_INIT();

    // disable all interrupts
    cli();

    // move interrupt vector table to bootloader section
    tempSREG = SREG;
    temp = MCUCR;
    MCUCR = temp | (1 << IVCE);     // needed to unlock IVSEL
    MCUCR = temp | (1 << IVSEL);    // set IVSEL (within 4 cycles)
    SREG = tempSREG;

    bld_status = 0;

    // initialize external SPI eeprom
    spi_master_init_blk();
    eep_initialize();

    // check internal EEProm if a new application has to be flashed
    bld_status = eeprom_read_byte(&g_reg_internal_eep[MOD_eCfg_BldFlag]);
    bld_status &= ~((1<<eBldFlagCRCMismatch) |
    		        (1 << eBldFlagControllerTypeMismatch) |
    		        (1 << eBldFlagBoardTypeMismatch));


    if (bld_status & (1<<eBldFlagAppProgram)) {
        bld_status &= ~(1<<eBldFlagAppProgram);
        DBG_SET_PIN0();
        do {
            // check external EEProm
            if (!check_crc(&length)) {
                bld_status |= (1 << eBldFlagCRCMismatch);
                break;
            }
            DBG_SET_PIN1();

            // check controller
            if (!check_controller_id()) {
                bld_status |= (1 << eBldFlagControllerTypeMismatch);
                DBG_SET_PIN5();
                break;
            }

            // check board type
            if (!check_board_type()) {
                bld_status |= (1 << eBldFlagBoardTypeMismatch);
                break;
            }

            // check application ID
            if (has_app_id_changed()) {
                bld_status |= (1 << eBldFlagAppIDChanged);
            }

            // check application version
            if (has_app_version_changed()) {
                bld_status |= (1 << eBldFlagAppVersionChanged);
            }

            DBG_SET_PIN2();

            // flash new application
            program_flash(0, length);

            DBG_SET_PIN3();

            bld_status |= (1 << eBldFlagNewSWProgrammed);
            // re-enable RWW-section again. We need this if we want to jump back
            // to the application after bootloading.
            boot_rww_enable ();
        } while ( false );
        eeprom_write_byte(&g_reg_internal_eep[MOD_eCfg_BldFlag], bld_status);
    }
    DBG_SET_PIN4();

    DBG_ALL_OFF();
    DBG_ALL_ON();
    DBG_ALL_OFF();
    DBG_ALL_ON();
    DBG_ALL_OFF();
    DBG_ALL_ON();
    DBG_ALL_OFF();

    // restore interrupt vector table
    cli();
    temp = MCUCR;
    MCUCR = temp | (1<<IVCE);
    MCUCR = temp & ~(1<<IVSEL);

    // start application
    start();
    return 0;
}
예제 #29
0
void main_loop(void* pvParameters)
{
    int loopcount = 0;
#define SHOW_DEBUG() 0 //((my_state == RUNNING) && (loopcount == 0))


#define SPI_SCLK     4
#define SPI_MISO    27
#define SPI_MOSI     2
#define SPI_CS      GPIO_NUM_16
#define SPI_CE      GPIO_NUM_17

    int power_left = 0;
    int power_right = 0;

#if 0
    int left_x_zero = 512;
    int left_y_zero = 512;
#endif
    int right_x_zero = 512;
    int right_y_zero = 512;
    bool first_reading = true;
    
    auto last_packet = xTaskGetTickCount();

    const int NOF_BATTERY_READINGS = 100;
    int32_t battery_readings[NOF_BATTERY_READINGS];
    int battery_reading_index = 0;
    for (int i = 0; i < NOF_BATTERY_READINGS; ++i)
        battery_readings[i] = 0;

    int max_power = 255;
    
    int count = 0;
    bool led_state = false;
    auto last_led_flip = xTaskGetTickCount();
    bool is_halted = false;

    RF24 radio(SPI_CE, SPI_CS);
    assert(radio_init(radio));

	while (1)
	{
        ++loopcount;
        if (loopcount >= 100)
            loopcount = 0;

        // if there is data ready
        if (radio.available())
        {
            last_packet = xTaskGetTickCount();

            ForwardAirFrame frame;
            // Fetch the payload, and see if this was the last one.
            while (radio.available())
                radio.read(&frame, sizeof(frame));

            if (frame.magic != ForwardAirFrame::MAGIC_VALUE)
            {
                printf("Bad magic value; expected %x, got %x\n", ForwardAirFrame::MAGIC_VALUE, frame.magic);
                continue;
            }

            if (!check_crc(frame))
            {
                printf("Bad CRC\n");
                continue;
            }

            // Echo back tick value so we can compute round trip time
            radio.stopListening();

            ReturnAirFrame ret_frame;
            ret_frame.magic = ReturnAirFrame::MAGIC_VALUE;
            ret_frame.ticks = frame.ticks;
#if 0
            battery_readings[battery_reading_index] = motor_get_battery(motor_device);
            ++battery_reading_index;
            if (battery_reading_index >= NOF_BATTERY_READINGS)
                battery_reading_index = 0;
            int n = 0;
            int32_t sum = 0;
            for (int i = 0; i < NOF_BATTERY_READINGS; ++i)
                if (battery_readings[i])
                {
                    sum += battery_readings[i];
                    ++n;
                }
            // Round to nearest 0.1 V to prevent flickering
            ret_frame.battery = n ? 100*((sum/n+50)/100) : 0;
#endif
            set_crc(ret_frame);
            radio.write(&ret_frame, sizeof(ret_frame));

            radio.startListening();

            frame.right_x = 1023 - frame.right_x; // hack!

#define PUSH(bit)   (is_pushed(frame, bit) ? '1' : '0')
#define TOGGLE(bit) (is_toggle_down(frame, bit) ? 'D' : (is_toggle_up(frame, bit) ? 'U' : '-'))
                
            const int rx = frame.right_x - right_x_zero;
            const int ry = frame.right_y - right_y_zero;

            // Map right pot (0-255) to pivot value (20-51)
            const int pivot = frame.right_pot*2;
            // Map left pot (0-255) to max_power (20-255)
            max_power = static_cast<int>(20 + (256-20)/256.0*frame.left_pot);
            compute_power(rx, ry, power_left, power_right, pivot, max_power);
            ++count;
            if (count > 10)
            {
                count = 0;
                printf("max %d\n", max_power);
                printf("L %4d/%4d R %4d/%4d (%d/%d) P %3d/%3d Push %c%c%c%c"
                       " Toggle %c%c%c%c"
                       " Power %d/%d\n",
                       (int) frame.left_x, (int) frame.left_y, (int) frame.right_x, (int) frame.right_y, rx, ry,
                       int(frame.left_pot), int(frame.right_pot),
                       PUSH(0), PUSH(1), PUSH(2), PUSH(3),
                       TOGGLE(0), TOGGLE(1), TOGGLE(2), TOGGLE(3),
                       power_left, power_right);
#if 0
                if (is_toggle_up(frame, 3))
                    signal_control_lights(signal_device, true, true);
                else if (is_toggle_down(frame, 3))
                    signal_control_lights(signal_device, true, false);
                else
                    signal_control_lights(signal_device, false, true);
#endif
            }
            
            //!!set_motors(power_left, power_right);
            is_halted = false;

#if 0
            if (is_pushed(frame, 0))
                signal_play_sound(signal_device, -1);
#endif
        }
        else
        {
            // No data from radio
            const auto cur_time = xTaskGetTickCount();
            if ((cur_time - last_packet > max_radio_idle_time) && !is_halted)
            {
                is_halted = true;
                printf("HALT: Last packet was seen at %d\n", last_packet);
                first_reading = true;
                set_motors(0, 0);
            }
        }

        // Change LED state every 3 seconds
        const auto cur_time = xTaskGetTickCount();
        if (cur_time - last_led_flip > 3000/portTICK_PERIOD_MS)
        {
            last_led_flip = cur_time;
            led_state = !led_state;
            gpio_set_level(GPIO_INTERNAL_LED, led_state);
        }

        vTaskDelay(1/portTICK_PERIOD_MS);

        //xTaskNotifyWait(0, 0, NULL, 1);
    }
}
예제 #30
0
void CComAdjust::AnalyseComFrame(char *v_szBuf, int v_iLen)
{
	int iRet = 0;
	if( !v_szBuf || v_iLen <= 0 ) 
		return ;

	DWORD dwPacketNum = 0;	
	static int i7ECount = 0;
	static int iFFCount = 0;
	
	for( int i = 0; i < v_iLen; i ++ )
	{
		if( 0x7e == v_szBuf[ i ] )
		{
			++ i7ECount;
			
			if( 0 == i7ECount % 2 ) // 若得到一帧调度屏的数据
			{
				if( 0 != m_iComFrameLen)
				{
					i7ECount = 0;
				
					// 反转义
					m_iComFrameLen = DetranData(m_szComFrameBuf, m_iComFrameLen);
					
					// 计算校验和,校验正确,送入接收队列
					if( check_crc((byte*)m_szComFrameBuf, m_iComFrameLen) )
					{						
						g_iTerminalType = 2;
						iRet = g_objDiaodu.m_objDiaoduReadMng.PushData(LV1, (DWORD)(m_iComFrameLen-1), m_szComFrameBuf+1, dwPacketNum);
						if( 0 != iRet )
						{
							PRTMSG(MSG_ERR, "Push one frame failed:%d\n",iRet);
							memset(m_szComFrameBuf, 0, m_iComFrameLen);
							m_iComFrameLen = 0;
						}
// 						else
// 						{
// 							PRTMSG(MSG_DBG, "push one frame:");
// 							PrintString(m_szComFrameBuf, m_iComFrameLen);
// 						}
					}
					else
					{
						PRTMSG(MSG_ERR, "Diaodu frame check crc err: ");
						PrintString(m_szComFrameBuf, m_iComFrameLen);
						memset(m_szComFrameBuf, 0, m_iComFrameLen);
						m_iComFrameLen = 0;
					}
				}	
					
				//无论校验正确与否,都将缓冲区清0
				memset(m_szComFrameBuf, 0, m_iComFrameLen);
				m_iComFrameLen = 0;
			}
		}
		else if( 0xFF == v_szBuf[i] && 0 == i7ECount%2 )
		{
			++iFFCount;

			if( iFFCount%2 == 0 )	// 收到一帧手柄的数据
			{
				if( 0 != m_iComFrameLen)
				{
					iFFCount = 0;

					g_iTerminalType = 1;

					// 推到手柄的接收队列
					iRet = g_hst.m_objHandleReadMng.PushData(LV1, (DWORD)m_iComFrameLen, m_szComFrameBuf, dwPacketNum);

					if( 0 != iRet )
					{
						PRTMSG(MSG_ERR, "Push one frame failed:%d\n",iRet);
						memset(m_szComFrameBuf, 0, m_iComFrameLen);
						m_iComFrameLen = 0;
					}
// 					else
// 					{
// 						PRTMSG(MSG_DBG, "push one frame:");
// 						PrintString(m_szComFrameBuf, m_iComFrameLen);
// 					}
				}

				memset(m_szComFrameBuf, 0, m_iComFrameLen);
				m_iComFrameLen = 0;
			}
		}
		else
		{
			m_szComFrameBuf[m_iComFrameLen++] = v_szBuf[i];
		}
	}
}