static bool zigbee_protocol_waitAndcheckReply(uint32_t fd, uint8_t* receivedFrame, uint32_t sizeBuffer,
    zigbee_decodedFrame* decodedData)
{
  fd_set rfs;
  struct timeval waitTime;
  bool bSuccess;
  uint16_t nextSizeToRead;
  FD_ZERO(&rfs);
  FD_SET(fd, &rfs);
  waitTime.tv_sec = 2;
  waitTime.tv_usec = 0;
  bSuccess = false;
  nextSizeToRead = 0;

  if (select(fd + 1, &rfs, NULL, NULL, &waitTime) > 0)
  {
    if (FD_ISSET(fd, &rfs))
    {
      bSuccess = serial_read(fd, receivedFrame, 3);
      if (bSuccess)
      {
        bSuccess = zigbee_decodeHeader(receivedFrame, 3, &nextSizeToRead);
      }

      if (bSuccess && ((uint16_t)(3 + nextSizeToRead + 1) <= sizeBuffer))
      {
        bSuccess = serial_read(fd, &receivedFrame[3], nextSizeToRead + 1);
      }
      else
      {
        bSuccess = false;
      }

      if (bSuccess)
      {
        bSuccess = zigbee_decodeFrame(&receivedFrame[3], nextSizeToRead + 1, decodedData);
        if (bSuccess == true)
        {
          display_frame("received (ok)", receivedFrame, nextSizeToRead + 1 + 3);
        }
        else
        {
          display_frame("received (ko)", receivedFrame, nextSizeToRead + 1 + 3);
        }
      }
    }
  }
  else
  {
#ifdef TRACE_ACTIVATED
    fprintf(stdout, "Timeout\n");
#endif // TRACE_ACTIVATED
  }

#ifdef TRACE_ACTIVATED
  fprintf(stdout, "bSuccess = %d nextSizeToRead = %d\n", bSuccess, nextSizeToRead);
#endif // TRACE_ACTIVATED

  return bSuccess;
}
Exemple #2
0
uint8_t GPS_MTK3339::continueRead(){
    #ifdef GPS_DEBUG_READ_VERBOSE
        GPS_DEBUG_READ_PRINTLN("READ GPS CONTINUE");
    #endif
    while(serial_available() > 0){
        char b = (char)serial_read();
        if(b == GPS_START_DELIM){
            GPS_DEBUG_READ_PRINTLN("unexpected start delimiter found");
            _machineState = GPS_MS_ERROR;
            return GPS_ERROR_PARSE_ERR;
        }
        if(b == GPS_CHKSUM_DELIM){
            writeBuffer(b);
            uint32_t ticks = millis();
            while(serial_available() < 2){
                if(millis() - ticks > 250){
                    GPS_DEBUG_READ_PRINTLN("too long to read checksum bytes");
                    _machineState = GPS_MS_ERROR;
                    return GPS_ERROR_TIMEOUT;
                }
            }
            b = serial_read();
            writeBuffer(b);
            
            b = serial_read();
            writeBuffer(b);
            
            writeBuffer(0x00);
            
            return parseSentence();
        }
        writeBuffer(b);
    }
    return GPS_STATUS_READING;
}
Exemple #3
0
static int
shearwater_common_slip_read (shearwater_common_device_t *device, unsigned char data[], unsigned int size)
{
	unsigned int received = 0;

	// Read bytes until a complete packet has been received. If the
	// buffer runs out of space, bytes are dropped. The caller can
	// detect this condition because the return value will be larger
	// than the supplied buffer size.
	while (1) {
		unsigned char c = 0;
		int n = 0;

		// Get a single character to process.
		n = serial_read (device->port, &c, 1);
		if (n != 1) {
			return EXITCODE(n);
		}

		switch (c) {
		case END:
			// If it's an END character then we're done.
			// As a minor optimization, empty packets are ignored. This
			// is to avoid bothering the upper layers with all the empty
			// packets generated by the duplicate END characters which
			// are sent to try to detect line noise.
			if (received)
				return received;
			else
				break;
		case ESC:
			// If it's an ESC character, get another character and then
			// figure out what to store in the packet based on that.
			n = serial_read (device->port, &c, 1);
			if (n != 1) {
				return EXITCODE(n);
			}

			// If it's not one of the two escaped characters, then we
			// have a protocol violation. The best bet seems to be to
			// leave the byte alone and just stuff it into the packet.
			switch (c) {
			case ESC_END:
				c = END;
				break;
			case ESC_ESC:
				c = ESC;
				break;
			}
			// Fall-through!
		default:
			if (received < size)
				data[received] = c;
			received++;
		}
	}

	return received;
}
Exemple #4
0
void term(void)
{
  uint8_t length = 4 + 2*6 + 4; //Se va a enviar HOLA
  char rec[length];
  int n;
  packet_t test_packet;
  test_packet.packet_id = PCK_HEADER;
  test_packet.destination = 0x1023;
  test_packet.source = 0x3211;
  test_packet.number = 0x0001;
  test_packet.length = 0x0004;
  test_packet.packet_type = 0x0012;
  test_packet.reserved = 0x0000;
  drone_ID_to_data(0x01FF,&test_packet);
  printf("%d\r\n",data_to_drone_ID(test_packet));

  send_packet(serial_fd,  test_packet);
  //This code shows that a no read character, remains in the buffer and will be processesed later
  n=serial_read(serial_fd,rec,length,TIMEOUT);
  int i;
  for (i = 0; i < n; i++)  
  {
      printf ("|%02x|", rec[i]);
        
  }
  printf ("\n\r");


  for (i = 0; i < n; i++)  
  {
      printf ("|%c|", rec[i]);
        
  }
  printf ("\n\r");
  fflush(stdout);

  sleep(1);

  n=serial_read(serial_fd,rec,length,TIMEOUT);
    
  for (i = 0; i < n; i++)  
  {
      printf ("|%02x|", rec[i]);
        
  }
  printf ("\n\r");


  for (i = 0; i < n; i++)  
  {
      printf ("|%c|", rec[i]);
        
  }
  printf ("\n\r");
  fflush(stdout);
}
Exemple #5
0
void test_loopback(void) {
    serial_t serial;
    unsigned int count;
    time_t start, stop;
    uint8_t lorem_ipsum[] = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
    uint8_t lorem_hugesum[4096*3];
    uint8_t buf[sizeof(lorem_hugesum)];

    ptest();

    passert(serial_open(&serial, device, 115200) == 0);

    /* Test write/flush/read */
    passert(serial_write(&serial, lorem_ipsum, sizeof(lorem_ipsum)) == sizeof(lorem_ipsum));
    passert(serial_flush(&serial) == 0);
    passert(serial_read(&serial, buf, sizeof(lorem_ipsum), -1) == sizeof(lorem_ipsum));
    passert(memcmp(lorem_ipsum, buf, sizeof(lorem_ipsum)) == 0);

    /* Test poll/write/flush/poll/input waiting/read */
    passert(serial_poll(&serial, 500) == 0); /* Should timeout */
    passert(serial_write(&serial, lorem_ipsum, sizeof(lorem_ipsum)) == sizeof(lorem_ipsum));
    passert(serial_flush(&serial) == 0);
    passert(serial_poll(&serial, 500) == 1);
    usleep(500000);
    passert(serial_input_waiting(&serial, &count) == 0);
    passert(count == sizeof(lorem_ipsum));
    passert(serial_read(&serial, buf, sizeof(lorem_ipsum), -1) == sizeof(lorem_ipsum));
    passert(memcmp(lorem_ipsum, buf, sizeof(lorem_ipsum)) == 0);

    /* Test non-blocking poll */
    passert(serial_poll(&serial, 0) == 0);

    /* Test a very large read-write (likely to exceed internal buffer size (~4096)) */
    memset(lorem_hugesum, 0xAA, sizeof(lorem_hugesum));
    passert(serial_write(&serial, lorem_hugesum, sizeof(lorem_hugesum)) == sizeof(lorem_hugesum));
    passert(serial_flush(&serial) == 0);
    passert(serial_read(&serial, buf, sizeof(lorem_hugesum), -1) == sizeof(lorem_hugesum));
    passert(memcmp(lorem_hugesum, buf, sizeof(lorem_hugesum)) == 0);

    /* Test read timeout */
    start = time(NULL);
    passert(serial_read(&serial, buf, sizeof(buf), 2000) == 0);
    stop = time(NULL);
    passert((stop - start) > 1);

    /* Test non-blocking read */
    start = time(NULL);
    passert(serial_read(&serial, buf, sizeof(buf), 0) == 0);
    stop = time(NULL);
    /* Assuming we weren't context switched out for a second and weren't on a
     * thin time boundary ;) */
    passert((stop - start) == 0);

    passert(serial_close(&serial) == 0);
}
Exemple #6
0
void get_name(void)
{
	int key, i;
	char show_buffer[64] = {0};
	char name[17] = {0};

	while (1) {
        lcd_clrscr();
        lcd_disp_string(0, 0, "      蓝牙名称    ");
	   
	   	/*获取蓝牙地址*/
		serial_clrbuf(CONFIG_BT_SERIAL_NUM, 1, 0);
    	serial_write(CONFIG_BT_SERIAL_NUM, "AT+NAME\r\n", sizeof("AT+NAME\r\n"));
	   	serial_read(CONFIG_BT_SERIAL_NUM, show_buffer, 64, 300);
		if(!strncmp("+NAME=\"", show_buffer, 7)){
            for(i = 0; i < 16; i ++) {
                if (show_buffer[7 + i] == '\"')
                    break;
                name[i] = show_buffer[7 + i];
            }
	   	    lcd_disp_string(0, 16, name);
		}
	   	else
            lcd_disp_string(0, 16, "获取失败");

        key = kb_get_key(0);
        if (key == KEY_ESC)
            return;
    }
}
Exemple #7
0
void get_mac(void)
{
	int key;
	char show_buffer[64];
	char addr[18];

	while (1) {
        lcd_clrscr();
        lcd_disp_string(0, 0, "      蓝牙MAC地址    ");
	   
	   	/*获取蓝牙地址*/
		serial_clrbuf(CONFIG_BT_SERIAL_NUM, 1, 0);
    	serial_write(CONFIG_BT_SERIAL_NUM, "AT+LADDR\r\n", sizeof("AT+LADDR\r\n"));
	   	serial_read(CONFIG_BT_SERIAL_NUM, show_buffer, 64, 300);
		if(!strncmp("+LADDR=", show_buffer, 7)){
            memcpy(addr, show_buffer + 7, 17);
	   	    lcd_disp_string(0, 16, addr);
		}
	   	else
            lcd_disp_string(0, 16, "获取失败");

        key = kb_get_key(0);
        if (key == KEY_ESC)
            return;
    }
}
Exemple #8
0
int main(int argc, char *argv[])
{
	int serial_dev;
	int ret;
	char data[256];

	if (argc < 2) {
		fprintf(stderr, "Please specify serial device to use \r\n");
		return -1;
	}
	
	printf("Serial device to open: %s \r\n", argv[1]);
	
	serial_dev = serial_open(argv[1]);
	if (serial_dev < 0) {
		fprintf(stderr, "Unable to open serial device: %s: %s\r\n", argv[1], strerror(errno));
		return -1;
	}
	
	if (serial_setup(serial_dev, 115200)) {
		fprintf(stderr, "Unable to setup serial device: %s: %s\r\n", argv[1], strerror(errno));
	}

	while (1) {
		serial_write(serial_dev, "Testing");
		ret = serial_read(serial_dev, data, sizeof(data));
		if (ret <= 0) {
			printf("No data available \r\n");
		} else {
			printf("Serial data received:\r\n");
			printf("%s\r\n", data);
		}
		sleep(1);
	}
}
Exemple #9
0
/*
 * Does OLS self-test
 * pump_fd - fd of pump com port
 */
