Exemple #1
0
int main(void) {
	// Create IP connection
	IPConnection ipcon;
	ipcon_create(&ipcon);

	// Create device object
	SolidStateRelay ssr;
	solid_state_relay_create(&ssr, UID, &ipcon);

	// Connect to brickd
	if(ipcon_connect(&ipcon, HOST, PORT) < 0) {
		fprintf(stderr, "Could not connect\n");
		return 1;
	}
	// Don't use device before ipcon is connected

	// Turn relay on/off 10 times with 1 second delay
	int i;
	for(i = 0; i < 5; ++i) {
		millisleep(1000);
		solid_state_relay_set_state(&ssr, true);
		millisleep(1000);
		solid_state_relay_set_state(&ssr, false);
	}

	printf("Press key to exit\n");
	getchar();
	solid_state_relay_destroy(&ssr);
	ipcon_destroy(&ipcon); // Calls ipcon_disconnect internally
	return 0;
}
Exemple #2
0
/*----------------------------------------------------------------------------+
 | This function toggles the DTS line.                                        |
 | It returns 0 if the DSR activity follows the DTR activity.                 |
 | Otherwise it returns 1 if DSR remains inactive when the DTR is toggled or  |
 | -1 if the DSR remains active regardless.                                   |
 +----------------------------------------------------------------------------*/
int cm10a_cable_check_full ( void )
{
   int status, savestatus;

   ioctl(tty, TIOCMGET, &status);
   savestatus = status;

   status &= ~TIOCM_DTR;
   ioctl(tty, TIOCMSET, &status);
   millisleep(10);
   ioctl(tty, TIOCMGET, &status);
   if ( status & TIOCM_DSR ) {
      ioctl(tty, TIOCMSET, &savestatus);
      return -1;
   }

   status |= TIOCM_DTR;
   ioctl(tty, TIOCMSET, &status);
   millisleep(10);
   ioctl(tty, TIOCMGET, &status);
   if ( !(status & TIOCM_DSR) ) {
      ioctl(tty, TIOCMSET, &savestatus);
      return 1;
   }

   ioctl(tty, TIOCMSET, &savestatus);

   return 0;
}   
static int can_echo_gen(void)
{
	struct can_frame tx_frames[CAN_MSG_COUNT];
	struct can_frame rx_frame;
	unsigned char counter = 0;
	int send_pos = 0, recv_pos = 0, unprocessed = 0, loops = 0;
	int i;

	while (running) {
		if (unprocessed < CAN_MSG_COUNT) {
			/* still send messages */
			tx_frames[send_pos].can_dlc = CAN_MSG_LEN;
			tx_frames[send_pos].can_id = CAN_MSG_ID;
			for (i = 0; i < CAN_MSG_LEN; i++)
				tx_frames[send_pos].data[i] = counter + i;
			if (send_frame(&tx_frames[send_pos]))
				return -1;

			/* increment to be equal to expected */
			tx_frames[send_pos].can_id++;
			for (i = 0; i < CAN_MSG_LEN; i++)
				tx_frames[send_pos].data[i]++;

			send_pos++;
			if (send_pos == CAN_MSG_COUNT)
				send_pos = 0;
			unprocessed++;
			if (verbose == 1)
				echo_progress(counter);
			counter++;

			if ((counter % 33) == 0)
				millisleep(3);
			else
				millisleep(1);
		} else {
			if (recv_frame(&rx_frame))
				return -1;

			if (verbose > 1)
				print_frame(&rx_frame);

			/* compare with expected */
			compare_frame(&tx_frames[recv_pos], &rx_frame);

			loops++;
			if (test_loops && loops >= test_loops)
				break;

			recv_pos++;
			if (recv_pos == CAN_MSG_COUNT)
				recv_pos = 0;
			unprocessed--;
		}
	}

	printf("\nTest messages sent and received: %d\n", loops);

	return 0;
}
Exemple #4
0
static void *longload_new(t_float f)
{
  t_longload *x = (t_longload *)pd_new(longload_class);
  if(f>0.f)
    millisleep(f);
  else
    millisleep(1000);
  return (x);
}
Exemple #5
0
	void semaphore::wait()
	{
		value_type uOld;
		value_type uVal=aValue.fetch();
		for (;;)
		{
			// if we have data
			if (uVal)
			{
				// if we successfully decrement the value
				if ((uOld=aValue.cas(uVal,uVal-1))==uVal)
					// we're done
					return;
				// unrolling a check to alternate checking uOld and uVal for optimization purposes.
				if (uOld)
				{
					// if we successfully decrement the value
					if ((uVal=aValue.cas(uOld,uOld-1))==uOld)
						// we're done
						return;
					// uVal has the value again, let the outer comparison take over
					continue;
				}
				// if we get here, we may failed to swap once and the current value is != 0
			}
			// if we have no data, this is different than simply being beaten by another thread on the update
			// so we'll put a delay here while we wait for a post() to complete. 
			millisleep(poll_rate);
			// retrieve the value after the sleep
			uVal=aValue.fetch();
		}	
	}
