Пример #1
0
cmd_type commBase::read()
{
	//Required - insures we can read the packets 
	startListening();

	cmd_type ret = PKT_EMPTY;
	byte packet[PACKET_SIZE]; //packet buffer
	if (com.available())
	{
		delay(5);
		com.read(packet, PACKET_SIZE);
	}
	else
		return ret;


	for (int i = 0; i < PACKET_SIZE; i++)
		PT(packet[i]);
	PTL();

	byte cmd = packet[0]; //first packet gives the type of packet
	if (cmd == PKT_UPDATE_TEMPERATURE)
	{
		PT("Updating Temp ");
		float * value = (float*)&packet[1];
		temperature_sensor = *value;
		ret = PKT_UPDATE_TEMPERATURE;
		PTL(*value);
	}

	// stopListening();
	return ret;
}
Пример #2
0
eServerSocket::eServerSocket(int port, eMainloop *ml): eSocket(ml)
{
	int res;
	struct addrinfo *addr = NULL;
	struct addrinfo hints;
	char portnumber[16];

	okflag = 0;
	strRemoteHost = "";

	memset(&hints, 0, sizeof(hints));
	hints.ai_family = AF_UNSPEC; /* both ipv4 and ipv6 */
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = 0; /* any */
#ifdef AI_ADDRCONFIG
	hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV | AI_ADDRCONFIG; /* only return ipv6 if we have an ipv6 address ourselves, and ipv4 if we have an ipv4 address ourselves */
#else
	hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV; /* AI_ADDRCONFIG is not available */
#endif
	snprintf(portnumber, sizeof(portnumber), "%d", port);

	if ((res = getaddrinfo(NULL, portnumber, &hints, &addr)) || !addr)
	{
		eDebug("[eServerSocket] getaddrinfo: %s", gai_strerror(res));
		return;
	}

	if (startListening(addr) >= 0)
	{
		okflag = 1;
		rsn->setRequested(eSocketNotifier::Read);
	}
	freeaddrinfo(addr);
}
Пример #3
0
FileTransferServer::FileTransferServer(QString file, bool isSender, QTcpSocket* withWho, QObject *parent) :
  m_fileName(file), m_state(IDLE), m_sender(isSender), m_withWho(withWho)
{
  m_parentThread = QThread::currentThread();

  connect(&m_serverThread, SIGNAL(started()), this, SLOT(startListening()));
}
Пример #4
0
eServerSocket::eServerSocket(std::string path, eMainloop *ml) : eSocket(ml)
{
	struct sockaddr_un serv_addr_un;
	struct addrinfo addr;

	okflag = 0;
	strRemoteHost = "";

	memset(&serv_addr_un, 0, sizeof(serv_addr_un));
	serv_addr_un.sun_family = AF_LOCAL;
	strcpy(serv_addr_un.sun_path, path.c_str());

	memset(&addr, 0, sizeof(addr));
	addr.ai_family = AF_LOCAL;
	addr.ai_socktype = SOCK_STREAM;
	addr.ai_protocol = 0; /* any */
	addr.ai_addr = (struct sockaddr *)&serv_addr_un;
	addr.ai_addrlen = sizeof(serv_addr_un);

	unlink(path.c_str());

	if (startListening(&addr) >= 0)
	{
		okflag = 1;
		rsn->setRequested(eSocketNotifier::Read);
	}
}
Пример #5
0
void UdpAsyncComm::listen(UdpPacketCallback receive)
{
	if (!listener)
		startListening();

	onUnhandledReceive = receive;
}
Пример #6
0
static void initHardware(void)
{
	Chip_SetupXtalClocking();
	Chip_SYSCTL_SetFLASHAccess(FLASHTIM_100MHZ_CPU);
    SystemCoreClockUpdate();


/*====================[PARA MODULO RF]====================*/
	Chip_GPIO_WriteDirBit(LPC_GPIO, CE_PIN, 1); //Puerto CE
	Chip_GPIO_SetPinOutLow(LPC_GPIO, CE_PIN); //Puerto CE
	InitSPI ();

	begin();
	setPALevel(RF24_PA_LOW);
	openWritingPipe(&addresses2[0]);
	openReadingPipe(1,&addresses1[0]);	//1Node: Transmite paquetes el tx por este pide (addres)

	startListening();

/*========================================================*/



//    Board_Init();

//    Board_LED_Set(0, false);

    SysTick_Config(SystemCoreClock/1000);		//1000 ticks por segundo

	InitPWM_motores(0);			//Función inicialización modulo PWM
	InitPWM_motores(1);			//Función inicialización modulo PWM
	InitPWM_motores(2);			//Función inicialización modulo PWM
	InitPWM_motores(3);			//Función inicialización modulo PWM
	InitPWM0();
	InitGPIO(0);			//Llamo función para inicializar GPIO
	InitGPIO(1);			//Llamo función para inicializar GPIO
	InitGPIO(2);			//Llamo función para inicializar GPIO
	InitGPIO(3);			//Llamo función para inicializar GPIO
	Stop_and_Default(0);	//Condiciones iniciales
	Stop_and_Default(1);	//Condiciones iniciales
	Stop_and_Default(2);	//Condiciones iniciales
	Stop_and_Default(3);	//Condiciones iniciales


    P2_6ER = 1;    P2_7ER = 1;    P2_8ER = 1;

    P2_6EF = 1;    P2_7EF = 1;    P2_8EF = 1;



    P0_15ER = 1;    P0_16ER = 1;    P2_9ER = 1;

    P0_15EF = 1;    P0_16EF = 1;    P2_9EF = 1;

    NVIC_SetPriority(EINT3_IRQn,1);			//Le pongo la mayor prioridad a la interrupcion
    NVIC_EnableIRQ(EINT3_IRQn);


}
Пример #7
0
RpcService::RpcService(const char* path, int port) : IOHandler(),
    _path(path),
    _port(port),
    _service(new rpcbuf),
    _running(false)
{
    startListening();
}
Пример #8
0
bool Server::serve(const char* staticPath, int port) {
    setStaticPath(staticPath);
    if (!startListening(port)) {
        return false;
    }

    return loop();
}
void DeviceEventDispatcherBase::addController(DeviceEventControllerBase* controller)
{
    bool wasEmpty = m_controllers.isEmpty();
    if (!m_controllers.contains(controller))
        m_controllers.append(controller);
    if (wasEmpty)
        startListening();
}
void PlatformEventDispatcher::addController(PlatformEventController* controller)
{
    bool wasEmpty = m_controllers.isEmpty();
    if (!m_controllers.contains(controller))
        m_controllers.append(controller);
    if (wasEmpty)
        startListening();
}
Пример #11
0
RpcService::RpcService(int port) : IOHandler(),
    _path(nil),
    _port(port),
    _service(new rpcbuf),
    _running(false)
{
    startListening();
}
Пример #12
0
SocketServer::SocketServer(int id, unsigned short port, ISocketCallback* callback) :
	id_(id),
	port_(port),
	callback_(callback),
	clientSocket_(0),
	serverSocket_(0)
{
	startListening();
}
int establishConnection(){
	int serverSock,clientSock;
	serverSock=createTcpSocket();
	bindToIpv4(serverSock,ip_addr,port_no);
	startListening(serverSock,2);
	clientSock=acceptConnections(serverSock);
	
	return clientSock;
}
Пример #14
0
    void handleConnect (RPCServerImp::pointer new_connection, boost::system::error_code const& error)
    {
        bool delay = false;

        if (!error)
        {
            // Restrict callers by IP
            // VFALCO NOTE Prevent exceptions from being thrown at all.
            try
            {
                if (! isClientAllowed (new_connection->getRemoteAddressText ()))
                {
                    startListening ();
                    return;
                }
            }
            catch (...)
            {
                // client may have disconnected
                startListening ();
                return;
            }

            new_connection->getSocket ().async_handshake (AutoSocket::ssl_socket::server,
                    boost::bind (&RPCServer::connected, new_connection));
        }
        else
        {
            if (error == boost::system::errc::too_many_files_open)
                delay = true;

            WriteLog (lsINFO, RPCDoor) << "RPCDoorImp::handleConnect Error: " << error;
        }

        if (delay)
        {
            mDelayTimer.expires_from_now (boost::posix_time::milliseconds (1000));
            mDelayTimer.async_wait (boost::bind (&RPCDoorImp::startListening, this));
        }
        else
        {
            startListening ();
        }
    }
