tcftrkdevice.cpp 48.5 KB
Newer Older
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
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "tcftrkdevice.h"
#include "json.h"
32
#include "trkutils.h"
33
34
35
36
37
38
39

#include <QtNetwork/QAbstractSocket>
#include <QtCore/QDebug>
#include <QtCore/QVector>
#include <QtCore/QQueue>
#include <QtCore/QTextStream>
#include <QtCore/QDateTime>
40
#include <QtCore/QFileInfo>
41
42
43

enum { debug = 0 };

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
static const char wlanMessageTerminatorC[] = "\003\001";

// Serial Ping: 0xfc,0x1f
static const char serialPingC[] = "\xfc\x1f";
// Serial Pong: 0xfc,0xf1, followed by version info
static const char serialPongC[] = "\xfc\xf1";

static const char locatorAnswerC[] = "E\0Locator\0Hello\0[\"Locator\"]";

static const unsigned serialChunkLength = 0x400;  // 1K max USB router
static const int maxSerialMessageLength = 0x10000; // give chunking scheme

// Create USB router frame
static inline void encodeSerialFrame(const QByteArray &data, QByteArray *target)
{
    target->append(char(0x01));
    target->append(char(0x92)); // CODA serial message ID
    appendShort(target, ushort(data.size()), trk::BigEndian);
    target->append(data);
}

// Split in chunks of 1K according to CODA protocol chunking
static inline QByteArray encodeUsbSerialMessage(const QByteArray &dataIn)
{
    static const int chunkSize = serialChunkLength -  2; // 2 Header bytes
    const int size = dataIn.size();
    QByteArray frame;
    // Do we need to split?
    if (size < chunkSize) {  // Nope, all happy.
        frame.reserve(size + 4);
        encodeSerialFrame(dataIn, &frame);
        return frame;
    }
    // Split.
    unsigned chunkCount = size / chunkSize;
    if (size % chunkSize)
        chunkCount++;
    if (debug)
        qDebug("Serial: Splitting message of %d bytes into %u chunks of %d", size, chunkCount, chunkSize);

    frame.reserve((4 + serialChunkLength) * chunkCount);
    int pos = 0;
    for (unsigned c = chunkCount - 1; pos < size ; c--) {
        QByteArray chunk; // chunk with long message start/continuation code
        chunk.reserve(serialChunkLength);
        chunk.append(pos ? char(0) : char(0xfe));
        chunk.append(char(static_cast<unsigned char>(c))); // Avoid any signedness issues.
        const int chunkEnd = qMin(pos + chunkSize, size);
        chunk.append(dataIn.mid(pos, chunkEnd - pos));
        encodeSerialFrame(chunk, &frame);
        pos = chunkEnd;
    }
    if (debug > 1)
        qDebug("Serial chunked:\n%s", qPrintable(tcftrk::formatData(frame)));
    return frame;
}
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115

namespace tcftrk {
// ------------- TcfTrkCommandError

TcfTrkCommandError::TcfTrkCommandError() : timeMS(0), code(0), alternativeCode(0)
{
}

void TcfTrkCommandError::clear()
{
    timeMS = 0;
    code = alternativeCode = 0;
    format.clear();
    alternativeOrganization.clear();
}

116
117
118
119
120
121
QDateTime TcfTrkCommandResult::tcfTimeToQDateTime(quint64 tcfTimeMS)
{
    const QDateTime time(QDate(1970, 1, 1));
    return time.addMSecs(tcfTimeMS);
}

122
123
void TcfTrkCommandError::write(QTextStream &str) const
{
124
    if (isError()) {
125
126
        if (timeMS)
            str << TcfTrkCommandResult::tcfTimeToQDateTime(timeMS).toString(Qt::ISODate) << ": ";
127
        str << "Error code: " << code
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
                << " '" << format << '\'';
        if (!alternativeOrganization.isEmpty())
            str << " ('" << alternativeOrganization << "', code: " << alternativeCode << ')';
    } else{
        str << "<No error>";
    }
}

QString TcfTrkCommandError::toString() const
{
    QString rc;
    QTextStream str(&rc);
    write(str);
    return rc;
}

144
145
146
147
148
bool TcfTrkCommandError::isError() const
{
    return timeMS != 0 || code != 0 || !format.isEmpty() || alternativeCode != 0;
}

149
150
151
152
/* {"Time":1277459762255,"Code":1,"AltCode":-6,"AltOrg":"POSIX","Format":"Unknown error: -6"} */
bool TcfTrkCommandError::parse(const QVector<JsonValue> &values)
{
    // Parse an arbitrary hash (that could as well be a command response)
153
154
    // and check for error elements. It looks like sometimes errors are appended
    // to other values.
155
156
157
    unsigned errorKeyCount = 0;
    clear();
    do {
158
159
160
161
162
163
164
165
        if (values.isEmpty())
            break;
        // Errors are mostly appended, except for FileSystem::open, in which case
        // a string "null" file handle (sic!) follows the error.
        const int last = values.size() - 1;
        const int checkIndex = last == 1 && values.at(last).data() == "null" ?
                    last - 1 : last;
        if (values.at(checkIndex).type() != JsonValue::Object)
166
            break;
167
        foreach (const JsonValue &c, values.at(checkIndex).children()) {
168
169
170
171
            if (c.name() == "Time") {
                timeMS = c.data().toULongLong();
                errorKeyCount++;
            } else if (c.name() == "Code") {
172
                code = c.data().toLongLong();
173
174
175
176
177
                errorKeyCount++;
            } else if (c.name() == "Format") {
                format = c.data();
                errorKeyCount++;
            } else if (c.name() == "AltCode") {
178
                alternativeCode = c.data().toULongLong();
179
180
181
182
183
184
185
186
187
188
189
                errorKeyCount++;
            } else if (c.name() == "AltOrg") {
                alternativeOrganization = c.data();
                errorKeyCount++;
            }
        }
    } while (false);
    const bool errorFound = errorKeyCount >= 2u; // Should be at least 'Time', 'Code'.
    if (!errorFound)
        clear();
    if (debug) {
190
        qDebug("TcfTrkCommandError::parse: Found error %d (%u): ", errorFound, errorKeyCount);
191
        if (!values.isEmpty())
192
            qDebug() << values.back().toString();
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
    }
    return errorFound;
}

// ------------ TcfTrkCommandResult

TcfTrkCommandResult::TcfTrkCommandResult(Type t) :
    type(t), service(LocatorService)
{
}

TcfTrkCommandResult::TcfTrkCommandResult(char typeChar, Services s,
                                         const QByteArray &r,
                                         const QVector<JsonValue> &v,
                                         const QVariant &ck) :
    type(FailReply), service(s), request(r), values(v), cookie(ck)
{
    switch (typeChar) {
    case 'N':
        type = FailReply;
        break;
    case 'P':
        type = ProgressReply;
        break;
    case 'R':
        type = commandError.parse(values) ? CommandErrorReply : SuccessReply;
        break;
    default:
        qWarning("Unknown TCF reply type '%c'", typeChar);
    }
}

QString TcfTrkCommandResult::errorString() const
{
    QString rc;
    QTextStream str(&rc);

    switch (type) {
    case SuccessReply:
    case ProgressReply:
        str << "<No error>";
        return rc;
    case FailReply:
        str << "NAK";
237
        return rc;
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
    case CommandErrorReply:
        commandError.write(str);
        break;
    }
    // Append the failed command for reference
    str << " (Command was: '";
    QByteArray printableRequest = request;
    printableRequest.replace('\0', '|');
    str << printableRequest << "')";
    return rc;
}

QString TcfTrkCommandResult::toString() const
{
    QString rc;
    QTextStream str(&rc);
    str << "Command answer ";
    switch (type) {
    case SuccessReply:
        str << "[success]";
        break;
    case CommandErrorReply:
        str << "[command error]";
        break;
    case FailReply:
        str << "[fail (NAK)]";
        break;
    case ProgressReply:
        str << "[progress]";
        break;
    }
    str << ", " << values.size() << " values(s) to request: '";
    QByteArray printableRequest = request;
    printableRequest.replace('\0', '|');
    str << printableRequest << "' ";
    if (cookie.isValid())
        str << " cookie: " << cookie.toString();
    str << '\n';
    for (int i = 0, count = values.size(); i < count; i++)
        str << '#' << i << ' ' << values.at(i).toString() << '\n';
    if (type == CommandErrorReply)
        str << "Error: " << errorString();
    return rc;
}

283
284
285
286
TcfTrkStatResponse::TcfTrkStatResponse() : size(0)
{
}

287
288
289
290
291
// Entry for send queue.
enum SpecialHandlingFlags { None =0,
                            FakeRegisterGetMIntermediate = 0x1,
                            FakeRegisterGetMFinal = 0x2 };

292
293
294
295
296
297
298
struct TcfTrkSendQueueEntry
{
    typedef TcfTrkDevice::MessageType MessageType;