Exemple #6
0
/*----------------------------------------------------------------------------+
 | Reset CM17A to the power-up state - with no log message.                   |
 +----------------------------------------------------------------------------*/
int reset_cm17a_quiet ( void ) 
{
   int status, retcode;

   retcode = ioctl(tty, TIOCMGET, &status);
   status &= FC_RESET;
   retcode |= ioctl(tty, TIOCMSET, &status);
   millisleep(10);

   retcode = ioctl(tty, TIOCMGET, &status);
   status = (status & FC_RESET) | FC_STANDBY;
   retcode |= ioctl(tty, TIOCMSET, &status);
   millisleep(500);

   return retcode;
}
Exemple #7
0
main(int ac, char *av[])
{
	char	msg[] = " Hello ";		/* notice padding spaces */
	int	dir = +1;
	int	pos = LEFTEDGE ;
	int	delay = TICKS;

	if ( ac > 1 )
		delay = atoi( av[1] );

	initscr();
	clear();

	while(1){
		move(ROW,pos);
		addstr( msg );			/* draw it */
		move(0,0);
		printw("pos = %02d", pos);
		refresh();
		pos += dir;			/* advance position	*/
		if ( pos >= RIGHTEDGE )		/* check for bounce	*/
			dir = -1;
		if ( pos <= LEFTEDGE )
			dir = +1;
		millisleep(delay);
	}
}
Exemple #8
0
void print_str_slowly(const char *str)
{
	for (; *str; str++) {
		addch(*str);
		refresh();
		millisleep(100);
	}
}
Exemple #9
0
	void mutex::lock()
	{
		// try to acquire an unclaimed lock 
		while (!aValue.bool_cas(0,1))
		{
			millisleep(poll_rate);
		}
	}
Exemple #10
0
/* returns the last stored handshake packet.
 */
