Ejemplo n.º 1
1
// buffer can stay in RAM of Flash
// ret -1 = error, ret 0 = disconnected
int32_t MTD_FLASHMEM Socket::write(void const *buffer, uint32_t length) {
  static uint32_t const MAXCHUNKSIZE = 128;

  if (!checkConnection())
    return -1;

  int32_t bytesSent = 0;
  // send in chunks of up to MAXCHUNKSIZE bytes
  uint8_t rambuf[min(length, MAXCHUNKSIZE)];
  uint8_t const *src = (uint8_t const *)buffer;
  while (bytesSent < length) {
    uint32_t bytesToSend = min(MAXCHUNKSIZE, length - bytesSent);
    f_memcpy(rambuf, src, bytesToSend);
    int32_t chunkBytesSent =
        m_remoteAddress.sin_len == 0
            ? lwip_send(m_socket, rambuf, bytesToSend, MSG_DONTWAIT)
            : lwip_sendto(m_socket, rambuf, bytesToSend, 0, (sockaddr *)&m_remoteAddress, sizeof(m_remoteAddress));
    int32_t lasterr = getLastError();
    if (lasterr == EAGAIN || lasterr == EWOULDBLOCK) {
      chunkBytesSent = 0;
    } else if (chunkBytesSent <= 0 || lasterr != 0) {
      // error
      bytesSent = -1;
      break;
    }
    bytesSent += chunkBytesSent;
    src += chunkBytesSent;
  }
  if (length > 0)
    m_connected = (bytesSent > 0);
  return bytesSent;
}
Ejemplo n.º 2
0
void * readClient(void *fd) //thread function to read client input
{
	int sd = *(int*)fd;
	char clibuff[BUFFSIZE]="";
	char *token="";
	while(strcmp(token,"exit\n\0")!=0) //while exit condition is not provided by the user
	{
		bzero(clibuff, BUFFSIZE); //clearing out the buffer to recieve the command
		int size_input=read(0, clibuff, BUFFSIZE);
		if(!checkConnection(sd)) exit(0);
		
		//update information if command is start
		if(strncmp(clibuff,"start",5)==0){
			strncpy(startedsession,clibuff+6,size_input-6);		// store the name of session
			startedsession[size_input-4]=='\0';
			finished=0;											//session started, not finished
			sockd=sd;											//update global variable 
			}
		else if(strncmp(clibuff,"finish",6)==0)					//update finished flag to 1
			finished=1;
			
		write(sd, clibuff, size_input);
		sleep(2);
		if(!checkConnection(sd)) exit(0);
		token=strtok(clibuff, "0");
	}	
	commandControl=1; //thread sync
	exit(0);
	return 0;
}
Ejemplo n.º 3
0
  /*! 
   * Very important function, allows all modules to sleep/start from 
   * send commands. Also if the module has been designated as a interupt
   * module then it will send back false for failure also can have 
   * additional data on how well the module has done 
   */
  void SamgarModule::SucceedFail( bool Awns, double additionaldata ) {
    if( modulemode == ModeInterupt ) {// only send it when you got
				      // worthwhile data
      Bottle &MyBottle = prepare();
      MyBottle.clear();
      MyBottle.addInt( ActivationCode ); // so it knows its a log report
      MyBottle.addString(MyName.c_str());
      MyBottle.addDouble(additionaldata);
      if(getOutputCount()>0)
        write(); 
      currentmode = StateStoped;
    }
    long i;
    while( currentmode != StateRunning)
    {
      yarp::os::Time::delay(0.01);
      i++;
      if (i%100==0)
      {
        checkConnection();
        //return;
      }
    }
    checkConnection();
  }
