Пример #1
0
void vProcessNews(XPCTcpSocket *_Socket, int _iNumComponents, char *_sMsgName)
{
    try
    {
        // A XPCMessage object is constructed using message components sent
        // over the network
        XPCMessage newMessage(_iNumComponents, _Socket, _sMsgName);

        if (strcmp(_sMsgName, "BUSINESS") == 0)
        // A thread to process the business message is created
#ifdef UNIX
            XPCPthread<int> businessThread(vNewsThread, (void *)&newMessage);
#else
            XPCThread businessThread(vNewsThread, (void *)&newMessage);
#endif
        else
            // A trhead to process the tech message is created
#ifdef UNIX
            XPCPthread<int> techThread(vNewsThread, (void *)&newMessage);
#else
            XPCThread techThread(vNewsThread, (void *)&newMessage);
#endif
    }
Пример #2
0
void Server::readData()
{
    qDebug()<<"Started Reading Message";
    QDataStream in(tcpSocket);
    in.setVersion(QDataStream::Qt_4_0);
    if (blockSize == 0) {
        if (tcpSocket->bytesAvailable() < (int)sizeof(quint16))
            return;
        in >> blockSize;
    }

    if (tcpSocket->bytesAvailable() < blockSize)
        return;

    QString newLink;
    in >> newLink;

    emit newMessage(newLink);   // sends link out, will be captured by downloader linked w/in main

    linkCombo->addItem(newLink);
    tcpSocket->disconnectFromHost();
    blockSize = 0;
}
Пример #3
0
int acquireLocks(char* serviceName, int servicePort, char* fileName,
                 int numLocks, int64_t offsets[], int64_t lengths[]) {
    int i;
    int lockID;

    printf("acquiring %d locks\n", numLocks);
    MessageClient client = newClient(serviceName, servicePort);

    Message m = newMessage();
    m->type = FILE_LOCK_CLIENT_SERVICE_CLIENT_MESSAGE;
    setStringParam(m, "functionName", "acquire");
    setStringParam(m, "fileName", fileName);
    setIntegerParam(m, "numLocks", numLocks);
    
    createLongArrayParam(m, "offsets", numLocks);
    createLongArrayParam(m, "lengths", numLocks);
    
    for (i = 0; i < numLocks; ++i) {
        setLongArrayParamValue(m, "offsets", i, offsets[i]);
        setLongArrayParamValue(m, "lengths", i, lengths[i]);
    }

    //printf("acquirelocks: Message to be sent:\n");
    //printMessage(m);

    Message reply = clientCall(client, m);
    clientDisconnect(client);
    //printf("acquirelocks: Reply:\n");
    //printMessage(reply);
    //printf("acquirelocks: before getIntegerParam()\n");
    lockID = getIntegerParam(reply, "lockID");

    destroyMessage(m);
    destroyMessage(reply);

    return lockID;
}
void CFullTestMotorWindow::motorAllButtonClicked()
{
    if(!property("testFlag").toBool())
    {
        hardwareTestFrame_0x30 b={_METER_FRAME_HARDWARE_TEST_,0x00};
        setBit(b.command[0],6);
        QByteArray tmp=QByteArray::fromRawData((const char*)&b,sizeof(b));
        ((CApp*)qApp)->_tjob->sendTestData232(tmp);

        _motorAllButton->setText(tr("停止步进电机整体测试"));
        emit newMessage(tr("开始步进电机整体测试"),0);
        setProperty("testFlag",1);
    }
    else
    {
        hardwareTestFrame_0x30 b={_METER_FRAME_HARDWARE_TEST_,0x00};
        clearBit(b.command[0],6);
        QByteArray tmp=QByteArray::fromRawData((const char*)&b,sizeof(b));
        ((CApp*)qApp)->_tjob->sendTestData232(tmp);

        _motorAllButton->setText(tr("开始步进电机整体测试"));
        setProperty("testFlag",0);
    }
}
Пример #5
0
void Connection::dataAvailable(SocketClient *)
{
    while (true) {
        int available = mClient->bytesAvailable();
        assert(available >= 0);
        if (!mPendingRead) {
            if (available < static_cast<int>(sizeof(uint32_t)))
                break;
            char buf[sizeof(uint32_t)];
            const int read = mClient->read(buf, 4);
            assert(read == 4);
            Deserializer strm(buf, read);
            strm >> mPendingRead;
            available -= 4;
        }
        if (available < mPendingRead)
            break;
        char buf[1024];
        char *buffer = buf;
        if (mPendingRead > static_cast<int>(sizeof(buf))) {
            buffer = new char[mPendingRead];
        }
        const int read = mClient->read(buffer, mPendingRead);
        assert(read == mPendingRead);
        Message *message = Messages::create(buffer, read);
        if (message) {
            newMessage()(message, this);
            delete message;
        }
        if (buffer != buf)
            delete[] buffer;

        mPendingRead = 0;
        // mClient->dataAvailable().disconnect(this, &Connection::dataAvailable);
    }
}
Пример #6
0
void Connection::processData()
{
    buffer = read(numBytesForCurrentDataType);
    if (buffer.size() != numBytesForCurrentDataType) {
        abort();
        return;
    }

    switch (currentDataType) {
    case PlainText:
        emit newMessage(username, QString::fromUtf8(buffer));
        break;
    case Code:
        qDebug()<<"emit code";
        emit newCode(username, QString::fromUtf8(buffer));
        break;
    default:
        break;
    }

    currentDataType = Undefined;
    numBytesForCurrentDataType = 0;
    buffer.clear();
}
Пример #7
0
ChatDialog::ChatDialog(QWidget *parent)
    : QDialog(parent)
{
    setupUi(this);

    lineEdit->setFocusPolicy(Qt::StrongFocus);
    textEdit->setFocusPolicy(Qt::NoFocus);
    textEdit->setReadOnly(true);
    listWidget->setFocusPolicy(Qt::NoFocus);

    connect(lineEdit, SIGNAL(returnPressed()), this, SLOT(returnPressed()));
    connect(lineEdit, SIGNAL(returnPressed()), this, SLOT(returnPressed()));
    connect(&client, SIGNAL(newMessage(QString,QString)),
            this, SLOT(appendMessage(QString,QString)));
    connect(&client, SIGNAL(newParticipant(QString)),
            this, SLOT(newParticipant(QString)));
    connect(&client, SIGNAL(participantLeft(QString)),
            this, SLOT(participantLeft(QString)));

    myNickName = client.nickName();
    newParticipant(myNickName);
    tableFormat.setBorder(0);
    QTimer::singleShot(10 * 1000, this, SLOT(showInformation()));
}
Пример #8
0
NetConsole::NetConsole() {
    m_outputPort = 0;
    connect (&m_inputSocket, &QUdpSocket::readyRead, [ = ]() {
        emit newMessage (QString::fromUtf8 (DS::readSocket (&m_inputSocket)));
    });
}
Пример #9
0
void UBWidgetAPIMessageBroker::sendMessage(const QString& pTopicName, const QString& pMessage)
{
    emit newMessage(pTopicName, pMessage);
}
Пример #10
0
MainWindow::MainWindow() : QMainWindow() {
	
	setWindowTitle("Miroslav Beta 7");
	
	menuBar();

	fileMenu = menuBar()->addMenu(tr("File"));
	settingsMenu = menuBar()->addMenu(tr("Settings"));
	
	connectAction = new QAction(tr("Connect..."), this);
	reconnectAction = new QAction(tr("Reconnect"), this);
	disconnectAction = new QAction(tr("Disconnect"), this);
	disconnectAction->setEnabled(false);
	closeWindowAction = new QAction(tr("Close Window"), this);
	quitAction = new QAction(tr("Quit"), this);
	

	fileMenu->addAction(connectAction);
	fileMenu->addAction(reconnectAction);
	fileMenu->addAction(disconnectAction);
	fileMenu->addSeparator();
	fileMenu->addAction(closeWindowAction);
	fileMenu->addAction(quitAction);

	changeNickAction = new QAction(tr("Change Nickname..."), this);
	changeNickAction->setEnabled(false);
	changeColorAction = new QAction(tr("Change Text Color..."), this);
	changeColorAction->setEnabled(false);

	settingsMenu->addAction(changeNickAction);
	settingsMenu->addAction(changeColorAction);

	mainWidget = new MainWidget(this);
	setCentralWidget(mainWidget);
	resize(600,350);
	
	trayIcon = new TrayIcon(this);
	
	// Menu connections
	connect(connectAction, SIGNAL(triggered()), mainWidget, SLOT(requestConnection()));
	connect(reconnectAction, SIGNAL(triggered()), mainWidget, SLOT(loadSettings()));
	connect(disconnectAction, SIGNAL(triggered()), mainWidget, SLOT(requestDisconnect()));
	connect(closeWindowAction, SIGNAL(triggered()), trayIcon, SLOT(showHideWindow()));
	connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
	
	connect(changeNickAction, SIGNAL(triggered()), mainWidget, SLOT(requestChangeNick()));
	connect(changeColorAction, SIGNAL(triggered()), mainWidget, SLOT(requestChangeColor()));
	
	// Menu activate connections
	connect(mainWidget, SIGNAL(canConnect(bool)), this, SLOT(canConnect(bool)));
	connect(mainWidget, SIGNAL(canDisconnect(bool)), this, SLOT(canDisconnect(bool)));
	connect(mainWidget, SIGNAL(canChangeNick(bool)), this, SLOT(canChangeNick(bool)));
	connect(mainWidget, SIGNAL(canChangeColor(bool)), this, SLOT(canChangeColor(bool)));
	
	// Tray Icon connections
	connect(trayIcon, SIGNAL(requestExit()), qApp, SLOT(quit()));
	connect(trayIcon, SIGNAL(showChatWindow(bool)), this, SLOT(setVisible(bool)));	

	connect(mainWidget, SIGNAL(newMessage(QString, QString)), this, SLOT(newMessage(QString, QString)));
	
	mainWidget->loadSettings();
	show();
}
Пример #11
0
void SmsClient::fetched( const QString& id, const QSMSMessage& message )
{
    if (!id.isEmpty()) {
        QMailMessage mail;
        QString subject;
        QString body;
        int part;

        // Construct a full identity for the message.  This should be
        // unique enough to identify messages on different SIM's.
        QDateTime dt = message.timestamp();
        QString identity = QString("sms:%1:%2%3%4%5%6%7:>%8")
                                .arg( simIdentity )
                                .arg( dt.date().year(), 4 )
                                .arg( dt.date().month(), 2 )
                                .arg( dt.date().day(), 2 )
                                .arg( dt.time().hour(), 2 )
                                .arg( dt.time().minute(), 2 )
                                .arg( dt.time().second(), 2 )
                                .arg( id );

        // Add it to the active list, so that we know what's on the
        // inserted SIM right now, as opposed to the cached copy in
        // the mailbox folder.
        activeIds += identity;
        timeStamps += dt;

        // If we already have this message in the mailbox, then ignore it.
        if ( account ) {
            QStringList list = account->getUidlList();
            if ( list.contains( identity ) ) {
                if ( account->deleteMail() )
                    deleteImmediately( id );
                req->nextMessage();
                return;
            }
            list += identity;
            account->setUidlList( list );
        }
        mail.setServerUid( identity );

        // If the sender is not set, but the recipient is, then this
        // is probably an outgoing message that was reflected back
        // by the phone simulator.
        if( !message.sender().isEmpty() )
            mail.setHeaderField( "From", message.sender() );
        else if( !message.recipient().isEmpty() )
            mail.setHeaderField( "From", message.recipient() );

        // Extract the subject and body.
        extractSubjectAndBody( message.text(), subject, body );

        // Set the subject from the first few words of the text.
        mail.setSubject( subject );

        // Determine if the entire body is text, or if it contains attachments.
        bool hasAttachments = false;
        QList<QSMSMessagePart> parts = message.parts();
        for ( part = 0; part < parts.count(); ++part ) {
            if ( !(parts[part].isText()) ) {
                hasAttachments = true;
                break;
            }
        }
        if( !hasAttachments ) {
            QMailMessageContentType type("text/plain; charset=UTF-8");
            mail.setBody( QMailMessageBody::fromData( body, type, QMailMessageBody::Base64 ) );
        } else {
            SMSDecoder::formatMessage( mail, message );
        }

        // Set the reception date.
        QDateTime date = message.timestamp();
        if (!date.isValid())
            date = QDateTime::currentDateTime();
        mail.setDate( QMailTimeStamp( date ) );

        // Synthesize some other headers
        QString smsType;
        switch(message.messageType()) {
            case QSMSMessage::Normal:
                smsType = "normal"; break;
            case QSMSMessage::CellBroadCast:
                smsType = "broadcast"; break;
            case QSMSMessage::StatusReport:
                smsType = "status-report"; break;
            default:
                smsType = "unknown"; break;
        }
        mail.setHeaderField( "X-Sms-Type", smsType );

        QMailId id;
        mail.setId( id );

        mail.setStatus( QMailMessage::Incoming, true);
        mail.setStatus( QMailMessage::Downloaded, true);
        mail.setFromAccount( account->id() );
        mail.setFromMailbox( "" );
        mail.setMessageType( QMailMessage::Sms );

        // Is this necessary?
        QByteArray mailStr = mail.toRfc2822();
        mail.setSize( mailStr.length() );

        emit newMessage(mail);
        
        // If the "deleteMail" flag is set, then delete the message
        // from the SIM immediately, rather than waiting for later.
        if ( account && account->deleteMail() )
            deleteImmediately( QString::number(id.toULongLong()) );

        req->nextMessage();

        sawNewMessage = true;
    } else {
        smsFetching = false;
        if ( sawNewMessage ) {
            // Check again, just in case another new message arrived
            // while we were performing the fetch.
            req->check();
            return;
        }

        emit allMessagesReceived();

        // Make sure there are always 5 free slots on the SIM card
        // so there is enough space for the reception of new messages.
        if ( account && !account->deleteMail()
             && (req->totalMessages() - req->usedMessages()) < 5
             && req->totalMessages() >= 5
             && !timeStamps.isEmpty() ) {
            int toBeDeleted = 5 - (req->totalMessages() - req->usedMessages());
            while ( toBeDeleted-- > 0 && activeIds.size() > 0 ) {
                QDateTime dt = timeStamps[0];
                int index = 0;
                for (int i = 1; i < timeStamps.size(); ++i) {
                    if (timeStamps[i] < dt) {
                        dt = timeStamps[i];
                        index = i;
                    }
                }
                deleteImmediately( activeIds[index] );
                activeIds.removeAt( index );
                timeStamps.removeAt( index );
            }
        }
    }
}
Пример #12
0
	void dcc_send_connection::incoming_message(irc::connection& aConnection, const message& aMessage)
	{
		if (&aConnection != iConnection)
			return;
		if (aMessage.command() != message::PRIVMSG)
			return;
		typedef std::vector<std::pair<std::string::const_iterator, std::string::const_iterator> > bits_t;
		bits_t bits;
		neolib::tokens(aMessage.content(), std::string("\001 "), bits);
		if (neolib::to_upper(neolib::to_string(bits[0])) != "DCC")
			return;
		if (iSendType == Download && neolib::to_upper(neolib::to_string(bits[1])) == "ACCEPT" && bits.size() >= 5)
		{
			if (*bits[2].first == '\"')
			{
				for (bits_t::size_type i = 3; i < bits.size(); ++i)
					if (*(bits[i].second - 1) == '\"')
					{
						bits[2].second = bits[i].second;
						bits.erase(bits.begin() + 3, bits.begin() + i + 1);
						break;
					}
			}
			std::string fileName = neolib::to_string(bits[2]);
			if (fileName == iResumeData->iFileName && 
				neolib::string_to_unsigned_integer(neolib::to_string(bits[3])) == iResumeData->iPort &&
				neolib::string_to_unsigned_integer(neolib::to_string(bits[4])) == iResumeData->iResumeFileSize)
			{
				u_long address = iResumeData->iAddress;
				u_short port = iResumeData->iPort;
				iBytesTransferred = iResumeData->iResumeFileSize;
				iLastBytesTransferred = iBytesTransferred;
				if (!connect(address, port))
				{
					close();
					return;
				}
				neolib::observable<dcc_send_connection_observer>::notify_observers(dcc_send_connection_observer::NotifyTransferStarted);
				if (!open_file())
					return;
			}
		}
		else if (iSendType == Listen && neolib::to_upper(neolib::to_string(bits[1])) == "RESUME" && bits.size() >= 5)
		{
			if (*bits[2].first == '\"')
			{
				for (bits_t::size_type i = 3; i < bits.size(); ++i)
					if (*(bits[i].second - 1) == '\"')
					{
						bits[2].second = bits[i].second;
						bits.erase(bits.begin() + 3, bits.begin() + i + 1);
						break;
					}
			}
			std::string fileName = neolib::to_string(bits[2]);
			if (fileName == iName && 
				neolib::string_to_unsigned_integer(neolib::to_string(bits[3])) == stream_server().local_port())
			{
				iResumeData = resume_data_t(0, stream_server().local_port(), name(), neolib::string_to_unsigned_integer(neolib::to_string(bits[4])));
				message newMessage(*iConnection, message::OUTGOING);
				newMessage.set_command(message::PRIVMSG);
				newMessage.parameters().push_back(iRemoteUser.nick_name());
				newMessage.parameters().push_back("\001DCC ACCEPT "); 
				newMessage.parameters().back() += iResumeData->iFileName + " ";
				newMessage.parameters().back() += neolib::unsigned_integer_to_string<char>(iResumeData->iPort) + " ";
				newMessage.parameters().back() += neolib::unsigned_integer_to_string<char>(iResumeData->iResumeFileSize) + "\001";
				iConnection->send_message(newMessage);
			}
		}
	}
	Private(ContactListAccountMenu* menu, ContactListAccountGroup* _account)
		: QObject(0)
		, account(_account)
		, menu_(menu)
	{
		connect(menu, SIGNAL(aboutToShow()), SLOT(updateActions()));
		connect(account->account(), SIGNAL(updatedActivity()), SLOT(updateActions()));
		connect(account->account(), SIGNAL(updatedAccount()), SLOT(updateActions()));

		statusMenu_ = new StatusMenu(0);
		statusMenu_->setTitle(tr("&Status"));
		connect(statusMenu_, SIGNAL(statusChanged(XMPP::Status::Type)), SLOT(statusChanged(XMPP::Status::Type)));

		moodAction_ = new QAction(tr("Mood"), this);
		connect(moodAction_, SIGNAL(triggered()), SLOT(setMood()));

		setAvatarAction_ = new QAction(tr("Set Avatar"), this);
		connect(setAvatarAction_, SIGNAL(triggered()), SLOT(setAvatar()));

		unsetAvatarAction_ = new QAction(tr("Unset Avatar"), this);
		connect(unsetAvatarAction_, SIGNAL(triggered()), SLOT(unsetAvatar()));

		bookmarksManageAction_ = new QAction(tr("Manage..."), this);
		connect(bookmarksManageAction_, SIGNAL(triggered()), SLOT(bookmarksManage()));

		addContactAction_ = new IconAction(tr("&Add a Contact"), this, "psi/addContact");
		connect(addContactAction_, SIGNAL(triggered()), SLOT(addContact()));

		serviceDiscoveryAction_ = new IconAction(tr("Service &Discovery"), this, "psi/disco");
		connect(serviceDiscoveryAction_, SIGNAL(triggered()), SLOT(serviceDiscovery()));

		newMessageAction_ = new IconAction(tr("New &Blank Message"), this, "psi/sendMessage");
		connect(newMessageAction_, SIGNAL(triggered()), SLOT(newMessage()));

		xmlConsoleAction_ = new IconAction(tr("&XML Console"), this, "psi/xml");
		connect(xmlConsoleAction_, SIGNAL(triggered()), SLOT(xmlConsole()));

		modifyAccountAction_ = new IconAction(tr("&Modify Account..."), this, "psi/account");
		connect(modifyAccountAction_, SIGNAL(triggered()), SLOT(modifyAccount()));

		adminOnlineUsersAction_ = new IconAction(tr("Online Users"), this, "psi/disco");
		connect(adminOnlineUsersAction_, SIGNAL(triggered()), SLOT(adminOnlineUsers()));

		adminSendServerMessageAction_ = new IconAction(tr("Send Server Message"), this, "psi/sendMessage");
		connect(adminSendServerMessageAction_, SIGNAL(triggered()), SLOT(adminSendServerMessage()));

		adminSetMotdAction_ = new QAction(tr("Set MOTD"), this);
		connect(adminSetMotdAction_, SIGNAL(triggered()), SLOT(adminSetMotd()));

		adminUpdateMotdAction_ = new QAction(tr("Update MOTD"), this);
		connect(adminUpdateMotdAction_, SIGNAL(triggered()), SLOT(adminUpdateMotd()));

		adminDeleteMotdAction_ = new IconAction(tr("Delete MOTD"), this, "psi/remove");
		connect(adminDeleteMotdAction_, SIGNAL(triggered()), SLOT(adminDeleteMotd()));

		menu->addMenu(statusMenu_);
		menu->addAction(moodAction_);
		avatarMenu_ = menu->addMenu(tr("Avatar"));
		avatarMenu_->addAction(setAvatarAction_);
		avatarMenu_->addAction(unsetAvatarAction_);
		bookmarksMenu_ = menu->addMenu(tr("Bookmarks"));
		bookmarksMenu_->addAction(bookmarksManageAction_);
		menu->addSeparator();
		menu->addAction(addContactAction_);
		menu->addAction(serviceDiscoveryAction_);
		menu->addAction(newMessageAction_);
		menu->addSeparator();
		menu->addAction(xmlConsoleAction_);
		menu->addSeparator();
		menu->addAction(modifyAccountAction_);
		adminMenu_ = menu->addMenu("&Admin");
		adminMenu_->addAction(adminOnlineUsersAction_);
		adminMenu_->addAction(adminSendServerMessageAction_);
		adminMenu_->addAction(adminSetMotdAction_);
		adminMenu_->addAction(adminUpdateMotdAction_);
		adminMenu_->addAction(adminDeleteMotdAction_);

		updateActions();
	}
Пример #14
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // Initial startup checks
    if (!FilePirate::Application().settingsLoaded)
    {
        settingsWindow.setParent(this, Qt::WindowFlags(Qt::Dialog));
        settingsWindow.show();
        settingsWindow.raise();
        settingsWindow.activateWindow();
    }

    // connect signals
    connect(ui->actionExit,SIGNAL(triggered()),this,SLOT(exitClicked()));
    connect(ui->actionAbout_FilePirate,SIGNAL(triggered()),this,SLOT(aboutClicked()));
    connect(ui->actionSettings,SIGNAL(triggered()),this,SLOT(settingsClicked()));
    connect(ui->actionRefreshFileList, SIGNAL(triggered()), FilePirate::Application().fileMon, SLOT(refreshTimerEvent()));

    /* set up our active transfers widget */
    activeTranfersWidget = new QTreeView(ui->transfersDock);
    activeTranfersWidget->setModel(new ActiveTransferModel(activeTranfersWidget));
    ui->transfersDock->setWidget(activeTranfersWidget);

    /* users widget */
    usersWidget = new QTreeView();
    usersWidget->setModel(new UserModel(usersWidget, FilePirate::Application().userInfo));
    ui->usersDock->setWidget(usersWidget);

    /* central widget */
    mainTabs = new QTabWidget(this);
    this->setCentralWidget(mainTabs);

    /* chat tab */
    chatTab = new TabChat(mainTabs);
    mainTabs->addTab(chatTab, QIcon(":/icons/res/text-balloon.ico"), "Chat");
    connect(FilePirate::Application().ocean, SIGNAL(messageReceived(QHostAddress,QString,QString)), chatTab, SLOT(newMessage(QHostAddress,QString,QString)));
    connect(chatTab, SIGNAL(messageSent(QString)), FilePirate::Application().ocean, SLOT(sendChatMessage(QString)));

    /* helper connections */
    connect(this, SIGNAL(destroyed()), FilePirate::Application().ocean, SLOT(returnToPort()));

    /* let everybody know we've set sail! */
    FilePirate::Application().ocean->start();
    FilePirate::Application().ocean->sendMessage(NET_OCEAN_SAIL, FilePirate::Application().username);
    FilePirate::Application().userInfo->start();
}
Пример #15
0
/**
 * Polls for new LibDS events and emits Qt signals as appropiate.
 * This function is called every 5 milliseconds.
 */