static int get_last_packet(gnutls_session_t session, gnutls_handshake_description_t htype,
  handshake_buffer_st * hsk)
{
handshake_buffer_st* recv_buf = session->internals.handshake_recv_buffer;

  if (IS_DTLS(session))
    {
      if (session->internals.handshake_recv_buffer_size == 0 ||
        (session->internals.dtls.hsk_read_seq != recv_buf[LAST_ELEMENT].sequence))
        goto timeout;

      if (htype != recv_buf[LAST_ELEMENT].htype)
        {
          hsk->htype = recv_buf[LAST_ELEMENT].htype;
          return gnutls_assert_val(GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET);
        }

      else if ((recv_buf[LAST_ELEMENT].start_offset == 0 &&
        recv_buf[LAST_ELEMENT].end_offset == recv_buf[LAST_ELEMENT].length -1) || 
        recv_buf[LAST_ELEMENT].length == 0)
        {
          session->internals.dtls.hsk_read_seq++;
          _gnutls_handshake_buffer_move(hsk, &recv_buf[LAST_ELEMENT]);
          session->internals.handshake_recv_buffer_size--;
          return 0;
        }
      else
        goto timeout;
    }
  else /* TLS */
    {
      if (session->internals.handshake_recv_buffer_size > 0 && recv_buf[0].length == recv_buf[0].data.length)
        {
          if (cmp_hsk_types(htype, recv_buf[0].htype) == 0)
            {
              hsk->htype = recv_buf[LAST_ELEMENT].htype;
              return gnutls_assert_val(GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET);
            }

          _gnutls_handshake_buffer_move(hsk, &recv_buf[0]);
          session->internals.handshake_recv_buffer_size--;
          return 0;
        }
      else
        return gnutls_assert_val(GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE);
    }

timeout:
  if (time(0)-session->internals.dtls.handshake_start_time > session->internals.dtls.total_timeout/1000) 
    return gnutls_assert_val(GNUTLS_E_TIMEDOUT);
  else
    {
      if (session->internals.dtls.blocking != 0)
        millisleep(50);
        
      return gnutls_assert_val(GNUTLS_E_AGAIN);
    }
}
Exemple #11
0
/*****************************************************************************
*
* Read the contents of the EEPROM memory and verify that it matches the data
* written to the EEPROM originally.
*
* @param	None.
*
* @return	0 if successful, else -1.
*
* @note		None.
*
*****************************************************************************/
int validate_iic_eeprom_memory(iic_eeprom_demo_t *pDemo)
{
	int8u ChipAddress = IIC_EEPROM_SLAVE_ADDRESS;
	int8u RegAddress  = 0x00;
	int8u WriteData[8], ReadData[8];
	int8u ByteCount   = 0;
	int8u page = 0;
	int ret, i;

    // Begin printing the content table to the terminal.
    xil_printf("+----------------------------------------------------------------------------+\r\n");
    xil_printf("|                        Validating IIC EEPROM Contents                      |\r\n");
    xil_printf("|----------------------------------------------------------------------------|\r\n");

    ByteCount   = 8;

    // Display all of the data from the EEPROM memory to the terminal.
	while (page < 32)
	{
		RegAddress = page*8;

		for (i=0;i<8;i++){
			WriteData[i] = RegAddress+i;
		}

		ret = pDemo->eeprom_iic.fpIicWrite(&(pDemo->eeprom_iic), ChipAddress, RegAddress, WriteData, ByteCount);
		if (!ret)
		{
			xil_printf("ERROR : Failed to Write to EEPROM\n\r");
			return -1;
		}
		millisleep(5);

		ret = pDemo->eeprom_iic.fpIicRead(&(pDemo->eeprom_iic), ChipAddress, RegAddress, ReadData, ByteCount);
		if (!ret)
		{
			xil_printf("ERROR : Failed to Read from EEPROM\n\r");
			return -1;
		}

		for (i=0; i<8;i++){
			if (WriteData[i] != ReadData[i]){
				xil_printf("ERROR : Validation failed at Address: 0x%02X\n\r", RegAddress + i);
				return -1;
			}
		}

		xil_printf("Data write and read verified for address range 0x%02X - 0x%02X\n\r", RegAddress, RegAddress + i);

		page++;
    }

    // Finish printing the content table to the terminal.
    xil_printf("+----------------------------------------------------------------------------+\r\n");
    xil_printf("\r\n");

    return 0;
}
Exemple #12
0
/*****************************************************************************
*
* Read the contents of the EEPROM memory and dump it to the terminal.
*
* @param	None.
*
* @return	0 if successful, else -1.
*
* @note		None.
*
*****************************************************************************/
int default_iic_eeprom_memory(iic_eeprom_demo_t *pDemo)
{
	int8u ChipAddress = IIC_EEPROM_SLAVE_ADDRESS;
	int8u RegAddress  = 0x00;
	int8u WriteData[8];
	int8u ByteCount = 8;
	int8u TotalByteCount = 0;
	int ret,i;

	xil_printf("Defaulting I2C EEPROM...");

	while (TotalByteCount < 128){
		for (i=0;i<8;i++){
			WriteData[i] = default_idt_config[TotalByteCount+i];
		}
		ByteCount = i;
		RegAddress = TotalByteCount;
		ret = pDemo->eeprom_iic.fpIicWrite(&(pDemo->eeprom_iic), ChipAddress, RegAddress, WriteData, ByteCount);
		if (!ret)
		{
			xil_printf("\n\rERROR : Failed to Write to EEPROM\n\r");
			return -1;
		}
		millisleep(5);
		TotalByteCount = TotalByteCount+8;
	}

	for (i=0;i<5;i++){
		WriteData[i] = default_idt_config[TotalByteCount+i];
	}
	ByteCount = i;
	RegAddress = TotalByteCount;
	ret = pDemo->eeprom_iic.fpIicWrite(&(pDemo->eeprom_iic), ChipAddress, RegAddress, WriteData, ByteCount);
	if (!ret)
	{
		xil_printf("\n\rERROR : Failed to Write to EEPROM\n\r");
		return -1;
	}
	millisleep(5);

	xil_printf("Done!\r\n");
	xil_printf("\r\n");

    return 0;
}
Exemple #13
0
int waitForStatusAndBlink(int statusIndex, int statusValue, int blinkGreen, int blinkRed, long timeout)
{
	int* status;
	
	int yesNo = 0;
	
	struct timeval startTime;
	struct timeval testTime;
	long timeDiff;
			
	if (timeout > 0)
	{
		gettimeofday(&startTime, NULL);
	}
	
	do {
		status = GetSensorStatus();
		
		if(status[statusIndex] == statusValue)
		{
			SetLedStatus(0, 0);
			return 1;
		}
		else
		{
			if(yesNo == 0)
			{
				if(blinkGreen)
				{
					SetLedStatus(1, 0);
				}
				else if (blinkRed)
				{
					SetLedStatus(0, 1);
				}		
			}
			else
			{
				SetLedStatus(0, 0);
			}
			yesNo = !yesNo;
			
			millisleep(BLINKING_SLEEP_TIME);
		}
		
		free(status);
		
		if (timeout > 0)
		{
			gettimeofday(&testTime, NULL);
			timeDiff = (testTime.tv_usec + 1000000 * testTime.tv_sec) - (startTime.tv_usec + 1000000 * startTime.tv_sec);			
		}
	}
	while(timeout == 0 || timeDiff < (timeout * 1000));
	
	return 0;
}
Exemple #14
0
void sleep(unsigned int seconds)
{
	int i = 0;

	//xil_printf( "sleep(%d)...\n\r", seconds );

	for (i=0; i<seconds; i++)
	{
		millisleep(1000);
	}
}
Exemple #15
0
static int fallback_wait(double timeout) {
	if (timeout < 0) timeout = 9999999.0; /* really a dummy high number */
	while (1) {
		/* use 100ms slices */
		double slice = (timeout > 0.1) ? 0.1 : timeout;
		if (slice <= 0.0) break;
		millisleep(slice);
		R_CheckUserInterrupt(); /* FIXME: we should adjust for time spent processing events */
		timeout -= slice;
	}
	return WAIT_TIMEOUT;
}
Exemple #16
0
/*----------------------------------------------------------------------------+
 | Toggle the RTS serial line off, then back on                               |
 +----------------------------------------------------------------------------*/
