Esempio n. 1
0
void MASASerial::update(){

  if (!messageAvailable()){
    while(SerialUSB.available()){
      if (lastIndex<PACKET_SIZE) bufferIn[lastIndex++] = SerialUSB.read();
    }
    
    if (inputState(bufferIn, lastIndex)==RESET){
      resetBuffer();
    }else if (!inAvailable&&inputState(bufferIn, lastIndex)==COMPLETE){
      inAvailable = true;
      for (uint8_t i = 3; i < 3+bufferIn[2]; i++){
        dataIn.data[i-3] = bufferIn[i];
      }
        dataIn.header = bufferIn[1];
        dataIn.lengthData = bufferIn[2];
    }
    
  }else{
	if (SerialUSB.available() == 64) resetBuffer();
  
  }
  
  
}
Esempio n. 2
0
void MessageQueue::readData() {
	// Append data to our internal buffer
	_recvbuffer.append(_socket->readAll());

	// We have enough to at least know how many bytes we need. Loop
	// until we have extracted all the packets we can.
	bool signal = false;
	while(_recvbuffer.length()>=3) {
		if(_expecting==0) {
			_expecting = Packet::sniffLength(_recvbuffer);
			if(_expecting==0) {
				emit badData();
				return;
			}
		}
		if(_expecting <= _recvbuffer.length()) {
			Packet *pkt = Packet::deserialize(_recvbuffer);
			if(pkt==0) {
				emit badData();
				return;
			}
			signal = true;
			_recvbuffer = _recvbuffer.mid(pkt->length());
			_recvqueue.enqueue(pkt);
			_expecting=0;
		} else {
			break;
		}
	}
	if(signal)
		emit messageAvailable();
}
Esempio n. 3
0
int main(int argc, char *argv[])
{

#ifndef QT_DEBUG
    QString fileName = FilePirate::StoragePath + "captains-log.log";
    QFile *log = new QFile(fileName);
    if (log->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) {
        out = new QTextStream(log);
        qInstallMsgHandler(logOutput);
    } else {
        qDebug() << "Error opening log file '" << fileName << "'. All debug output redirected to console.";
    }
#endif


    SingleApplication a(argc, argv, "9578A25E-F82A-4558-842C-1DE074F3C232");

    if (a.alreadyExists()) {
        qDebug() << "FilePirate is already running.";
        a.sendMessage("fg");
        return 0;
    }

    QPixmap pixmap(":/images/splash.png");
    QSplashScreen *splash = new QSplashScreen(pixmap);
    splash->show();
    a.processEvents();
    splash->showMessage("Loading...",Qt::AlignCenter | Qt::AlignBottom,Qt::white);
    qDebug() << "Registering URL handler...";
    QDesktopServices::setUrlHandler("pirate",&FilePirate::Application(),"handleUrl");
    a.processEvents();
    // Force the user to see the splash screen for at least some time
    QMutex dummy;
    dummy.lock();
    QWaitCondition wait;
    wait.wait(&dummy, 750);
    dummy.unlock();
    // And move on to the rest of loading
    splash->showMessage("Loading settings...",Qt::AlignCenter | Qt::AlignBottom,Qt::white);
    // load the settings here
    FilePirate::Application().settingsLoaded = FilePirate::Application().loadSettings();
    splash->showMessage("Loading local filelist...",Qt::AlignCenter | Qt::AlignBottom,Qt::white);
    FilePirate::Application().fileMon->fullRefreshFileList();

    // bring up the filelist - this is a good time to start up the settings dialog
    // if the user hasn't done so yet...
    splash->showMessage("Finishing up...",Qt::AlignCenter | Qt::AlignBottom,Qt::white);
    FilePirate::Application().moveHelpersToThreads();

    MainWindow w;
    w.show();
    splash->finish(&w);

    a.connect(&a, SIGNAL(messageAvailable(QStringList)), &w, SLOT(secondInstanceMessages(QStringList)));

    delete splash;

    return a.exec();
}
Esempio n. 4
0
void PerformanceDialog::MessageReceived(QString& recv)
{
    QMutexLocker lock(&mMessagesMutex);
    mMessages.push_back(recv);
    if (mMessages.size()==1) {
        // only ever signal on 0 -> 1
        emit messageAvailable();
    }
}
Esempio n. 5
0
// Message coming from a node.
// Consider _only_ UserMessage. Discard other types of messages (debug, etc.)
void DashelInterface::incomingData(Dashel::Stream *stream)
{
	Aseba::Message *message = Aseba::Message::receive(stream);
	Aseba::UserMessage *userMessage = dynamic_cast<Aseba::UserMessage *>(message);

	if (userMessage)
		emit messageAvailable(userMessage);
	else
		delete message;
}
 void deliverMessages(int32_t n = -1) {
   while (n > 0 || (n < 0 && !m_messageQueue.empty())) {
     EXPECT_FALSE(m_messageQueue.empty());
     auto message = std::move(m_messageQueue.front());
     auto m_transport = message.m_transport;
     m_transport->messageAvailable(std::move(message));
     m_messageQueue.pop_front();
     n--;
   }
 }
