summaryrefslogtreecommitdiffstats
path: root/src/nfc/qnearfieldtagtype2.cpp
blob: b679fa9d3c614ede0ed83eceefbc2585fd5a9126 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtNfc module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qnearfieldtagtype2_p.h"
#include "qnearfieldtarget_p.h"

#include <QtCore/QVariant>
#include <QtCore/QCoreApplication>
#include <QtCore/QTime>

#include <QtCore/QDebug>

QT_BEGIN_NAMESPACE

/*!
    \class QNearFieldTagType2
    \brief The QNearFieldTagType2 class provides an interface for communicating with an NFC Tag
           Type 2 tag.

    \ingroup connectivity-nfc
    \inmodule QtNfc
    \internal
*/

/*!
    \fn Type QNearFieldTagType2::type() const
    \reimp
*/

struct SectorSelectState {
    int timerId;    // id of timer used for passive ack
    quint8 sector;  // sector being selected
};

class QNearFieldTagType2Private
{
public:
    QNearFieldTagType2Private() : m_currentSector(0) { }

    QMap<QNearFieldTarget::RequestId, QByteArray> m_pendingInternalCommands;

    quint8 m_currentSector;

    QMap<QNearFieldTarget::RequestId, SectorSelectState> m_pendingSectorSelectCommands;
};

static QVariant decodeResponse(const QByteArray &command, const QByteArray &response)
{
    quint8 opcode = command.at(0);

    switch (opcode) {
    case 0xa2:  // WRITE
        return quint8(response.at(0)) == 0x0a;
    case 0xc2:  // SECTOR SELECT (Command Packet 1)
        return quint8(response.at(0)) == 0x0a;
    }

    return QVariant();
}

/*!
    Constructs a new tag type 2 near field target with \a parent.
*/
QNearFieldTagType2::QNearFieldTagType2(QObject *parent)
:   QNearFieldTarget(parent), d_ptr(new QNearFieldTagType2Private)
{
}

/*!
    Destroys the tag type 2 near field target.
*/
QNearFieldTagType2::~QNearFieldTagType2()
{
    delete d_ptr;
}

/*!
    \reimp
*/
bool QNearFieldTagType2::hasNdefMessage()
{
    qWarning() << Q_FUNC_INFO << "is unimplemeted";
    return false;
}

/*!
    \reimp
*/
QNearFieldTarget::RequestId QNearFieldTagType2::readNdefMessages()
{
    return RequestId();
}

/*!
    \reimp
*/
QNearFieldTarget::RequestId QNearFieldTagType2::writeNdefMessages(const QList<QNdefMessage> &messages)
{
    Q_UNUSED(messages);

    return RequestId();
}

/*!
    Returns the NFC Tag Type 2 specification version number that the tag supports.
*/
quint8 QNearFieldTagType2::version()
{
    Q_D(QNearFieldTagType2);
    if (d->m_currentSector != 0) {
        RequestId id = selectSector(0);
        if (!waitForRequestCompleted(id))
            return 0;
    }

    RequestId id = readBlock(0);
    if (!waitForRequestCompleted(id))
        return 0;

    const QByteArray data = requestResponse(id).toByteArray();
    return data.at(13);
}

/*!
    Returns the memory size in bytes of the tag.
*/
int QNearFieldTagType2::memorySize()
{
    Q_D(QNearFieldTagType2);
    if (d->m_currentSector != 0) {
        RequestId id = selectSector(0);
        if (!waitForRequestCompleted(id))
            return 0;
    }

    RequestId id = readBlock(0);
    if (!waitForRequestCompleted(id))
        return 0;

    const QByteArray data = requestResponse(id).toByteArray();
    return 8 * quint8(data.at(14));
}

/*!
    Requests 16 bytes of data starting at \a blockAddress. Returns a request id which can be used
    to track the completion status of the request.

    Once the request completes successfully the response can be retrieved from the
    requestResponse() function. The response of this request will be a QByteArray.

    \sa requestCompleted(), waitForRequestCompleted()
*/
QNearFieldTarget::RequestId QNearFieldTagType2::readBlock(quint8 blockAddress)
{
    QByteArray command;
    command.append(char(0x30));         // READ
    command.append(char(blockAddress)); // Block address

    return sendCommand(command);
}