int toggle_rts( void ) 
{
   int retcode;

   retcode = turn_rts_off();

   millisleep(100);

   retcode |= turn_rts_on();

   return retcode;
}
Exemple #17
0
static int audiounits_wait(void *usr, double timeout) {
	au_instance_t *p = (au_instance_t*) usr;
	if (timeout < 0) timeout = 9999999.0; /* really a dummy high number */
	while (p == NULL || !p->done) {
		/* use 100ms slices */
		double slice = (timeout > 0.1) ? 0.1 : timeout;
		if (slice <= 0.0) break;
		millisleep(slice);
		R_CheckUserInterrupt(); /* FIXME: we should adjust for time spent processing events */
		timeout -= slice;
	}
	return (p && p->done) ? WAIT_DONE : WAIT_TIMEOUT;
}
Exemple #18
0
bool cometd_connect(cometd_client_t * client, cometd_message * msg) {
	CMTD_TRACE_IN
	CALLOC(cometd_message, message);
	cometd_client_impl* cli = (cometd_client_impl*)client;
	message->channel = META_CONNECT;
	message->version = DEFAULT_VERSION;
	message->clientId = cli->clientId;
	message->connectionType = LONG_POLLING;
	if (msg && msg->advice.interval)
		millisleep(msg->advice.interval);
	client->transport->sender(client->transport, message, client, false);
	CMTD_RETURN(false);
}
Exemple #19
0
int main(int ac, char **av) {
  int px[2], py[2];
  pthread_attr_t ta;
  pthread_t pt;

  struct tis tx={0,1}, ty={0,2};
  int rv, cwait=0;

  if (ac<3) {
    fprintf(stderr, "\n Usage: consh <command> <logfile> [-a]\n\n");
    return 1;
  }

  lf = fopen(av[2], (ac>3 && !strcmp(av[3],"-a"))?"a":"w");
  if (!lf)
    fprintf(stderr, "*** ERROR: consh unable to create %s, all output will be lost\n", av[2]); 

  pipe(px);
  pipe(py);
  dup2(px[1], STDOUT_FILENO); tx.fd=px[0];
  dup2(py[1], STDERR_FILENO); ty.fd=py[0];
  
  pthread_attr_init(&ta);
  pthread_attr_setdetachstate(&ta, PTHREAD_CREATE_DETACHED);
  pthread_create(&pt, &ta, wt, &tx);
  pthread_create(&pt, &ta, wt, &ty);
  rv=system(av[1]);
  closing=1;
  fflush(stderr);
  fflush(stdout);
  fclose(stderr);
  fclose(stdout);
  while (done!=3 && cwait<50) { /* don't wait more than 5s for flush */
    millisleep(100);
    cwait++;
  }
  if (lf) {
    if (last_type) fprintf(lf, "%s\n", suffix[last_type]);
    fflush(lf);
    fprintf(lf, "[[system return code 0x%x]]\n", rv);
    fclose(lf);
  }
  if (rv != 0) {
    if (rv>0 && rv!=127)
      rv=WEXITSTATUS(rv);
    else
      rv=127;
  }
  return rv;
}
Exemple #20
0
void wait_next_tick (void )
{
   time_t first, now;
   int j;

   time(&first);
   
   for ( j = 0; j < 25; j++ ) {
      time(&now);
      if ( now > first )
         break;
      millisleep(50);
   }
   return;
}   
Exemple #21
0
int main()
{
    ThreadPool pool( 5, 200 );
    pool.start();
    
    for( int i = 0; i < 200; i++)
    {
        pool.pushTask( new HelloTask( i ) );
    }

    while( pool.getTaskSize() > 0 )
    {
        millisleep( 1 * 1000 );
    }
    
    printf( "task done!\n" );
    millisleep( 10 * 1000 );
    printf( "continue...\n" );

    pool.stop();
    millisleep( 2 * 1000 );

    return 0;
}
int main(void) {
	// Create IP connection
	IPConnection ipcon;
	ipcon_create(&ipcon);

	// Create device object
	OLED64x48 oled;
	oled_64x48_create(&oled, UID, &ipcon);

	// Connect to brickd
	if(ipcon_connect(&ipcon, HOST, PORT) < 0) {
		fprintf(stderr, "Could not connect\n");
		return 1;
	}
	// Don't use device before ipcon is connected

	// Clear display
	oled_64x48_clear_display(&oled);

	// Draw rotating line
	gdImagePtr image = gdImageCreate(WIDTH, HEIGHT);
	int black = gdImageColorAllocate(image, 0, 0, 0);
	int white = gdImageColorAllocate(image, 255, 255, 255);
	int origin_x = WIDTH / 2;
	int origin_y = HEIGHT / 2;
	int length = HEIGHT / 2 - 2;
	int angle = 0;

	printf("Press ctrl+c exit\n");

	while (true) {
		double radians = M_PI * angle / 180.0;
		int x = (int)(origin_x + length * cos(radians));
		int y = (int)(origin_y + length * sin(radians));

		gdImageFilledRectangle(image, 0, 0, WIDTH, HEIGHT, black);
		gdImageLine(image, origin_x, origin_y, x, y, white);

		draw_image(&oled, image);
		millisleep(25);

		angle++;
	}

	gdImageDestroy(image);
	ipcon_destroy(&ipcon); // Calls ipcon_disconnect internally
	return 0;
}
Exemple #23
0
/*----------------------------------------------------------------------------+
 | Ask the CM10A to identify itself.                                          |
 +----------------------------------------------------------------------------*/