void ServerClientProxy::threadedFunction(){
    startListening();
    while(isThreadRunning()) {
        this->update();
        this->listenTCP();
        this->synchronizeSpeeds();
        sleep(25);
    }
	TCP.close();
}
Пример #16
0
SocketServer::SocketServer(int id, unsigned short port, ISocketCallback* callback, int timeoutSeconds, int timeoutMicroseconds) :
	id_(id),
	port_(port),
	callback_(callback),
	clientSocket_(0),
	serverSocket_(0),
	timeoutSeconds_(timeoutSeconds),
	timeoutMicroseconds_(timeoutMicroseconds)
{
	startListening();
}
Пример #17
0
listener::listener(const char *id, bool listening)
{
#ifdef WIN32
  this->id = _strdup(id);
#else
  this->id = strdup(id);
#endif
  this->listening = false;
  if (listening) {
    startListening();
  }
}
Пример #18
0
/*
 * Host constructor: opens a socket on the specified port
 * and listens for and accepts connections (on separate thread if specified).
 */
tcpSocket::tcpSocket(int port, bool threaded)
{
  std::cout << "opening port " << port << std::endl;

  this->port = port;
  this->threaded = threaded;

  openSocket();
  startListening();

  std::thread t(&tcpSocket::acceptConnections, this);
  t.detach();
}
Пример #19
0
void commBase::begin()
{
	com.begin();
	// Set the PA Level low to prevent power supply related issues since this is a
	// getting_started sketch, and the likelihood of close proximity of the devices. RF24_PA_MAX is default.
	com.setPALevel(RF24_PA_LOW);
  
	com.openWritingPipe(ADDR_BASE);
	com.openReadingPipe(1,ADDR_REMOTE);

	// Start the radio listening for data
	startListening();
}
Пример #20
0
int main(int argc, char *argv[]){
	int numPort,longMax,socketIdC,i=0,j=0;
	socketStruct *socketStC;
	pthread_t thread_id[100];
	/***/
	int valor,proc;
	char * retorno;
	char **mensaje;
	int read_size;
	int len;
	char limitador[2] = "\r\n";
	char *ptr;
	char ** contestacion;
	/***/
	
	if(argc != 4){
		printf("Error en el numero de parametros\n");
		return ERROR;
	}

	usersHash_init();
	channelsHash_init();

	numPort = atoi(argv[2]);
	longMax = atoi(argv[3]);
	strcpy(servidor,argv[1]);
	if(initServer(argv[1],numPort,longMax)==ERROR){
		syslog(LOG_ERR,"Error al abrir el servidor\n");		
		exit(ERROR);
	}

	i=0;
	syslog(LOG_INFO,"Esperando conexion\n");
	socketStC = (socketStruct*) calloc(512,sizeof(socketStruct));
	while(1){
		socketIdC = startListening(socketId);
		if(socketIdC < 0){
			syslog(LOG_ERR,"Error al conectar con el cliente \n");
			return ERROR;
		}
		socketStC[socketIdC].socketId = socketIdC;
		socketStC[socketIdC].buffer = calloc (50,sizeof(char));

		if(pthread_create(&thread_id[i],NULL,conexionCliente,(void*) &socketStC[socketIdC]) < 0){
			printf("No se ha podido crear el hilo.\n");
			return ERROR;
       		}
		i++;
	}	
	return OK;
}
Пример #21
0
    void handleConnect (RPCServerImp::pointer new_connection,
        boost::system::error_code const& error)
    {
        bool delay = false;

        if (!error)
        {
            // Restrict callers by IP
            std::string client_ip (
                new_connection->getRemoteEndpoint ().address ().to_string ());

            if (! isClientAllowed (client_ip))
            {
                startListening ();
                return;
            }

            new_connection->getSocket ().async_handshake (AutoSocket::ssl_socket::server,
                    std::bind (&RPCServer::connected, new_connection));
        }
        else
        {
            if (error == boost::system::errc::too_many_files_open)
                delay = true;

            WriteLog (lsINFO, RPCDoor) << "RPCDoorImp::handleConnect Error: " << error;
        }

        if (delay)
        {
            mDelayTimer.expires_from_now (boost::posix_time::milliseconds (1000));
            mDelayTimer.async_wait (std::bind (&RPCDoorImp::startListening, this));
        }
        else
        {
            startListening ();
        }
    }
