void PendingCallWatcher::readNdefMessagesFinished(QDBusPendingCallWatcher *watcher)
{
    QNearFieldTarget::RequestId id = m_pendingNdefReads.take(watcher);

    if (!id.isValid()) {
        watcher->deleteLater();
        return;
    }

    QDBusPendingReply<QList<QByteArray> > reply = *watcher;
    if (reply.isError()) {
        QMetaObject::invokeMethod(parent(), "error",
                                  Q_ARG(QNearFieldTarget::Error, QNearFieldTarget::NdefReadError),
                                  Q_ARG(QNearFieldTarget::RequestId, id));
    } else {
        const QList<QByteArray> data = reply.argumentAt<0>();
        foreach (const QByteArray &m, data) {
            qDebug() << Q_FUNC_INFO << m.toHex();
            const QNdefMessage message = QNdefMessage::fromByteArray(m);

            qDebug() << "record count:" << message.count();
            foreach (const QNdefRecord &record, message)
                qDebug() << record.typeNameFormat() << record.type() << record.payload().toHex();

            QMetaObject::invokeMethod(parent(), "ndefMessageRead", Q_ARG(QNdefMessage, message));
        }

        QMetaObject::invokeMethod(parent(), "requestCompleted",
                                  Q_ARG(QNearFieldTarget::RequestId, id));
    }
void CreateEditPage::storeAndExit(void)
{
	bool success;

	QNdefMessage message = prepareDataForStorage();
	if (message.isEmpty() == true) {
		goto fail;
	}

	if (m_tag == TagStorage::NULL_TAG) {
		success = TagStorage::storage()->append(m_name->contents(), 
							message);
	} else if (m_tag == TagStorage::TEMPORARY_TAG) {
		TagStorage::storage()->remove(TagStorage::TEMPORARY_TAG);
		success = TagStorage::storage()->append(m_name->contents(), 
							message);
	} else {
		success = TagStorage::storage()->update(m_tag,
							m_name->contents(),
							message);
	}

	if (success == false) {
		goto fail;
	}

	dismiss();
	return;

fail:
	MMessageBox *box = new MMessageBox(tr("Cannot store the tag. "));
	box->appear(MSceneWindow::DestroyWhenDismissed);
}
/*!
  \brief Deletes any details currently stored in the Smart Poster
  and re-initializes them by parsing the contents of the payload.
  */
void NdefNfcSpRecord::parseRecords()
{
    initializeData();
    QNdefMessage message = QNdefMessage::fromByteArray(payload());
    qDebug() << "Sp Record Count: " << message.count();

    foreach (const QNdefRecord &record, message) {
        qDebug() << "Sp Record type: " << QString(record.type());
        qDebug() << "Sp Type name: " << record.typeNameFormat();

        // URI
        if (record.isRecordType<QNdefNfcUriRecord>()) {
            if (recordUri) { delete recordUri; recordUri = NULL; }
            recordUri = new QNdefNfcUriRecord(record);
            qDebug() << "Sp URI: " << recordUri->uri().toString();
        }
        // Title
        else if (record.isRecordType<QNdefNfcTextRecord>()) {
            QNdefNfcTextRecord* recordTitle = new QNdefNfcTextRecord(record);
            addTitle(*recordTitle);
            if (!recordTitleList.isEmpty()) {
                qDebug() << "Sp Title: " << recordTitleList.last().text();
            }
        }
        // Image
        else if (record.typeNameFormat() == QNdefRecord::Mime &&
                   record.type().startsWith("image/")) {
            if (recordImage) { delete recordImage; recordImage = NULL; }
            recordImage = new NdefNfcMimeImageRecord(record);
            qDebug() << "Sp Image: " << recordImage->format();
        }
        // Action
        else if (record.typeNameFormat() == QNdefRecord::NfcRtd &&
                 QString(record.type()) == "act") {
            if (recordAction) { delete recordAction; recordAction = NULL; }
            recordAction = new NdefNfcActRecord(record);
            qDebug() << "Sp Action: " << action();
        }
        // Size
        else if (record.typeNameFormat() == QNdefRecord::NfcRtd &&
                 QString(record.type()) == "s") {
            if (recordSize) { delete recordSize; recordSize = NULL; }
            recordSize = new NdefNfcSizeRecord(record);
            qDebug() << "Sp Size: " << size();
        }
        // Type
        else if (record.typeNameFormat() == QNdefRecord::NfcRtd &&
                 QString(record.type()) == "t") {
            if (recordType) { delete recordType; recordType = NULL; }
            recordType = new NdefNfcTypeRecord(record);
            qDebug() << "Sp Type: " << type();
        }
        else
        {
            // This class handles all records defined in the Smart Poster
            // specification, so this case should never happen for a valid
            // Smart Poster record in the current version.
            qDebug() << "Sp: Don't know how to handle this record";
        }
    }
Exemple #4
0
void MainPage::messageRead(const QNdefMessage contents)
{
	bool success;
	QNdefMessage in;
	QString name;

	if (contents.length() == 0) {
		success = false;
		goto done;
	}

	/* TODO: UI notification if conversion drops data? */

	/* Convert incoming data so we don't have to deal with this
	   mess later on -- Qt API could have had some consideration
	   for this */
	if (VCardNdefRecord::hasSupportedMimeType(contents[0]) &&
	    contents.length() == 1) {
		in << VCardNdefRecord::fromSupportedMimeType(contents[0]);
	} else if (BtNdefRecord::hasSupportedMimeType(contents[0]) &&
		   contents.length() == 1) {
		in << BtNdefRecord::fromSupportedMimeType(contents[0]);
	} else if (contents[0].isRecordType<NfcHandoverSelectNdefRecord>() &&
		   contents.length() == 2 &&
		   BtNdefRecord::hasSupportedMimeType(contents[1])) {
		in << contents[0];
		in << BtNdefRecord::fromSupportedMimeType(contents[1]);
	} else {
		in = contents;
	}

	mDebug(__func__) << "Saving temp";
	name = "Harvested tag";
	success = TagStorage::storage()->update(TagStorage::TEMPORARY_TAG,
						name, 
						in);
done:
	if (success == false) {
		MMessageBox *box = 
			new MMessageBox(tr("Cannot store the tag. "));
		box->appear(MSceneWindow::DestroyWhenDismissed);
	} else {
		mDebug(__func__) << "Editing temp";
		editTag(TagStorage::TEMPORARY_TAG);
	}
}
Exemple #5
0
/*!
 Description: Unit test for NFC registerNdefMessageHandler with a NDef filter

 TestScenario: 1. Touch a tag with random NDef message/with 'Image + Multiple Text + URI' NDef message/with 'Text + URI' NDef message

 TestExpectedResults: 1. matchedNdefMessage signal will be emitted
*/
void tst_QNearFieldManager::registerNdefMessageHandler_filter()
{
    QFETCH(QNdefFilter, filter);
    QFETCH(QString, hint);

    QNearFieldManager manager;

    MessageListener listener;
    QSignalSpy messageSpy(&listener, SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));

    int id = manager.registerNdefMessageHandler(filter, &listener,
                                                SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));

    QVERIFY(id != -1);

    QNfcTestUtil::ShowAutoMsg(hint, &messageSpy, 1);

    QTRY_VERIFY(!messageSpy.isEmpty());

    const QNdefMessage message = messageSpy.first().at(0).value<QNdefMessage>();

    QNearFieldTarget *target = messageSpy.first().at(1).value<QNearFieldTarget *>();

    QVERIFY(target == NULL);//symbain backend always return NULL target
    QCOMPARE(filter.recordCount(), message.count());
    qDebug()<<"message.count()="<<message.count();
    for (int i = 0; i < filter.recordCount(); ++i)
        {
        if (filter.orderMatch())
            {
            QCOMPARE(filter.recordAt(i).typeNameFormat, message.at(i).typeNameFormat());
            QCOMPARE(filter.recordAt(i).type, message.at(i).type());
            }
        else
            {
            bool matched = false;
            for (int j = 0; j < filter.recordCount(); ++j)
                {
                if (message.at(i).typeNameFormat() == filter.recordAt(i).typeNameFormat && message.at(i).type() == filter.recordAt(i).type)
                    {
                    matched = true;
                    break;
                    }
                }
            QVERIFY(matched);
            }
        }

    QVERIFY(manager.unregisterNdefMessageHandler(id));
}
bool QNXNFCShareManager::shareNdef(const QNdefMessage &message)
{
    bool ok = false;
    NfcShareDataContent content;
    content.setMimeType(RECORD_NDEF);
    content.setData(message.toByteArray());

    NfcShareSetContentError::Type err = _manager->setShareContent(content);

    switch (err) {
        case NfcShareSetContentError::None: {
            ok = true;
            break;
        }

        case NfcShareSetContentError::TransferInProgress: {
            emit error(NfcShareError::TransferInProgress);
            break;
        }

        case NfcShareSetContentError::InvalidShareMode:
        case NfcShareSetContentError::InvalidShareRequest: {
            emit error(NfcShareError::UnsupportedShareMode);
            break;
        }

        case NfcShareSetContentError::Unknown: {
            emit error(NfcShareError::Unknown);
            break;
        }
    }

    if (ok)
        _manager->startTransfer();

    return ok;
}
void NfcPeerToPeer::readText(QLlcpSocket* socket, const bool isServerSocket)
{
    if (!socket)
        return;

    bool hasDatagramWaiting = socket->hasPendingDatagrams();
    if (hasDatagramWaiting)
    {
        // Connection-less
        qint64 datagramSize = socket->pendingDatagramSize();
        char* rawData = new char[datagramSize];
        socket->readDatagram ( rawData, datagramSize );

        // Check if data is NDEF formatted
        QNdefMessage containedNdef = QNdefMessage::fromByteArray(rawData);
        if (containedNdef.count() > 0) {
            // NDEF message found
            qDebug() << "Raw NDEF message received (" << containedNdef.count() << " records)";
            emit ndefMessage(containedNdef);
        }
        else
        {
            // No NDEF message found - output raw data
            QString data = QString::fromUtf8(rawData, datagramSize);
            QString dataLength;
            dataLength.setNum(datagramSize);
            QString message = (isServerSocket ? "Server" : "Client");
            message.append(" (" + dataLength + "): " + data);
            emit rawMessage(message);
        }
        delete rawData;
    }
    else
    {
        // Connection-oriented
        // Parse SNEP
        qDebug() << "Received peer-to-peer data";
        QByteArray rawData = socket->readAll();
        if (m_appSettings->useSnep()) {
            QString snepAnalysis;
            QNdefMessage containedNdef = m_snepManager->analyzeSnepMessage(rawData, snepAnalysis);
            emit rawMessage(snepAnalysis);
            if (containedNdef.count() > 0) {
                // NDEF message
                qDebug() << "SNEP NDEF message received (" << containedNdef.count() << " records)";
                emit ndefMessage(containedNdef);

                // Send back success response
                emit sendData(m_snepManager->createSnepSuccessResponse());
            } else {
                qDebug() << "No / empty NDEF message contained";
            }
        } else {
            // Check if data is NDEF formatted
            QNdefMessage containedNdef = QNdefMessage::fromByteArray(rawData);


            // TODO: Debug
            QString arrayContents = "";
            for (int i = 0; i < rawData.size(); ++i) {
                arrayContents.append(QString("0x") + QString::number(rawData.at(i), 16) + " ");
            }
            qDebug() << "Raw contents of message:\n" << arrayContents;


            if (containedNdef.count() > 0) {
                // NDEF message found
                qDebug() << "Raw NDEF message received (" << containedNdef.count() << " records)";
                emit ndefMessage(containedNdef);
            }
            else
            {
                // No NDEF message found - output raw data
                QString data = QString::fromUtf8(rawData.constData(), rawData.size());
                QString message = (isServerSocket ? "Server" : "Client");
                message.append(": " + data);
                emit rawMessage(message);
            }
        }
    }
}
/*!
  \brief Convert the current data in the record model to an NDEF message.
  */