int c_cm10a_ident ( int argc, char *argv[] )	
{
    unsigned char buf[50];
    unsigned char *bp;
    int      j, count, nread, left;
    extern void millisleep();
    
    if ( (toggle_rts()) != 0 ) {
       fprintf(stderr, "Unable to toggle RTS line.\n");
       return 1;
    }

    bp = buf;
    nread = 0; left = 30;
    for ( j = 0; j < 3; j++ ) {
       count = exread(sptty, bp, left, 1);
       nread += count;
       if ( nread == 29 ) {
          if ( memcmp(buf, cm10a_standard_response, 29) == 0 ) {
             printf("CM10 is connected.\n");
	     check4poll(0,1);
             return 0;
          }
          else {
             fprintf(stderr, "Non-standard CM10A response.\n");
	     check4poll(0,1);
             return 1;
          }
       }
       bp += count;
       left -= count;
       millisleep(10);
   }
 
   if ( nread == 0 ) {    
     fprintf(stderr, "No response from CM10A\n");
   }
   else {
     fprintf(stderr, "Invalid response, %d bytes returned.\n", nread);
   }

   return 1;
}
Exemple #24
0
//
//	Function		:
//		lock_mutex()
//
//	Arguments		:
//		lock			a pointer to an initialized mutex
//						to lock.
//
//	Description		:
//		Locks a mutex for a thread.
//
//	Return value	:
//		None
//
static void
lock_mutex( pthread_mutex_t * lock )
{
	int	status;

	for (;;)
	{
		if ( (status = pthread_mutex_trylock( lock )) == 0 )
			break;
		else 
		if ( status != EBUSY )
		{
			NETERROR( 	MISPD,
						("ispd_init.c : mutex lock error\n" ));
		}

		millisleep( 500 );
	}
}
Exemple #25
0
		void mutex::lock()
		{
			atomic_uint_value_t uOld,uSelf;

			if (!numeric::convert(static_cast<const uintpid_t&>(self_pid()),uSelf))
				throw std::runtime_error("ERROR: pids have more significant bits than our atomic type supports!");

			// try to acquire an unclaimed lock 
			while ((uOld=aValue.cas(0,uSelf)) != 0)
			{
				// if this pid holds the mutex already, there's no point in doing reclaimation. (and no reusing the lock)
				// so, if we detect uOld to be dead even for a moment, we know the mutex is permanently locked (pid crashed
				// or forgot to unlock before close).. so we can try to swap the lock to our own.
				if (uOld != uSelf && dead_process(uOld) && aValue.bool_cas(uOld,uSelf)) { isReclaimed=true; return; }
				// otherwise, the lock cannot be contested, so we wait for data.
				millisleep(poll_rate);
			}
			isReclaimed=false;
		}
