Exemple #1
0
Worker::Worker(Communicator *communicator, QObject *parent) :
    QObject(parent)
{
    m_waitingCount = 0;

    m_communicator = communicator;
    m_ready = false;
    m_currentLine = -1;
    m_commandList = QStringList();
    m_currentState = StoppedState;
    m_bufferSize = 3;

    aliveTimer = new QTimer(this);
    aliveTimer->setInterval(1000); // 1s
    aliveTimer->start();

    connect(m_communicator, SIGNAL(usbConnected()),
            this, SLOT(usbConnected()));
    connect(m_communicator, SIGNAL(usbDisconnected()),
            this, SLOT(usbDisconnected()));
    connect(m_communicator, SIGNAL(commandReceived(QByteArray)),
            this, SLOT(commandReceived(QByteArray)));

    connect(aliveTimer, SIGNAL(timeout()),
            this, SLOT(aliveTimerTick()));
}
void NetServerCom::startCommunication()
{
    socket = server->nextPendingConnection();

    connect(socket, SIGNAL(disconnected()), this, SLOT(closeSocket()));

    while (comActive && socket->isOpen())
    {
        //read queued commands and send to host
        if (writeCmd.size()>0)
        {
            NetCommand cmd = writeCmd.dequeue();
            QString m = cmd.toString().append("\n");
            socket->write(m.toAscii());
            socket->flush();
            cout << "queued cmd sent: " << cmd.toString().toStdString() << endl;
        }

        //read command from host
        if (socket->waitForReadyRead(100))
        {
            QByteArray data = socket->readAll();
            NetCommand cmd = NetCommand(QString(data.constData()));
            emit commandReceived(cmd);
        }
    }


    socket->disconnect();
    delete socket;
    emit finished();
    emit lostConnection(comActive);
}
/*!
  \internal
  Slot to receive QSocketNotifier activation from data arriving on the socket
  */
