Beispiel #1
0
int main(int argc, char** argv) {
  qRegisterMetaType<std::shared_ptr<CANConnection::Message> >();
  qRegisterMetaType<std::string>();
  QApplication application(argc, argv);
  CANConnection device;
  CANScanCom canCom(device);
  MainWindow mainWindow;
  mainWindow.setWindowTitle("Toyota PRIUS CAN Scan");
  ScannedMessagesTab scannedMessagesTab;
  mainWindow.addControl("Scanned Messages", scannedMessagesTab);
  QObject::connect(&canCom,
    SIGNAL(comException(const std::string&)),
    &mainWindow,
    SLOT(comException(const std::string&)));
  QObject::connect(&canCom,
    SIGNAL(readMessage(std::shared_ptr<CANConnection::Message>)),
    &scannedMessagesTab,
    SLOT(readMessage(std::shared_ptr<CANConnection::Message>)));
  mainWindow.show();
  const int ret = application.exec();
  QObject::disconnect(&canCom,
    SIGNAL(comException(const std::string&)),
    &mainWindow,
    SLOT(comException(const std::string&)));
  QObject::disconnect(&canCom,
    SIGNAL(readMessage(std::shared_ptr<CANConnection::Message>)),
    &scannedMessagesTab,
    SLOT(readMessage(std::shared_ptr<CANConnection::Message>)));
  return ret;
}
Beispiel #2
0
void Client::writeToSocket(std::string const &buffer)
{
  int len = buffer.size();
  int len2;

  len2 = 0;
  if (_step == GAME_STEP)
    ++_nbCmd;
  std::string buff(buffer);

  if (!buff.empty() && buffer[buff.length() - 1] == '\n')
    buff.erase(buff.length() - 1);

  std::cout << "\033[1;34m[CLIENT] Sending message : " << buff << "\033[0m"
	    << std::endl;

  while (len2 < len)
    {
      if ((len2 += write(_socket, buffer.c_str() + len2, len)) == -1)
	throw NException("Error : write failed");
    }
  if (_step == GAME_STEP)
    {
      refreshTime();
      getAns();
      if (_messages.size() == 0 && _regroupMessage.size() > 3
	  && _reading == false)
	{
	  _reading = true;
	  readMessage(_regroupMessage);
	  _reading = false;
	  _regroupMessage.clear();
	}
      if (_messages.size() > 0 && _reading == false)
	{
	  std::cout << "READING" << std::endl;
	  _reading = true;
	  for (size_t i = 0; i < _messages.size() ; ++i)
	    readMessage(_messages[i]);
	  _messages.clear();
	  if (_regroupMessage.size() > 3)
	    readMessage(_regroupMessage);
	  _regroupMessage.clear();
	  std::cout << "CLEAR" << std::endl;
	  _reading = false;
	  std::cout << "STOP READING" << std::endl;
	  std::cout << "TIME: " << _time << std::endl;
	}
    }
}
void *atenderPeticion (void *arguments)
{
    strarg *threadArguments = (strarg*)arguments;
    char *httpMessage = malloc(8092);
    char logMessage[BUFFER_SIZE];
    int salida = 0;
    
    do
    {
        salida = readMessage(threadArguments->socketDescriptor, httpMessage);
        if(salida == -1)
        {
            sprintf(logMessage, "ERROR: Cliente %d desconectado abruptamente. Cerrando thread\n", threadArguments->socketDescriptor);;;
        }
        else if (salida == 0)
        {
            sprintf(logMessage, "Cliente %d desconectado de forma normal.\n", threadArguments->socketDescriptor);
        }
        logger(logMessage);
        processHttpMessage(httpMessage, threadArguments->socketDescriptor);
    }
    while(salida > 0);  //TODO El corte debería ser el error de read_message, por ejemplo que se desconecto el cliente es un 0...
    //FD_CLR(argumentosDelThread->socketDescriptor, &readset);
    return NULL;
}
Beispiel #4
0
static int set_array_element(jsobjtype array, int idx,
			     const char *value, enum ej_proptype proptype)
{
	int l;

	if (!allowJS || !cw->winobj || !array)
		return -1;

	debugPrint(5, "> set [%d]=%s", idx, debugString(value));

	head.cmd = EJ_CMD_SETAREL;
	head.obj = array;
	head.proptype = proptype;
	head.proplength = 0;
	if (value)
		head.proplength = strlen(value);
	head.n = idx;
	if (writeHeader())
		return -1;
	if (writeToJS(value, head.proplength))
		return -1;
	if (readMessage())
		return -1;
	ack5();

	return 0;
}				/* set_array_element */
Beispiel #5
0
char sendMessage(char devAddress, char address, char* data, char length, char rw)
{
    char rData = 0;
    I2CIdle();
    I2C2CONbits.SEN = 1;  //Send Start condition
    I2CIdle();

    //SET Slave Address & write (Address shifted one bit left and then the write(0) bit is added)
    I2C2TRN = devAddress << 1; //If reading, the read process is specified after the dummy bytes.

    if (rw == READ) //If in reading mode
    {
        rData = readMessage(devAddress, address);
    }
    else //Otherwise go into writing mode
    {
       writeMessage(address,data, length);
    }

    I2CIdle();
    I2C2CONbits.PEN = 1; //Send Stop condition

    I2CIdle();

    return rData;

}
void processHttpMessage(char *httpMessage, int sockClient)
{
    printf("funcion processHttpMessage\n");
    printf("Full HTTP Message:\n");
    logger(httpMessage);
    char GET[4] = "GET\0";
    char *method = substring(httpMessage, 0, 3);
    logger("Method: ");
    logger(method);
    
    if(strcmp(method, GET) == 0) {
        
        int i = 0;
        while(httpMessage[i] != '\n')
        {
            i++;
        }

        char *path = substring(httpMessage, 5, i - 10);
        logger(path);
        int sockIndexProcess = sendPathToIndexProcess(path);
        char *realPath = malloc(8092);
        readMessage(sockIndexProcess, realPath);
        sendFile(sockClient, realPath);
    }
}
Beispiel #7
0
 void threadFunction(void)
 {
     bool iterate = true;
     for(;iterate;)
     {
         int sensorValue = 0;
         int16_t size = 0;
         size = readMessage(reinterpret_cast<uint8_t*>(&sensorValue), sizeof(sensorValue), 1000);
         std::stringstream ss;
         if(0 > size)
         {
             ss << name() << " : data timeout" << std::endl;
             iterate = false;
         }
         else
         {
             if(sizeof(int) == size)
             {
                 ss << name() << " : received " <<  sensorValue << std::endl;
             }
             else
             {
                 ss << name() << " : received strange message!" << std::endl;
             }
         }
         CLogger() << ss.str();
     }
 }