Пример #22
0
void MainWindow::toggleRun(bool buttonPressed)
{
    if (buttonPressed) {
        ui->pushButtonRun->setText("stop");        
        params->setOutputDir(ui->lineEdit->text());
        qDebug() << "Setting output dir: " << params->getOutDir().absolutePath();
        emit startListening();
    }
    else {
        emit stopListening();
        ui->pushButtonRun->setText("run ");
        newSession();
    }
}
Пример #23
0
void TcpAsyncServer::handle_accept(std::shared_ptr<TcpAsyncStream> connection, const boost::system::error_code& error)
{
	if (!error)
	{
		connection->setAsConnected();

		if (acceptCallback)
			acceptCallback(connection);

		startListening();
	}
	else
		TCP_LOG("accept: " << error.message())
}
Пример #24
0
void PlatformEventDispatcher::addController(PlatformEventController* controller)
{
    ASSERT(controller);
    // TODO: If we can avoid to register a same controller twice, we can change
    // this 'if' to ASSERT.
    if (m_controllers.contains(controller))
        return;

    m_controllers.add(controller);

    if (!m_isListening) {
        startListening();
        m_isListening = true;
    }
}
Пример #25
0
    RPCDoorImp (boost::asio::io_service& io_service, RPCServer::Handler& handler)
        : m_rpcServerHandler (handler)
        , mAcceptor (io_service,
                     boost::asio::ip::tcp::endpoint (boost::asio::ip::address::from_string (getConfig ().getRpcIP ()), getConfig ().getRpcPort ()))
        , mDelayTimer (io_service)
        , m_sslContext ((getConfig ().RPC_SECURE == 0) ?
                RippleSSLContext::createBare () :
                RippleSSLContext::createAuthenticated (
                    getConfig ().RPC_SSL_KEY,
                    getConfig ().RPC_SSL_CERT,
                    getConfig ().RPC_SSL_CHAIN))
    {
        WriteLog (lsINFO, RPCDoor) << "RPC port: " << getConfig ().getRpcAddress().toRawUTF8() << " allow remote: " << getConfig ().RPC_ALLOW_REMOTE;

        startListening ();
    }