Esempio n. 7
0
void MessageQueue::readData() {
	bool gotmessage = false, gotsnapshot = false;
	int read, totalread=0;
	do {
		// Read available data
		read = _socket->read(_recvbuffer+_recvcount, MAX_BUF_LEN-_recvcount);
		if(read<0) {
			// Error!
			emit socketError(_socket->errorString());
			return;
		}
		_recvcount += read;

		// Extract all complete messages
		int len;
		while(2 < _recvcount && (len=Message::sniffLength(_recvbuffer)) <= _recvcount) {
			// Whole message received!
			Message *msg = Message::deserialize((const uchar*)_recvbuffer);
			if(!msg) {
				emit badData(len, _recvbuffer[2]);
			} else {
				if(msg->type() == MSG_STREAMPOS) {
					// Special handling for Stream Position message
					emit expectingBytes(static_cast<StreamPos*>(msg)->bytes() + totalread);
					delete msg;
				} else if(_expectingSnapshot) {
					// A message preceded by SnapshotMode::SNAPSHOT goes into the snapshot queue
					_snapshot_recv.enqueue(MessagePtr(msg));
					_expectingSnapshot = false;
					gotsnapshot = true;
				} else {
					if(msg->type() == MSG_SNAPSHOT && static_cast<SnapshotMode*>(msg)->mode() == SnapshotMode::SNAPSHOT) {
						delete msg;
						_expectingSnapshot = true;
					} else {
						_recvqueue.enqueue(MessagePtr(msg));
						gotmessage = true;
					}
				}
			}
			if(len < _recvcount) {
				memmove(_recvbuffer, _recvbuffer+len, _recvcount-len);
			}
			_recvcount -= len;
		}
		totalread += read;
	} while(read>0);

	if(totalread)
		emit bytesReceived(totalread);
	if(gotmessage)
		emit messageAvailable();
	if(gotsnapshot)
		emit snapshotAvailable();
}
/**
	Slot gerant la reception des messages.
	Lorsque l'application recoit un message, ce slot emet le signal
	messageAvailable avec le message recu.
*/
void QETSingleApplication::receiveMessage() {
	QLocalSocket *local_socket = local_server_ -> nextPendingConnection();
	if (!local_socket -> waitForReadyRead(timeout_)) {
		qDebug() << "QETSingleApplication::receiveMessage() :" << qPrintable(local_socket -> errorString()) << "(" << qPrintable(unique_key_) << ")";
		return;
	}
	QByteArray byteArray = local_socket -> readAll();
	QString message = QString::fromUtf8(byteArray.constData());
	emit(messageAvailable(message));
	local_socket -> disconnectFromServer();
}
Esempio n. 9
0
uint8_t* MASASerial::getMessage(){
  if (messageAvailable()){
    inAvailable = false;
    
    resetBuffer();
    
    return dataIn.data;
  
  } else 
    return NULL;
}
Esempio n. 10
0
void MessagePort::start() {
  // Do nothing if we've been cloned or closed.
  if (!isEntangled())
    return;

  DCHECK(getExecutionContext());
  if (m_started)
    return;

  m_entangledChannel->setClient(this);
  m_started = true;
  messageAvailable();
}
Esempio n. 11
0
void MessagePort::start()
{
    // Do nothing if we've been cloned or closed.
    if (!isEntangled())
        return;

    ASSERT(executionContext());
    if (m_started)
        return;

    m_started = true;
    messageAvailable();
}
Esempio n. 12
0
void SingleApplication::receiveMessage()
{
        QLocalSocket *localSocket = localServer->nextPendingConnection();
        if (!localSocket->waitForReadyRead(timeout))
        {
                qDebug(localSocket->errorString().toLatin1());
                return;
        }
        QByteArray byteArray = localSocket->readAll();
        QString message = QString::fromUtf8(byteArray.constData());
        emit messageAvailable(message);
        localSocket->disconnectFromServer();
}
Esempio n. 13
0
int main(int argc, char *argv[])
{
    SingleApplication app(argc, argv, "f35fe4692ace47cb2390a381ccbd30ae"); // md5 hash of "sbrowserSytchev"

    if (app.isRunning())
    {
            app.sendMessage("Hello. I'm the other instance of sbrowser. I'll die. Bye.");
            return 0;
    }

    QDir::setCurrent(QCoreApplication::applicationFilePath().remove(QRegExp("/[^/]+$")));

    // set local codec
    QTextCodec *cyrillicCodec = QTextCodec::codecForName("CP1251");
    QTextCodec::setCodecForTr(cyrillicCodec);
    QTextCodec::setCodecForLocale(cyrillicCodec);
    QTextCodec::setCodecForCStrings(cyrillicCodec);
    QTextCodec::setCodecForTr(QTextCodec::codecForName("CP1251"));

    qInstallMsgHandler(myMessageOutput);

    bool silentStart = false;
    //qDebug() << "Параметры старта всего" << argc;
    QString testplanDirectoryKey("-d");
    QString testplanFileKey("-f");
    for(int i = 0; i < argc; ++i) {
        if (QString(argv[i]) == testplanDirectoryKey) {
            silentStart = true;
        }
        if (QString(argv[i]) == testplanFileKey) {
            silentStart = true;
        }
        //qDebug() << "Параметр [" << i << "] =" << argv[i];
    }


    MainWindow *mainWindow = new MainWindow();

    // Канал связи между приложениями
    QObject::connect(&app, SIGNAL(messageAvailable(QString)), mainWindow, SLOT(receiveApplicationMessage(QString)));

    if (!silentStart)
        mainWindow->show();

    int returnCode;
    returnCode = app.exec();

    delete mainWindow;
    return returnCode;
}
void MainWindow::connectToHost()
{
    client = new AnonymousClient(this);

    connect(client, SIGNAL(sslErrors(QList<QSslError>)), SLOT(sslErrors(QList<QSslError>)));
    connect(client, SIGNAL(messageAvailable(QString)), SLOT(displayMessage(QString)));
    connect(client, SIGNAL(debugAvailable(QString)), debugConsole, SLOT(displayDebug(QString)));
    connect(client, SIGNAL(setPhase0()), SLOT(phase0()));
    connect(client, SIGNAL(setPhase1()), SLOT(phase1()));
    connect(client, SIGNAL(disconnected()), SLOT(disconnectFromhost()));
    connectButton->setEnabled(false);
    disconnectButton->setEnabled(true);

    displayMessage(tr("Connecting..."));
    client->connectToHostEncrypted(settings->value("HostAddress", "localhost").toString(), settings->value("port", 9001).toInt());
}
Esempio n. 15
0
	void Hub::incomingData(Stream *stream)
	{
		// receive message
		Message *message(0);
		try
		{
			message = Message::receive(stream);
		}
		catch (DashelException e)
		{
			// if this stream has a problem, ignore it for now, and let Hub call connectionClosed later.
			std::cerr << "error while reading message" << std::endl;
		}
		
		// send on DBus, the receiver can delete it
		emit messageAvailable(message, stream);
	}