Ejemplo n.º 4
0
bool Ubidots::sendAll(){
    bool connected = checkConnection();
    char* _packet = (char *) malloc(sizeof(char) * PACKETSIZE);
    populatePacket(_packet);
    if (strstr(_packet, "ERROR") != NULL || strlen(_packet) > PACKETSIZE){
        free(_packet);
        return false;  // Could not populate the array or max bytes size exceed
    }

    while (!connected){
        connected = checkConnection();
        loraConnect(_band);  //Attempts to connect
        delay(1000);
    }

    if (!connected){
        free(_packet);
        return false;  // The device is not connected
    }

    Serial.print("AT+SEND=");
    Serial.print(_packet);
    Serial.print("\r\n");

    if(!readGateway(1000)){
        free(_packet);
        return false;
    }

    Serial.flush();
    free(_packet);
    delay(100);
    return true;
}
Ejemplo n.º 5
0
void Simonoid::init() {
  kDebug() << "Restoring";
  KConfigGroup lconfig = config();
  m_layouttype = ( LayoutType ) lconfig.readEntry ( "LayoutType", ( int ) LayoutTiny);
  m_interval = lconfig.readEntry ( "RefreshInterval", 3 );

  kDebug() << "Restored to: " << m_layouttype << m_interval;
  
  kDebug() << "Init called";
  Plasma::Applet::init();

  if ( m_icon.isNull() ) {
    setFailedToLaunch ( true, i18n ( "Could not load Simon icon." ) );
    exit ( -1 );
  }

  m_meter = new Plasma::Meter;
  m_meter->setVisible ( true );
  m_meter->setMeterType ( Plasma::Meter::BarMeterHorizontal );
//   m_meter->setMaximumWidth ( 32 );
//   m_meter->setSizePolicy ( QSizePolicy::Maximum, QSizePolicy::Expanding );
  m_meter->setMaximum ( 100 );
  m_meter->setValue ( 0 );

  m_lb_status = new Plasma::Label;
  m_lb_status->setText ( i18n ( "Status:" ) );
  m_lb_status_value = new Plasma::Label;
  m_lb_status_value->setText ( "1" );

  m_lb_peak = new Plasma::Label;
  m_lb_peak->setText ( i18n ( "Peak:" ) );
  m_lb_peak_value = new Plasma::Label;
  m_lb_peak_value->setText ( "2" );

  m_simonicon = new Plasma::IconWidget();
//   m_simonicon->setSizePolicy ( QSizePolicy::Expanding, QSizePolicy::Maximum );
  m_simonicon->setIcon ( m_icon );
  m_simonicon->setOrientation ( Qt::Vertical );
  m_simonicon->setDrawBackground ( true );
  //m_simonicon->setMaximumHeight(36);
  m_simonicon->setAcceptDrops ( false );
  

  initLayout ( m_layouttype );
  m_interval = m_interval;

  connect ( &m_checkConnectionTimer, SIGNAL (timeout()), this, SLOT (checkConnection()) );
  m_checkConnectionTimer.start ( 1000*m_interval );

  checkConnection();
  update();
}
Ejemplo n.º 6
0
 // (PHP)
 folly::Future<folly::Optional<folly::dynamic>> watchmanFlush(
   std::chrono::milliseconds timeout
 ) {
   return !checkConnection() || m_unsubcribeInProgress || !m_subscriptionPtr
     ? folly::makeFuture(folly::Optional<folly::dynamic>())
     : m_watchmanClient->flushSubscription(m_subscriptionPtr, timeout);
 }