bool SharedVisualizationClient::receiveServerUpdate(Comm::NetPipe& pipe)
	{
	/* Ignore a list of global server messages: */
	MessageIdType message;
	while((message=readMessage(pipe))!=UPDATE_END)
		switch(message)
			{
			case CREATE_ELEMENT:
				{
				/* Skip an element creation message: */
				unsigned int elementId=pipe.read<Card>();
				std::string algorithmName=read<std::string>(pipe);
				size_t parametersSize=pipe.read<Card>();
				Byte* parameters=new Byte[parametersSize];
				pipe.read(parameters,parametersSize);
				pipe.read<Byte>(); // bool enabled=pipe.read<unsigned char>()!=0;
				
				#ifdef VERBOSE
				std::cout<<"Ignored creation of "<<algorithmName<<" element with ID "<<elementId<<std::endl;
				#endif
				}
			}
	
	return false;
	}
Beispiel #9
0
void Server::incomingConnection ( int socketDescriptor )
{
    if(this->clientSocketList.size() >= playerSum)
        return;
    ClientSocket* newSocket=new ClientSocket;
    newSocket->setSocketDescriptor(socketDescriptor);

    clientSocketList.append(newSocket);
    ready.append(false);
    this->socketDescriptorList.append(socketDescriptor);
    newSocket->id=clientSocketList.count()-1;
    connect(newSocket,SIGNAL(disconnected()),newSocket,SLOT(onDisconnected()));
    connect(newSocket,SIGNAL(disconnectedSIN(ClientSocket*)),this,SLOT(onDisconnectedSIG(ClientSocket*)));
    connect(newSocket,SIGNAL(disconnected()),newSocket,SLOT(deleteLater()));
    connect(newSocket,SIGNAL(readyRead()),newSocket,SLOT(readMessage()));
    connect(newSocket,SIGNAL(getMessage(int,QString)),this,SLOT(decoder(int,QString)));

    QString temp = "1;";
    int howMany=clientSocketList.size();
    temp += QString::number(this->clientSocketList.size()-1);
    temp += ";";
    this->sendMessage(this->clientSocketList.size()-1,temp);

    if(howMany == playerSum)
        emit this->seatArrangeSIG();
    else
        sendMessage(-1,tr("现有")+QString::number(howMany)+tr("名玩家进入房间,请耐心等候"));
}
Beispiel #10
0
jsobjtype instantiate_array(jsobjtype parent, const char *name)
{
	jsobjtype p = 0;

	if (whichproc == 'j')
		return instantiate_array_nat(parent, name);

	if (!allowJS || !cw->winobj || !parent)
		return 0;

	debugPrint(5, "> new array %s", name);

	head.cmd = EJ_CMD_SETPROP;
	head.obj = parent;
	head.proptype = EJ_PROP_ARRAY;
	head.proplength = 0;
	head.n = strlen(name);
	if (writeHeader())
		return 0;
	if (writeToJS(name, head.n))
		return 0;
	if (readMessage())
		return 0;
	ack5();

	if (propval) {
		sscanf(propval, "%p", &p);
		free(propval);
		propval = 0;
	}

	return p;
}				/* instantiate_array */
Beispiel #11
0
static int set_property(jsobjtype obj, const char *name,
			const char *value, enum ej_proptype proptype)
{
	int l;

	if (!allowJS || !cw->winobj || !obj)
		return -1;

	debugPrint(5, "> set %s=%s", name, debugString(value));

	head.cmd = EJ_CMD_SETPROP;
	head.obj = obj;
	head.proptype = proptype;
	head.proplength = strlen(value);
	head.n = strlen(name);
	if (writeHeader())
		return -1;
	if (writeToJS(name, head.n))
		return -1;
	if (writeToJS(value, strlen(value)))
		return -1;
	if (proptype == EJ_PROP_FUNCTION)
		jsSourceFile = name;
	if (readMessage())
		return -1;
	jsSourceFile = NULL;
	ack5();

	return 0;
}				/* set_property */
Beispiel #12
0
/* Create a js context for the current window.
 * The corresponding js context will be stored in cw->jcx. */