int PUMP_selftest(int pump_fd) 
{
  static const uint8_t cmd[4] = {0x07, 0x00, 0x00, 0x00};
  uint8_t status;
  int res, retry;

  res = serial_write(pump_fd, cmd, 4);
  if (res != 4) return OLSRESULT_CMDWRITE_ERROR;

  retry=0;
  while (1) {
    res = serial_read(pump_fd, &status, 1);
    if (res<1) retry++;

    if (res == 1)
      break;

    // 20 second timenout
    if (retry > 60) 
      return OLSRESULT_TIMEOUT;
  }

  if (status & 0x01) return OLSRESULT_1V2SUPPLY_BAD;
  if (status & 0x02) return OLSRESULT_2V5SUPPLY_BAD;
  if (status & 0x04) return OLSRESULT_PROGB_BAD;
  if (status & 0x08) return OLSRESULT_DONE_BAD;
  if (status & 0x10) return OLSRESULT_UNKNOWN_JEDICID;
  if (status & 0x20) return OLSRESULT_UPDATE_BAD;
  return OLSRESULT_SUCCESS;
}
Exemple #10
0
static void handle_new_data(struct sr_dev_inst *sdi, int dmm, void *info)
{
	struct dev_context *devc;
	int len, i, offset = 0;
	struct sr_serial_dev_inst *serial;

	devc = sdi->priv;
	serial = sdi->conn;

	/* Try to get as much data as the buffer can hold. */
	len = DMM_BUFSIZE - devc->buflen;
	len = serial_read(serial, devc->buf + devc->buflen, len);
	if (len == 0)
		return; /* No new bytes, nothing to do. */
	if (len < 0) {
		sr_err("Serial port read error: %d.", len);
		return;
	}
	devc->buflen += len;

	/* Now look for packets in that data. */
	while ((devc->buflen - offset) >= dmms[dmm].packet_size) {
		if (dmms[dmm].packet_valid(devc->buf + offset)) {
			handle_packet(devc->buf + offset, sdi, dmm, info);
			offset += dmms[dmm].packet_size;
		} else {
			offset++;
		}
	}

	/* If we have any data left, move it to the beginning of our buffer. */
	for (i = 0; i < devc->buflen - offset; i++)
		devc->buf[i] = devc->buf[offset + i];
	devc->buflen -= offset;
}
Exemple #11
0
int get_dht11(serial *s,struct DHT11* data)
{
	int state=0;
//	static int count_err=0;	//连续错误次数
	char buffer[128];

	serial_write(s,"DHT11");
	usleep(90000);
	serial_read(s, buffer, '\n', 128);
	debug("receive from serial's data length is :%d\n",strlen(buffer));
	debug("receive from serial's data content is :%s\n",buffer);

	//判定接收到的字符串长度,小于50失败
	if(strlen(buffer)>50){
		sscanf(buffer,"%*s%*s%*s%*s%d%*s%d",&data->temp,&data->rehum);
		debug("temp:%d rehum:%d\n",data->temp,data->rehum);
		if(data->rehum>100||data->rehum<0||data->temp<0||data->temp>80){
			state=1;
//			count_err++;	//连续错误累加
		}
	}else{
		state=1;
	}

//	if(count_err>=100){	//如果连续错误超过100次,仍然将函数返回值置0,目的是为了让程序跳出死循环
//		state=0;
//	}
//
//	if(state==0){
//		count_err=0;
//	}
	return state;
}
Exemple #12
0
void get_bt_status(void)
{
	int key;
	char show_buffer[50];
	char des[10] = {0};

	while (1) {
        lcd_clrscr();
        lcd_disp_string(0, 0, "      蓝牙状态    ");
	   
		serial_clrbuf(CONFIG_BT_SERIAL_NUM, 1, 0);
    	serial_write(CONFIG_BT_SERIAL_NUM, "AT+STATUS\r\n", sizeof("AT+STATUS\r\n"));
	   	serial_read(CONFIG_BT_SERIAL_NUM, show_buffer, 20, 300);
		if(!strncmp(show_buffer, "+STATUS=", sizeof("+STATUS=") - 1)){
			des[0] = show_buffer[sizeof("+STATUS=") - 1];            
            if (strcmp(des, "2") == 0)
                lcd_disp_string(0, 16, "蓝牙已连接");
            else if (strcmp(des, "1") == 0)
                lcd_disp_string(0, 16, "蓝牙广播中...");
            else if (strcmp(des, "0") == 0)
                lcd_disp_string(0, 16, "蓝牙空闲");
	   		else
                lcd_disp_string(0, 16, "未知状态");
		}
	   	else
            lcd_disp_string(0, 16, "获取失败");

        key = kb_get_key(0);
        if (key == KEY_ESC)
            return;
    }
}
Exemple #13
0
serial_interrupt_rx()
{
	uint8_t end = serial_input.end;

	serial_input.buf[end] = serial_read();
	serial_input.end = (end + 1) & (SERIAL_INBUF - 1);
}
Exemple #14
0
void __attribute__((noreturn)) serial_recv_task(struct vcom * vcom)
{
	struct serial_dev * serial = vcom->serial;
	struct usb_cdc_class * cdc = vcom->cdc;
	uint8_t buf[VCOM_BUF_SIZE];
	int len;

	DCC_LOG1(LOG_TRACE, "[%d] started.", thinkos_thread_self());

	/* wait for line configuration */
	usb_cdc_acm_lc_wait(cdc);

	/* enable serial */
	serial_enable(serial);

	for (;;) {
		len = serial_read(serial, buf, VCOM_BUF_SIZE, 1000);
		if (len > 0) {
//			dbg_write(buf, len);
			if (vcom->mode == VCOM_MODE_CONVERTER) {
				led_flash(LED_AMBER, 50);
				usb_cdc_write(cdc, buf, len);
			}
			if (vcom->mode == VCOM_MODE_SDU_TRACE) {
				led_flash(LED_AMBER, 50);
				sdu_decode(buf, len);
			}
#if RAW_TRACE
			if (len == 1)
				DCC_LOG1(LOG_TRACE, "RX: %02x", buf[0]);
			else if (len == 2)
				DCC_LOG2(LOG_TRACE, "RX: %02x %02x", 
						 buf[0], buf[1]);
			else if (len == 3)
				DCC_LOG3(LOG_TRACE, "RX: %02x %02x %02x", 
						 buf[0], buf[1], buf[2]);
			else if (len == 4)
				DCC_LOG4(LOG_TRACE, "RX: %02x %02x %02x %02x", 
						 buf[0], buf[1], buf[2], buf[3]);
			else if (len == 5)
				DCC_LOG5(LOG_TRACE, "RX: %02x %02x %02x %02x %02x", 
						 buf[0], buf[1], buf[2], buf[3], buf[4]);
			else if (len == 6)
				DCC_LOG6(LOG_TRACE, "RX: %02x %02x %02x %02x %02x %02x", 
						 buf[0], buf[1], buf[2], buf[3], buf[4], buf[5]);
			else if (len == 7)
				DCC_LOG7(LOG_TRACE, "RX: %02x %02x %02x %02x %02x %02x %02x ",
						 buf[0], buf[1], buf[2], buf[3], 
						 buf[4], buf[5], buf[6]);
			else
				DCC_LOG8(LOG_TRACE, "RX: %02x %02x %02x %02x %02x %02x "
						 "%02x %02x ...", buf[0], buf[1], buf[2], buf[3], 
						 buf[4], buf[5], buf[6], buf[7]);
#endif
#if SDU_TRACE
			RX(buf, len);
#endif
		}
	}
}
Exemple #15
0
/****************************************************************
FunctionName    :   GAgent_Local_RecAll
Description     :   receive all of data form local io one time.
                    and put data int local cycle buf.This func will
                    change data 0xff55 isn't SYNC HEAD to 0xff
pgc             :   gagent global struct. 
return          :   void.
****************************************************************/
int32 GAgent_Local_RecAll(pgcontext pgc)
{
    int32 fd;
    int32 available_len =0;
    int32 read_count = 0;
    uint32 offRec;

    fd = pgc->rtinfo.local.uart_fd;
    if(fd < 0)
    {
        return RET_FAILED;
    }

    if(RET_SUCCESS == GAgent_Local_IsDataValid(pgc))
    {
        /* step 1.read data into loopbuf */
        available_len = get_available_buf_space( pos_current, pos_start );
        read_count = serial_read( fd, &hal_RxBuffer[pos_current & HAL_BUF_MASK],available_len );
        offRec = pos_current;
        if(read_count <= 0)
        {
            return read_count;
        }

        pos_current += read_count;

    }

    return read_count;
}
// Process and report status one line of incoming serial data. Performs an initial filtering
// by removing spaces and comments and capitalizing all letters.
void protocol_process()
{
  uint8_t c;
  while((c = serial_read()) != SERIAL_NO_DATA) {
    if ((c == '\n') || (c == '\r')) { // End of line reached
      // Runtime command check point before executing line. Prevent any furthur line executions.
      // NOTE: If there is no line, this function should quickly return to the main program when
      // the buffer empties of non-executable data.
      protocol_execute_runtime();
      if (sys.abort) {
		return;  // Bail to main program upon system abort
      }
      if (char_counter > 0) {// Line is complete. Then execute!
        line[char_counter] = 0; // Terminate string
        report_status_message(protocol_execute_line(line));
      }
      else {
        // Empty or comment line. Skip block.
        report_status_message(STATUS_OK); // Send status message for syncing purposes.
      }
      protocol_reset_line_buffer();
    }
    else {
      if (iscomment) {
        // Throw away all comment characters
        if (c == ')') {
          // End of comment. Resume line.
          iscomment = false;
        }
      }
      else {
        if (c <= ' ') {
          // Throw away whitepace and control characters
        }
        else
		if (c == '/') {
          // Block delete not supported. Ignore character.
        }
        else
        if (c == '(') {
          // Enable comments flag and ignore all characters until ')' or EOL.
          iscomment = true;
        }
        else
        if (char_counter >= LINE_BUFFER_SIZE-1) {
          // Report line buffer overflow and reset
          report_status_message(STATUS_OVERFLOW);
          protocol_reset_line_buffer();
        }
        else
        if (c >= 'a' && c <= 'z') { // Upcase lowercase
          line[char_counter++] = c-'a'+'A';
        }
        else {
          line[char_counter++] = c;
        }
      }
    }
  }
}
void serial_port_serialr (struct serial_port* port)
{
	int			r;

	DBG_LOG(fprintf(debug_log_file, "event: serialr\n"));

	/* The serial port has data ready.  Load into the incoming buffer.
	 * Only make one call here, as some operating systems (like the
	 * Windows implementation) won't quite work properly if multiple
	 * serial_read calls were made in one pass in an attempt to fill
	 * the buffer.  On systems like UNIX where you can make read calls
	 * until errno == EAGAIN the loop should be implemented within
	 * serial_read itself.
	 */
	r = serial_read(
		port->chan,
		port->incoming + port->incomingLen,
		port->incomingBufSz - port->incomingLen);

	if (r >= 0)
	{
		port->incomingLen += r;

	} else if (serial_last_error(port->chan))
	{
		port->lastError.error_code = serial_last_error(port->chan);
		serial_format_error(
			port->chan,
			port->lastError.error_code,
			port->lastError.error_msg,
			sizeof(port->lastError.error_msg));
	}
}
Exemple #18
0
void readSerialCmd() {
	int result;
	char data;
	static uint8_t pos = 0;

	while (serial_available() && (serialMode == SERIALCMDMODE)) { //ATSL changes commandmode while there is a char waiting in the serial buffer.
		result = NOTHING;
		data = serial_read();
		serialData[pos++] = data; //serialData is our global serial buffer
		if (data == SERIALCMDTERMINATOR) {
			if (pos > 3) { // we need 4 bytes
				result = processSerialCmd(pos);
			} else {
				result = ERR;
			}
			pos = 0;
		}
		// check if we don't overrun the buffer, if so empty it
		if (pos > BUFFLEN) {
			result = ERR;
			pos = 0;
		}
		if (result == OK) {
			printf("ok\r\n");
		} else if (result == ERR) {
			printf("error\r\n");
		}
	}
}
Exemple #19
0
void GPS_Read(GpsInfo *pGPS)
{
	
	while(1){
		memset((char *)Gps_str, 0, 512);
		len = serial_read(&GpsDevice, Gps_str, 512);
		
		if(len>0){

			if(strstr(Gps_str,"$GPRMC")!=NULL){
				nmea_parse_GPRMC(Gps_str, len, &vGPRMC);

				pGPS->status    = vGPRMC.status;
				pGPS->lat       = vGPRMC.lat;
				pGPS->ns        = vGPRMC.ns;
				pGPS->lon       = vGPRMC.lon;
				pGPS->ew        = vGPRMC.ew;
				pGPS->speed     = (vGPRMC.speed * NMEA_TUD_KNOTS);
				pGPS->direction = vGPRMC.direction;
				
				break;
			}
		}
	}
}
int get_num_files(serial_handle_t serial_handle) {
    int r;
    char reply[2];


    // flush the serial port
    r = serial_flush(serial_handle);
    if (r < 0) {
        return -1;
    }

    // send the command to request the number of recorded files
    r = serial_write_byte(serial_handle, 0x01);
    if (r < 1) {
        return -1;
    }

    // read the reply, 2 bytes
    r = serial_read(serial_handle, reply, 2, 500*1000);
    if (r < 2) {
        return -1;
    }

    g_debug("cmd 0x01 (get num files), 2-byte response: 0x%02x 0x%02x", reply[0], reply[1]);

    // but only the second byte matters
    return reply[1];
} 
Exemple #21
0
static int read_byte(serial_source src, int non_blocking)
/* Returns: next byte (>= 0), or -1 if no data available and non-blocking is true.
*/
{
  if (src->recv.bufpos >= src->recv.bufused)
    {
      for (;;)
	{
	  int n = serial_read(src, non_blocking, src->recv.buffer, sizeof src->recv.buffer);

	  if (n == 0) /* Can't occur because of serial_read bug workaround */
	    {
	      message(src, msg_closed);
	      return -1;
	    }
	  if (n > 0)
	    {
#ifdef DEBUG
	      dump("raw", src->recv.buffer, n);
#endif
	      src->recv.bufpos = 0;
	      src->recv.bufused = n;
	      break;
	    }
#ifndef LOSE32
	  if (errno == EAGAIN)
	    return -1;
	  if (errno != EINTR)
	    message(src, msg_unix_error);
#endif
    }
    }
  return src->recv.buffer[src->recv.bufpos++];
}
Exemple #22
0
void buffer_clear(serial* s){
	char buffer[128];

	do{
		serial_read(s, buffer, '\n', 128);
	}while(strlen(buffer) > 0);
}
Exemple #23
0
void GPS_Parse_thread(void)
{
    while(1){

		memset((char *)Gps_str, 0, 512);
		len = serial_read(&GpsDevice, Gps_str, 512);
		
		if(len>0){

			if(strstr(Gps_str,"$GPRMC")!=NULL){
				nmea_parse_GPRMC(Gps_str, len, &vGPRMC);

                pthread_rwlock_wrlock(&GPS_rwlock);
				gps_tmp.status    = vGPRMC.status;
				gps_tmp.lat       = (vGPRMC.status == 'A') ? vGPRMC.lat : gps_tmp.lat;
				gps_tmp.ns        = vGPRMC.ns;
				gps_tmp.lon       = (vGPRMC.status == 'A') ? vGPRMC.lon : gps_tmp.lon;
				gps_tmp.ew        = vGPRMC.ew;
				gps_tmp.speed     = (vGPRMC.status == 'A') ? vGPRMC.speed : gps_tmp.speed;
				gps_tmp.direction = vGPRMC.direction;
			    pthread_rwlock_unlock(&GPS_rwlock);
            }
		}

        sleep(2);
	}
}
Exemple #24
0
static dc_status_t
oceanic_vtpro_send (oceanic_vtpro_device_t *device, const unsigned char command[], unsigned int csize)
{
	dc_device_t *abstract = (dc_device_t *) device;

	if (device_is_cancelled (abstract))
		return DC_STATUS_CANCELLED;

	// Send the command to the dive computer.
	int n = serial_write (device->port, command, csize);
	if (n != csize) {
		ERROR (abstract->context, "Failed to send the command.");
		return EXITCODE (n);
	}

	// Receive the response (ACK/NAK) of the dive computer.
	unsigned char response = NAK;
	n = serial_read (device->port, &response, 1);
	if (n != 1) {
		ERROR (abstract->context, "Failed to receive the answer.");
		return EXITCODE (n);
	}

	// Verify the response of the dive computer.
	if (response != ACK) {
		ERROR (abstract->context, "Unexpected answer start byte(s).");
		return DC_STATUS_PROTOCOL;
	}

	return DC_STATUS_SUCCESS;
}
Exemple #25
0
void jeti_update (void) {
	uint8_t c = 0;
	uint8_t res = 0;
	if (jeti_serial_fd >= 0) {
		while ((res = serial_read(jeti_serial_fd, jeti_serial_buf, 1)) > 0) {
			last_connection = time(0);
			c = jeti_serial_buf[0];
//			SDL_Log("jeti: %i: %i (%c)\n", jeti_line_cn, c, c);
			if (c == 254) {
				jeti_line_cn = 0;
			} else if (c == 255) {
				if (jeti_line_cn == 32) {
					strncpy(jeti_line1, jeti_line, 16);
					strncpy(jeti_line2, jeti_line + 16, 16);
//					SDL_Log("jeti: | %s |\n", jeti_line1);
//					SDL_Log("jeti: | %s |\n", jeti_line2);
//					SDL_Log("jeti: --------------------\n");
					if (jeti_button > 0) {
						usleep(10000);
						SDL_Log("jeti: Button: %c\n", jeti_button);
//						serial_write(jeti_serial_fd, jeti_button, 1);
						jeti_button = 0;
					}
					jeti_ok = 1;
				}
			} else if (jeti_line_cn < 32) {
				jeti_line[jeti_line_cn++] = c;
			}
		}
	} else {
		strncpy(jeti_line2, "----------------", 16);
		strncpy(jeti_line2, " no connection  ", 16);
	}
}
Exemple #26
0
static dc_status_t
oceanic_vtpro_transfer (oceanic_vtpro_device_t *device, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize)
{
	dc_device_t *abstract = (dc_device_t *) device;

	// Send the command to the device. If the device responds with an
	// ACK byte, the command was received successfully and the answer
	// (if any) follows after the ACK byte. If the device responds with
	// a NAK byte, we try to resend the command a number of times before
	// returning an error.

	unsigned int nretries = 0;
	dc_status_t rc = DC_STATUS_SUCCESS;
	while ((rc = oceanic_vtpro_send (device, command, csize)) != DC_STATUS_SUCCESS) {
		if (rc != DC_STATUS_TIMEOUT && rc != DC_STATUS_PROTOCOL)
			return rc;

		// Abort if the maximum number of retries is reached.
		if (nretries++ >= MAXRETRIES)
			return rc;
	}

	// Receive the answer of the dive computer.
	int n = serial_read (device->port, answer, asize);
	if (n != asize) {
		ERROR (abstract->context, "Failed to receive the answer.");
		return EXITCODE (n);
	}

	return DC_STATUS_SUCCESS;
}
Exemple #27
0
int SERDATS (void)
{
    unsigned char z;

    if (!serdev)           /* || (serdat&0x4000)) */
		return 0;

    if (waitqueue == 1) {
		intreq |= 0x0800;
		return 1;
    }

    if ((serial_read ((char *)&z)) == 1) {
		waitqueue = 1;
		serdat = 0x4100; /* RBF and STP set! */
		serdat |= ((unsigned int)z) & 0xff;
		intreq |= 0x0800; /* Set RBF flag (Receive Buffer full) */

#if SERIALDEBUG > 1
		write_log ("SERDATS: received 0x%02x --> serdat==0x%04x\n",
			(unsigned int)z, (unsigned int)serdat);
#endif
		return 1;
    }
    return 0;
}
Exemple #28
0
static dc_status_t
oceanic_vtpro_init (oceanic_vtpro_device_t *device)
{
	dc_device_t *abstract = (dc_device_t *) device;

	// Send the command to the dive computer.
	unsigned char command[2] = {0xAA, 0x00};
	int n = serial_write (device->port, command, sizeof (command));
	if (n != sizeof (command)) {
		ERROR (abstract->context, "Failed to send the command.");
		return EXITCODE (n);
	}

	// Receive the answer of the dive computer.
	unsigned char answer[13] = {0};
	n = serial_read (device->port, answer, sizeof (answer));
	if (n != sizeof (answer)) {
		ERROR (abstract->context, "Failed to receive the answer.");
		return EXITCODE (n);
	}

	// Verify the answer.
	const unsigned char response[13] = {
		0x4D, 0x4F, 0x44, 0x2D, 0x2D, 0x4F, 0x4B,
		0x5F, 0x56, 0x32, 0x2E, 0x30, 0x30};
	if (memcmp (answer, response, sizeof (response)) != 0) {
		ERROR (abstract->context, "Unexpected answer byte(s).");
		return DC_STATUS_PROTOCOL;
	}

	return DC_STATUS_SUCCESS;
}
Exemple #29
0
/*
 * erases OLS flash
 * pump_fd - fd of pump com port
 */