Ejemplo n.º 7
0
	void ClientConnection::socketError(QAbstractSocket::SocketError pSocketError)
	{
		switch(pSocketError)
		{
			case QAbstractSocket::ConnectionRefusedError:
				_socketError = "Connection Refused";
				break;
			case QAbstractSocket::RemoteHostClosedError:
				_socketError = "Remote Host Closed Connection";
				break;
			case QAbstractSocket::HostNotFoundError:
				_socketError = "Host Not Found";
				break;
			case QAbstractSocket::SocketAccessError:
				_socketError = "Error Accessing Socket";
				break;
			case QAbstractSocket::SocketResourceError:
				_socketError = "Socket Resource Error";
				break;
			case QAbstractSocket::SocketTimeoutError:
				_socketError = "Timeout";
				break;
			case QAbstractSocket::DatagramTooLargeError:
				_socketError = "Datagram Too Large";
				break;
			case QAbstractSocket::NetworkError:
				_socketError = "Network Error";
				break;
			case QAbstractSocket::AddressInUseError:
				_socketError = "Address already in use";
				break;
			case QAbstractSocket::SocketAddressNotAvailableError:
				_socketError = "Address Not Available";
				break;
			case QAbstractSocket::UnsupportedSocketOperationError:
				_socketError = "Unsupported Socket Operation";
				break;
			case QAbstractSocket::UnfinishedSocketOperationError:
				_socketError = "Socket Operation Unfinished";
				break;
			case QAbstractSocket::ProxyAuthenticationRequiredError:
				_socketError = "Proxy Authentication Requierd";
				break;
			case QAbstractSocket::SslHandshakeFailedError:
				_socketError = "Failed SSL Handshake";
				break;
			case QAbstractSocket::UnknownSocketError:
				_socketError = "Unknown Error";
				break;
		}

		if(_status == Connection_Connecting && _connectTimer)
		{
			checkConnection();
		}
		else
		{
			setStatus(MaraClient::Connection_Error);
		}
	}
Ejemplo n.º 8
0
void PollServerThread::run()
{
    extern volatile bool gPhoneScreenSyncOn;
    while ( !m_exit && gPhoneScreenSyncOn ) {
        if ( !connecting() ) {
            int n = WaitForMessage(m_rfbClient, 500);
            if ( n < 0 ) {
                m_exit = true;
                break;
            } else if ( n > 0 ) {
                emit messageArrived();
                m_lastMessageReceivedTimer.start();
            } else if ( checkConnection() ) {
                if ( ((ConnectionWindow *)parent())->connected() && m_lastMessageReceivedTimer.elapsed() > QVNCVIEWER_CONNPEND_TIMEOUT ) {
                    setCheckConnection(false);
                    m_rfbClient->updateRect.x = m_rfbClient->updateRect.y = 0;
                    m_rfbClient->updateRect.w = m_rfbClient->width;
                    m_rfbClient->updateRect.h = m_rfbClient->height;
                    SendIncrementalFramebufferUpdateRequest(m_rfbClient);
                }
            }
            QTest::qWait(0);
        } else  if ( connecting() ) {
            setCheckConnection(true);
            qApp->processEvents(QEventLoop::AllEvents, 10);
        }
    }

    emit connectionClosed();
}
Ejemplo n.º 9
0
//----------------------------------------------------------------------------
void ctkPluginStorageSQL::cleanupDB()
{
  checkConnection();

  QSqlDatabase database = QSqlDatabase::database(m_connectionName);
  QSqlQuery query(database);

  beginTransaction(&query, Write);

  try
  {
    // remove all plug-ins marked as UNINSTALLED
    QString statement = "DELETE FROM " PLUGINS_TABLE " WHERE StartLevel==-2";
    executeQuery(&query, statement);

    // remove all old plug-in generations
    statement = "DELETE FROM " PLUGINS_TABLE
                " WHERE K NOT IN (SELECT K FROM (SELECT K, MAX(Generation) FROM " PLUGINS_TABLE " GROUP BY ID))";
  }
  catch (...)
  {
    rollbackTransaction(&query);
    throw;
  }

  commitTransaction(&query);
}
Ejemplo n.º 10
0
//----------------------------------------------------------------------------
void ctkPluginStorageSQL::initNextFreeIds()
{
  checkConnection();

  QSqlDatabase database = QSqlDatabase::database(m_connectionName);
  QSqlQuery query(database);

  QString statement = "SELECT ID,MAX(Generation) FROM " PLUGINS_TABLE " GROUP BY ID";
  executeQuery(&query, statement);

  while (query.next())
  {
    m_generations.insert(query.value(EBindIndex).toInt(),
                         query.value(EBindIndex1).toInt()+1);
  }

  query.finish();
  query.clear();

  statement = "SELECT MAX(ID) FROM " PLUGINS_TABLE;
  executeQuery(&query, statement);
  QVariant id = query.next() ? query.value(EBindIndex) : QVariant();
  if (id.isValid())
  {
    m_nextFreeId = id.toInt() + 1;
  }
  else
  {
    m_nextFreeId = 1;
  }
}
Ejemplo n.º 11
0
void ofxCanonConnection::update() {
	if(ofGetElapsedTimeMillis() > should_check_on) {
        OFXLOG("ofxCanonConnection: update -> go and check connection.");
		checkConnection();
		should_check_on = ofGetElapsedTimeMillis() + timeout;
	}
}
std::unique_ptr<mongo::DBClientCursor> MockDBClientConnection::query(const string& ns,
                                                                     mongo::Query query,
                                                                     int nToReturn,
                                                                     int nToSkip,
                                                                     const BSONObj* fieldsToReturn,
                                                                     int queryOptions,
                                                                     int batchSize) {
    checkConnection();

    try {
        mongo::BSONArray result(_remoteServer->query(_remoteServerInstanceID,
                                                     ns,
                                                     query,
                                                     nToReturn,
                                                     nToSkip,
                                                     fieldsToReturn,
                                                     queryOptions,
                                                     batchSize));

        std::unique_ptr<mongo::DBClientCursor> cursor;
        cursor.reset(new MockDBClientCursor(this, result));
        return cursor;
    } catch (const mongo::SocketException&) {
        _isFailed = true;
        throw;
    }

    std::unique_ptr<mongo::DBClientCursor> nullPtr;
    return nullPtr;
}
Ejemplo n.º 13
0
Archivo: core.cpp Proyecto: Pik-9/qTox
/**
 * @brief Processes toxcore events and ensure we stay connected, called by its own timer
 */