void createJavaContext(void)
{
	if (!allowJS)
		return;

	if (!js_pid) {
		js_start();
		update_var_in_js(1);
	}

	debugPrint(5, "> create context for session %d", context);

	memset(&head, 0, sizeof(head));
	head.cmd = EJ_CMD_CREATE;
	if (writeHeader())
		return;
	if (readMessage())
		return;
	ack5();

	if (head.highstat)
		return;

/* Copy the context pointer back to edbrowse. */
	cw->jcx = head.jcx;
	cw->winobj = head.winobj;
	cw->docobj = head.docobj;

	setupJavaDom();
}				/* createJavaContext */
Beispiel #13
0
Client::Client()
{
    connect(this,SIGNAL(readyRead()),this,SLOT(readMessage()));
    connect(logic,SIGNAL(gameStart()),this,SIGNAL(readyToStart()));
    connect(logic,SIGNAL(sendCommand(QString)),this,SLOT(sendMessage(QString)));
    connect(this,SIGNAL(getMessage(QString)),logic,SLOT(getCommand(QString)));
    logic->setClient(this);
}
Beispiel #14
0
void handler_client::doListen(quint16 client_port) {
    socket = new QUdpSocket(this);
    connect(socket, SIGNAL(readyRead()), this, SLOT(readMessage()));

    qDebug() << "binding...";

    socket->bind(QHostAddress::Any, client_port);
}
IncomingMessageParser::IncomingMessageParser(QIODevice *device) :
    m_device(device),
    m_in_progress_msg(NULL)
{
    bool success;
    success = connect(m_device, SIGNAL(readyRead()), this, SLOT(readMessage()), Qt::QueuedConnection);
    Q_ASSERT(success);
}
static int receiveMessage(int sock, char **msg) {
	int ret = readMessage(sock, (void *)msg);

	//logMessage(*msg, SERVER);
	mqueue_enqueue(dispEvents, *msg, ret * sizeof(char));

	return ret;
}
//------------------------------------------------------------------------------
void SpeakAnnounce::incomingEvent(HANDLE user, HANDLE event)
{
	if (m_event_info.isValidEvent(event))
	{
		bool speak = false;
		switch (m_event_info.getLastEvent())
		{
		  case EVENTTYPE_MESSAGE:
			speak = m_db.getEventFlag(AnnounceDatabase::EventFlag_Message);
			break;

		  case EVENTTYPE_URL:
			speak = m_db.getEventFlag(AnnounceDatabase::EventFlag_Url);
			break;

		  case EVENTTYPE_ADDED:
			speak = m_db.getEventFlag(AnnounceDatabase::EventFlag_Added);
			break;

		  case EVENTTYPE_AUTHREQUEST:
			speak = m_db.getEventFlag(AnnounceDatabase::EventFlag_AuthRequest);
			break;

		  case EVENTTYPE_FILE:
			speak = m_db.getEventFlag(AnnounceDatabase::EventFlag_File);
			break;

		}

		if (!speak)
		{
			return;
		}
		std::wstring event_str = L"";

		if (EVENTTYPE_MESSAGE == m_event_info.getLastEvent())
		{
			if (!readMessage(user))
			{
				return; // message dialog is open so just leave without saying anything
			}
			if ((m_db.getEventFlag(AnnounceDatabase::EventFlag_ReadMsgLength)) && (m_event_info.getMessageSize() <= m_db.getMaxMsgSize()))
			{
				event_str = m_event_info.getMessage(); // conditions met to read the message
			}
			else
			{
				event_str = m_event_info.eventString();
			}
		}
		else
		{
			event_str = m_event_info.eventString();
		}
		m_user_info.insertName(event_str, user); // translate the string, insert the name, then speak it
		message(event_str, user);
	}
}
void FreeBracketClient::connectToServer(QString host, quint16 port) {
    qDebug() << "Connecting to server...";
    tcpSocket = new QTcpSocket(this);
    connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readMessage()));
    connect(tcpSocket, SIGNAL(connected()), this, SLOT(connected()));
    connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError)));
    tcpSocket->abort();
    tcpSocket->connectToHost(QHostAddress(host), port);
}
Beispiel #19
0
AMCPDevice::AMCPDevice(QObject* parent)
    : QObject(parent), command(AMCPDevice::NONE), state(AMCPDevice::ExpectingHeader), connected(false)
{
    this->socket = new QTcpSocket(this);

    QObject::connect(this->socket, SIGNAL(readyRead()), this, SLOT(readMessage()));
    QObject::connect(this->socket, SIGNAL(connected()), this, SLOT(setConnected()));
    QObject::connect(this->socket, SIGNAL(disconnected()), this, SLOT(setDisconnected()));
}
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
	tcpSocket=new QTcpSocket(this);
	connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readMessage()));
	connect(tcpSocket,SIGNAL(error(QAbstractSocker::SocketError)),this,SLOT(dispalyError(QAbstractSocket::SocketError)));
}
void loop() {
    Usb.Task();

    if (!adk.isReady()) {
        return;
    }
    
    readMessage();
}
Beispiel #22
0
void ClipboardMonitor::readyRead()
{
    m_socket->blockSignals(true);

    while ( m_socket->bytesAvailable() > 0 ) {
        QByteArray msg;
        if( !readMessage(m_socket, &msg) ) {
            log( tr("Cannot read message from server!"), LogError );
            return;
        }

        ClipboardItem item;
        QDataStream in(&msg, QIODevice::ReadOnly);
        in >> item;

        /* Does server send settings for monitor? */
        QByteArray settings_data = item.data()->data("application/x-copyq-settings");
        if ( !settings_data.isEmpty() ) {

            QDataStream settings_in(settings_data);
            QVariantMap settings;
            settings_in >> settings;

#ifdef COPYQ_LOG_DEBUG
            {
                COPYQ_LOG("Loading configuration:");
                foreach (const QString &key, settings.keys()) {
                    QVariant val = settings[key];
                    const QString str = val.canConvert<QStringList>() ? val.toStringList().join(",")
                                                                      : val.toString();
                    COPYQ_LOG( QString("    %1=%2").arg(key).arg(str) );
                }
            }
#endif

            if ( settings.contains("formats") )
                m_formats = settings["formats"].toStringList();
#ifdef COPYQ_WS_X11
            if ( settings.contains("copy_clipboard") )
                m_copyclip = settings["copy_clipboard"].toBool();
            if ( settings.contains("copy_selection") )
                m_copysel = settings["copy_selection"].toBool();
            if ( settings.contains("check_selection") )
                m_checksel = settings["check_selection"].toBool();
#endif

            connect( QApplication::clipboard(), SIGNAL(changed(QClipboard::Mode)),
                     this, SLOT(checkClipboard(QClipboard::Mode)) );

#ifdef COPYQ_WS_X11
            checkClipboard(QClipboard::Selection);
#endif
            checkClipboard(QClipboard::Clipboard);

            COPYQ_LOG("Configured");
        } else {
//Connect to specified server ,wait for reply
void LoginDialog::connectToServer()
{
    client = new QTcpSocket(this);
    client->abort();
    client->connectToHost(serverIp,serverPort.toUInt());
    blockSize = 0;
    connect(client,SIGNAL(connected()),this,SLOT(verify()));
    connect(client,SIGNAL(readyRead()),this,SLOT(readMessage()));

}
void SonicPiTCPOSCServer::client(){
    //In TCP we have no ack signal as we don't block the main loop.
    //Hence assume if we get a connection from a client its booted and ready.
    QMetaObject::invokeMethod(parent, "serverStarted", Qt::QueuedConnection);
    socket = tcpServer->nextPendingConnection();
    connect(socket, SIGNAL(readyRead()), this, SLOT(readMessage()));
    connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(logError(QAbstractSocket::SocketError)));
    connect(socket, SIGNAL(disconnected()), socket, SLOT(deleteLater()));
    std::vector<char>().swap(buffer);
}
CommWithClient::CommWithClient(QTcpSocket *socket){
    tcpClient = socket;
    //初始化
    status = 0;
    totalMessageSize = 0;
    total= 0;
    connect(tcpClient,SIGNAL(readyRead()),this,SLOT(readMessage()));
    //connect(tcpClient,SIGNAL(disconnected()),this,SLOT(deleteLater()));
    connect(this,SIGNAL(receStuObject()),&stu,SLOT(print()));
}
Beispiel #26
0
AMCPDevice::AMCPDevice(const QString& address, int port, QObject* parent)
    : QObject(parent),
      command(AMCPDevice::NONE), port(port), state(AMCPDevice::ExpectingHeader), connected(false), address(address)
{
    this->socket = new QTcpSocket(this);

    connect(this->socket, SIGNAL(readyRead()), this, SLOT(readMessage()));
    connect(this->socket, SIGNAL(connected()), this, SLOT(setConnected()));
    connect(this->socket, SIGNAL(disconnected()), this, SLOT(setDisconnected()));
}
Beispiel #27
0
void Socket::readLoop() {
    while (connected) {
        char *buffer = readMessage();
        if (buffer) {
            std::unique_lock<std::mutex> lock(processingMutex);
            processingQueue.push_back(buffer);
            lock.unlock();
            processingCondition.notify_one();
        }
    }
}
Beispiel #28
0
void CANCom::timerTimeout() {
  try {
    if (!mDevice.getConnection().isOpen())
      mDevice.getConnection().open();
    std::shared_ptr<PRIUSMessage> message = mDevice.readMessage();
    emit readMessage(message);
    emit deviceConnected(true);
  }
  catch (IOException& e) {
    emit comException(e.what());
  }
}
Beispiel #29
0
monitorclient::monitorclient(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::monitorclient)
{
    ui->setupUi(this);
    TcpClientSocket =new QTcpSocket(this);
    connect(TcpClientSocket,SIGNAL(readyRead()),this,SLOT(readMessage()));
    connect(TcpClientSocket,SIGNAL(error(QAbstractSocket::SocketError)),
             this,SLOT(displayError(QAbstractSocket::SocketError)));
    connect(ui->LandingButton,SIGNAL(clicked()),this,SLOT(landing()));
    connect(ui->RegisterButton,SIGNAL(clicked()),this,SLOT(new_register()));
}
Beispiel #30
0
/*
** Reads message using given file descriptor and classifies
** the header of the message into an event
** Returns message on success, NULL on failure
**
** Arguments:
** evt - event to be set to the classified header
** sock - the file descriptor for a socket for which to read from  
*/
char * readAndClassifyMessage(event * evt, int sock){
	char * msg = readMessage(sock);
	if(msg == NULL){
		return NULL;
	}
	int classified = classifyMessage(evt, msg);
	if(classified == -1){
		free(msg);
		return NULL;
	}
	return msg;
}