void LocalSocketListener::receiveMessage()
{
    int resultCode;
    char msg[1024];
    QByteArray bytes;
    int clientDescriptor;
    struct sockaddr_un clientAddress;
    socklen_t addrSize = sizeof(clientAddress);

    clientDescriptor = ::accept( descriptor(), (struct sockaddr*)&clientAddress, &addrSize );
    if ( clientDescriptor == -1 )
    {
        qWarning() << "Could not accept connection" << strerror( errno );
        return;
    }

    ::memset( msg, '\0', 1024 );
    while (( resultCode = ::read( clientDescriptor, msg, 1023 )))
    {
        bytes.append( msg );
        ::memset( msg, '\0', 1024 );
    }
    ::close( clientDescriptor );
    QString command( (QChar*)bytes.constData(), bytes.size() / 2 );
    emit commandReceived( command );
}
Exemple #4
0
// Receive IMs from other bots
void Robot::listenPort() const
{
	// Return if nothing to do
	if (my_socket == -1)
		return;

	// Get message from other bot
	int length;
	struct sockaddr_in si_other;
	socklen_t other_length = sizeof(struct sockaddr_in);

	length = recvfrom(
		my_socket,
		buffer,
		BUFFLEN,
		0,
		(struct sockaddr *) &si_other,
		&other_length);

	// Return if nothing (length = -1) or
	// empty message (length = 0) received
	if (length <= 0)
		return;

	// Security: check that the data comes from one of the other robots
	int num;
	for (num = 0; num < NUMCLIENTS; num++)
	{
		if (client[num])
		{
			if (si_client[num].sin_addr.s_addr == si_other.sin_addr.s_addr &&
                si_client[num].sin_port        == si_other.sin_port)
				break;
		}
	}
	if (num == NUMCLIENTS)
	{
		printf("Received data from an unknown source: \"%s\"\n", buffer);
		return;
	}

	// Security: ensure the buffer is NUL-terminated
	if (length >= BUFFLEN)
		length = BUFFLEN - 1;
	buffer[length] = '\0';

	// Analyze data received
	switch (*buffer)
	{
		case 'D':
			dataReceived(num, buffer + 1, length - 1);
			break;
		case 'C':
			commandReceived(num, buffer + 1, length - 1);
			break;
		default:
			printf("Received invalid data: \"%s\"\n", buffer);
	}
}
void RemoteComponent::subscribeToWeb(bool subscribe)
{
  QVariantMap arg = {
    { "method", "GET" },
    { "path",  "/player/timeline/" +  (subscribe ? QLatin1String("subscribe") : QLatin1String("unsubscribe")) },
    { "commandID", m_commandId}
  };

  emit commandReceived(arg);
}
Exemple #6
0
Pager::Pager(KWMModuleApplication *a, char *name) : QWidget(NULL,  "kwmpager")
{
    kwmmapp = a;
    a->setMainWidget(this);
    kwmmapp -> connectToKWM();
    KWM::setSticky(winId(), true);
    KWM::setDecoration(winId(), KWM::tinyDecoration | KWM::noFocus);
    KWM::setWmCommand(winId(), name);
    KWM::setUnsavedDataHint(winId(), false);

    int count = KWM::numberOfDesktops();
    desktop_font = new QFont();
    Desktop *desk;

    desktops.resize(count);
    for (int i = 0; i < count; i++) {
        desk = new Desktop(a, i + 1, this);
        desktops[i] = desk;
    }
    
    activeDesktop = desktops.at(KWM::currentDesktop() - 1);
    activeDesktop->activate(true);
    
    connect(kwmmapp, SIGNAL(desktopChange(int)) , 
	    SLOT(changeDesktop(int)));
    connect(kwmmapp, SIGNAL(init()), 
	    SLOT(initDesktops()));
    connect(kwmmapp, SIGNAL( desktopNumberChange(int)), 
	    SLOT(changeNumber(int)));
    connect(kwmmapp, SIGNAL( windowAdd(Window)), 
	    SLOT(addWindow(Window)));
    connect(kwmmapp, SIGNAL( windowRemove(Window)), 
	    SLOT(removeWindow(Window)));
    connect(kwmmapp, SIGNAL( windowChange(Window)), 
	    SLOT(windowChange(Window)));
    connect(kwmmapp, SIGNAL( windowRaise(Window)), 
	    SLOT(raiseWindow(Window)));
    connect(kwmmapp, SIGNAL( windowLower(Window)), 
	    SLOT(lowerWindow(Window)));
    connect(kwmmapp, SIGNAL( windowActivate(Window)), 
	    SLOT(windowActivate(Window)));
    connect(kwmmapp, SIGNAL( commandReceived(QString)),
	    SLOT(receiveCommand(QString)));

    moved = false;
    readSettings();
    initDesktops();
    show();
    placeIt();
}
Exemple #7
0
void Server::newDataReceived()
{
    qDebug("Données recues");
    // 1 : on reçoit un paquet (ou un sous-paquet) d'un des clients

    // On détermine quel client envoie le message (recherche du QTcpSocket du client)
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    if (socket == 0) // Si par hasard on n'a pas trouvé le client à l'origine du signal, on arrête la méthode
        return;

    // Si tout va bien, on continue : on récupère le message
    //QDataStream in(socket);
    QString data = socket->readAll();

    QVariantMap json = QtJson::Json::parse(data).toMap();
    qDebug(data.toUtf8());

    emit commandReceived(json);

}
Exemple #8
0
int main(void)
{
    initPic32();

    PORTSetPinsDigitalIn(IOPORT_A, BIT_0);
    PORTSetPinsDigitalIn(IOPORT_A, BIT_1);
    PORTSetPinsDigitalIn(IOPORT_B, BIT_14);

    PPSInput(1, SS1, RPA0);
    PPSInput(2, SDI1, RPA1);

#ifndef NO_SDO
    PPSOutput(3, RPA2, SDO1);
#endif

    SpiChnOpen(1, SPI_OPEN_MODE8|SPI_OPEN_SLVEN|SPI_OPEN_SSEN
#ifdef NO_SDO
               |SPI_OPEN_DISSDO
#endif
               , 2);

    init();

    uint8_t lastByteReceived = 0;
    uint8_t cmd[8];
    uint8_t length=0;
    uint8_t toRead = 1;
    while(1) {
        if(SpiChnTxBuffEmpty(1))
            SpiChnPutC(1, lastByteReceived);
        lastByteReceived = 0;

        while(!SpiChnDataRdy(1))
            loop();
        uint8_t byte = SpiChnGetC(1);
        cmd[length++] = byte;
        toRead--;
        if(toRead==0)
            toRead = commandReceived(cmd, length);
    }
}
bool AbstractManager::queueCommand(ICommand* command)
{
    if(!command)
        return false;

    command = command->cloneCommand();           //   creating a clone
    bool bSucces=false;
    if(mLock.tryLockForWrite(mWriteMaxWait))
    {
        int severity = (int)command->getSeverity();
        CommandQueue* queue = mHashCommandQueues.value(severity,0);
        if(!queue)
        {
            queue = new CommandQueue();
            mHashCommandQueues.insert(severity,queue);
        }
        queue->enqueue(command);
        mLock.unlock();
        bSucces = true;
        emit commandReceived(command);
    }
    return bSucces;
}
void NetClientCom::startCommunication()
{
    bool autoReconnect = true;

    // Connect to Host
    socket=new QTcpSocket;
    socket->connectToHost(host, port);

    connect(socket, SIGNAL(disconnected()), this, SLOT(closeSocket()));

    if (!socket->waitForConnected(5000)) {
        cout << "Error: Could not connect to " << host.toStdString() << ":" << port << endl;
        emit couldNotConnect();
        return;
    }

    cout << "Connected to " << host.toStdString() << ":" << port << endl;
    isconnected=true;

    int i=0;
    while (comActive && socket->isOpen()) {

        /*if (autoReconnect && (!socket->isOpen()))
        {
            socket->connectToHost(host, port);
            cout << "RECONNECTING..." << endl;

            if (!socket->waitForConnected())
            {
                isconnected=false;
                comActive=false;
                cout << "Error: Could not reconnect to " << host.toStdString() << ":" << port << endl;
            }
        }*/

        //read queued commands and send to host
        if (writeCmd.size()>0)
        {
            NetCommand cmd = writeCmd.dequeue();
            QString m = cmd.toString().append("\n");
            socket->write(m.toAscii());
            socket->flush();
            cout << "CLIENT CMD OUT: " << cmd.toString().toStdString() << endl;
        }

        //read command from host
        if (socket->waitForReadyRead(100))
        {
            QByteArray data = socket->readAll();
            cout << "----" << endl << QString(data.constData()).toStdString() << "----" << endl;
            QStringList list = QString(data.constData()).trimmed().split("\n");
            for (int i=0; i<list.size(); i++)
            {
                NetCommand cmd = NetCommand(list.at(i));
                cout << "CLIENT CMD IN : " << cmd.toString().toStdString() << endl;
                emit commandReceived(cmd);
            }

        }
    }

    isconnected=false;
    socket->disconnect();
    cout << "client: " << "socket->disconnect();" << endl;
    delete socket;
    emit finished();
    emit lostConnection(comActive);
    cout << "client: " << "delete socket, emit finished()" << endl;
}
Exemple #11
0
Browser::Browser() {
  QObject::connect(&reader, SIGNAL(commandReceived(QVariant)), this, SLOT(onCommandReceived(QVariant)));
  QObject::connect(&page, SIGNAL(loadFinished(bool)), this, SLOT(onLoadFinished(bool)));
  QObject::connect(&page.jsCallbackObject, SIGNAL(asyncScriptCallback(QVariant)), this, SLOT(onAsyncScriptCallback(QVariant)));  
  isRunning = false;
}
void RemoteComponent::handleCommand(QHttpRequest* request, QHttpResponse* response)
{

  QVariantMap queryMap = QueryToMap(request->url());
  QVariantMap headerMap = HeaderToMap(request->headers());
  QString identifier = headerMap["x-plex-client-identifier"].toString();

  response->addHeader("Access-Control-Allow-Origin", "*");
  response->addHeader("X-Plex-Client-Identifier",  SettingsComponent::Get().value(SETTINGS_SECTION_WEBCLIENT, "clientID").toByteArray());

  // handle CORS requests here
  if ((request->method() == qhttp::EHTTP_OPTIONS) && headerMap.contains("access-control-request-method"))
  {    
    response->addHeader("Content-Type", "text/plain");
    response->addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, HEAD");
    response->addHeader("Access-Control-Max-Age", "1209600");
    response->addHeader("Connection", "close");

    if (headerMap.contains("access-control-request-headers"))
    {
      response->addHeader("Access-Control-Allow-Headers", headerMap.value("access-control-request-headers").toByteArray());
    }

    response->setStatusCode(qhttp::ESTATUS_OK);
    response->end();
    return;
  }

  // we want to handle the subscription events in the host
  // since we are going to handle the updating later.
  //
  if (request->url().path() == "/player/timeline/subscribe")
  {
    handleSubscription(request, response, false);
    return;
  }
  else if (request->url().path() == "/player/timeline/unsubscribe")
  {
    subscriberRemove(request->headers()["x-plex-client-identifier"]);
    response->setStatusCode(qhttp::ESTATUS_OK);
    response->end();
    return;
  }
  else if ((request->url().path() == "/player/timeline/poll"))
  {
    QMutexLocker lk(&m_subscriberLock);
    if (!m_subscriberMap.contains(identifier))
    {
      lk.unlock();
      handleSubscription(request, response, true);
      lk.relock();
    }

    RemotePollSubscriber *subscriber = (RemotePollSubscriber *)m_subscriberMap[identifier];
    if (subscriber)
    {
      subscriber->reSubscribe();
      subscriber->setHTTPResponse(response);

      // if we don't have to wait, just ship the update right away
      // otherwise, this will wait until next update
      if (! (queryMap.contains("wait") && (queryMap["wait"].toList()[0].toInt() == 1)))
      {
        subscriber->sendUpdate();
      }
    }

    return;
  }


  // handle commandID
  if (!headerMap.contains("x-plex-client-identifier") || !queryMap.contains("commandID"))
  {
    QLOG_WARN() << "Can't find a X-Plex-Client-Identifier header";
    response->setStatusCode(qhttp::ESTATUS_NOT_ACCEPTABLE);
    response->end();
    return;
  }

  quint64 commandId = 0;
  {
    QMutexLocker lk(&m_responseLock);
    commandId = ++m_commandId;
    m_responseMap[commandId] = response;

    connect(response, &QHttpResponse::done, this, &RemoteComponent::responseDone);
  }

  {
    QMutexLocker lk(&m_subscriberLock);
    if (!m_subscriberMap.contains(identifier))
    {
      QLOG_WARN() << "Failed to lock up subscriber" << identifier;
      response->setStatusCode(qhttp::ESTATUS_NOT_ACCEPTABLE);
      response->end();
      return;
    }

    RemoteSubscriber* subscriber = m_subscriberMap[identifier];
    subscriber->setCommandId(m_commandId, queryMap["commandID"].toList()[0].toInt());
  }

  QVariantMap arg = {
    { "method", request->methodString() },
    { "headers", headerMap },
    { "path", request->url().path() },
    { "query", queryMap },
    { "commandID", m_commandId}
  };

  emit commandReceived(arg);
}