Exemple #26
0
/*****************************************************************************
*
* Read the contents of the EEPROM memory and dump it to the terminal.
*
* @param	None.
*
* @return	0 if successful, else -1.
*
* @note		None.
*
*****************************************************************************/
int erase_iic_eeprom_memory(iic_eeprom_demo_t *pDemo)
{
	int8u ChipAddress = IIC_EEPROM_SLAVE_ADDRESS;
	int8u RegAddress  = 0x00;
	int8u WriteData[8];
	int8u ByteCount   = 0;
	int8u page = 0;
	int ret, i;

	xil_printf("Erasing I2C EEPROM...");

    //ret = pDemo->eeprom_iic.fpIicWrite(&(pDemo->eeprom_iic), ChipAddress, RegAddress, RegData, ByteCount);

    ByteCount   = 8;

    // Erasing all data from the EEPROM memory.
    while (page < 32)
	{
		RegAddress = page*8;

		for (i=0;i<8;i++){
			WriteData[i] = 0xFF;
		}

		ret = pDemo->eeprom_iic.fpIicWrite(&(pDemo->eeprom_iic), ChipAddress, RegAddress, WriteData, ByteCount);
		if (!ret)
		{
			xil_printf("\n\rERROR : Failed to Write to EEPROM\n\r");
			return -1;
		}
		millisleep(5);

		page++;
    }

    // Finish printing the content table to the terminal.
    xil_printf("Done!\r\n");
    xil_printf("\r\n");

    return 0;
}
Exemple #27
0
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
bool ClientConnection::connect()
{
	unsigned login_retry_interval, login_retries, attempts(0);
	bool reset_sequence_numbers;
	default_appl_ver_id davi;
	_session.get_login_parameters(login_retry_interval, login_retries, davi, reset_sequence_numbers);

	Poco::Timespan timeout(1000000);

	while (attempts < login_retries)
	{
		ostringstream ostr;

		try
		{
			ostr.str("");
			ostr << "Trying to connect to: " << _addr.toString() << " (" << ++attempts << ')';
			_session.log(ostr.str());
			_sock->connect(_addr, timeout);
			_sock->setLinger(false, 0);
			_sock->setNoDelay(_no_delay);
			_session.log("Connection successful");
			return _connected = true;
		}
		catch (exception& e)	// also catches Poco::Net::NetException
		{
			ostr.str("");
			ostr << "exception: ";
			if (dynamic_cast<Poco::Exception*>(&e))
				ostr << (static_cast<Poco::Exception&>(e)).displayText();
			else
				ostr << e.what();
			_session.log(ostr.str());
			millisleep(login_retry_interval);
		}
	}

	_session.log("Connection failed");
	return false;
}
Exemple #28
0
/******************************************************************************
 * sendCmd(...)
 * Sends the given string to the given open serial port, retries sending when
 * not completely done and returns with an error when send was not completed
 * after MAX_TX_RETRY retries or 0 when everything is sent.
 *****************************************************************************/