void SingleApplication::checkForMessage()
{
    sharedMemory.lock();
    QByteArray byteArray = QByteArray((char*)sharedMemory.constData(), sharedMemory.size());
    sharedMemory.unlock();
    if (byteArray.left(1) == "0")
        return;
    byteArray.remove(0, 1);
    QString message = QString::fromUtf8(byteArray.constData());
    emit messageAvailable(message);

    // remove message from shared memory.
    byteArray = "0";
    sharedMemory.lock();
    char *to = (char*)sharedMemory.data();
    const char *from = byteArray.data();
    memcpy(to, from, qMin(sharedMemory.size(), byteArray.size()));
    sharedMemory.unlock();
}
Esempio n. 17
0
bool KNSingletonApplication::event(QEvent *e)
{
    //Under Mac OS X, we have to handle open file event as a new argument.
    if(e->type()==QEvent::FileOpen)
    {
        //Cast event as file open event.
        QFileOpenEvent *fileOpenEvent=static_cast<QFileOpenEvent *>(e);
        //Prepare the message stringlist.
        QStringList parameters;
        //Insert an empty string for the first part, follow the file path.
        parameters << "" << fileOpenEvent->file();
        //Emit the file open information.
        emit messageAvailable(parameters);
        //Mission complete.
        return true;
    }
    //Do original event.
    return QApplication::event(e);
}
Esempio n. 18
0
void KNSingletonApplication::onMessageReceive()
{
    //Get the socket from the sender.
    QLocalSocket *client=m_messageServer->nextPendingConnection();
    //Waiting for reading client data.
    if(!client->waitForReadyRead(TimeoutLimit))
    {
        qDebug("Cannot read the client data.");
        return;
    }
    //Get the data, and parse it as string list.
    QByteArray messageData=client->readAll();
    //Disconnect the socket.
    client->disconnectFromServer();
    //Use a data stream to flush data to string list.
    QStringList messages;
    QDataStream dataReader(&messageData, QIODevice::ReadOnly);
    dataReader >> messages;
    //Emit the messages.
    emit messageAvailable(messages);
}
Esempio n. 19
0
PerformanceDialog::PerformanceDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::PerformanceDialog),
    mFirstVSync(true),
    mCurrentRow(0)
{
    ui->setupUi(this);
    mScene = new GridScene;
    mScene->setBackgroundBrush(QBrush(Qt::black));
    mScene->setSceneRect(0,0,33.333,100);
    ui->graphicsView->setScene(mScene);

    ui->graphicsView->setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
//    ui->graphicsView->viewport()->installEventFilter(this);
    ui->tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    ui->pauseButton->setEnabled(false);

    mUpdateValues = new CircularBuffer(60);
    mRenderValues = new CircularBuffer(60);
    mSwapValues = new CircularBuffer(60);
    QObject::connect(this,SIGNAL(messageAvailable()),this,SLOT(processMessages()), Qt::QueuedConnection);

}
Esempio n. 20
0
void SingleApplication::checkForMessage()
{
    QStringList arguments;

    sharedMemory.lock();
    char *from = (char*)sharedMemory.data();

    while(*from != '\0'){
        int sizeToRead = int(*from);
        ++from;

        QByteArray byteArray = QByteArray(from, sizeToRead);
        byteArray[sizeToRead] = '\0';
        from += sizeToRead;

        arguments << QString::fromUtf8(byteArray.constData());
    }

    *(char*)sharedMemory.data() = '\0';
    sharedMemory.unlock();

    if(arguments.size()) emit messageAvailable( arguments );
}
Esempio n. 21
0
/**
 * @brief MainWindow::setApp
 * @param app
 */