QNdefMessage* NfcModelToNdef::convertToNdefMessage()
{
    QNdefMessage* ndefMessage = new QNdefMessage();

    NfcTypes::MessageType curMessageType;
    NfcTypes::RecordContent curRecordContent;
    int curRecordIndex = 0;
    if (m_nfcStats) {
        m_nfcStats->resetComposedMsgCount();
    }
    //qDebug() << "NfcModelToNdef::convertToNdefMessage() Record item array size: " << recordItems.size();
    // Go through array and convert the data to Ndef Records
    while(curRecordIndex < m_recordItems.size())
    {
        NfcRecordItem* curItem = m_recordItems[curRecordIndex];
        curRecordContent = curItem->recordContent();
        curMessageType = curItem->messageType();

        // If we find a new record header, check the message type
        // and convert this to a QNdefRecord, which is appended to the
        // ndefMessage.
        if (curRecordContent == NfcTypes::RecordHeader) {
            // Starting a new Ndef Record
            int parseEndIndex = -1;
            curMessageType = curItem->messageType();
            if (m_nfcStats) {
                m_nfcStats->incComposedMsgCount(curMessageType);
            }
            switch (curMessageType) {
            case NfcTypes::MsgSmartPoster:
                ndefMessage->append(*convertSpFromModel(curRecordIndex, parseEndIndex));
                break;
            case NfcTypes::MsgUri:
                ndefMessage->append(*convertUriFromModel(curRecordIndex, parseEndIndex, true));
                break;
            case NfcTypes::MsgText:
                ndefMessage->append(*convertTextFromModel(curRecordIndex, parseEndIndex, true));
                break;
            case NfcTypes::MsgSms:
                ndefMessage->append(*convertSmsFromModel(curRecordIndex, parseEndIndex));
                break;
            case NfcTypes::MsgBusinessCard:
                ndefMessage->append(*convertBusinessCardFromModel(curRecordIndex, parseEndIndex));
                break;
            case NfcTypes::MsgSocialNetwork:
                ndefMessage->append(*convertSocialNetworkFromModel(curRecordIndex, parseEndIndex));
                break;
            case NfcTypes::MsgGeo:
                ndefMessage->append(*convertGeoFromModel(curRecordIndex, parseEndIndex));
                break;
            case NfcTypes::MsgStore:
                ndefMessage->append(*convertStoreFromModel(curRecordIndex, parseEndIndex));
                break;
            case NfcTypes::MsgImage:
                ndefMessage->append(*convertImageFromModel(curRecordIndex, parseEndIndex, true));
                break;
            case NfcTypes::MsgCustom:
                ndefMessage->append(*convertCustomFromModel(curRecordIndex, parseEndIndex));
                break;
            case NfcTypes::MsgLaunchApp:
                ndefMessage->append(*convertLaunchAppFromModel(curRecordIndex, parseEndIndex));
                break;
            case NfcTypes::MsgAndroidAppRecord:
                ndefMessage->append(*convertAndroidAppRecordFromModel(curRecordIndex, parseEndIndex));
                break;
            default:
                // MsgAnnotatedUrl, MsgCombination and a few others
                // are just templates to add multiple records
                // at once and don't exist as a type in the final model.
                qDebug() << "Warning: don't know how to handle this message type in NfcModelToNdef::convertToNdefMessage().";
                break;
            }

            if (parseEndIndex == curRecordIndex || parseEndIndex == -1) {
                // Record wasn't parsed
                // Skip it
                qDebug() << "Warning: unable to parse record " << curRecordIndex;
                curRecordIndex++;
            } else {
                // Parse end index is set - jump over the already parsed items.
                // parseEndIndex is the index of the next item to be looked at,
                // so no need to increment here.
                curRecordIndex = parseEndIndex;
            }
        } else {
            // It shouldn't be possible to have a different record type without
            // having a header item before, so this would be an error in the UI
            qDebug() << "Error in model: new message type without header item at index " << curRecordIndex << " (can be the case while deleting a record)";
            curRecordIndex++;
        }
    }
    return ndefMessage;
}