Пример #26
0
    Server::Server()
    {
        // Sets listeners as non-blocking.
        listener.setBlocking(false);

        // Opens thread to listen.
        startListening();

        // Initializes random seed.
        srand(time(NULL));

        // Initializes first position to be filled later.
        // The clients vectors must always have one free position for someone to fill.
        // Reason: sf::TcpSocket not copyable/movable.
        clients.emplace_back();
    }
Пример #27
0
void DlgPrefController::showLearningWizard() {
    // If the user has checked the "Enabled" checkbox but they haven't hit OK to
    // apply it yet, prompt them to apply the settings before we open the
    // learning dialog. If we don't apply the settings first and open the
    // device, the dialog won't react to controller messages.
    if (m_ui.chkEnabledDevice->isChecked() && !m_pController->isOpen()) {
        QMessageBox::StandardButton result = QMessageBox::question(
            this,
            tr("Apply device settings?"),
            tr("Your settings must be applied before starting the learning wizard.\n"
               "Apply settings and continue?"),
            QMessageBox::Ok | QMessageBox::Cancel,  // Buttons to be displayed
            QMessageBox::Ok);  // Default button
        // Stop if the user has not pressed the Ok button,
        // which could be the Cancel or the Close Button.
        if (result != QMessageBox::Ok) {
            return;
        }
    }
    slotApply();

    // After this point we consider the mapping wizard as dirtying the preset.
    slotDirty();

    // Note that DlgControllerLearning is set to delete itself on close using
    // the Qt::WA_DeleteOnClose attribute (so this "new" doesn't leak memory)
    m_pDlgControllerLearning = new DlgControllerLearning(this, m_pController);
    m_pDlgControllerLearning->show();
    ControllerLearningEventFilter* pControllerLearning =
            m_pControllerManager->getControllerLearningEventFilter();
    pControllerLearning->startListening();
    connect(pControllerLearning, SIGNAL(controlClicked(ControlObject*)),
            m_pDlgControllerLearning, SLOT(controlClicked(ControlObject*)));
    connect(m_pDlgControllerLearning, SIGNAL(listenForClicks()),
            pControllerLearning, SLOT(startListening()));
    connect(m_pDlgControllerLearning, SIGNAL(stopListeningForClicks()),
            pControllerLearning, SLOT(stopListening()));
    connect(m_pDlgControllerLearning, SIGNAL(stopLearning()),
            this, SLOT(show()));
    connect(m_pDlgControllerLearning, SIGNAL(inputMappingsLearned(MidiInputMappings)),
            this, SLOT(midiInputMappingsLearned(MidiInputMappings)));

    emit(mappingStarted());
    connect(m_pDlgControllerLearning, SIGNAL(stopLearning()),
            this, SIGNAL(mappingEnded()));
}
Пример #28
0
bool NetworkManager::startConnection()
{
    bool cont = true;
    while (cont)
    {
        // Server setup
        if (m_configDialog->isServer())
        {
            cont = !startListening();
            m_port = m_configDialog->getPort();
        }
        else
        {
            m_port = m_configDialog->getPort();
            m_address = m_configDialog->getHost();
            if(startConnectionToServer())
            {
                cont = false;
            }
        }
        if(cont)
        {
            m_dialog->startTimer();
           int value = m_dialog->exec();

           if(value == QDialog::Accepted)
           {
               cont = true;
           }
           else
           {
               cont = false;
               return false;
           }
        }



    }

    m_playersList->sendOffLocalPlayerInformations();
    m_playersList->sendOffFeatures(m_localPlayer);

    setConnectionState(true);
    return true;
}
Пример #29
0
QWidget *TcpServerListener::requestGui(QWidget *parent)
{
    NetworkConfWidget *ncw = new(std::nothrow)NetworkConfWidget(NetworkConfWidget::TCP_SERVER,parent);
    if (ncw == NULL) {
        qFatal("Cannot allocate memory for NetworkConfWidget X{");
    }
    ncw->setPort(port);
    ncw->setIP(listeningAddress);
    ncw->enableDecodeEncodeOption(true);
    connect(ncw, SIGNAL(newIp(QHostAddress)), this, SLOT(setListeningAddress(QHostAddress)));
    connect(ncw, SIGNAL(newPort(quint16)), this, SLOT(setPort(quint16)));
    connect(ncw, SIGNAL(start()), this, SLOT(startListening()));
    connect(ncw, SIGNAL(stop()), this, SLOT(stopListening()));
    connect(ncw,SIGNAL(restart()), this, SLOT(restart()));
    connect(this, SIGNAL(started()), ncw, SLOT(onServerStarted()));
    connect(this, SIGNAL(stopped()), ncw, SLOT(onServerStopped()));
    return ncw;
}
Пример #30
0
void TcpServerListener::handlingClient(int socketDescriptor)
#endif
{
    TcpListener * listener = new(std::nothrow) TcpListener(socketDescriptor);
    if (listener != NULL) {
       // qDebug() << "Listener created" << listener;
        listener->setDecodeinput(decodeInput);
        listener->setEncodeOutput(encodeOutput);
        clients.append(listener);
        listener->moveToThread(workerThread);
        connect(listener, SIGNAL(blockReceived(Block)), SLOT(onClientReceivedBlock(Block)));
        connect(listener, SIGNAL(stopped()), SLOT(clientFinished()));
        connect(listener, SIGNAL(error(QString,QString)), SIGNAL(error(QString,QString)));
        connect(listener, SIGNAL(status(QString,QString)), SIGNAL(status(QString,QString)));
        QTimer::singleShot(0,listener,SLOT(startListening()));
    } else {
        qFatal("Cannot allocate memory for TcpListener X{");
    }
}