void Core::process()
{
    if (!isReady())
    {
        av->stop();
        return;
    }

    static int tolerance = CORE_DISCONNECT_TOLERANCE;
    tox_iterate(tox);

#ifdef DEBUG
    //we want to see the debug messages immediately
    fflush(stdout);
#endif

    if (checkConnection())
    {
        tolerance = CORE_DISCONNECT_TOLERANCE;
    }
    else if (!(--tolerance))
    {
        bootstrapDht();
        tolerance = 3*CORE_DISCONNECT_TOLERANCE;
    }

    unsigned sleeptime = qMin(tox_iteration_interval(tox), CoreFile::corefileIterationInterval());
    toxTimer->start(sleeptime);
}
Ejemplo n.º 14
0
TcpComm::TcpComm(const char* ip, int port, int maxPackageSendSize, int maxPackageReceiveSize) :
  createSocket(0),
  transferSocket(0),
  overallBytesSent(0),
  overallBytesReceived(0),
  maxPackageSendSize(maxPackageSendSize),
  maxPackageReceiveSize(maxPackageReceiveSize),
  wasConnected(false)
{
  address.sin_family = AF_INET;
  address.sin_port = htons(port);
  if(ip) // connect as client?
    address.sin_addr.s_addr = inet_addr(ip);
  else
  {
    createSocket = socket(AF_INET, SOCK_STREAM, 0);
    ASSERT(createSocket > 0);
    int val = 1;
    setsockopt(createSocket, SOL_SOCKET, SO_REUSEADDR, (char*) &val, sizeof(val));
    address.sin_addr.s_addr = INADDR_ANY;
    VERIFY(bind(createSocket, (sockaddr*) &address, sizeof(sockaddr_in)) == 0);
    VERIFY(listen(createSocket, SOMAXCONN) == 0);
    NON_BLOCK(createSocket);
  }
  checkConnection();
}
Ejemplo n.º 15
0
Receiver::Receiver(Rsa *r) : rsa(r)
{
#ifdef REN_DEBUG
	qWarning("Receiver::Receiver(Rsa *r) : rsa(r)");
#endif
	setName("Receiver");

	working = false;
	received = false;

	if ((inputBuffer = (char *)malloc(IN_BUFSIZE))==NULL)
		throw Error(Error::IHU_ERR_MEMORY);
	if ((streamBuffer = (char *)malloc(MAXBUFSIZE))==NULL)
		throw Error(Error::IHU_ERR_MEMORY);

	s = -1;
	notifier = NULL;
	calen = sizeof(ca);

	blowfish = NULL;
	outFile = NULL;

	checkTimer = new QTimer(this);

	reset();
	resetStream();

	// renyang-modify - 初始化primaddr
	primaddr = "";
	// renyang-modify - end

	connect(checkTimer, SIGNAL(timeout()), this, SLOT(checkConnection()));
}
Ejemplo n.º 16
0
TcpComm::TcpComm(const char* ip, int port, int maxPackageSendSize, int maxPackageReceiveSize) :
  maxPackageSendSize(maxPackageSendSize), maxPackageReceiveSize(maxPackageReceiveSize)
{
  address.sin_family = AF_INET;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wconversion"
#endif
  address.sin_port = htons(static_cast<unsigned short>(port));
#ifdef __clang__
#pragma clang diagnostic pop
#endif
  if(ip) // connect as client?
    address.sin_addr.s_addr = inet_addr(ip);
  else
  {
    createSocket = socket(AF_INET, SOCK_STREAM, 0);
    ASSERT(createSocket > 0);
    int val = 1;
    setsockopt(createSocket, SOL_SOCKET, SO_REUSEADDR, (char*)&val, sizeof(val));
    address.sin_addr.s_addr = INADDR_ANY;
    VERIFY(bind(createSocket, (sockaddr*)&address, sizeof(sockaddr_in)) == 0);
    VERIFY(listen(createSocket, SOMAXCONN) == 0);
    NON_BLOCK(createSocket);
  }
  checkConnection();
}
Ejemplo n.º 17
0
void Core::process()
{
    if (!isReady())
        return;

    static int tolerance = CORE_DISCONNECT_TOLERANCE;
    tox_iterate(tox);
    toxav_do(toxav);

#ifdef DEBUG
    //we want to see the debug messages immediately
    fflush(stdout);
#endif

    if (checkConnection())
    {
        tolerance = CORE_DISCONNECT_TOLERANCE;
    }
    else if (!(--tolerance))
    {
        bootstrapDht();
        tolerance = 3*CORE_DISCONNECT_TOLERANCE;
    }

    toxTimer->start(qMin(tox_iteration_interval(tox), toxav_do_interval(toxav)));
}
Ejemplo n.º 18
0
void loop() {
  checkConnection();

  processAcDisplayData();

  // process display data here
  delay(5000); // Sleep 1 second
}
Ejemplo n.º 19
0
void Core::process()
{
    tox_do(tox);
#ifdef DEBUG
    //we want to see the debug messages immediately
    fflush(stdout);
#endif
    checkConnection();
}
Ejemplo n.º 20
0
void Mpris::setPid(quint64 pid)
{
    if (m_pid != pid) {
        m_pid = pid;
        emit targetChanged();
        setValid(false);
        checkConnection();
    }
}
Ejemplo n.º 21
0
 void DBClientConnection::say( Message &toSend ) {
     checkConnection();
     try { 
         port().say( toSend );
     } catch( SocketException & ) { 
         failed = true;
         throw;
     }
 }