void MainWindow::setApp(SingleApplication *app)
{
    a = app;
    connect(a, SIGNAL(messageAvailable(QString)), this, SLOT(messageAvailable(QString)));
}
Esempio n. 22
0
File: main.cpp Progetto: 173210/qcma
int main(int argc, char *argv[])
{
    if(SingleApplication::sendMessage(QObject::tr("A instance of QCMA is already running"))) {
        return 0;
    }

    SingleApplication app(argc, argv);

#ifndef Q_OS_WIN32
    // FIXME: libmtp sends SIGPIPE if a socket write fails crashing the whole app
    // the proper fix is to libmtp to handle the cancel properly or ignoring
    // SIGPIPE on the socket
    signal(SIGPIPE, SIG_IGN);
#endif

    if(app.arguments().contains("--with-debug")) {
        VitaMTP_Set_Logging(VitaMTP_DEBUG);
    } else if(app.arguments().contains("--verbose")) {
        VitaMTP_Set_Logging(VitaMTP_VERBOSE);
    } else {
        VitaMTP_Set_Logging(VitaMTP_NONE);
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
        qInstallMessageHandler(noMessageOutput);
#else
        qInstallMsgHandler(noMessageOutput);
#endif
    }

#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
#endif

    qDebug("Starting QCMA %s", QCMA_VER);

    QTranslator translator;
    QString locale = QLocale().system().name();
    qDebug() << "Current locale:" << locale;

    if(app.arguments().contains("--set-locale")) {
        int index = app.arguments().indexOf("--set-locale");
        if(index + 1 < app.arguments().length()) {
            qDebug("Enforcing locale: %s", app.arguments().at(index + 1).toUtf8().data());
            locale = app.arguments().at(index + 1);
        }
    }

    if(translator.load("qcma_" + locale, ":/resources/translations")) {
        app.installTranslator(&translator);
    } else {
        qDebug() << "Cannot load translation for locale:" << locale;
    }

    QTranslator system_translator;
    system_translator.load("qt_" + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    app.installTranslator(&system_translator);

    qDebug("Starting main thread: 0x%016" PRIxPTR, (uintptr_t)QThread::currentThreadId());

    // set the organization/application for QSettings to work properly
    app.setOrganizationName("qcma");
    app.setApplicationName("qcma");

    //TODO: check if this is actually needed since we don't have a main window by default
    QApplication::setQuitOnLastWindowClosed(false);

    bool showSystray = !app.arguments().contains("--no-systray");

    MainWidget widget;
    widget.prepareApplication(showSystray);

    // receive the message from another process
    QObject::connect(&app, SIGNAL(messageAvailable(QString)), &widget, SLOT(receiveMessage(QString)));

    return app.exec();
}
Esempio n. 23
0
int main(int argc, char *argv[])
{


    SingleApplication a(argc, argv, "some unique");
    if (a.isRunning()){
        qDebug() << a.arguments().count() << "arguments count---";
        if (a.arguments().count() > 1){
            a.sendMessage(QVariant(a.arguments().at(1)).toString());
        }else{
            a.sendMessage("");
        }
        return 0;
    }
    QPixmap pixmap(":/images/splash.png");
    QSplashScreen splash(pixmap);
    //splash.setMask(pixmap.mask());
    splash.show();

    a.setApplicationName("TheocBase");
    a.setOrganizationDomain("theocbase.net");
    a.setApplicationVersion(APP_VERSION);
    qDebug() << "VERSION = " << a.applicationVersion();

    theocbaseDirPath = a.applicationDirPath();
    setDefaultLanguage(true);

    QString databasepath, localdatabasepath;

    // database from resource file
    databasepath = ":/database/theocbase.sqlite";

    // database path

    QString localdatabasedir = QDir::homePath() + "/.TheocBase";
#ifdef Q_OS_WIN
    //localdatabasedir = QString(getenv("APPDATA")) + "/TheocBase";
    QSettings reg("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", QSettings::NativeFormat);
    localdatabasedir = reg.value("AppData").toString() + "\\TheocBase";
#endif
#ifdef Q_OS_MAC
    localdatabasedir = QDir::homePath() + "/Library/TheocBase";
#endif    

    // if users's local database not exist
    if(localdatabasepath == ""){
        localdatabasepath = localdatabasedir + "/theocbase.sqlite";
        if(!QFile::exists(localdatabasepath)){
            // copy database to user's local
            QDir d;
            if(!d.exists(localdatabasedir)) d.mkdir(localdatabasedir);
            QFile::copy(databasepath,localdatabasepath);
            QFile::setPermissions(localdatabasepath,QFile::ReadOwner | QFile::WriteOwner |
                                  QFile::ReadUser | QFile::WriteUser | QFile::ReadGroup |
                                  QFile::WriteOwner | QFile::ReadOther | QFile::WriteOther);
            QMessageBox::information(0,"",QObject::tr("Database copied to ") + localdatabasedir);
        }
    }else{
        if(!QFile::exists(localdatabasepath)){
            QMessageBox::critical(0,"",QObject::tr("Database not found!") + localdatabasepath);
            localdatabasepath = "";
            localdatabasepath = QFileDialog::getOpenFileName(0,
                                        QObject::tr("Choose database"), "/", QObject::tr("SQLite files (*.sqlite)"));
            if(localdatabasepath == "") return -1;
        }
    }

    databasepath = localdatabasepath;

    if(QFile::exists(localdatabasedir + "/restore_backup.sqlite")){
        // restore backup
        QString backupfile = databasepath + "." +
                             QDateTime::currentDateTime().toString("yyyyMMddhhmmss");
        bool ok1 = false;
        bool ok2 = false;
        for(int i=0; i<10;i++){
            SleepThread::sleep(1);
            if (!ok1) ok1 = QFile::rename(databasepath,backupfile);
            if (ok1){
                ok2 = QFile::rename(localdatabasedir + "/restore_backup.sqlite",databasepath);
                if (ok2) break;
            }
        }
        if (!ok2) QMessageBox::information(0,"",QObject::tr("Database restoring failed"));
    }

    sql.databasepath=databasepath;
    tempdatabasepath=databasepath;

    sql.createConnection();    
    sql.updateDatabase(a.applicationVersion());

    setDefaultLanguage(false);

    if(!checkPassword()) return -1;

    transactionStarted = false;
    MainWindow *w = new MainWindow();
    QObject::connect(&a,SIGNAL(messageAvailable(QString)), w, SLOT(receiveMessage(QString)));

    if (a.arguments().count() > 1)
        w->openfile = a.arguments().at(1);
    // hide splash
    splash.finish(w);
    w->show();

    int r = a.exec();

    if (transactionStarted){
        // commit or rollback??
        if (QMessageBox::question(0,"",QObject::tr("Save changes?"),
                QMessageBox::No,QMessageBox::Yes) == QMessageBox::Yes){
            sql.commitTransaction();
        }else{
            sql.rollbackTransaction();
        }
    }
    sql.closeConnection();

    return r;
    //return 0;
}
Esempio n. 24
0
IRCMessageQueue::~IRCMessageQueue()
{
	while (messageAvailable())
		delete getMessage();
}