/*!
    Writes 4 bytes of \a data to the block at \a blockAddress. Returns a request id which can be
    used to track the completion status of the request.

    Once the request completes the response can be retrieved from the requestResponse() function.
    The response of this request will be a boolean value, true for success; otherwise false.

    Returns true on success; otherwise returns false.
*/
QNearFieldTarget::RequestId QNearFieldTagType2::writeBlock(quint8 blockAddress,
                                                           const QByteArray &data)
{
    if (data.length() != 4)
        return RequestId();

    QByteArray command;
    command.append(char(0xa2));         // WRITE
    command.append(char(blockAddress)); // Block address
    command.append(data);               // Data

    RequestId id = sendCommand(command);

    Q_D(QNearFieldTagType2);

    d->m_pendingInternalCommands.insert(id, command);

    return id;
}

/*!
    Selects the \a sector upon which subsequent readBlock() and writeBlock() operations will act.

    Returns a request id which can be used to track the completion status of the request.

    Once the request completes the response can be retrieved from the requestResponse() function.
    The response of this request will be a boolean value, true for success; otherwise false.

    \note this request has a passive acknowledgement mechanism. The operation is deemed successful
    if no response is received within 1ms. It will therefore take a minimum of 1 millisecond for
    the requestCompleted() signal to be emitted and calling waitForRequestCompleted() on the
    returned request id may cause the current thread to block for up to 1 millisecond.
*/
QNearFieldTarget::RequestId QNearFieldTagType2::selectSector(quint8 sector)
{
    QByteArray command;
    command.append(char(0xc2));     // SECTOR SELECT (Command Packet 1)
    command.append(char(0xff));

    RequestId id = sendCommand(command);

    Q_D(QNearFieldTagType2);

    d->m_pendingInternalCommands.insert(id, command);

    SectorSelectState state;
    state.timerId = -1;
    state.sector = sector;

    d->m_pendingSectorSelectCommands.insert(id, state);

    return id;
}

/*!
    \reimp
*/
bool QNearFieldTagType2::handleResponse(const QNearFieldTarget::RequestId &id,
                                        const QByteArray &response)
{
    Q_D(QNearFieldTagType2);

    if (d->m_pendingInternalCommands.contains(id)) {
        const QByteArray command = d->m_pendingInternalCommands.take(id);

        QVariant decodedResponse = decodeResponse(command, response);
        if (quint8(command.at(0)) == 0xc2 && decodedResponse.toBool()) {
            // SECTOR SELECT (Command Packet 2)
            SectorSelectState &state = d->m_pendingSectorSelectCommands[id];

            QByteArray packet2;
            packet2.append(char(state.sector));
            packet2.append(QByteArray(3, 0x00));

            sendCommand(packet2);

            state.timerId = startTimer(1);
        } else {
            setResponseForRequest(id, decodedResponse);
        }

        return true;
    } else if (d->m_pendingSectorSelectCommands.contains(id)) {
        if (!response.isEmpty()) {
            d->m_pendingSectorSelectCommands.remove(id);
            setResponseForRequest(id, false);

            return true;
        }
    }

    return QNearFieldTarget::handleResponse(id, response);
}

/*!
    \internal
*/
void QNearFieldTagType2::timerEvent(QTimerEvent *event)
{
    Q_D(QNearFieldTagType2);

    killTimer(event->timerId());

    QMutableMapIterator<QNearFieldTarget::RequestId, SectorSelectState> i(d->m_pendingSectorSelectCommands);
    while (i.hasNext()) {
        i.next();

        SectorSelectState &state = i.value();

        if (state.timerId == event->timerId()) {
            d->m_currentSector = state.sector;

            setResponseForRequest(i.key(), true);

            i.remove();

            break;
        }
    }
}

QT_END_NAMESPACE