Ejemplo n.º 22
0
void Server::setUrl(const QString& url) {
    if ("http://" == url.left(7) || "https://" == url.left(8)) {
        url_ = url;
    } else {
        url_ = "http://" + url;
    }

    checkConnection();
}
Ejemplo n.º 23
0
OceanServerReader::OceanServerReader( const string        &serialPort,
                                      gbxutilacfr::Tracer &tracer )
    : serial_( serialPort, BAUDRATE, gbxserialacfr::Serial::Timeout(TIMEOUT_SEC,0) ),
      tracer_(tracer),
      parser_(tracer),
      firstTime_(true)
{
    checkConnection();
    reset();
}
Ejemplo n.º 24
0
void Connection::idle()
{
	checkConnection();
	if (!m_idle)
	{
		mpd_send_idle(m_connection.get());
		checkErrors();
	}
	m_idle = true;
}
Ejemplo n.º 25
0
    SimpleHttpResult* SimpleHttpClient::request (
            int method, 
            const std::string& location,
            const char* body, 
            size_t bodyLength,
            const map<string, string>& headerFields) {

      SimpleHttpResult* result = new SimpleHttpResult();
      SimpleHttpResult::resultTypes type = SimpleHttpResult::UNKNOWN;

      size_t retries = 0;
      
      // build request
      stringstream requestBuffer;
      fillRequestBuffer(requestBuffer, method, location, body, bodyLength, headerFields);
      LOGGER_TRACE << "Request: " << requestBuffer.str();

      double start = now();
      double runtime = 0.0;
      
      // TODO requestTimeout
      while (++retries < _retries && runtime < _requestTimeout) {

        // check connection
        if (!checkConnection()) {
          type = SimpleHttpResult::COULD_NOT_CONNECT;
          // LOGGER_WARNING << "could not connect to '" << _connection->getHostname() << ":" << _connection->getPort() << "'";
        }

        // write
        else if (!write(requestBuffer, _requestTimeout - runtime)) {
          closeConnection();
          type = SimpleHttpResult::WRITE_ERROR;
          // LOGGER_WARNING << "write error";
        }

        // read
        else if (!read(result, _requestTimeout - runtime)) {
          closeConnection();
          type = SimpleHttpResult::READ_ERROR;
          // LOGGER_WARNING << "read error";
        }
        else {
          type = SimpleHttpResult::COMPLETE; 
          break;
        }
        
        runtime = now() - start;
      }

      result->setResultType(type);

      return result;
    }