    explicit TcfTrkSendQueueEntry(MessageType mt,
                                  int tok,
                                  Services s,
299
300
301
302
303
304
                                  const QByteArray &d,
                                  const TcfTrkCallback &cb= TcfTrkCallback(),
                                  const QVariant &ck = QVariant(),
                                  unsigned sh = 0) :
        messageType(mt), service(s), data(d), token(tok), cookie(ck), callback(cb),
        specialHandling(sh) {}
305
306
307
308
309
310
311

    MessageType messageType;
    Services service;
    QByteArray data;
    int token;
    QVariant cookie;
    TcfTrkCallback callback;
312
    unsigned specialHandling;
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
};

struct TcfTrkDevicePrivate {
    typedef TcfTrkDevice::IODevicePtr IODevicePtr;
    typedef QHash<int, TcfTrkSendQueueEntry> TokenWrittenMessageMap;

    TcfTrkDevicePrivate();

    const QByteArray m_messageTerminator;

    IODevicePtr m_device;
    unsigned m_verbose;
    QByteArray m_readBuffer;
    int m_token;
    QQueue<TcfTrkSendQueueEntry> m_sendQueue;
    TokenWrittenMessageMap m_writtenMessages;
    QVector<QByteArray> m_registerNames;
330
    QVector<QByteArray> m_fakeGetMRegisterValues;
331
    bool m_serialFrame;
332
333
334
};

TcfTrkDevicePrivate::TcfTrkDevicePrivate() :
335
336
    m_messageTerminator(wlanMessageTerminatorC),
    m_verbose(0), m_token(0), m_serialFrame(false)
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
{
}

TcfTrkDevice::TcfTrkDevice(QObject *parent) :
    QObject(parent), d(new TcfTrkDevicePrivate)
{
}

TcfTrkDevice::~TcfTrkDevice()
{
    delete d;
}

QVector<QByteArray> TcfTrkDevice::registerNames() const
{
    return d->m_registerNames;
}

void TcfTrkDevice::setRegisterNames(const QVector<QByteArray>& n)
{
    d->m_registerNames = n;
    if (d->m_verbose) {
        QString msg;
        QTextStream str(&msg);
        const int count = n.size();
        str << "Registers (" << count << "): ";
        for (int i = 0; i < count; i++)
            str << '#' << i << '=' << n.at(i) << ' ';
        emitLogMessage(msg);
    }
}

TcfTrkDevice::IODevicePtr TcfTrkDevice::device() const
{
    return d->m_device;
}

TcfTrkDevice::IODevicePtr TcfTrkDevice::takeDevice()
{
    const IODevicePtr old = d->m_device;
    if (!old.isNull()) {
        old.data()->disconnect(this);
        d->m_device = IODevicePtr();
    }
    d->m_readBuffer.clear();
    d->m_token = 0;
    d->m_sendQueue.clear();
    return old;
}

void TcfTrkDevice::setDevice(const IODevicePtr &dp)
{
    if (dp.data() == d->m_device.data())
        return;
    if (dp.isNull()) {
        emitLogMessage(QLatin1String("Internal error: Attempt to set NULL device."));
        return;
    }
    takeDevice();
    d->m_device = dp;
    connect(dp.data(), SIGNAL(readyRead()), this, SLOT(slotDeviceReadyRead()));
    if (QAbstractSocket *s = qobject_cast<QAbstractSocket *>(dp.data())) {
        connect(s, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(slotDeviceError()));
        connect(s, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(slotDeviceSocketStateChanged()));
    }
}

void TcfTrkDevice::slotDeviceError()
{
    const QString message = d->m_device->errorString();
    emitLogMessage(message);
    emit error(message);
}

void TcfTrkDevice::slotDeviceSocketStateChanged()
{
    if (const QAbstractSocket *s = qobject_cast<const QAbstractSocket *>(d->m_device.data())) {
        const QAbstractSocket::SocketState st = s->state();
        switch (st) {
        case QAbstractSocket::UnconnectedState:
            emitLogMessage(QLatin1String("Unconnected"));
            break;
        case QAbstractSocket::HostLookupState:
            emitLogMessage(QLatin1String("HostLookupState"));
            break;
        case QAbstractSocket::ConnectingState:
            emitLogMessage(QLatin1String("Connecting"));
            break;
        case QAbstractSocket::ConnectedState:
            emitLogMessage(QLatin1String("Connected"));
            break;
        case QAbstractSocket::ClosingState:
            emitLogMessage(QLatin1String("Closing"));
            break;
        default:
            emitLogMessage(QString::fromLatin1("State %1").arg(st));
            break;
        }
    }
}

static inline QString debugMessage(QByteArray  message, const char *prefix = 0)
{
440
441
442
443
444
445
    const bool isBinary = !message.isEmpty() && message.at(0) < 0;
    if (isBinary) {
        message = message.toHex(); // Some serial special message
    } else {
        message.replace('\0', '|');
    }
446
447
448
449
450
451
452
    const QString messageS = QString::fromLatin1(message);
    return prefix ?
            (QLatin1String(prefix) + messageS) :  messageS;
}

void TcfTrkDevice::slotDeviceReadyRead()
{
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
    const QByteArray newData = d->m_device->readAll();
    d->m_readBuffer += newData;
    if (debug)
        qDebug("ReadBuffer: %s", qPrintable(trk::stringFromArray(newData)));
    if (d->m_serialFrame) {
        deviceReadyReadSerial();
    } else {
        deviceReadyReadWLAN();
    }
}

// Find a serial header in input stream '0x1', '0x92', 'lenH', 'lenL'
// and return message position and size.
static inline QPair<int, int> findSerialHeader(const QByteArray &in)
{
    const int size = in.size();
    const char header1 = 0x1;
    const char header2 = char(0x92);
    // Header should in theory always be at beginning of
    // buffer. Warn if  there are bogus data in-between.
    for (int pos = 0; pos < size; ) {
        if (pos + 4 < size && in.at(pos) == header1 &&  in.at(pos + 1) == header2) {
            const int length = trk::extractShort(in.constData() + 2);
            return QPair<int, int>(pos + 4, length);
        }
        // Find next
        pos = in.indexOf(header1, pos + 1);
        qWarning("Bogus data received on serial line: %s\n"
                 "Frame Header at: %d", qPrintable(trk::stringFromArray(in)), pos);
        if (pos < 0)
           break;
    }
    return QPair<int, int>(-1, -1);
}

void TcfTrkDevice::deviceReadyReadSerial()
{
    do {
        // Extract message (pos,len)
        const QPair<int, int> messagePos = findSerialHeader(d->m_readBuffer);
        if (messagePos.first < 0)
            break;
        // Do we have the complete message?
        const int messageEnd = messagePos.first + messagePos.second;
        if (messageEnd > d->m_readBuffer.size())
            break;
        const QByteArray message = d->m_readBuffer.mid(messagePos.first, messagePos.second);
        // Is thing a ping/pong response
        if (debug > 1)
            qDebug("Serial message: at %d (%d bytes) of %d: %s",
                   messagePos.first, messagePos.second, d->m_readBuffer.size(),
                   qPrintable(trk::stringFromArray(message)));
        if (message.startsWith(serialPongC)) {
            const QString version = QString::fromLatin1(message.mid(sizeof(serialPongC) -  1));
            emitLogMessage(QString::fromLatin1("Serial connection from '%1'").arg(version));
            emit serialPong(version);
            // Answer with locator.
            writeMessage(QByteArray(locatorAnswerC, sizeof(locatorAnswerC)));
        } else {
            processMessage(message);
        }
        d->m_readBuffer.remove(0, messageEnd);
    } while (d->m_readBuffer.isEmpty());
    checkSendQueue(); // Send off further messages
}

void TcfTrkDevice::deviceReadyReadWLAN()
{
521
522
    // Take complete message off front of readbuffer.
    do {
523
        const int messageEndPos = d->m_readBuffer.indexOf(d->m_messageTerminator);
524
525
        if (messageEndPos == -1)
            break;
526
527
528
529
        if (messageEndPos == 0) {
            // TCF TRK 4.0.5 emits empty messages on errors.
            emitLogMessage(QString::fromLatin1("An empty TCF TRK message has been received."));
        } else {
530
            processMessage(d->m_readBuffer.left(messageEndPos));
531
532
533
        }
        d->m_readBuffer.remove(0, messageEndPos + d->m_messageTerminator.size());
    } while (!d->m_readBuffer.isEmpty());
534
535
536
537
538
539
540
541
542
543
544
545
546
547
    checkSendQueue(); // Send off further messages
}

void TcfTrkDevice::processMessage(const QByteArray &message)
{
    if (debug)
        qDebug("Read %d bytes:\n%s", message.size(), qPrintable(formatData(message)));
    if (const int errorCode = parseMessage(message)) {
        emitLogMessage(QString::fromLatin1("Parse error %1 : %2").
                       arg(errorCode).arg(debugMessage(message)));
        if (debug)
            qDebug("Parse error %d for %d bytes:\n%s", errorCode,
                   message.size(), qPrintable(formatData(message)));
    }
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
}

// Split \0-terminated message into tokens, skipping the initial type character
static inline QVector<QByteArray> splitMessage(const QByteArray &message)
{
    QVector<QByteArray> tokens;
    tokens.reserve(7);
    const int messageSize = message.size();
    for (int pos = 2; pos < messageSize; ) {
        const int nextPos = message.indexOf('\0', pos);
        if (nextPos == -1)
            break;
        tokens.push_back(message.mid(pos, nextPos - pos));
        pos = nextPos + 1;
    }
    return tokens;
}

int TcfTrkDevice::parseMessage(const QByteArray &message)
{
    if (d->m_verbose)
        emitLogMessage(debugMessage(message, "TCF ->"));
    // Special JSON parse error message or protocol format error.
    // The port is usually closed after receiving it.
    // "\3\2{"Time":1276096098255,"Code":3,"Format": "Protocol format error"}"
    if (message.startsWith("\003\002")) {
        QByteArray text = message.mid(2);
        const QString errorMessage = QString::fromLatin1("Parse error received: %1").arg(QString::fromAscii(text));
        emit error(errorMessage);
        return 0;
    }
    if (message.size() < 4 || message.at(1) != '\0')
        return 1;
    // Split into tokens
    const char type = message.at(0);
    const QVector<QByteArray> tokens = splitMessage(message);
    switch (type) {
    case 'E':
        return parseTcfEvent(tokens);
    case 'R': // Command replies
    case 'N':
    case 'P':
        return parseTcfCommandReply(type, tokens);
    default:
        emitLogMessage(QString::fromLatin1("Unhandled message type: %1").arg(debugMessage(message)));
        return 756;
    }
    return 0;
}

int TcfTrkDevice::parseTcfCommandReply(char type, const QVector<QByteArray> &tokens)
{
    typedef TcfTrkDevicePrivate::TokenWrittenMessageMap::iterator TokenWrittenMessageMapIterator;
    // Find the corresponding entry in the written messages hash.
    const int tokenCount = tokens.size();
    if (tokenCount < 1)
        return 234;
    bool tokenOk;
    const int token = tokens.at(0).toInt(&tokenOk);
    if (!tokenOk)
        return 235;
    const TokenWrittenMessageMapIterator it = d->m_writtenMessages.find(token);
    if (it == d->m_writtenMessages.end()) {
        qWarning("TcfTrkDevice: Internal error: token %d not found for '%s'",
                 token, qPrintable(joinByteArrays(tokens)));
        return 236;
    }
    // No callback: remove entry from map, happy
616
617
    const unsigned specialHandling = it.value().specialHandling;
    if (!it.value().callback && specialHandling == 0u) {
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
        d->m_writtenMessages.erase(it);
        return 0;
    }
    // Parse values into JSON
    QVector<JsonValue> values;
    values.reserve(tokenCount);
    for (int i = 1; i < tokenCount; i++) {
        if (!tokens.at(i).isEmpty()) { // Strange: Empty tokens occur.
            const JsonValue value(tokens.at(i));
            if (value.isValid()) {
                values.push_back(value);
            } else {
                qWarning("JSON parse error for reply to command token %d: #%d '%s'",
                         token, i, tokens.at(i).constData());
                d->m_writtenMessages.erase(it);
                return -1;
            }
        }
    }
    // Construct result and invoke callback, remove entry from map.
    TcfTrkCommandResult result(type, it.value().service, it.value().data,
                               values, it.value().cookie);
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682

    // Check special handling
    if (specialHandling) {
        if (!result) {
            qWarning("Error in special handling: %s", qPrintable(result.errorString()));
            return -2;
        }
        // Fake 'Registers:getm': Store single register values in cache
        if ((specialHandling & FakeRegisterGetMIntermediate)
                || (specialHandling & FakeRegisterGetMFinal)) {
            if (result.values.size() == 1) {
                const int index = int(specialHandling) >> 16;
                if (index >= 0 && index < d->m_fakeGetMRegisterValues.size()) {
                    const QByteArray base64 = result.values.front().data();
                    d->m_fakeGetMRegisterValues[index] = base64;
                    if (d->m_verbose) {
                        const QString msg = QString::fromLatin1("Caching register value #%1 '%2' 0x%3 (%4)").
                                arg(index).arg(QString::fromAscii(d->m_registerNames.at(index))).
                                arg(QString::fromAscii(QByteArray::fromBase64(base64).toHex())).
                                arg(QString::fromAscii(base64));
                        emitLogMessage(msg);
                    }
                }
            }
        }
        // Fake 'Registers:getm' final value: Reformat entries as array and send off
        if (specialHandling & FakeRegisterGetMFinal) {
            QByteArray str;
            str.append('[');
            foreach(const QByteArray &rval, d->m_fakeGetMRegisterValues)
                if (!rval.isEmpty()) {
                    if (str.size() > 1)
                        str.append(',');
                    str.append('"');
                    str.append(rval);
                    str.append('"');
                }
            str.append(']');
            result.values[0] = JsonValue(str);
        }
    }
    if (it.value().callback)
        it.value().callback(result);
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
    d->m_writtenMessages.erase(it);
    return 0;
}

int TcfTrkDevice::parseTcfEvent(const QVector<QByteArray> &tokens)
{
    // Event: Ignore the periodical heartbeat event, answer 'Hello',
    // emit signal for the rest
    if (tokens.size() < 3)
        return 433;
    const Services service = serviceFromName(tokens.at(0).constData());
    if (service == LocatorService && tokens.at(1) == "peerHeartBeat")
        return 0;
    QVector<JsonValue> values;
    for (int i = 2; i < tokens.size(); i++) {
        const JsonValue value(tokens.at(i));
        if (!value.isValid())
            return 434;
        values.push_back(value);
    }
    // Parse known events, emit signals
    QScopedPointer<TcfTrkEvent> knownEvent(TcfTrkEvent::parseEvent(service, tokens.at(1), values));
    if (!knownEvent.isNull()) {
706
        // Answer hello event (WLAN)
707
        if (knownEvent->type() == TcfTrkEvent::LocatorHello)
708
709
            if (!d->m_serialFrame)
                writeMessage(QByteArray(locatorAnswerC, sizeof(locatorAnswerC)));
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
        emit tcfEvent(*knownEvent);
    }
    emit genericTcfEvent(service, tokens.at(1), values);

    if (debug || d->m_verbose) {
        QString msg;
        QTextStream str(&msg);
        if (knownEvent.isNull()) {
            str << "Event: " << tokens.at(0) << ' ' << tokens.at(1) << '\n';
            foreach(const JsonValue &val, values)
                str << "  " << val.toString() << '\n';
        } else {
            str << knownEvent->toString();
        }
        emitLogMessage(msg);
    }

    return 0;
}

unsigned TcfTrkDevice::verbose() const
{
    return d->m_verbose;
}

735
736
737
738
739
740
741
742
743
744
bool TcfTrkDevice::serialFrame() const
{
    return d->m_serialFrame;
}

void TcfTrkDevice::setSerialFrame(bool s)
{
    d->m_serialFrame = s;
}

745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
void TcfTrkDevice::setVerbose(unsigned v)
{
    d->m_verbose = v;
}

void TcfTrkDevice::emitLogMessage(const QString &m)
{
    if (debug)
        qWarning("%s", qPrintable(m));
    emit logMessage(m);
}

bool TcfTrkDevice::checkOpen()
{
    if (d->m_device.isNull()) {
        emitLogMessage(QLatin1String("Internal error: No device set on TcfTrkDevice."));
        return false;
    }
    if (!d->m_device->isOpen()) {
        emitLogMessage(QLatin1String("Internal error: Device not open in TcfTrkDevice."));
        return false;
    }
    return true;
}

770
771
772
773
774
775
776
777
778
779
780
void TcfTrkDevice::sendSerialPing()
{
    if (!checkOpen())
        return;

    setSerialFrame(true);
    writeMessage(QByteArray(serialPingC, qstrlen(serialPingC)), false);
    if (d->m_verbose)
        emitLogMessage(QLatin1String("Ping..."));
}

781
void TcfTrkDevice::sendTcfTrkMessage(MessageType mt, Services service, const char *command,
782
783
                                     const char *commandParameters, // may contain '\0'
                                     int commandParametersLength,
784
785
                                     const TcfTrkCallback &callBack,
                                     const QVariant &cookie)
786
787
788
789
790
791
792
793
794
795
{
    sendTcfTrkMessage(mt, service, command, commandParameters, commandParametersLength,
                      callBack, cookie, 0u);
}

void TcfTrkDevice::sendTcfTrkMessage(MessageType mt, Services service,
                       const char *command,
                       const char *commandParameters, int commandParametersLength,
                       const TcfTrkCallback &callBack, const QVariant &cookie,
                       unsigned specialHandling)
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813

{
    if (!checkOpen())
        return;
    // Format the message
    const int  token = d->m_token++;
    QByteArray data;
    data.reserve(30 + commandParametersLength);
    data.append('C');
    data.append('\0');
    data.append(QByteArray::number(token));
    data.append('\0');
    data.append(serviceName(service));
    data.append('\0');
    data.append(command);
    data.append('\0');
    if (commandParametersLength)
        data.append(commandParameters, commandParametersLength);
814
    const TcfTrkSendQueueEntry entry(mt, token, service, data, callBack, cookie, specialHandling);
815
816
817
818
819
820
821
822
823
824
825
826
827
828
    d->m_sendQueue.enqueue(entry);
    checkSendQueue();
}

void TcfTrkDevice::sendTcfTrkMessage(MessageType mt, Services service, const char *command,
                                     const QByteArray &commandParameters,
                                     const TcfTrkCallback &callBack,
                                     const QVariant &cookie)
{
    sendTcfTrkMessage(mt, service, command, commandParameters.constData(), commandParameters.size(),
                      callBack, cookie);
}

// Enclose in message frame and write.
829
void TcfTrkDevice::writeMessage(QByteArray data, bool ensureTerminating0)
830
831
832
833
{
    if (!checkOpen())
        return;

834
835
836
837
838
839
840
    if (d->m_serialFrame && data.size() > maxSerialMessageLength) {
        qCritical("Attempt to send large message (%d bytes) exceeding the "
                  "limit of %d bytes over serial channel. Skipping.",
                  data.size(), maxSerialMessageLength);
        return;
    }

841
842
843
844
    if (d->m_verbose)
        emitLogMessage(debugMessage(data, "TCF <-"));

    // Ensure \0-termination which easily gets lost in QByteArray CT.
845
    if (ensureTerminating0 && !data.endsWith('\0'))
846
        data.append('\0');
847
848
849
850
851
    if (d->m_serialFrame) {
        data = encodeUsbSerialMessage(data);
    } else {
        data += d->m_messageTerminator;
    }
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929

    if (debug > 1)
        qDebug("Writing:\n%s", qPrintable(formatData(data)));

    d->m_device->write(data);
    if (QAbstractSocket *as = qobject_cast<QAbstractSocket *>(d->m_device.data()))
        as->flush();
}

void TcfTrkDevice::checkSendQueue()
{
    // Fire off messages or invoke noops until a message with reply is found
    // and an entry to writtenMessages is made.
    while (d->m_writtenMessages.empty()) {
        if (d->m_sendQueue.isEmpty())
            break;
        TcfTrkSendQueueEntry entry = d->m_sendQueue.dequeue();
        switch (entry.messageType) {
        case MessageWithReply:
            d->m_writtenMessages.insert(entry.token, entry);
            writeMessage(entry.data);
            break;
        case MessageWithoutReply:
            writeMessage(entry.data);
            break;
        case NoopMessage: // Invoke the noop-callback for synchronization
            if (entry.callback) {
                TcfTrkCommandResult noopResult(TcfTrkCommandResult::SuccessReply);
                noopResult.cookie = entry.cookie;
                entry.callback(noopResult);
            }
            break;
        }
    }
}

// Fix slashes
static inline QString fixFileName(QString in)
{
    in.replace(QLatin1Char('/'), QLatin1Char('\\'));
    return in;
}

// Start a process (consisting of a non-reply setSettings and start).
void TcfTrkDevice::sendProcessStartCommand(const TcfTrkCallback &callBack,
                                                 const QString &binaryIn,
                                                 unsigned uid,
                                                 QStringList arguments,
                                                 QString workingDirectory,
                                                 bool debugControl,
                                                 const QStringList &additionalLibraries,
                                                 const QVariant &cookie)
{
    // Obtain the bin directory, expand by c:/sys/bin if missing
    const QChar backSlash('\\');
    int slashPos = binaryIn.lastIndexOf(QLatin1Char('/'));
    if (slashPos == -1)
        slashPos = binaryIn.lastIndexOf(backSlash);
    const QString sysBin = QLatin1String("c:/sys/bin");
    const QString binaryFileName  = slashPos == -1 ? binaryIn : binaryIn.mid(slashPos + 1);
    const QString binaryDirectory = slashPos == -1 ? sysBin : binaryIn.left(slashPos);
    const QString binary = fixFileName(binaryDirectory + QLatin1Char('/') + binaryFileName);

    // Fixup: Does argv[0] convention exist on Symbian?
    arguments.push_front(binary);
    if (workingDirectory.isEmpty())
        workingDirectory = sysBin;

    // Format settings with empty dummy parameter
    QByteArray setData;
    JsonInputStream setStr(setData);
    setStr << "" << '\0'
            << '[' << "exeToLaunch" << ',' << "addExecutables" << ',' << "addLibraries" << ']'
            << '\0' << '['
                << binary << ','
                << '{' << binaryFileName << ':' << QString::number(uid, 16) << '}' << ','
                << additionalLibraries
            << ']';
930
931
932
933
934
935
936
    sendTcfTrkMessage(
#if 1
                MessageWithReply,    // TCF TRK 4.0.5 onwards
#else
                MessageWithoutReply, // TCF TRK 4.0.2
#endif
                SettingsService, "set", setData);
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956

    QByteArray startData;
    JsonInputStream startStr(startData);
    startStr << fixFileName(workingDirectory)
            << '\0' << binary << '\0' << arguments << '\0'
            << QStringList() << '\0' // Env is an array ["PATH=value"] (non-standard)
            << debugControl;
    sendTcfTrkMessage(MessageWithReply, ProcessesService, "start", startData, callBack, cookie);
}

void TcfTrkDevice::sendProcessTerminateCommand(const TcfTrkCallback &callBack,
                                               const QByteArray &id,
                                               const QVariant &cookie)
{
    QByteArray data;
    JsonInputStream str(data);
    str << id;
    sendTcfTrkMessage(MessageWithReply, ProcessesService, "terminate", data, callBack, cookie);
}

957
958
959
960
961
962
963
964
965
966
void TcfTrkDevice::sendRunControlTerminateCommand(const TcfTrkCallback &callBack,
                                                  const QByteArray &id,
                                                  const QVariant &cookie)
{
    QByteArray data;
    JsonInputStream str(data);
    str << id;
    sendTcfTrkMessage(MessageWithReply, RunControlService, "terminate", data, callBack, cookie);
}

967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
// Non-standard: Remove executable from settings
void TcfTrkDevice::sendSettingsRemoveExecutableCommand(const QString &binaryIn,
                                                       unsigned uid,
                                                       const QStringList &additionalLibraries,
                                                       const QVariant &cookie)
{
    QByteArray setData;
    JsonInputStream setStr(setData);
    setStr << "" << '\0'
            << '[' << "removedExecutables" << ',' << "removedLibraries" << ']'
            << '\0' << '['
                << '{' << QFileInfo(binaryIn).fileName() << ':' << QString::number(uid, 16) << '}' << ','
                << additionalLibraries
            << ']';
    sendTcfTrkMessage(MessageWithoutReply, SettingsService, "set", setData, TcfTrkCallback(), cookie);
}

984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
void TcfTrkDevice::sendRunControlResumeCommand(const TcfTrkCallback &callBack,
                                               const QByteArray &id,
                                               RunControlResumeMode mode,
                                               unsigned count,
                                               quint64 rangeStart,
                                               quint64 rangeEnd,
                                               const QVariant &cookie)
{
    QByteArray resumeData;
    JsonInputStream str(resumeData);
    str << id << '\0' << int(mode) << '\0' << count;
    switch (mode) {
    case RM_STEP_OVER_RANGE:
    case RM_STEP_INTO_RANGE:
    case RM_REVERSE_STEP_OVER_RANGE:
    case RM_REVERSE_STEP_INTO_RANGE:
        str << '\0' << '{' << "RANGE_START" << ':' << rangeStart
                << ',' << "RANGE_END" << ':' << rangeEnd << '}';
        break;
    default:
        break;
    }
    sendTcfTrkMessage(MessageWithReply, RunControlService, "resume", resumeData, callBack, cookie);
}

void TcfTrkDevice::sendRunControlSuspendCommand(const TcfTrkCallback &callBack,
                                                const QByteArray &id,
                                                const QVariant &cookie)
{
    QByteArray data;
    JsonInputStream str(data);
    str << id;
    sendTcfTrkMessage(MessageWithReply, RunControlService, "suspend", data, callBack, cookie);
}

void TcfTrkDevice::sendRunControlResumeCommand(const TcfTrkCallback &callBack,
                                               const QByteArray &id,
                                               const QVariant &cookie)
{
    sendRunControlResumeCommand(callBack, id, RM_RESUME, 1, 0, 0, cookie);
}

void TcfTrkDevice::sendBreakpointsAddCommand(const TcfTrkCallback &callBack,
                                             const Breakpoint &bp,
                                             const QVariant &cookie)
{
    QByteArray data;
    JsonInputStream str(data);
    str << bp;
    sendTcfTrkMessage(MessageWithReply, BreakpointsService, "add", data, callBack, cookie);
}

void TcfTrkDevice::sendBreakpointsRemoveCommand(const TcfTrkCallback &callBack,
                                                const QByteArray &id,
                                                const QVariant &cookie)
{
    sendBreakpointsRemoveCommand(callBack, QVector<QByteArray>(1, id), cookie);
}

void TcfTrkDevice::sendBreakpointsRemoveCommand(const TcfTrkCallback &callBack,
                                                const QVector<QByteArray> &ids,
                                                const QVariant &cookie)
{
    QByteArray data;
    JsonInputStream str(data);
    str << ids;
    sendTcfTrkMessage(MessageWithReply, BreakpointsService, "remove", data, callBack, cookie);
}

void TcfTrkDevice::sendBreakpointsEnableCommand(const TcfTrkCallback &callBack,
                                                const QByteArray &id,
                                                bool enable,
                                                const QVariant &cookie)
{
    sendBreakpointsEnableCommand(callBack, QVector<QByteArray>(1, id), enable, cookie);
}

void TcfTrkDevice::sendBreakpointsEnableCommand(const TcfTrkCallback &callBack,
                                                const QVector<QByteArray> &ids,
                                                bool enable,
                                                const QVariant &cookie)
{
    QByteArray data;
    JsonInputStream str(data);
    str << ids;
    sendTcfTrkMessage(MessageWithReply, BreakpointsService,
                      enable ? "enable" : "disable",
                      data, callBack, cookie);
}

void TcfTrkDevice::sendMemorySetCommand(const TcfTrkCallback &callBack,
                                        const QByteArray &contextId,
                                        quint64 start, const QByteArray& data,
                                        const QVariant &cookie)
{
    QByteArray getData;
    JsonInputStream str(getData);
    // start/word size/mode. Mode should ideally be 1 (continue on error?)
    str << contextId << '\0' << start << '\0' << 1 << '\0' << data.size() << '\0' << 1
        << '\0' << data.toBase64();
    sendTcfTrkMessage(MessageWithReply, MemoryService, "set", getData, callBack, cookie);
}

void TcfTrkDevice::sendMemoryGetCommand(const TcfTrkCallback &callBack,
                                        const QByteArray &contextId,
                                        quint64 start, quint64 size,
                                        const QVariant &cookie)
{
    QByteArray data;
    JsonInputStream str(data);
    // start/word size/mode. Mode should ideally be 1 (continue on error?)
    str << contextId << '\0' << start << '\0' << 1 << '\0' << size << '\0' << 1;
    sendTcfTrkMessage(MessageWithReply, MemoryService, "get", data, callBack, cookie);
}

QByteArray TcfTrkDevice::parseMemoryGet(const TcfTrkCommandResult &r)
{
    if (r.type != TcfTrkCommandResult::SuccessReply || r.values.size() < 1)
        return QByteArray();
    const JsonValue &memoryV = r.values.front();

    if (memoryV.type() != JsonValue::String || memoryV.data().size() < 2
        || !memoryV.data().endsWith('='))
        return QByteArray();
    // Catch errors reported as hash:
    // R.4."TlVMTA==".{"Time":1276786871255,"Code":1,"AltCode":-38,"AltOrg":"POSIX","Format":"BadDescriptor"}
    // Not sure what to make of it.
    if (r.values.size() >= 2 && r.values.at(1).type() == JsonValue::Object)
1112
        qWarning("TcfTrkDevice::parseMemoryGet(): Error retrieving memory: %s", r.values.at(1).toString(false).constData());
1113
1114
1115
1116
1117
1118
1119
1120
1121
    // decode
    const QByteArray memory = QByteArray::fromBase64(memoryV.data());
    if (memory.isEmpty())
        qWarning("Base64 decoding of %s failed.", memoryV.data().constData());
    if (debug)
        qDebug("TcfTrkDevice::parseMemoryGet: received %d bytes", memory.size());
    return memory;
}

1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
// Parse register children (array of names)
QVector<QByteArray> TcfTrkDevice::parseRegisterGetChildren(const TcfTrkCommandResult &r)
{
    QVector<QByteArray> rc;
    if (!r || r.values.size() < 1 || r.values.front().type() != JsonValue::Array)
        return rc;
    const JsonValue &front = r.values.front();
    rc.reserve(front.childCount());
    foreach(const JsonValue &v, front.children())
        rc.push_back(v.data());
    return rc;
}

1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
TcfTrkStatResponse TcfTrkDevice::parseStat(const TcfTrkCommandResult &r)
{
    TcfTrkStatResponse rc;
    if (!r || r.values.size() < 1 || r.values.front().type() != JsonValue::Object)
        return rc;
    foreach(const JsonValue &v, r.values.front().children()) {
        if (v.name() == "Size") {
            rc.size = v.data().toULongLong();
        } else if (v.name() == "ATime") {
            if (const quint64 atime = v.data().toULongLong())
                rc.accessTime = TcfTrkCommandResult::tcfTimeToQDateTime(atime);
        } else if (v.name() == "MTime") {
            if (const quint64 mtime = v.data().toULongLong())
                rc.modTime = TcfTrkCommandResult::tcfTimeToQDateTime(mtime);
        }
    }
    return rc;
}

1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
void TcfTrkDevice::sendRegistersGetChildrenCommand(const TcfTrkCallback &callBack,
                                     const QByteArray &contextId,
                                     const QVariant &cookie)
{
    QByteArray data;
    JsonInputStream str(data);
    str << contextId;
    sendTcfTrkMessage(MessageWithReply, RegistersService, "getChildren", data, callBack, cookie);
}

// Format id of register get request (needs contextId containing process and thread)
static inline QByteArray registerId(const QByteArray &contextId, QByteArray id)
{
    QByteArray completeId = contextId;
    if (!completeId.isEmpty())
        completeId.append('.');
    completeId.append(id);
    return completeId;
}

// Format parameters of register get request
static inline QByteArray registerGetData(const QByteArray &contextId, QByteArray id)
{
    QByteArray data;
    JsonInputStream str(data);
    str << registerId(contextId, id);
    return data;
}

void TcfTrkDevice::sendRegistersGetCommand(const TcfTrkCallback &callBack,
                                            const QByteArray &contextId,
                                            QByteArray id,
                                            const QVariant &cookie)
{
    sendTcfTrkMessage(MessageWithReply, RegistersService, "get",
                      registerGetData(contextId, id), callBack, cookie);
}

1192
1193
1194
1195
1196
1197
void TcfTrkDevice::sendRegistersGetMCommand(const TcfTrkCallback &callBack,
                                            const QByteArray &contextId,
                                            const QVector<QByteArray> &ids,
                                            const QVariant &cookie)
{
    // TODO: use "Registers" (which uses base64-encoded values)
1198
1199
#if 0 // Once 'getm' is supported:
    // Manually format the complete register ids as an array
1200
1201
    QByteArray data;
    JsonInputStream str(data);
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
    str << '[';
    const int count = ids.size();
    for (int r = 0; r < count; r++) {
        if (r)
            str << ',';
        str << registerId(contextId, ids.at(r));
    }
    str << ']';
    sendTcfTrkMessage(MessageWithReply, RegistersService, "getm", data, callBack, cookie);
#else
    // TCF TRK 4.0.5: Fake 'getm' by sending all requests, pass on callback to the last
    // @Todo: Hopefully, we get 'getm'?
    const int last = ids.size() - 1;
    d->m_fakeGetMRegisterValues = QVector<QByteArray>(ids.size(), QByteArray());
    for (int r = 0; r <= last; r++) {
        const QByteArray data = registerGetData(contextId, ids.at(r));
        // Determine special flags along with index
        unsigned specialFlags = r == last ? FakeRegisterGetMFinal : FakeRegisterGetMIntermediate;
        const int index = d->m_registerNames.indexOf(ids.at(r));
        if (index == -1) { // Should not happen
            qWarning("Invalid register name %s", ids.at(r).constData());
            return;
        }
        specialFlags |= unsigned(index) << 16;
        sendTcfTrkMessage(MessageWithReply, RegistersService, "get",
                          data.constData(), data.size(),
                          r == last ? callBack : TcfTrkCallback(),
                          cookie, specialFlags);
    }
#endif
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
}

void TcfTrkDevice::sendRegistersGetMRangeCommand(const TcfTrkCallback &callBack,
                                                 const QByteArray &contextId,
                                                 unsigned start, unsigned count)
{
    const unsigned end = start + count;
    if (end > (unsigned)d->m_registerNames.size()) {
        qWarning("TcfTrkDevice: No register name set for index %u (size: %d).", end, d->m_registerNames.size());
        return;
    }

    QVector<QByteArray> ids;
    ids.reserve(count);
    for (unsigned i = start; i < end; i++)
        ids.push_back(d->m_registerNames.at(i));
    sendRegistersGetMCommand(callBack, contextId, ids, QVariant(start));
}

// Set register
void TcfTrkDevice::sendRegistersSetCommand(const TcfTrkCallback &callBack,
                                           const QByteArray &contextId,
1254
1255
                                           QByteArray id,
                                           const QByteArray &value,
1256
1257
1258
1259
                                           const QVariant &cookie)
{
    QByteArray data;
    JsonInputStream str(data);
1260
1261
1262
1263
1264
1265
    if (!contextId.isEmpty()) {
        id.prepend('.');
        id.prepend(contextId);
    }
    str << id << '\0' << value.toBase64();
    sendTcfTrkMessage(MessageWithReply, RegistersService, "set", data, callBack, cookie);
1266
1267
1268
1269
1270
1271
}

// Set register
void TcfTrkDevice::sendRegistersSetCommand(const TcfTrkCallback &callBack,
                                           const QByteArray &contextId,
                                           unsigned registerNumber,
1272
                                           const QByteArray &value,
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
                                           const QVariant &cookie)
{
    if (registerNumber >= (unsigned)d->m_registerNames.size()) {
        qWarning("TcfTrkDevice: No register name set for index %u (size: %d).", registerNumber, d->m_registerNames.size());
        return;
    }
    sendRegistersSetCommand(callBack, contextId,
                            d->m_registerNames[registerNumber],
                            value, cookie);
}

1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
static const char outputListenerIDC[] = "org.eclipse.cdt.debug.edc.ui.ProgramOutputConsoleLogger";

void TcfTrkDevice::sendLoggingAddListenerCommand(const TcfTrkCallback &callBack,
                                                 const QVariant &cookie)
{
    QByteArray data;
    JsonInputStream str(data);
    str << outputListenerIDC;
    sendTcfTrkMessage(MessageWithReply, LoggingService, "addListener", data, callBack, cookie);
}

1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
void tcftrk::TcfTrkDevice::sendFileSystemOpenCommand(const tcftrk::TcfTrkCallback &callBack,
                                                     const QByteArray &name,
                                                     unsigned flags,
                                                     const QVariant &cookie)
{
    QByteArray data;
    JsonInputStream str(data);
    str << name << '\0' << flags << '\0' << '{' << '}';
    sendTcfTrkMessage(MessageWithReply, FileSystemService, "open", data, callBack, cookie);
}

void tcftrk::TcfTrkDevice::sendFileSystemFstatCommand(const TcfTrkCallback &callBack,
                                                      const QByteArray &handle,
                                                      const QVariant &cookie)
{
    QByteArray data;
    JsonInputStream str(data);
    str << handle;
    sendTcfTrkMessage(MessageWithReply, FileSystemService, "fstat", data, callBack, cookie);
}

void tcftrk::TcfTrkDevice::sendFileSystemWriteCommand(const tcftrk::TcfTrkCallback &callBack,
                                                      const QByteArray &handle,
                                                      const QByteArray &dataIn,
                                                      unsigned offset,
                                                      const QVariant &cookie)
{
    QByteArray data;
    JsonInputStream str(data);
    str << handle << '\0' << offset << '\0' << dataIn.toBase64();
    sendTcfTrkMessage(MessageWithReply, FileSystemService, "write", data, callBack, cookie);
}

void tcftrk::TcfTrkDevice::sendFileSystemCloseCommand(const tcftrk::TcfTrkCallback &callBack,
                                                      const QByteArray &handle,
                                                      const QVariant &cookie)
{
    QByteArray data;
    JsonInputStream str(data);
    str << handle;
    sendTcfTrkMessage(MessageWithReply, FileSystemService, "close", data, callBack, cookie);
}

void tcftrk::TcfTrkDevice::sendSymbianInstallSilentInstallCommand(const tcftrk::TcfTrkCallback &callBack,
                                                                  const QByteArray &file,
                                                                  const QByteArray &targetDrive,
                                                                  const QVariant &cookie)
{
    QByteArray data;
    JsonInputStream str(data);
    str << file << '\0' << targetDrive;
    sendTcfTrkMessage(MessageWithReply, SymbianInstallService, "install", data, callBack, cookie);
}

void tcftrk::TcfTrkDevice::sendSymbianInstallUIInstallCommand(const tcftrk::TcfTrkCallback &callBack,
                                                              const QByteArray &file,
                                                              const QVariant &cookie)
{
    QByteArray data;
    JsonInputStream str(data);
    str << file;
    sendTcfTrkMessage(MessageWithReply, SymbianInstallService, "installWithUI", data, callBack, cookie);
}
1358
} // namespace tcftrk