int PUMP_FlashErase(int pump_fd, int flashid) {
  static const uint8_t cmd[4] = {0x04, 0x00, 0x00, 0x00};
  uint8_t status;
  int res;
  int retry = 0;

  if (flashid < 0)
    return OLSRESULT_FLASHID_UNKNOWN;

  res = serial_write(pump_fd, cmd, 4);
  if (res != 4)
    return OLSRESULT_CMDWRITE_ERROR;

  while (1) {
    res = serial_read(pump_fd, &status, 1);
    if (res < 1)
      retry++;

    if (res == 1)
      return (status == 0x01) ? OLSRESULT_SUCCESS : OLSRESULT_ERASE_ERROR;

    // 20 second timenout
    if (retry > 60)
      return OLSRESULT_TIMEOUT;
  }

  return OLSRESULT_SUCCESS;
}
Exemple #30
0
int serial_find(int com, int timeout, char* ack1, char* ack2) {
	if (!recvlst) {
		recvlst = List_create();
	}
	int i;
	for (i = 0; i <= timeout * 10; i++) {
		if (!serial_read(com, __serial_buf2)) {
			delay(100);
			continue;
		}	
		console_write(__serial_buf2);

		char* x = strtok(__serial_buf2, "\n");
		while (x != 0) {
			if (ack1 && strstr(x, ack1) == x) {
				return 1;	 
			}
			if (ack2 && strstr(x, ack2) == x) {
				return 1;	 
			}
			x = strtok(0, "\n");
		}						
	}
//	console_write("ERROR/TIMEOUT\n");
	return 0;
}