int
sendCmd(PORT_STAT *pstat, const char *data)
{
  int retval = 0;
  int len = strlen(data);
  int i = 0;
  int retry_cnt = 0;

  pthread_mutex_lock(&pstat->mutex_rx);
  pstat->protocol_stat = PSTAT_TX_CMD_START;
  pstat->rx_cnt = 0;
  pstat->tail = pstat->head;
  pstat->rxstr[0] = '\0';
  pthread_mutex_unlock(&pstat->mutex_rx);

  do {
    retval = write(pstat->fd, &(data[i]), len);
    if (retval != len && retval > 0) {
      //device output buffer full
      //wait some ms then try to send the remaining bytes
      sys_debug_log(3, "tx congestion on serial port %s.",
                        pstat->dev_name);
      millisleep(SAMPLE_MS);
      len -= retval;
      i += retval;
      retry_cnt++;
    }
  } while ((retval != len && retval > 0) && (retry_cnt < MAX_TX_RETRY));

  if  (retry_cnt > MAX_TX_RETRY) {
    sys_log(ILOG_ERR, "tx congestion on serial port %s after %i retries.",
                       pstat->dev_name, MAX_TX_RETRY);
    pstat->protocol_stat = PSTAT_TX_CMD_SEND_FAIL;
    return -1;
  }

  pstat->protocol_stat = PSTAT_TX_CMD_SENT;
  return 0;
}
Exemple #29
0
int waitForStatus(int statusIndex, int statusValue, long timeout)
{
	int* status;	
	
	struct timeval startTime;
	struct timeval testTime;
	long timeDiff;
	
	if (timeout > 0)
	{
		gettimeofday(&startTime, NULL);
	}

	do {
		status = GetSensorStatus();
		
		if(status[statusIndex] == statusValue)
		{
			return 1;
		}
		else
		{
			millisleep(WAITING_SLEEP_TIME);
		}
		
		free(status);
		
		if (timeout > 0)
		{
			gettimeofday(&testTime, NULL);
			timeDiff = (testTime.tv_usec + 1000000 * testTime.tv_sec) - (startTime.tv_usec + 1000000 * startTime.tv_sec);			
		}
	}
	while(timeout == 0 || timeDiff < (timeout * 1000));
	
	return 0;
}
Exemple #30
0
//
//	Function :
//		conf_inetd()
//
//  Arguments       :
//		None
//
//
//	Description :
//		This function adds the appropriate entries to
//		inetd.conf and rpc in the safest way.
//
//	Return Values:
//		None
//
static void
conf_inetd( void )
{
	FILE *			cmdfile;

	// The following command appends appropriate lines to
	// inetd.conf and rpc in etc if they are not already there
	// and tells inetd to reread the input files. only works
	// properly with the real popen.

	char *	command = 
		"/bin/sh -c \'"
			"PATH=/usr/bin:/sbin:/bin;"
			"grep \"^ispd\" /etc/inetd.conf >/dev/null 2>&1;"
			"if [ $? != 0 ]; then"
			"	echo \"ispd/1\ttli\trpc/tcp\twait\troot"
			"\t/usr/local/nextone/bin/ispd\tispd\"	>>/etc/inetd.conf;"
			"fi;"
			"grep \"^ispd\" /etc/rpc >/dev/null 2>&1;"
			"if [ $? != 0 ]; then"
			"	echo \"ispd\t540000001\" >>/etc/rpc;"
			"fi;"
			"pkill -HUP -x inetd;\'";

	//
	// Issue command to configure inetd for ispd and
	// tell inetd to re-read configuration files.
	//

	if ( ( cmdfile = popen( command, "r" ) ) >= 0 )
	{
		pclose( cmdfile );
	}

	millisleep(1000);
}