Ejemplo n.º 1
0
void MaxCube::decodeMetadataMessage(QByteArray data)
{
    QList<QByteArray> list = data.left(data.length()-2).split(',');
    QByteArray dataDecoded = QByteArray::fromBase64(list.at(2));
    qCDebug(dcEQ3) << "====================================================";
    qCDebug(dcEQ3) << "               METADATA message:";
    qCDebug(dcEQ3) << "====================================================";

    // parse room list
    int roomCount = dataDecoded.toHex().mid(4,2).toInt(0,16);

    QByteArray roomRawData = dataDecoded.toHex();
    roomRawData = roomRawData.right(roomRawData.length()-6);

    for(int i = 0; i < roomCount; i++){
        Room *room = new Room(this);
        room->setRoomId(roomRawData.left(2).toInt(0,16));
        int roomNameLength = roomRawData.mid(2,2).toInt(0,16);
        room->setRoomName(QByteArray::fromHex(roomRawData.mid(4,roomNameLength*2)));
        room->setGroupRfAddress(roomRawData.mid(roomNameLength*2 + 4, 6));
        m_roomList.append(room);
        roomRawData = roomRawData.right(roomRawData.length() - ((roomNameLength*2) + 10));
    }
    qCDebug(dcEQ3) << "-------------------------|-------------------------";
    qCDebug(dcEQ3) << "found " << m_roomList.count() << "rooms";
    qCDebug(dcEQ3) << "-------------------------|-------------------------";

    foreach (Room *room, m_roomList) {
        qCDebug(dcEQ3) << "               Room Name | " << room->roomName();
        qCDebug(dcEQ3) << "                 Room ID | " << room->roomId();
        qCDebug(dcEQ3) << "        Group RF Address | " << room->groupRfAddress();
        qCDebug(dcEQ3) << "-------------------------|-------------------------";
    }
void HeadlessHubIntegration::processNewMessage(QByteArray message) {

	qDebug()  << "HeadlessHubIntegration::processNewMessage: message: " << message;

    bool notify = false;
    QString priority("");
    QString from("Test");
    QString title("");
    QString body("");

    do {
    	int index = message.indexOf('|');
		qDebug() << "HeadlessHubIntegration::processNewMessage: index: " << index << "\n";
    	if (index > 0) {
    		if (priority.size() == 0) {
    			priority = message.left(index);
    			message = message.right(message.size() - index - 1);

    			qDebug() << "HeadlessHubIntegration::processNewMessage: priority: " << priority << "\n";
    			qDebug() << "HeadlessHubIntegration::processNewMessage: message: " << message << "\n";

    		} else
    		if (title.size() == 0) {
    			title = message.left(index);
    			message = message.right(message.size() - index - 1);

    			qDebug() << "HeadlessHubIntegration::processNewMessage: title: " << title << "\n";
    			qDebug() << "HeadlessHubIntegration::processNewMessage: message: " << message << "\n";
    		}
    	} else {
    		if (body.size() == 0) {
    			body += message;

    			qDebug() << "HeadlessHubIntegration::processNewMessage: body: " << body << "\n";
    		}

    		message.clear();
    	}
    } while (message.size() > 0);

	//The first part of the push denotes the priority of the message
	switch (priority.toInt()) {
	case PushManager::Low:
		break;
	case PushManager::Medium:
		break;
	case PushManager::High:
		notify = true;
		break;
	default:
		break;
	}

    QVariantMap* itemMap = new QVariantMap();
    (*itemMap)["body"] = body;

    _itemCounter++;
    bool retVal = _testAccount->addHubItem(_testAccount->categoryId(), *itemMap, from, title, QDateTime::currentDateTime().toMSecsSinceEpoch(), QString::number(_itemCounter),"", "",  notify);
}
Ejemplo n.º 3
0
char KGrGameIO::getALine (const bool kgr3, QByteArray & line)
{
    char c;
    line = "";
    while (openFile.getChar (&c)) {
        line = line.append (c);
        if (c == '\n') {
            break;
        }
    }

    // kDebug() << "Raw line:" << line;
    if (line.size() <= 0) {
        // Return a '\0' byte if end-of-file.
        return ('\0');
    }
    if (kgr3) {
        // In KGr 3 format, strip off leading and trailing syntax.
        if (line.startsWith ("// ")) {
            line = line.right (line.size() - 3);
            // kDebug() << "Stripped comment is:" << line;
        }
        else {
            if (line.startsWith (" i18n(\"")) {
                line = ' ' + line.right (line.size() - 7);
            }
            else if (line.startsWith (" NOTi18n(\"")) {
                line = ' ' + line.right (line.size() - 10);
            }
            else if (line.startsWith (" \"")) {
                line = ' ' + line.right (line.size() - 2);
            }
            if (line.endsWith ("\");\n")) {
                line = line.left (line.size() - 4) + '\n';
            }
            else if (line.endsWith ("\\n\"\n")) {
                line = line.left (line.size() - 4) + '\n';
            }
            else if (line.endsWith ("\"\n")) {
                line = line.left (line.size() - 2);
            }
            // kDebug() << "Stripped syntax is:" << line;
        }
        // In Kgr 3 format, return the first byte if not end-of-file.
        c = line.at (0);
        line = line.right (line.size() - 1);
        return (c);
    }
    else {
        // In KGr 2 format, return a space if not end-of-file.
        return (' ');
    }
}
Ejemplo n.º 4
0
void PointPropertyView::updateProperty(Member *m, const QByteArray &array)
{
    MatrixEdit *e = findChild<MatrixEdit*>(QLatin1String("inputLoads"));
    QVBoxLayout *v = findChild<QVBoxLayout*>(QLatin1String("index"));
    QVBoxLayout *u = findChild<QVBoxLayout*>(QLatin1String("insert"));
    QVBoxLayout *w = findChild<QVBoxLayout*>(QLatin1String("remove"));
    if (array.startsWith('i'))
    {
        e->insertRow(array.right(array.size()-1).toInt());
        for (int i=0;i<6;++i)
            e->setText(array.right(array.size()-1).toInt(),i,QString::number(static_cast<Point*>(m)->loads.at(array.right(array.size()-1).toInt())[i]));
        v->addWidget(new QLabel(QString::number(v->count()+1).prepend(QLatin1String("No."))));
        static_cast<QLabel*>(v->itemAt(v->count()-1)->widget())->setFrameShape(QFrame::StyledPanel);
        u->addWidget(new QToolButton);
        static_cast<QToolButton*>(u->itemAt(u->count()-1)->widget())->setText(QLatin1String("+"));
        connect(u->itemAt(u->count()-1)->widget(),SIGNAL(clicked()),SLOT(addLoad()));
        w->addWidget(new QToolButton);
        static_cast<QToolButton*>(w->itemAt(w->count()-1)->widget())->setText(QLatin1String("-"));
        connect(w->itemAt(w->count()-1)->widget(),SIGNAL(clicked()),SLOT(removeLoad()));
    }
    else if (array.startsWith('r'))
    {
        e->removeRow(array.right(array.size()-1).toInt());
        delete v->takeAt(v->count()-1)->widget();
        delete u->takeAt(u->count()-1)->widget();
        delete w->takeAt(w->count()-1)->widget();
    }
    else if (array.startsWith('s'))
    {
        e->insertColumns(0,6);
        e->insertRows(0,static_cast<Point*>(m)->loads.size());
        for (int i=0,j;i<static_cast<Point*>(m)->loads.size();)
        {
            for (j=0;j<6;++j)
                e->setText(i,j,QString::number(static_cast<Point*>(m)->loads.at(i)[j]));
            u->addWidget(new QToolButton);
            static_cast<QToolButton*>(u->itemAt(i)->widget())->setText(QLatin1String("+"));
            connect(u->itemAt(i)->widget(),SIGNAL(clicked()),SLOT(addLoad()));
            w->addWidget(new QToolButton);
            static_cast<QToolButton*>(w->itemAt(w->count()-1)->widget())->setText(QLatin1String("-"));
            connect(w->itemAt(w->count()-1)->widget(),SIGNAL(clicked()),SLOT(removeLoad()));
            v->addWidget(new QLabel(QString::number(++i).prepend(QLatin1String("No."))));
            static_cast<QLabel*>(v->itemAt(i-1)->widget())->setFrameShape(QFrame::StyledPanel);
        }
    }
    else
        e->setText(array.split(' ').first().toInt(),array.split(' ').last().toInt(),QString::number(static_cast<Point*>(m)->loads.at(array.split(' ').first().toInt())[array.split(' ').last().toInt()]));
}
Ejemplo n.º 5
0
//This function gets the node's sequence.  The full parameter only has an effect
//for Velvet LastGraph files where the sequences are shifted from their reverse
//complement.  If full is true and the graph is from Velvet, this function will
//extend the sequence using either the reverse complement or upstream nodes.
QByteArray DeBruijnNode::getFullSequence() const
{
    if (g_assemblyGraph->m_graphFileType != LAST_GRAPH)
        return getSequence();

    //If the code got here, then we are getting a full sequence from a Velvet
    //LastGraph graph, so we need to extend the beginning of the sequence.
    int extensionLength = g_assemblyGraph->m_kmer - 1;

    //If the node is at least k-1 in length, then the necessary sequence can be
    //deduced from the reverse complement node.
    if (getLength() >= extensionLength)
    {
        QByteArray revCompSeq = getReverseComplement()->getSequence();
        QByteArray endOfRevCompSeq = revCompSeq.right(extensionLength);
        QByteArray extension = AssemblyGraph::getReverseComplement(endOfRevCompSeq);
        return extension + getSequence();
    }

    //If the node is not long enough, then we must look in upstream nodes for
    //the rest of the sequence.
    else
    {
        QByteArray extension = getUpstreamSequence(extensionLength);
        if (extension.length() < extensionLength)
        {
            int additionalBases = extensionLength - extension.length();
            QByteArray n;
            n.fill('N', additionalBases);
            extension = n + extension;
        }
        return extension + getSequence();
    }
}
QString NdefFactory::getUriFromUriRecordPayload(const QByteArray &payload) {

	QString uri;

	qDebug() << "XXXX Uri - raw: " << payload.toHex();

	uchar_t uriType;
	int uriLength;

	uriType = payload[0];
	uriLength = payload.length() - 1;

	qDebug() << "XXXX UriType: " << uriType;
	qDebug() << "XXXX UriLength: " << uriLength;

	uri = QString::fromUtf8(payload.right(uriLength).constData(), uriLength);

	if (prefixMapContains(uriType)) {
		uri.prepend(prefixMapFromType(uriType));
	} else {
		qDebug() << QString("URI Prefix %1 not implemented").arg(uriType);
	}

	qDebug() << "XXXX Uri: " << uri;

	return uri;
}
Ejemplo n.º 7
0
RSUERRORCODE rsutransframe::TransB6(QFrame_B6 &rsuB6, const QByteArray message)
{
    int len;
    QFrame_B6Raw raw;

    len=message.length()-3;
    rsuB6.initQFrame_B6();

    if(len != sizeof(QFrame_B6Raw))
    {
        LogMessageToConsle(QObject::tr("B6帧数据的长度ERROR:QFrame_B6Raw:%1,QFrame_B6:%2")
                           .arg(sizeof(QFrame_B6Raw)).arg(len));
        return rsuLenghError;
    }
    else
    {
        memcpy(&raw,message.right(message.length()-2).data(),sizeof(QFrame_B6Raw));
    }

    if(raw.ErrorCode != 0x00)
    {
        LogMessageToConsle(QObject::tr("B6帧数据CodeError"));
        return rsuRecivedB6CodeError;
    }

    rsuB6.OBUID=Swapquint32(raw.OBUID);
    rsuB6.ErrorCode=raw.ErrorCode;
    memcpy(&rsuB6.FileData0ARaw, &raw.FileData0ARaw, sizeof(raw.FileData0ARaw));
    LogMessageToConsle(QObject::tr("B6帧数据解析:正确"));
    return rsuNoError;
}
Ejemplo n.º 8
0
void
setupLogfile()
{
    if ( QFileInfo( logFile().toLocal8Bit() ).size() > LOGFILE_SIZE )
    {
        QByteArray lc;
        {
            QFile f( logFile().toLocal8Bit() );
            f.open( QIODevice::ReadOnly | QIODevice::Text );
            lc = f.readAll();
            f.close();
        }

        QFile::remove( logFile().toLocal8Bit() );

        {
            QFile f( logFile().toLocal8Bit() );
            f.open( QIODevice::WriteOnly | QIODevice::Text );
            f.write( lc.right( LOGFILE_SIZE - ( LOGFILE_SIZE / 4 ) ) );
            f.close();
        }
    }

    logfile.open( logFile().toLocal8Bit(), ios::app );
    qInstallMsgHandler( TomahawkLogHandler );
}
 // The following constants change the appearance of the identicon
 // they have been choosen by trying to make the output look nice.
 Identicon::Identicon(const QByteArray& data)
 {
   //  static_assert(Identicon::COLORS == 2, "Only two colors are implemented");
     // hash with sha256
     QByteArray hash = QCryptographicHash::hash(data, QCryptographicHash::Sha256);
     for (int colorIndex = 0; colorIndex < COLORS; ++colorIndex) {
         const QByteArray hashPart = hash.right(IDENTICON_COLOR_BYTES);
         hash.truncate(hash.length() - IDENTICON_COLOR_BYTES);
 
         const qreal hue = bytesToColor(hashPart);
         // change offset when COLORS != 2
         const qreal lig = static_cast<qreal>(colorIndex) / COLORS + 0.2;
         const qreal sat = 0.5;
         colors[colorIndex].setHslF(hue, sat, lig);
     }
 
     const uint8_t* const hashBytes = reinterpret_cast<const uint8_t*>(hash.constData());
     // compute the block colors from the hash
     for (int row = 0; row < IDENTICON_ROWS; ++row) {
         for (int col = 0; col < ACTIVE_COLS; ++col) {
             const int hashIdx = row * ACTIVE_COLS + col;
             const uint8_t colorIndex = hashBytes[hashIdx] % COLORS;
             identiconColors[row][col] = colorIndex;
         }
     }
 }
Ejemplo n.º 10
0
TagMessage
TagMessage::fromVarLengthMessage( const QByteArray & data )
{
    QString tag = data.constData();
    VarLengthMessage ba = data.right( data.size() - tag.size() - 1 );
    return TagMessage( tag, ba );
}
Ejemplo n.º 11
0
bool KeyStream::decodeMessage(QByteArray& buffer, int macOffset, int offset, int length)
{
    //qDebug() << "decodeMessage seq:" << seq;
    QByteArray base = buffer.left(buffer.size() - 4);
    QByteArray hmac = buffer.right(4);
    QByteArray buffer2 = processBuffer(base, seq++);
    buffer2 = mac->hmacSha1(buffer2);

    QByteArray origBuffer = buffer;
    buffer = base;
    rc4->Cipher(buffer.data(),0,buffer.size());

    for (int i = 0; i < 4; i++)
    {
        if (buffer2[macOffset + i] != hmac[i])
        {
            qDebug() << "error decoding message. macOffset:" << macOffset << "offset:" << offset << "length:" << length << "bufferSize:" << buffer.size();
            qDebug() << "buffer mac:" << buffer2.toHex() << "hmac:" << hmac.toHex();
            qDebug() << "buffer:" << buffer.toHex();
            qDebug() << "origBuffer:" << origBuffer.toHex();
            return false;
        }
    }
    return true;
}
Ejemplo n.º 12
0
void HandshakeResponder::responderParseHalfKeyAndResponderIntegrity(){ //R:2 parse
    m_timeout.stop();
    QByteArray encryptedSymKey;
    m_socketStream >> encryptedSymKey;
    if(isError(encryptedSymKey)) return;

    QByteArray clearSymKey = rsaDecrypt(encryptedSymKey);
    if(clearSymKey.size()<32){
        processError(BadSymmetricKey);
        return;
    }
    m_gcmKey.append(clearSymKey.left(16));      //second half key
    m_gcmBaseIV.append(clearSymKey.right(16));  //second half IV

    QByteArray encryptedRespIntegrity, responderIntegrity;
    m_socketStream >> encryptedRespIntegrity;
    responderIntegrity = gcmDecrypt(encryptedRespIntegrity);

    if(responderIntegrity != m_responderIntegrityHash){
        processError(DataCorrupted);
        return;
    }

    updateIntegrityHash(&m_starterIntegrityHash, clearSymKey+responderIntegrity);
    responderSendStarterIntegrity();
}
Ejemplo n.º 13
0
QByteArray RSAKeyPair::decrypt(QByteArray cryptotext) {
    Q_D(RSAKeyPair);

    QByteArray output;

    int rsize = d->key.len;

    unsigned char *chunk = new unsigned char[rsize];

    for(; cryptotext.size() > 0; ) {
        int dlen = qMin<int>(rsize, cryptotext.size());

        int dec;

        rsa_pkcs1_decrypt(&d->key, RSA_PRIVATE, &dec, (unsigned char *) cryptotext.data(), chunk, dlen);

        output += QByteArray((char *) chunk, dec);

        cryptotext = cryptotext.right(cryptotext.size() - rsize);
    }

    delete chunk;

    return output;
}
QVariant QNearFieldTagType4Symbian::decodeResponse(const QByteArray &command, const QByteArray &response)
{
    BEGIN
    QVariant result;

    OutputByteArray(response);
    if ((command.count() > 2) && (0x00 == command.at(0)))
    {
        if ( (0xA4 == command.at(1)) || (0xD6 == command.at(1)) )
        {
            if (response.count() >= 2)
            {
                LOG("select or write command");
                QByteArray resp = response.right(2);
                result = ((resp.at(0) == 0x90) && (resp.at(1) == 0x00));
            }
        }
        else
        {
            LOG("read command");
            result = response;
        }
    }
    END
    return result;
}
Ejemplo n.º 15
0
RSUERRORCODE rsutransframe::TransB0(QRSUState &rsuState, const QByteArray message)
{
    int len = 0;
    QFrame_B0Raw raw;

    len=message.length()-3;
    rsuState.initQRSUState();

    if(len != sizeof(QFrame_B0Raw))
    {
        LogMessageToConsle(QObject::tr("B0帧数据的长度ERROR:QFrame_B0Raw:%1,QRSUState:%2")
                           .arg(sizeof(QFrame_B0Raw))
                           .arg(len));
        return rsuLenghError;
    }
    else
    {
        memcpy(&raw,message.right(message.length()-2).data(),sizeof(raw));
    }
    rsuState.status = raw.RSUStatus;
    memcpy(rsuState.RSUTerminalID1,raw.OLDRSUTerminalId,sizeof(raw.OLDRSUTerminalId));
    memcpy(rsuState.RSUTerminalID2,raw.NEWRSUTerminalId,sizeof(raw.NEWRSUTerminalId));
    rsuState.bRsuAlgID  = raw.RSUAlgId;
    rsuState.bRsuManuID = raw.RSUManulID;
    rsuState.RsuID = BCDToString(raw.RSUID,3);
    rsuState.RsuVersion=swapWORD(raw.RSUVersion);
    return rsuNoError;
}
Ejemplo n.º 16
0
void setupLogfile()
{
    if ( QFileInfo( LOGFILE ).size() > LOGFILE_SIZE )
    {
        QByteArray lc;
        {
            QFile f( LOGFILE );
            f.open( QIODevice::ReadOnly | QIODevice::Text );
            lc = f.readAll();
            f.close();
        }

        QFile::remove( LOGFILE );

        {
            QFile f( LOGFILE );
            f.open( QIODevice::WriteOnly | QIODevice::Text );
            f.write( lc.right( LOGFILE_SIZE - (LOGFILE_SIZE / 4) ) );
            f.close();
        }
    }

    logfile.open( LOGFILE, std::ios::app );
    qInstallMsgHandler( LogHandler );
}
Ejemplo n.º 17
0
void UCHome_Main_SiteConst::clean_my_name_lable()
{
    //<my:name uid="1673222" />
    //<my:name uid="1673222"></my:name>

    //QString unis = this->codec->toUnicode(this->feed_page_html);
    //QByteArray u8s = this->u8codec->fromUnicode(unis);
    //unis = u8s;
    QByteArray tarr = this->feed_page_html;

    QRegExp exp1 ("<my:name uid=\"[0-9]{1,12}\" />");
    QRegExp exp2 ( "<my:name uid=\"[0-9]{1,12}\"></my:name>");
    
    tarr = tarr.trimmed();
    if(tarr.startsWith("f5b")) {
        tarr = tarr.right(tarr.length()-3);
    }
    if(tarr.endsWith("0")) {
        tarr = tarr.left(tarr.length()-1);
    }
    //unis = unis.replace(exp1, QString(""));
    //unis = unis.replace(exp2, QString(""));
    
    //u8s = this->u8codec->fromUnicode(unis);
    QString unis = this->codec->toUnicode(tarr);

    this->feed_page_utf8_html = this->u8codec->fromUnicode(unis);

    this->feed_page_utf8_html = this->u8codec->fromUnicode(this->codec->toUnicode(this->feed_page_html));
}
Ejemplo n.º 18
0
header_t readBlockHeader(const QByteArray& blockHeader) {
    Q_ASSERT(blockHeader.size() >= 12);
    header_t header;
    header.fingerprint = readShortFromByteArray(blockHeader);
    header.recordCount = readIntFromByteArray(blockHeader.mid(4, 4));
    header.recordSize = readIntFromByteArray(blockHeader.right(4));

    return header;
}
Ejemplo n.º 19
0
bool PwDatabaseV3::readDatabase(const QByteArray& dbBytes) {
    QDataStream stream (dbBytes);
    stream.setByteOrder(QDataStream::LittleEndian);

    PwHeaderV3::ErrorCode headerErrCode = header.read(stream);
    if (headerErrCode != PwHeaderV3::SUCCESS) {
        LOG("%s: %d", PwHeaderV3::getErrorMessage(headerErrCode).toUtf8().constData(), headerErrCode);
        emit dbLoadError(PwHeaderV3::getErrorMessage(headerErrCode), headerErrCode);
        return false;
    }

    /* Calculate the encryption key */
    setPhaseProgressBounds(UNLOCK_PROGRESS_KEY_TRANSFORM);
    PwDatabase::ErrorCode dbErr = transformKey(header.getMasterSeed(), header.getTransformSeed(),
            header.getTransformRounds(), combinedKey, masterKey);
    if (dbErr != PwDatabase::SUCCESS) {
        LOG("Cannot decrypt database - transformKey: %d", dbErr);
        emit dbLoadError(tr("Cannot decrypt database", "A generic error message"), dbErr);
        return false;
    }


    /* Decrypt data */
    setPhaseProgressBounds(UNLOCK_PROGRESS_DECRYPTION);
    int dataSize = dbBytes.size() - header.HEADER_SIZE;
    // DB header not needed for decryption
    QByteArray dbBytesWithoutHeader = dbBytes.right(dataSize);
    QByteArray decryptedData(dataSize, 0);
    ErrorCode err = decryptData(dbBytesWithoutHeader, decryptedData);
    Util::safeClear(dbBytesWithoutHeader);
    if (err != SUCCESS) {
        if (err == DECRYPTED_PADDING_ERROR || err == DECRYPTED_CHECKSUM_MISMATCH) {
            LOG("Cannot decrypt database - decryptData: %d", err);
            emit invalidPasswordOrKey();
        } else {
            // err == CANNOT_DECRYPT_DB
            // err == CONTENT_HASHING_ERROR
            // err == something else
            LOG("Cannot decrypt database - decryptData: %d", err);
            emit dbLoadError(tr("Cannot decrypt database", "An error message"), err);
        }
        return false;
    }

    /* Reading and parsing data*/
    setPhaseProgressBounds(UNLOCK_PROGRESS_PARSE_DATA);
    QDataStream decryptedDataStream(decryptedData);
    decryptedDataStream.setByteOrder(QDataStream::LittleEndian);
    err = readContent(decryptedDataStream);
    Util::safeClear(decryptedData);
    if (err != SUCCESS) {
        emit dbLoadError(tr("Cannot parse database", "An error message. Parsing refers to the analysis/understanding of file content (do not confuse with reading it)."), err);
        return false;
    }

    return true;
}
Ejemplo n.º 20
0
RSUERRORCODE rsutransframe::TransB4(QFrame_B4 &rsuB4, const QByteArray message)
{
    int len;
    QFrame_B4Raw raw;

    len=message.length()-3;
    rsuB4.initQFrame_B4();
    int len1 = sizeof(QFrame_B4Raw);

    if(len != len1)
    {
        LogMessageToConsle(QObject::tr("B4帧数据的长度ERROR:QFrame_B4Raw:%1,QFrame_B4:%2")
                           .arg(sizeof(QFrame_B3Raw)).arg(len));
        return rsuLenghError;
    }
    else
    {
        memcpy(&raw,message.right(message.length()-2).data(),sizeof(QFrame_B4Raw));
    }

    if(raw.ErrorCode != 0x00)
    {
        LogMessageToConsle(QObject::tr("B4帧数据CodeError"));
        return rsuRecivedB4CodeError;
    }

    rsuB4.OBUID=Swapquint32(raw.OBUID);
    rsuB4.ErrorCode=raw.ErrorCode;
    rsuB4.CardRestMoney=Swapquint32(raw.CardRestMoney);

    //卡片基本信息,0015文件内容,
    if(raw.CardType == 0x00)//0:国标卡
    {
        sCardFileConverter.ProBasicRaw2ProCardBasicInfo(rsuB4.CardBasicInfo, raw.FileData0015);
        sCardFileConverter.Pro0012Raw2CardTollInfo(rsuB4.CardTollInfo, raw.FileData0019.raw0012, raw.FileData0009);
    }
    else if(raw.CardType == 0x01)//1: 原云南卡片
    {
//        POldPro0015Raw pOld0015;
//        pOld0015= (POldPro0015Raw)&raw.FileData0015;
//        sCardFileConverter.OldProBasicRaw2ProCardBasicInfo(rsuB4.CardBasicInfo, *pOld0015);//(TOldPro0015Raw)raw.FileData0015

//        POldPro0012Raw pOld0012;
//        pOld0012 = (POldPro0012Raw)&raw.FileData0019.raw0012;
//        sCardFileConverter.Old_Pro0012Raw2CardTollInfo(rsuB4.CardTollInfo, *pOld0012);
//        rsuB4.CardRestMoney = rsuB4.CardRestMoney*100;
    }
    else
    {
        LogMessageToConsle(QObject::tr("B4帧数据错误:卡类型未知"));
        return rsuCardTypeUnknown;
    }
    LogMessageToConsle(QObject::tr("B4帧数据解析:正确"));
    return rsuNoError;
}
void BluetoothRobotCommunicationThread::sendI2C(QObject *addressee
		, QByteArray const &buffer, unsigned const responseSize
		, details::lowLevelInputPort::InputPortEnum const &port)
{
	if (!mPort) {
		emit response(addressee, QByteArray());
		return;
	}

	QByteArray command(buffer.length() + 7, 0);
	command[0] = buffer.length() + 5;
	command[1] = 0x00;
	command[2] = telegramType::directCommandNoResponse;
	command[3] = commandCode::LSWRITE;
	command[4] = port;
	command[5] = buffer.length();
	command[6] = responseSize;
	for (int i = 0; i < buffer.length(); ++i) {
		command[i + 7] = buffer[i];
	}

	send(command);

	if (responseSize < 0)
		return;

	if (!waitForBytes(responseSize, port)) {
		qDebug() << "No response, connection error";
		emit response(addressee, QByteArray());
		return;
	}

	if (responseSize > 0) {
		command.clear();
		command.resize(5);

		command[0] = 0x03;
		command[1] = 0x00;
		command[2] = telegramType::directCommandResponseRequired;
		command[3] = commandCode::LSREAD;
		command[4] = port;

		send(command);

		QByteArray const result = receive(22);
		QByteArray decodedResult = result.right(result.length() - 5);

		emit response(addressee, decodedResult);
	} else {
		// TODO: Correctly process empty required response
		QByteArray result(1, 0);
		emit response(addressee, result);
	}
}
Ejemplo n.º 22
0
void AudioScope::addStereoSamplesToScope(const QByteArray& samples) {
    if (!_isEnabled || _isPaused) {
        return;
    }
    const int16_t* samplesData = reinterpret_cast<const int16_t*>(samples.data());
    int samplesPerChannel = samples.size() / sizeof(int16_t) / STEREO_FACTOR;
    
    addBufferToScope(_scopeOutputLeft, _scopeOutputOffset, samplesData, samplesPerChannel, 0, STEREO_FACTOR);
    _scopeOutputOffset = addBufferToScope(_scopeOutputRight, _scopeOutputOffset, samplesData, samplesPerChannel, 1, STEREO_FACTOR);
    
    _scopeLastFrame = samples.right(AudioConstants::NETWORK_FRAME_BYTES_STEREO);
}
Ejemplo n.º 23
0
RSUERRORCODE rsutransframe::TransB5(QFrame_B5 &rsuB5, const QByteArray message)
{
    int len;
    QFrame_B5Raw raw;

    len=message.length()-3;
    rsuB5.initQFrame_B5();

    if(len != sizeof(QFrame_B5Raw))
    {
        LogMessageToConsle(QObject::tr("B5帧数据的长度ERROR:QFrame_B5Raw:%1,QFrame_B5:%2")
                           .arg(sizeof(QFrame_B5Raw)).arg(len));
        return rsuLenghError;
    }
    else
    {
        memcpy(&raw,message.right(message.length()-2).data(),sizeof(QFrame_B5Raw));
    }
    if(raw.ErrorCode!=0x00)
    {
        LogMessageToConsle(QObject::tr("B5帧数据CodeError"));
        return rsuRecivedB5CodeError;
    }

    rsuB5.OBUID=Swapquint32(raw.OBUID);
    rsuB5.ErrorCode=raw.ErrorCode;

    //消费时间
    bcd2systime(&(rsuB5.PurchaseTime),(char *)(raw.PurchaseTime),7);

    //终端机交易序号
    Raw2HexStr(rsuB5.PSAMTerminalID, raw.PSAMTerminalID,6);

    //PSAM卡交易序号
    rsuB5.PSAMTransSerial=Swapquint32(raw.PSAMTransSerial);

    //CPU卡脱机交易序号
    rsuB5.ICCPayserial=Swapquint16(raw.ICCPayserial);

    //交易类型
    rsuB5.TransType=raw.TransType;

    //交易后卡余额,高位在前,低位在后;
    rsuB5.CardRestMoney=Swapquint32(raw.CardRestMoney);

    //TAC码
    rsuB5.TAC=Swapquint32(raw.TAC);

    //写文件时间,UNIX格式(此时间为天线自己计时时间,只能参考,不能用于验证)????
    UnixTimeToCTime2000(raw.WrFileTime,rsuB5.WrFileTime);
    LogMessageToConsle(QObject::tr("B4帧数据解析:正确"));
    return rsuNoError;
}
Ejemplo n.º 24
0
void WebEngine::writeToSocket(QSslSocket *sslSocket, QByteArray raw) {
    int bytesWritten = 0;
    int bytesRemaining = 0;
    do {
        bytesWritten = sslSocket->write(raw);
        if(bytesWritten == -1) {
            break;
        }
        raw = raw.right(raw.count() - bytesWritten);
        bytesRemaining = raw.count();
    } while(bytesRemaining > 0);
}
Ejemplo n.º 25
0
void Pong::slotDataAvailable()
{
    QByteArray array = mPort->readAll();

    switch(array[0]) {
        case InitGame:
        {
            mSeed = array.right(array.size() - 1).toUInt();

            qsrand(mSeed);

            mThisPIsLeftP = false;
            slotNewGame(false);
            break;
        }
        case StartGame:
        {
            slotStartGame(false);
            break;
        }
        case NewGame:
        {
            slotNewGame(false);
            break;
        }
        case StopGame:
        {
            slotStopGame(false);
            break;
        }
        case MoveSecondPlayerUp:
        {
            if (mThisPIsLeftP) {
                mRightP->r->moveBy(0, -mPaddleInc);
            } else {
                mLeftP->r->moveBy(0, -mPaddleInc);
            }
            checkIfPlayersGoOutOfMap();
            break;
        }
        case MoveSecondPlayerDown:
        {
            if (mThisPIsLeftP) {
                mRightP->r->moveBy(0, mPaddleInc);
            } else {
                mLeftP->r->moveBy(0, mPaddleInc);
            }
            checkIfPlayersGoOutOfMap();
            break;
        }
    }
}
Ejemplo n.º 26
0
void QTerminal::doControlSeq(const QByteArray & seq) {
  switch (seq.right(1).at(0)) {
    case '@':
      this->insertPlainText(QString().fill(' ', seq.left(seq.length() - 1).toInt()));
      break;
    case 'C':
      for (int i = 0; i < seq.left(seq.length() - 1).toInt(); ++i) {
        if (this->textCursor().atEnd()) {
          this->insertPlainText(" ");
        } else {
          this->moveCursor(QTextCursor::Right, QTextCursor::MoveAnchor);
        }
      }
      break;
    case 'D':
      {
        QTextCursor cursor = this->textCursor();
        cursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor,
            seq.left(seq.length() - 1).toInt());
      }
      break;
    case 'J':
      eraseDisplay(seq.left(seq.length() - 1).toInt());
      /* Perl would parse the number at the beginning of the string :-P */
      break;
    case 'K':
      eraseInLine(seq.left(seq.length() - 1).toInt());
      break;
    case 'P':
      deleteChars(seq.left(seq.length() - 1).toInt());
      break;
    case 'h':
      if (seq.left(seq.length() -1).toInt() == 4) {
        insertMode = true;
      } else {
        qDebug("No Can Do ESC [ %s", seq.constData());
      }
      break;
    case 'l':
      if (seq.left(seq.length() -1).toInt() == 4) {
        insertMode = false;
      } else {
        qDebug("No Can Do ESC [ %s", seq.constData());
      }
      break;
    default:
      qDebug("No Can Do ESC [ %s", seq.constData());
      break;
  }
}
Ejemplo n.º 27
0
ReplayViewer::ReplayViewer(const QString &file) : finished(false), paused(false), speeding(false), timerDiff(0), nextRead(quint32(-1))
{
    in = new QFile(file);

    if (!in->open(QFile::ReadOnly)) {
        QMessageBox::critical(nullptr, tr("Error when opening replay file"), tr("The replay file couldn't be opened: %1").arg(file));
        deleteLater();
        return;
    }

    QByteArray version = in->readLine().trimmed();

    if (version != "battle_logs_v2" && version != "battle_logs_v3") {
        QMessageBox::critical(nullptr, tr("Log format not supported"), tr("The replay version of the file isn't supported by this client."));
        deleteLater();
        return;
    }

    this->version = version.right(1).toInt();

    DataStream stream(in, this->version);

    stream >> conf;

    window = new SpectatorWindow(conf);

    QWidget *widget = new QWidget();
    QGridLayout *gl = new QGridLayout(widget);
    gl->addWidget(window->getSceneWidget(), 0, 0);
    gl->addWidget(window->getLogWidget(), 0, 1);

    bar.init();
    gl->addLayout(bar.getLayout(), 1, 0, 1, 2);
    connect(&bar, SIGNAL(paused()), SLOT(pause()));
    connect(&bar, SIGNAL(speedChange(bool)), SLOT(changeSpeed(bool)));
    connect(&bar, SIGNAL(play()), SLOT(play()));
    connect(&bar, SIGNAL(seekNext()), SLOT(seekNext()));

    widget->setWindowTitle(tr("Pok\303\251mon Online Replay"));

    widget->setObjectName("ReplayViewer");
    widget->show();
    //widget->setWindowFlags(Qt::Window);
    widget->setAttribute(Qt::WA_DeleteOnClose);

    connect(widget, SIGNAL(destroyed()), SLOT(deleteLater()));

    t.start();
    read();
}
Ejemplo n.º 28
0
void ClientConnection::sendAllFunction(const QByteArray& array)
{
    if (m_isConnected && m_socket != 0L) {
        quint64 size = array.size();
        quint64 send = 0;

        do {
            QByteArray arrayTmp = array.right(size - send);
            send += m_socket->write(arrayTmp);
        } while (send < size);
    } else {
        qDebug() << "Writing to not opened connection";
    }
}
Ejemplo n.º 29
0
void ServerWorker::_handlePixelStreamMessage( const QByteArray& byteArray )
{
    const SegmentParameters* parameters =
            reinterpret_cast< const SegmentParameters* >( byteArray.data( ));

    Segment segment;
    segment.parameters = *parameters;

    QByteArray imageData =
            byteArray.right( byteArray.size() - sizeof( SegmentParameters ));
    segment.imageData = imageData;

    emit( receivedSegment( _streamUri, _sourceId, segment ));
}
QString UdevAudioInterfacePrivate::cardNumberToName()
{
    QString toFind;
    toFind.sprintf("%2d [", m_cardnum);

    QByteArray line = grepHelper(QLatin1String("/proc/asound/cards"), toFind.toAscii());

    int cut =  line.length() - line.lastIndexOf(" - ") - 3;
    QString name = line.right(cut);
    if (!name.isEmpty()) {
        return name;
    }

    return QString();
}