void DriverStation::processEvents()
{
    DS_Event event;
    while (DS_PollEvent (&event)) {
        switch (event.type) {
        case DS_FMS_COMMS_CHANGED:
            emit fmsAddressChanged();
            emit fmsCommunicationsChanged (event.fms.connected);
            break;
        case DS_RADIO_COMMS_CHANGED:
            emit radioAddressChanged();
            emit radioCommunicationsChanged (event.radio.connected);
            break;
        case DS_NETCONSOLE_NEW_MESSAGE:
            emit newMessage (QString::fromUtf8 (event.netconsole.message));
            break;
        case DS_ROBOT_ENABLED_CHANGED:
            emit enabledChanged (event.robot.enabled);
            break;
        case DS_ROBOT_MODE_CHANGED:
            emit controlModeChanged (controlMode());
            break;
        case DS_ROBOT_COMMS_CHANGED:
            emit robotAddressChanged();
            emit robotCommunicationsChanged (event.robot.connected);
            break;
        case DS_ROBOT_CODE_CHANGED:
            emit robotCodeChanged (event.robot.code);
            break;
        case DS_ROBOT_VOLTAGE_CHANGED:
            emit voltageChanged (event.robot.voltage);
            break;
        case DS_ROBOT_CAN_UTIL_CHANGED:
            emit canUsageChanged (event.robot.can_util);
            break;
        case DS_ROBOT_CPU_INFO_CHANGED:
            emit cpuUsageChanged (event.robot.cpu_usage);
            break;
        case DS_ROBOT_RAM_INFO_CHANGED:
            emit ramUsageChanged (event.robot.ram_usage);
            break;
        case DS_ROBOT_DISK_INFO_CHANGED:
            emit diskUsageChanged (event.robot.disk_usage);
            break;
        case DS_ROBOT_STATION_CHANGED:
            emit stationChanged();
            emit allianceChanged (teamAlliance());
            emit positionChanged (teamPosition());
            break;
        case DS_ROBOT_ESTOP_CHANGED:
            emit emergencyStoppedChanged (event.robot.estopped);
            break;
        case DS_STATUS_STRING_CHANGED:
            emit statusChanged (QString::fromUtf8 (DS_GetStatusString()));
            break;
        default:
            break;
        }
    }

    QTimer::singleShot (5, Qt::CoarseTimer, this, SLOT (processEvents()));
}
Пример #16
0
void
BSCWindow::MessageReceived(BMessage *message)
{
	switch (message->what) {				
		case kSelectArea:
		{
			Minimize(true);
			BMessenger messenger(this);
			SelectionWindow *window = new SelectionWindow(messenger, kSelectionWindowClosed);			
			window->Show();
			break;
		}
		
		case kSelectionWindowClosed:
		{
			if (IsMinimized())
				Minimize(false);
				
			SendNotices(kSelectionWindowClosed, message);
			break;
		}
		
		case kCmdToggleRecording:
			fStartStopButton->Invoke();
			break;
		
		case B_OBSERVER_NOTICE_CHANGE:
		{
			int32 code;
			message->FindInt32("be:observe_change_what", &code);
			switch (code) {		
				case B_UPDATE_STATUS_BAR:
				case B_RESET_STATUS_BAR:
				{
					BMessage newMessage(*message);
					message->what = code;
					PostMessage(message, fStatusBar);
					break;
				}
	
				case kMsgControllerCaptureStarted:
					_CaptureStarted();
					break;
	
				case kMsgControllerCaptureStopped:
					_CaptureFinished();
					break;
	
				case kMsgControllerEncodeStarted:
					fStringView->SetText(kEncodingString);
					fCardLayout->SetVisibleItem(1);
					break;
					
				case kMsgControllerEncodeProgress:
				{
					int32 numFiles = 0;
					message->FindInt32("num_files", &numFiles);
					
					fStatusBar->SetMaxValue(float(numFiles));
					
					break;
				}
		
				case kMsgControllerEncodeFinished:
				{
					fStartStopButton->SetEnabled(true);
					//fStringView->SetText(kDoneString);
					fCardLayout->SetVisibleItem((int32)0);
					status_t status = B_OK;
					if (message->FindInt32("status", (int32*)&status) == B_OK
						&& status != B_OK) {
						char errorString[128];
						snprintf(errorString, 128, "A problem has occurred:\n"
							"%s", strerror(status));
						(new BAlert("yo", errorString, "Ok"))->Go();
					}
					
					break;
				}
				default:
					break;
			}
			break;
		}
		

		default:
			BWindow::MessageReceived(message);
			break;
	}
}
Пример #17
0
RosterBox::RosterBox( QWidget* parent, const char* name )
	: QListView( parent, name ), QToolTip( viewport() )
{
	QSettings settings;
	settings.setPath( "qtlen.sf.net", "QTlen" );
	
	settings.beginGroup( "/look" );
	
	header()->hide();
	
	setResizeMode( QListView::AllColumns );
	addColumn( QString::null );
	setTreeStepSize( 5 );
	
	setPaletteBackgroundColor( (QColor)settings.readEntry( "/roster/background", "#eeeeee" ) );
	setPaletteForegroundColor( (QColor)settings.readEntry( "/roster/foreground", "#000000" ) );
	
	setSorting( -1 );
	
	connect( roster_manager, SIGNAL( refreshContext() ),
			this, SLOT( refreshContext() ) );
	
	connect( this, SIGNAL( clicked( QListViewItem * ) ),
			SLOT( clicked( QListViewItem * ) ) );
	connect( this, SIGNAL( doubleClicked( QListViewItem *, const QPoint &, int ) ),
			SLOT( doubleClicked( QListViewItem *, const QPoint &, int ) ) );
	connect( this, SIGNAL( contextMenuRequested( QListViewItem *, const QPoint &, int ) ),
			SLOT( contextMenuRequested( QListViewItem *, const QPoint &, int ) ) );
	
	connect( this, SIGNAL( itemRenamed(QListViewItem *, int, const QString &) ),
			SLOT( itemRenamed(QListViewItem *, int, const QString &) ) );
	
	menu = new QPopupMenu( this );
	menu->insertItem( QIconSet( takePixmap( "msg" ) ), tr( "New &message" ),  this, SLOT( newMessage() ), CTRL+Key_M );
	menu->insertItem( QIconSet( takePixmap( "msg-chat" ) ), tr( "New &chat" ),  this, SLOT( newChatMessage() ), CTRL+Key_C );
	menu->insertSeparator();
	menu->insertItem( QIconSet( takePixmap( "edit" ) ), tr( "Edit contact" ),  this, SLOT( edit() ) );
	menu->insertItem( QIconSet( takePixmap( "find" ) ), tr( "Check in pubdir" ),  this, SLOT( pubdir() ) );
	menu->insertSeparator();
	menu->insertItem( QIconSet( takePixmap( "rename" ) ), tr( "Rename contect" ),  this, SLOT( rename() ) );
	menu->insertItem( QIconSet( takePixmap( "delete" ) ), tr( "Remove contect" ),  this, SLOT( remove() ) );
	
	settings.endGroup();
	
	settings.beginGroup( "/roster" );
	
	setShowOffline( settings.readBoolEntry( "/showOffline", true ) );
	setShowAway( settings.readBoolEntry( "/showAway", true ) );
	
	settings.endGroup();
}
Пример #18
0
void QYoutubeChat::onMessagesLoaded()
{
    QNetworkReply * reply = qobject_cast< QNetworkReply * >( sender() );

    const QString HTML_CONTENT_START = "<html_content><![CDATA[";
    const QString HTML_CONTENT_END = "]]></html_content>";

    QString messagesData = reply->readAll();

    int startMessagesDataPos = messagesData.indexOf( HTML_CONTENT_START ) + HTML_CONTENT_START.length();
    int endMessagesDataPos = messagesData.indexOf( HTML_CONTENT_END, startMessagesDataPos ) - 1;

    messagesData = messagesData.mid( startMessagesDataPos, endMessagesDataPos - startMessagesDataPos + 1 );

    QJsonParseError parseError;

    QJsonDocument jsonDoc = QJsonDocument::fromJson( QByteArray( messagesData.toStdString().c_str() ), &parseError );

    if( parseError.error == QJsonParseError::NoError )
    {
        if( jsonDoc.isObject() )
        {
            QJsonObject jsonObj = jsonDoc.object();

            QJsonArray jsonMessagesArr = jsonObj[ "comments" ].toArray();

            QList< QJsonObject > messagesList;

            foreach( const QJsonValue & value, jsonMessagesArr )
            {
                messagesList.append( value.toObject() );
            }

            qSort( messagesList.begin(), messagesList.end(), cmpJsonObjectByTimeCreated );

            for( int i = 0; i < messagesList.size(); ++i )
            {
                QJsonObject jsonMessageInfo = messagesList[ i ];

                QString message = jsonMessageInfo[ "comment" ].toString();
                QString nickName = jsonMessageInfo[ "author_name" ].toString();

                bool blackListUser = blackList().contains( nickName );
                bool supportersListUser = supportersList().contains( nickName );

                if( !isRemoveBlackListUsers() || !blackListUser )
                {
                    if( blackListUser )
                    {
                        //TODO: игнорируемые
                        emit newMessage( new QChatMessage( YOUTUBE_SERVICE, nickName, message, "ignore", this ) );
                    }
                    else
                    {
                        if( supportersListUser )
                        {
                            //TODO: саппортеры
                            emit newMessage( new QChatMessage( YOUTUBE_SERVICE, nickName, message, "supporter", this ) );
                        }
                        else
                        {
                            if( isContainsAliases( message ) )
                            {
                                //TODO: сообщение к стримеру
                                emit newMessage( new QChatMessage( YOUTUBE_SERVICE, nickName, message, "alias", this ) );
                            }
                            else
                            {
                                //TODO: простое сообщение
                                emit newMessage( new QChatMessage( YOUTUBE_SERVICE, nickName, message, "", this ) );
                            }
                        }
                    }
                }
            }

            lastMessageTime_ = QString::number( jsonObj[ "latest_time" ].toInt() );
        }
Пример #19
0
int main(int argc, char *argv[])
{
    char sBuf[256];        // Stores the user-entered values

    // Initialize the WinSock library
    WSADATA wsaData;
    if (WSAStartup(0x101, &wsaData) != 0)
    {
        cout << "Error initializing WinSock library: " << WSAGetLastError() << endl;
        return 0;
    }

    try
    {
        // A XPCTcpSocket object is created using socket port #6800 and 
        // connected to the host specified on the command-line.  The host 
        // specified must be executing the PubSubServer application
        XPCTcpSocket techSocket((long int)6800);
        techSocket.vConnect(argv[1]);

        while(1)    // Loop forever
        {
            // The user is prompted for the news message.  If the user enters 
            // "QUIT", the client exits.
            cout << "Enter News Item: " << flush;
            cin.getline(sBuf, 256);

            if (strcmp(sBuf, "QUIT") == 0)
                    break;

            // A new XPCMessage object is created.  Three CBodyComponent 
            // objects are specified and the message is given the name of 
            // "TECH".
            XPCMessage newMessage(3, "TECH", PUBLISH, &techSocket);

            // The user-entered news item is inserted into the XPCMessage 
            // object and is given a label of "News"
            newMessage.vInsert("News", sBuf);
            
            // The source of the news item is prompted for.
            cout << "Enter Source: " << flush;
            cin.getline(sBuf, 256);

            // The user-entered source is inserted into the XPCMessage
            // object and is given a label of "Source"
            newMessage.vInsert("Source", sBuf);
    
            // The priority level of the news item is prompted for.
            cout << "Enter Priority Level: " << flush;
            cin.getline(sBuf, 256);

            // The user-entered priority is converted to an integer and
            // inserted into the XPCMessage object.  The priority is given a
            // label of "Priority"
            newMessage.vInsert("Priority", atoi(sBuf));     
            
            // The XPCMessage object is published
            newMessage.vPublish();
        }
    }
    catch(XPCException &exceptOb)
    {
        // All socket communication related exceptions are caught and displayed to
        // the user.
        cout << "Communication Error: " << exceptOb.sGetException() << endl;
        return 0;
    }

    return 1;
}
Пример #20
0
void QTwitchChat::parseMessage()
{
    if( !socket_ )
        return;

    if( socket_->state() == QAbstractSocket::ConnectedState )
    {
        QString line = socket_->readLine();

        //qDebug() << line;

        //поадекватнее надо быть

        if( line.contains ( "376 " + DEFAULT_USER_NICK_NAME ) )
        {
            socket_->write( QString( "JOIN #" + channelName_ + "\r\n" ).toStdString().c_str() );
            getSelf();

            //emit newMessage( new QChatMessage( "qrc:/resources/twitchlogo.png", TWITCH_USER, "Connecting to " + channelName_ + "...", this ) );
            if( isShowSystemMessages() )
                emit newMessage( new QChatMessage( TWITCH_SERVICE, TWITCH_USER, "Connected to " + channelName_ + "...", "", this ) );

            getStatistic();
            if( statisticTimerId_ )
                statisticTimerId_ = startTimer( statisticInterval_ );
        }
        else if( line.contains( "PING" ) )
        {
            qDebug() << line;
            //socket_->write( "PONG tmi.twitch.tv\r\n" );
            socket_->write( "PONG :tmi.twitch.tv\r\n" );
        }
        else
        {
            //TODO: parse message
            if( line.contains( "PRIVMSG" ) && !line.contains( "HISTORYEND" ) && !line.contains( "USERCOLOR") )
            {
                QString nickName = line.mid( 1, line.indexOf( '!' ) - 1 );
                QString message = line.right( line.size() - line.indexOf( ':', 1 ) - 1 );

                //\r\n
                message = message.left( message.size() - 2 );

                //qDebug() << message;

                message = QChatMessage::replaceEscapeCharecters( message );
                message = insertEmotIcons( message );
                //message = QChatMessage::insertLinks( message );

                bool blackListUser = blackList().contains( nickName );
                bool supportersListUser = supportersList().contains( nickName );

                if( !isRemoveBlackListUsers() || !blackListUser )
                {
                    if( blackListUser )
                    {
                        emit newMessage( new QChatMessage( TWITCH_SERVICE, nickName, message, "ignore", this ) );
                    }
                    else
                    {
                        if( supportersListUser )
                        {
                            emit newMessage( new QChatMessage( TWITCH_SERVICE, nickName, message, "supporter", this ) );
                        }
                        else
                        {
                            if( isContainsAliases( message ) )
                            {
                                emit newMessage( new QChatMessage( TWITCH_SERVICE, nickName, message, "alias", this ) );
                            }
                            else
                            {
                                emit newMessage( new QChatMessage( TWITCH_SERVICE, nickName, message, "", this ) );
                            }
                        }
                    }
                }
            }
        }

        if( socket_->canReadLine() )
        {
            parseMessage();
        }
    }
}
Пример #21
0
void mitk::USImageLoggingFilter::AddMessageToCurrentImage(std::string message)
{
  std::pair<int,std::string> newMessage(m_LoggedImages.size()-1,message);
  m_LoggedMessages.insert(newMessage);
}
Пример #22
0
DriverStation::DriverStation()
{
    m_init = false;

    /* Initialize private members */
    m_client      = new DS_Client;
    m_netConsole  = new DS_NetConsole;
    m_elapsedTime = new DS_ElapsedTime;
    m_manager     = new DS_ProtocolManager;
    m_protocol    = Q_NULLPTR;

    /* Update internal values and notify object on robot status events */
    connect (m_manager, SIGNAL (codeChanged            (bool)),
             this,        SLOT (updateRobotStatus      (bool)));
    connect (m_manager, SIGNAL (communicationsChanged  (DS_CommStatus)),
             this,        SLOT (updateRobotStatus      (DS_CommStatus)));
    connect (m_manager, SIGNAL (controlModeChanged     (DS_ControlMode)),
             this,        SLOT (resetElapsedTimer      (DS_ControlMode)));
    connect (m_manager, SIGNAL (codeChanged            (bool)),
             this,      SIGNAL (codeChanged            (bool)));
    connect (m_manager, SIGNAL (communicationsChanged  (DS_CommStatus)),
             this,      SIGNAL (communicationsChanged  (DS_CommStatus)));
    connect (m_manager, SIGNAL (controlModeChanged     (DS_ControlMode)),
             this,      SIGNAL (controlModeChanged     (DS_ControlMode)));
    connect (m_manager, SIGNAL (diskUsageChanged       (int)),
             this,      SIGNAL (diskUsageChanged       (int)));
    connect (m_manager, SIGNAL (ramUsageChanged        (int)),
             this,      SIGNAL (ramUsageChanged        (int)));
    connect (m_manager, SIGNAL (cpuUsageChanged        (int)),
             this,      SIGNAL (cpuUsageChanged        (int)));
    connect (m_manager, SIGNAL (voltageChanged         (QString)),
             this,      SIGNAL (voltageChanged         (QString)));
    connect (m_manager, SIGNAL (voltageBrownoutChanged (bool)),
             this,      SIGNAL (voltageBrownoutChanged (bool)));
    connect (m_manager, SIGNAL (CANInfoReceived        (DS_CAN)),
             this,      SIGNAL (CANInfoReceived        (DS_CAN)));
    connect (m_manager, SIGNAL (emergencyStopped       (void)),
             this,      SIGNAL (emergencyStopped       (void)));
    connect (m_manager, SIGNAL (fmsChanged             (bool)),
             this,      SIGNAL (fmsChanged             (bool)));

    /* Stop timer when the communications status changes */
    connect (m_manager,     SIGNAL (communicationsChanged (DS_CommStatus)),
             m_elapsedTime,   SLOT (stopTimer()));

    /* Robot information has changed */
    connect (m_manager, SIGNAL (libVersionChanged (QString)),
             this,      SIGNAL (libVersionChanged (QString)));
    connect (m_manager, SIGNAL (rioVersionChanged (QString)),
             this,      SIGNAL (rioVersionChanged (QString)));
    connect (m_manager, SIGNAL (pcmVersionChanged (QString)),
             this,      SIGNAL (pcmVersionChanged (QString)));
    connect (m_manager, SIGNAL (pdpVersionChanged (QString)),
             this,      SIGNAL (pdpVersionChanged (QString)));

    /* Sync robot address and calculated IPs automatically */
    connect (m_manager, SIGNAL (robotAddressChanged (QString)),
             m_client,  SLOT   (setRobotAddress     (QString)));

    /* Update the elapsed time text automatically */
    connect (m_elapsedTime, SIGNAL (elapsedTimeChanged (QString)),
             this,          SIGNAL (elapsedTimeChanged (QString)));

    /* New NetConsole message received */
    connect (m_netConsole,  SIGNAL (newMessage (QString)),
             this,          SIGNAL (newMessage (QString)));

    /* Send and read robot packets */
    connect (m_client,  SIGNAL (dataReceived     (QByteArray)),
             this,        SLOT (readRobotPacket  (QByteArray)));
    connect (DS_Timers::getInstance(), SIGNAL    (timeout20()),
             this,                       SLOT    (sendClientPacket()));
}
Пример #23
0
int messenger()
{	
	messengerbg = oslLoadImageFilePNG("system/app/messenger/messengerbg.png", OSL_IN_RAM, OSL_PF_8888);
	
	if (!messengerbg)
		debugDisplay();
	
	oslSetFont(Roboto);
		
	while (!osl_quit)
	{
		LowMemExit();

		oslStartDrawing();	
		
		oslClearScreen(RGB(0,0,0));
		
		oslIntraFontSetStyle(Roboto, fontSize, BLACK, 0, INTRAFONT_ALIGN_LEFT);
		
		controls();	

		oslDrawImageXY(messengerbg, 0, 0);

		navbarButtons(2);
		battery(330,2,0);
		digitaltime(381,4,0,hrTime);
		androidQuickSettings();
		volumeController();
		oslDrawImage(cursor);
		
		if (osl_keys->pressed.square)
		{
			powermenu();
		}
		
		if (osl_keys->pressed.L)
		{
			oslPlaySound(Lock, 1);  
			lockscreen();
		}
		
		if (osl_keys->pressed.circle)
		{
			oslDeleteImage(messengerbg);
			appdrawer();
		}
	
		if ((cursor->x  >= 444 && cursor->x  <= 480) && (cursor->y >= 157 && cursor->y <= 213) && (osl_keys->pressed.cross))
		{
			oslPlaySound(KeypressStandard, 1);  
			oslDeleteImage(messengerbg);
			appdrawer();
		}

		if ((cursor->x  >= 444 && cursor->x  <= 480) && (cursor->y >= 76 && cursor->y <= 155) && (osl_keys->pressed.cross))
		{
			oslPlaySound(KeypressStandard, 1);  
			oslDeleteImage(messengerbg);
			home();
		}
		
		if ((cursor->x  >= 444 && cursor->x  <= 480) && (cursor->y >= 19 && cursor->y <= 75) && (osl_keys->pressed.cross))
		{
			oslPlaySound(KeypressStandard, 1);  
			multitask();
		}
		
		captureScreenshot();
		
		if (cursor->x >= 385 && cursor->x <= 428 && cursor->y >= 210 && cursor->y <= 258 && osl_keys->pressed.cross)
		{
			oslPlaySound(KeypressStandard, 1);  
			oslDeleteImage(messengerbg);
			newMessage();
		}
		
		/*
		if (cursor->x >= 378 && cursor->x <= 434 && cursor->y >= 20 && cursor->y <= 52 && osl_keys->pressed.cross)
		{
			oslPlaySound(KeypressStandard, 1);  
			oslDeleteImage(messengerbg);
			doClient();
		}
		*/
		
		oslEndDrawing(); 
		oslEndFrame(); 
		oslSyncFrame();
	}
	return 0;
}
Пример #24
0
void
BSCWindow::MessageReceived(BMessage *message)
{
	switch (message->what) {			
		case kPauseResumeCapture:
			fController->TogglePause();
			break;
		
		case kSelectArea:
		{
			Minimize(true);
			SelectionWindow *window = new SelectionWindow();
			window->SetTarget(this);
			window->SetCommand(kAreaSelected);
			window->Show();
			break;
		}
		
		case kAreaSelected:
		{
			SendNotices(kAreaSelected, message);
			break;
		}
								
		case kMsgControllerAreaSelectionChanged:
			if (IsMinimized())
				Minimize(false);
			break;
				
		case kMsgGUIToggleCapture:
			if (fCapturing)
				_CaptureFinished();
			else
				_CaptureStarted();
			SendNotices(kMsgGUIToggleCapture);
			break;
		
		
		case B_OBSERVER_NOTICE_CHANGE:
		{
			int32 code;
			message->FindInt32("be:observe_change_what", &code);
			switch (code) {		
				case B_UPDATE_STATUS_BAR:
				case B_RESET_STATUS_BAR:
				{
					BMessage newMessage(*message);
					message->what = code;
					PostMessage(message, fStatusBar);
					break;
				}
				case kMsgControllerEncodeStarted:
					fStringView->Show();
					fStatusBar->Show();
					break;
					
				case kMsgControllerEncodeProgress:
				{
					int32 numFiles = 0;
					message->FindInt32("num_files", &numFiles);
					
					fStatusBar->SetMaxValue(float(numFiles));
					
					break;
				}
		
				case kMsgControllerEncodeFinished:
				{
					fStartStopButton->SetEnabled(true);
					fStringView->Hide();
					fStatusBar->Hide();
					
					status_t status = B_OK;
					if (message->FindInt32("status", (int32*)&status) == B_OK
						&& status != B_OK) {
						char errorString[128];
						snprintf(errorString, 128, "A problem has occurred:\n"
							"%s", strerror(status));
						(new BAlert("yo", errorString, "Ok"))->Go();
					}
					
					break;
				}
				default:
					break;
			}
		}
		

		default:
			BWindow::MessageReceived(message);
			break;
	}
}
void CAdjustTestWaterTemperatureWindow::sendBackData(CDataFrame a)
{
    if(property("testFlag").toBool()||property("read").toInt()!=-1 ||
            property("zero").toInt())
    {
        QByteArray d = a.getData();

        if(a._command == _METER_FRAME_INIT_PRESPONSE_ADJUST_)
        {
            if(property("read").toInt()==1)
            {
                adjustInitPResponseFrame_0x51 rt = frame51FromData(d);

                int num = rt.num_meter[2];

                adjustSaveParaFrame_0x42_0x45 b={_METER_FRAME_SAVE_PARA_WTEMP_ADJUST_,0x00};
                b.command = (0x01<<4);
                b.number = num;

                QByteArray tmp=QByteArray::fromRawData((const char*)&b,sizeof(b));
                ((CApp*)qApp)->_tjob->sendTestData232(tmp);
            }
            else if(property("read").toInt()==0)
            {
                //***保存到结构
                adjustSaveParaFrame_0x42_0x45 b={_METER_FRAME_SAVE_PARA_WTEMP_ADJUST_,0x00};
                b.command = (0x02<<4);
                b.number = property("number").toInt();

                QByteArray tmp;
                for(int i=0;i<property("number").toInt();i++)
                {
                    cf->value_meter["wtemp"][i] = _theoryValue[i]->text().toInt();
                    cf->sample_meter["wtemp"][i] = _sampleValue[i]->text().toInt();
                }

                if(property("number").toInt()>0)
                {
                    tmp = arrangeByte(_sampleValue[0]->text().toInt(),2);
                    b.sample0[0] = tmp[0];
                    b.sample0[1] = tmp[1];
                    tmp = arrangeByte(_theoryValue[0]->text().toInt()+40,2);
                    b.value0[0] = tmp[0];
                    b.value0[1] = tmp[1];
                }
                if(property("number").toInt()>1)
                {
                    tmp = arrangeByte(_sampleValue[1]->text().toInt(),2);
                    b.sample1[0] = tmp[0];
                    b.sample1[1] = tmp[1];
                    tmp = arrangeByte(_theoryValue[1]->text().toInt()+40,2);
                    b.value1[0] = tmp[0];
                    b.value1[1] = tmp[1];
                }
                if(property("number").toInt()>2)
                {
                    tmp = arrangeByte(_sampleValue[2]->text().toInt(),2);
                    b.sample2[0] = tmp[0];
                    b.sample2[1] = tmp[1];
                    tmp = arrangeByte(_theoryValue[2]->text().toInt()+40,2);
                    b.value2[0] = tmp[0];
                    b.value2[1] = tmp[1];
                }
                if(property("number").toInt()>3)
                {
                    tmp = arrangeByte(_sampleValue[3]->text().toInt(),2);
                    b.sample3[0] = tmp[0];
                    b.sample3[1] = tmp[1];
                    tmp = arrangeByte(_theoryValue[3]->text().toInt()+40,2);
                    b.value3[0] = tmp[0];
                    b.value3[1] = tmp[1];
                }
                if(property("number").toInt()>4)
                {
                    tmp = arrangeByte(_sampleValue[4]->text().toInt(),2);
                    b.sample4[0] = tmp[0];
                    b.sample4[1] = tmp[1];
                    tmp = arrangeByte(_theoryValue[4]->text().toInt()+40,2);
                    b.value4[0] = tmp[0];
                    b.value4[1] = tmp[1];
                }
                if(property("number").toInt()>5)
                {
                    tmp = arrangeByte(_sampleValue[5]->text().toInt(),2);
                    b.sample5[0] = tmp[0];
                    b.sample5[1] = tmp[1];
                    tmp = arrangeByte(_theoryValue[5]->text().toInt()+40,2);
                    b.value5[0] = tmp[0];
                    b.value5[1] = tmp[1];
                }
                if(property("number").toInt()>6)
                {
                    tmp = arrangeByte(_sampleValue[6]->text().toInt(),2);
                    b.sample6[0] = tmp[0];
                    b.sample6[1] = tmp[1];
                    tmp = arrangeByte(_theoryValue[6]->text().toInt()+40,2);
                    b.value6[0] = tmp[0];
                    b.value6[1] = tmp[1];
                }
                if(property("number").toInt()>7)
                {
                    tmp = arrangeByte(_sampleValue[7]->text().toInt(),2);
                    b.sample7[0] = tmp[0];
                    b.sample7[1] = tmp[1];
                    tmp = arrangeByte(_theoryValue[7]->text().toInt()+40,2);
                    b.value7[0] = tmp[0];
                    b.value7[1] = tmp[1];
                }

                tmp=QByteArray::fromRawData((const char*)&b,sizeof(b));
                ((CApp*)qApp)->_tjob->sendTestData232(tmp);
            }
        }
        else if(a._command == _METER_FRAME_RSAVE_PARA_WTEMP_ADJUST_)
        {
            if(property("read").toInt()==1)
            {
                adjustSPResponseFrame_0x52_0x55 rt = frame52_55FromData(d);

                if(rt.number <= _MAX_MADJUST_POINT_ && rt.number>0)
                {
                    vu16    value;
                    v16     sample;

	                for(int j=0;j<rt.number;j++)
	                {
                        value[j] = rt.value[j+rt.start]-40;
	                    sample[j] = rt.sample[j+rt.start];
	                }

	                    updateInterface(rt.number,value,sample);
                }
                else
                {
                    setProperty("read",-1);
                    newMessage(tr("参数读取错误,请确定仪表内有正确参数!"),0);
                }
            }
            else if(property("read").toInt()==0)
            {
                _savaStatusLabel->setText(tr("参数保存结束!"));
                setProperty("read",-1);

                for(int i=0;i<_MAX_MADJUST_POINT_;i++)
                {
                    _adjustButton[i]->setEnabled(true);
                    _currentStep[i]->setEnabled(true);
                }
                _zeroButton->setEnabled(true);
                _savaAllAdjustButton->setEnabled(true);
                _writeButton->setEnabled(true);

            }
        }
        else if(a._command == _METER_FRAME_CRESPONSE_ADJUST_)
        {
            if( property("zero").toInt()==1)
            {
                sendFrame(0x3,0x1,0x0);
                setProperty("zero",0);
                setProperty("wait0",1);
                _zeroButton->setEnabled(true);
            }
            else
            {
                adjustCResponseFrame_0x50 rt = frame50FromData(d);
                if(property("wait0").toInt()&&rt.sample!=0)
                {

                }
                else if(property("wait0").toInt()&&rt.sample==0)
                {
                    setProperty("wait0",0);
                }
                else
                {
                    _sampleValue[property("id").toInt()]->setText(QString::number(rt.sample));
                }
            }
        }
        else if(a._command == _METER_FRAME_RSAVE_ADJUST_)
        {
            adjustRSaveFrame_0x5F rt = frame5FFromData(d);
            _savaStatusLabel->setText(tr("参数固化入仪表成功!用时 ") + rt.time + tr(" ms"));
        }
    }
}
Пример #26
0
void MenuItem::mountItem(){
  //Mount the device
  
  //Create the full path to the mountpoint
  QString deviceName = devLabel->text();
  QString mntpoint = MOUNTDIR + deviceName.replace(" ","-"); //take into account spaces in the name

  //Create the fileystem specific command for mounting
  QString tmpFileSystem;
  QString cmd;
  if(filesystem=="UNKNOWN"){
    //prompt for filesystem
    bool selected = false;
    tmpFileSystem = QInputDialog::getItem(0, deviceName+"("+devType+")", tr("Mount as:"), DEVCHECK->AvailableFS(), 0, false, &selected);
    if( !selected || tmpFileSystem.isEmpty() ){ return; } //cancelled
    //Now get the mount command
    cmd = DEVCHECK->getMountCommand(tmpFileSystem, device, mntpoint);
  }else{
    cmd = DEVCHECK->getMountCommand(filesystem, device, mntpoint);
  }

  //Make sure the mntpoint is available
  QDir mpd(mntpoint);
  if(mpd.exists() && !rootRequired){
    //Remove the existing directory (will work only if it is empty)
    mpd.cdUp();
    mpd.rmdir(mntpoint);
  }
  //Prepare the mount command to run
  //QString cmd = fstype + " " +fsopts + " " + device + " " + mntpoint;
  qDebug() << "Mounting device" << device << "on" << mntpoint << "("<<filesystem<<")";
  if(DEBUG_MODE){ qDebug() << " - command:" << cmd; }
  //Generate the run script
  QString runscript = createRunScript( mntpoint, cmd);
  //Now run the script 
  bool ok = !runscript.isEmpty();
  bool tryroot = false;
  QStringList outL("ERROR:SCRIPT");
  //Run the mounting commands
  if(ok && !rootRequired){
    outL.clear();
    outL = systemCMD(runscript);
    //qDebug() << "Mount return code 1:" << outL;
    //if it could not mount device with permissions issues - try as root
    if( !outL.filter("Permission denied").isEmpty() || !outL.filter("not permitted").isEmpty() ){ 
      qDebug() << " - Permissions issue, try as root";
      tryroot = true; 
    } 
  }
  if( (ok && rootRequired) || tryroot ){
    outL.clear();
    outL = systemCMD("pc-su "+runscript);
    //qDebug() << "Mount return code 2:" << outL;
  }
  //Now parse the return code
  QString result, title;
  mountedHere = true; //need to set this before running isMounted to update icons right
  ok = isMounted();
  mountedHere = ok; //now make sure it is the proper value
  if( ok ){
	title = tr("Success");
	result = QString( tr("%1 mounted at %2") ).arg(deviceName).arg(mntpoint);
	if(tryroot){ rootRequired = true; } //flag this as requiring root for later
  }else if( !outL.filter("ERROR:MOUNTPOINT").isEmpty() ){
	title = tr("Failure");
	result = QString( tr("Could not create mountpoint: %1") ).arg(mntpoint);
  }else if( !outL.filter("ERROR:MOUNTING").isEmpty() ){
	title = tr("Failure");
	result = QString( tr("Could not mount device %1 on %2 (%3)") ).arg(deviceName, mntpoint, filesystem);
  }else{
	QString tmp = outL.join("");
	  tmp.remove("password:"******"General Error output:" << outL;
	  title = tr("General Error");
	  result = tr("Could not create/run the device mounting script");
	}
  }
  qDebug() << "pc-mounttray: "<<title << result;
  if(DEBUG_MODE){ qDebug() << " - output:" << outL; }
  
  //Output the proper signals depending upon success
  if(ok){
    emit itemMounted(mntpoint);
    mountpoint = mntpoint;
    if( !tmpFileSystem.isEmpty() ){ filesystem = tmpFileSystem; } //this one worked - use it in the future
  }else{
    mountpoint.clear();
  }
  if( !checkAutomount->isChecked()  && !(title.isEmpty() && result.isEmpty()) ){
    emit newMessage(title, result); //suppress the output message if it was automounted
  }
  //Now remove the runscript
  //if(ok)  //only for testing purposes
    QFile::remove(runscript);
  
}
Пример #27
0
void Guitest::sendMsg(QString message){
    this->message = message;
    emit newMessage(user, message);
}
Пример #28
0
void ChatDialog::chatNewMessage(ChatWidget*)
{
	emit newMessage(this);
}
Пример #29
0
    void DemodCW::demod(float *buffer, int length)
    {
        //OK
        int i;
        int c;
        QString message = "";

        /* main decoding loop */
           while(length > 0) {
                buffer++;
                length--;
                c = *buffer;
                if (c > 32767) c = 65536 - c;
                state->l1.demodcw.s += c;
            }

        while(state->l1.demodcw.s > state->l1.demodcw.nsamp) {
            --state->l1.demodcw.s;

            state->l1.demodcw.tt = state->l1.demodcw.tt + state->l1.demodcw.s - state->l1.demodcw.subsamp[state->l1.demodcw.bp];
            state->l1.demodcw.subsamp[state->l1.demodcw.bp] = state->l1.demodcw.s;
            state->l1.demodcw.bp = (state->l1.demodcw.bp+1) % state->l1.demodcw.range;

            /* wait until we have an idea of the average signal level */
            if (++state->l1.demodcw.pass <= state->l1.demodcw.range)
            {
                qDebug() << "Range pass";
                continue;
            }

            state->l1.demodcw.thres = state->l1.demodcw.tt / state->l1.demodcw.range;
            state->l1.demodcw.bit = (10*state->l1.demodcw.s) > (12*state->l1.demodcw.thres) ? 1 : 0;

            if (state->l1.demodcw.bit == state->l1.demodcw.lbit)
            {
                state->l1.demodcw.run++;
                //qDebug() << "run++";
                continue;
            }

            state->l1.demodcw.d = (10*state->l1.demodcw.run) / state->l1.demodcw.ditlength;

            if (state->l1.demodcw.lbit == 1)
            {
                if ((state->l1.demodcw.d > 5) && (state->l1.demodcw.d < 20))
                {
                    *state->l1.demodcw.lp++ = '.';
                    qDebug() << "Dot";
                }

                if ((state->l1.demodcw.d >= 20) && (state->l1.demodcw.d < 40))
                {
                    *state->l1.demodcw.lp++ = '-';
                    qDebug() << "Dit";
                }
                //*state->l1.demodcw.lp = '\0';
                state->l1.demodcw.run1 = state->l1.demodcw.run;
                if (state->l1.demodcw.lp == &state->l1.demodcw.line[79]) state->l1.demodcw.lp--; /* prevent overflow */
            }

            if ((state->l1.demodcw.lbit == 0) && (state->l1.demodcw.lp != state->l1.demodcw.line))
            {
                if (state->l1.demodcw.d >= 20)
                {
                    for (i=0; *morse[i+1] != '?'; i += 2)
                        if (strcmp (morse[i+1], state->l1.demodcw.line) == 0)
                            break;
                    if (*morse[i+1] == '?')
                    {
                        message.append(state->l1.demodcw.line);
                        qDebug() << message;
                    }
                    else
                    {
                        message.append(*morse[i]);
                        qDebug() << message;
                    }
                    if (state->l1.demodcw.d > 80)
                    {
                        message.append(" ");
                        qDebug() << message;
                        emit newMessage(message);
                    }
                    state->l1.demodcw.lp = state->l1.demodcw.line;
                }
                /* check if a "dah-do" */
                if ((state->l1.demodcw.run1 > 2) && ((state->l1.demodcw.run1) > (2*state->l1.demodcw.run)))
                {
                    state->l1.demodcw.d = (state->l1.demodcw.run+state->l1.demodcw.run1) / 4;
                    if ((state->l1.demodcw.d > (SUBSAMP/2)) &&
                            ((3*state->l1.demodcw.d) > (2*state->l1.demodcw.ditlength)) && ((2*state->l1.demodcw.d) < (3*state->l1.demodcw.ditlength)))
                    {
                        state->l1.demodcw.ditlength = state->l1.demodcw.d;
                        qDebug() << state->l1.demodcw.ditlength;
                    }
                    state->l1.demodcw.run1=0;
                }
            }
            state->l1.demodcw.lbit = state->l1.demodcw.bit;
            state->l1.demodcw.run = 1;
        }

    }
Пример #30
0
void ChatWidget::addChatMsg(bool incoming, const QString &name, const QDateTime &sendTime, const QDateTime &recvTime, const QString &message, enumChatType chatType)
{
#ifdef CHAT_DEBUG
	std::cout << "ChatWidget::addChatMsg message : " << message.toStdString() << std::endl;
#endif

	unsigned int formatTextFlag = RSHTML_FORMATTEXT_EMBED_LINKS | RSHTML_FORMATTEXT_OPTIMIZE;
	unsigned int formatFlag = 0;

	// embed smileys ?
	if (Settings->valueFromGroup(QString("Chat"), QString::fromUtf8("Emoteicons_PrivatChat"), true).toBool()) {
		formatTextFlag |= RSHTML_FORMATTEXT_EMBED_SMILEYS;
	}

	// Always fix colors
	formatTextFlag |= RSHTML_FORMATTEXT_FIX_COLORS;
	qreal desiredContrast = Settings->valueFromGroup("Chat", "MinimumContrast", 4.5).toDouble();
	QColor backgroundColor = ui->textBrowser->palette().base().color();

	// Remove font name, size, bold, italics?
	if (!Settings->valueFromGroup("Chat", "EnableCustomFonts", true).toBool()) {
		formatTextFlag |= RSHTML_FORMATTEXT_REMOVE_FONT_FAMILY;
	}
	if (!Settings->valueFromGroup("Chat", "EnableCustomFontSize", true).toBool()) {
		formatTextFlag |= RSHTML_FORMATTEXT_REMOVE_FONT_SIZE;
	}
	if (!Settings->valueFromGroup("Chat", "EnableBold", true).toBool()) {
		formatTextFlag |= RSHTML_FORMATTEXT_REMOVE_FONT_WEIGHT;
	}
	if (!Settings->valueFromGroup("Chat", "EnableItalics", true).toBool()) {
		formatTextFlag |= RSHTML_FORMATTEXT_REMOVE_FONT_STYLE;
	}

	ChatStyle::enumFormatMessage type;
	if (chatType == TYPE_OFFLINE) {
		type = ChatStyle::FORMATMSG_OOUTGOING;
	} else if (chatType == TYPE_SYSTEM) {
		type = ChatStyle::FORMATMSG_SYSTEM;
	} else if (chatType == TYPE_HISTORY) {
		type = incoming ? ChatStyle::FORMATMSG_HINCOMING : ChatStyle::FORMATMSG_HOUTGOING;
	} else {
		type = incoming ? ChatStyle::FORMATMSG_INCOMING : ChatStyle::FORMATMSG_OUTGOING;
	}

	if (chatType == TYPE_SYSTEM) {
		formatFlag |= CHAT_FORMATMSG_SYSTEM;
	}

	QString formattedMessage = RsHtml().formatText(ui->textBrowser->document(), message, formatTextFlag, backgroundColor, desiredContrast);
	QString formatMsg = chatStyle.formatMessage(type, name, incoming ? sendTime : recvTime, formattedMessage, formatFlag);

	ui->textBrowser->append(formatMsg);

	resetStatusBar();

	if (incoming && chatType == TYPE_NORMAL) {
		emit newMessage(this);

		if (!isActive()) {
			newMessages = true;
		}

		emit infoChanged(this);
	}
}