Ejemplo n.º 26
0
void Core::process()
{
    tox_do(tox);
#ifdef DEBUG
    //we want to see the debug messages immediately
    fflush(stdout);
#endif
    checkConnection();
    //int toxInterval = tox_do_interval(tox);
    //qDebug() << QString("Tox interval %1").arg(toxInterval);
    toxTimer->start(50);
}
Ejemplo n.º 27
0
void terrama2::services::view::core::Service::updateAdditionalInfo(const QJsonObject& obj) noexcept
{
  if(!obj.contains("maps_server"))
    TERRAMA2_LOG_ERROR() << tr("Missing the Maps Server URI in service additional info!");
  else
  {
    mapsServerUri_ = te::core::URI(obj["maps_server"].toString().toStdString());
    auto mapsServer = MapsServerFactory::getInstance().make(mapsServerUri_, "GEOSERVER");

    mapsServerConnectionStatus_ = mapsServer->checkConnection();
  }
}
Ejemplo n.º 28
0
void * readServer(void *fd) //thread function to read the messages from the server for the user
{
	int sd = *(int*)fd;
	char servbuff[BUFFSIZE]="";
	while(commandControl!=1) //thread sync
	{
		if(!checkConnection(sd)) exit(0);
		bzero(servbuff, BUFFSIZE);
		while(read(sd, servbuff,BUFFSIZE)==0 && commandControl!=1)
		{
			if(!checkConnection(sd)) exit(0); //chilling while waiting instruction to be put in
			sleep(5);
		}
		if(commandControl==1)
			break;
		printf("Message from server:  %s\n",servbuff); //output message from server
		if(!checkConnection(sd)) exit(0);
	}
	close(sd);
	return 0;
}
Ejemplo n.º 29
0
std::pair<rpc::UniqueReply, DBClientBase*> MockDBClientConnection::runCommandWithTarget(
    OpMsgRequest request) {

    checkConnection();

    try {
        return {_remoteServer->runCommand(_remoteServerInstanceID, request), this};
    } catch (const mongo::SocketException&) {
        _isFailed = true;
        throw;
    }
}
Ejemplo n.º 30
0
//This function will constantly listen for the server sending new data
void ListenThread::run()
{
    connect(this, SIGNAL(tryConnection()), NetworkHandler::networkHandler, SLOT(checkConnection()));

    while(true){

        this->sleep(1);

        //emit a signal to tell the NetworkHandler to check the connection
        //emit tryConnection();
    }
}