codaclientapplication.cpp 18.9 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 "codaclientapplication.h"

32
33
34
35
#ifdef HAS_SERIALPORT
#    include <qextserialport/qextserialport.h>
#endif

36
37
#include "tcftrkdevice.h"
#include <QtNetwork/QTcpSocket>
38
39
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
40
41
42
43
44
45
46

#include <cstdio>

static const char usageC[] =
"\n%1 v0.1 built "__DATE__"\n\n"
"Test client for Symbian CODA\n\n"
"Usage:\n"
47
48
49
50
"%1 launch [-d]     address[:port] binary uid [--] [arguments]\n"
"%1 install[-s]     address[:port] remote-sis-file [targetdrive]\n"
"%1 put    [c size] address[:port] local-file remote-file\n"
"%1 stat            address[:port] remote-file\n"
51
"\nOptions:\n"
52
"-d            Launch: Launch under Debug control (wait for termination)\n"
53
54
55
56
57
58
59
60
61
62
"-c [size]     Put: Chunk size in KB (default %2KB)\n"
"-s            Install: Silent installation\n\n"
"Notes:\n"
"UIDs take the form '0xfdaa278'. The target directory for sis-files on a\n"
"device typically is 'c:\\data'. CODA's default port is %3.\n\n"
"Example session:\n"
"%1 put     192.168.0.42 test.sis c:\\data\\test.sis\n"
"%1 stat    192.168.0.42 c:\\data\\test.sis\n"
"%1 install 192.168.0.42 c:\\data\\test.sis c:\n"
"%1 launch  192.168.0.42 c:\\sys\\bin\\test.exe  0x34f2b\n";
63
64

static const unsigned short defaultPort = 65029;
65
static const quint64  defaultChunkSize = 10240;
66
67
68
69
70
71
72
73
74
75
76
77
78
79

static inline QString fixSlashes(QString s)
{
    s.replace(QLatin1Char('/'), QLatin1Char('\\'));
    return s;
}

CodaClientApplication::CodaClientApplication(int &argc, char **argv) :
    QCoreApplication(argc, argv),
    m_mode(Invalid),
    m_port(defaultPort),
    m_launchUID(0),
    m_launchDebug(false),
    m_installTargetDrive(QLatin1String("C:")),
80
81
82
    m_installSilently(false),
    m_putWriteOk(false),
    m_statFstatOk(false),
83
84
    m_putLastChunkSize(0),
    m_putChunkSize(defaultChunkSize),
85
86
87
88
89
90
91
92
93
94
95
96
    m_verbose(0)
{
    setApplicationName(QLatin1String("codaclient"));
}

CodaClientApplication::~CodaClientApplication()
{
}

QString CodaClientApplication::usage()
{
    return QString::fromLatin1(usageC)
97
98
            .arg(QCoreApplication::applicationName())
            .arg(defaultChunkSize / 1024).arg(defaultPort);
99
100
101
102
103
104
105
106
}

static inline CodaClientApplication::Mode modeArg(const QString &a)
{
    if (a == QLatin1String("launch"))
        return CodaClientApplication::Launch;
    if (a == QLatin1String("install"))
        return CodaClientApplication::Install;
107
108
109
110
    if (a == QLatin1String("put"))
        return CodaClientApplication::Put;
    if (a == QLatin1String("stat"))
        return CodaClientApplication::Stat;
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
    return CodaClientApplication::Invalid;
}

bool CodaClientApplication::parseArgument(const QString &a, int argNumber, QString *errorMessage)
{
    switch (argNumber) {
    case 1:
        m_mode = modeArg(a);
        if (m_mode == Invalid) {
            *errorMessage = QLatin1String("Invalid mode");
            return false;
        }
        return true;
    case 2:  { // Address/port
        m_address = a;
        const int colonPos = m_address.indexOf(':');
        if (colonPos != -1) {
            m_port = m_address.mid(colonPos + 1).toUInt();
            m_address.truncate(colonPos);
        }
    }
        break;
    case 3:
        switch (m_mode) {
        case Launch:
            m_launchBinary = fixSlashes(a);
            break;
        case Install:
            m_installSisFile = a;
            break;
141
142
143
144
145
        case Put:
            m_putLocalFile = a;
            break;
        case Stat:
            m_statRemoteFile = fixSlashes(a);
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
            break;
        default:
            break;
        }
        return true;
    case 4:
        switch (m_mode) {
        case Launch:
            m_launchUID = a.toUInt(0, 0);
            if (!m_launchUID) {
                *errorMessage = QLatin1String("Invalid UID");
                return false;
            }
            break;
        case Install:
            m_installTargetDrive = a;
            break;
163
164
        case Put:
            m_putRemoteFile = fixSlashes(a);
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
            break;
        default:
            break;
        }
        return true;

    default:
        if (m_mode == Launch)
            m_launchArgs.push_back(a);
        break;
    }
    return true;
}

CodaClientApplication::ParseArgsResult CodaClientApplication::parseArguments(QString *errorMessage)
{
    int argNumber = 1;
    const QStringList args = QCoreApplication::arguments();
    const QStringList::const_iterator cend = args.constEnd();
    QStringList::const_iterator it = args.constBegin();
    bool optionsEnd = false;
    for (++it; it != cend; ++it) {
        if (!optionsEnd  && *it == QLatin1String("--")) {
            optionsEnd = true;
            continue;
        }
        if (!optionsEnd &&  it->startsWith(QLatin1Char('-')) && it->size() == 2) {
            switch (it->at(1).toAscii()) {
            case 'v':
                m_verbose++;
                break;
            case 'd':
                m_launchDebug = true;
                break;
199
200
201
            case 's':
                m_installSilently = true;
                break;
202
203
204
205
206
207
208
209
210
211
212
            case 'c':
                if (++it == cend) {
                    *errorMessage = QString::fromLatin1("Parameter missing for -c");
                    return ParseArgsError;
                }
                m_putChunkSize = it->toULongLong() * 1024;
                if (!m_putChunkSize) {
                    *errorMessage = QString::fromLatin1("Invalid chunk size.");
                    return ParseArgsError;
                }
                break;
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
            default:
                *errorMessage = QString::fromLatin1("Invalid option %1").arg(*it);
                return ParseArgsError;
            }
        } else {
            if (!parseArgument(*it, argNumber++, errorMessage))
                return ParseArgsError;
        }
    } //for loop
    // Basic Check & init
    switch (m_mode) {
    case Invalid:
        return ParseArgsError;
    case Launch:
        if (m_address.isEmpty() || !m_launchUID || m_launchBinary.isEmpty()) {
            *errorMessage = QString::fromLatin1("Not enough parameters for launch.");
            return ParseInitError;
        }
        break;
    case Install:
        if (m_address.isEmpty() || m_installSisFile.isEmpty()) {
            *errorMessage = QString::fromLatin1("Not enough parameters for install.");
            return ParseInitError;
        }
        break;
238
239
240
241
242
243
244
245
    case Put: {
        if (m_address.isEmpty() || m_putLocalFile.isEmpty() || m_putRemoteFile.isEmpty()) {
            *errorMessage = QString::fromLatin1("Not enough parameters for put.");
            return ParseInitError;
        }
        const QFileInfo fi(m_putLocalFile);
        if (!fi.isFile() || !fi.isReadable()) {
            *errorMessage = QString::fromLatin1("Local file '%1' not readable.").arg(m_putLocalFile);
246
247
            return ParseInitError;
        }
248
    }
249
250
251
252
253
254
255
256
257
        break;
    default:
        break;
    }
    return ParseArgsOk;
}

bool CodaClientApplication::start()
{
258
    m_startTime.start();
259
260
261
    switch (m_mode) {
    case Launch: {
        const QString args = m_launchArgs.join(QString(QLatin1Char(' ')));
262
        std::printf("Launching 0x%x '%s '%s' (debug: %d)\n",
263
                    m_launchUID, qPrintable(m_launchBinary),
264
                    qPrintable(args), m_launchDebug);
265
266
267
    }
        break;
    case Install:
268
269
        std::printf("Installing '%s' to '%s'\n",
                    qPrintable(m_installSisFile), qPrintable(m_installTargetDrive));
270
        break;
271
    case Put:
272
        std::printf("Copying '%s' to '%s' in chunks of %lluKB\n",
273
                    qPrintable(m_putLocalFile), qPrintable(m_putRemoteFile),
274
                    m_putChunkSize / 1024);
275
        break;
276
    case Stat:
277
        std::printf("Retrieving attributes of '%s'\n", qPrintable(m_statRemoteFile));
278
        break;
279
280
281
282
283
284
285
286
287
288
289
290
    case Invalid:
        break;
    }
    // Start connection
    m_trkDevice.reset(new tcftrk::TcfTrkDevice);
    m_trkDevice->setVerbose(m_verbose);
    connect(m_trkDevice.data(), SIGNAL(error(QString)),
        this, SLOT(slotError(QString)));
    connect(m_trkDevice.data(), SIGNAL(logMessage(QString)),
        this, SLOT(slotTrkLogMessage(QString)));
    connect(m_trkDevice.data(), SIGNAL(tcfEvent(tcftrk::TcfTrkEvent)),
        this, SLOT(slotTcftrkEvent(tcftrk::TcfTrkEvent)));
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
331
332
    if (m_address.startsWith(QLatin1String("/dev"))
            || m_address.startsWith(QLatin1String("com"), Qt::CaseInsensitive)
            || m_address.startsWith(QLatin1Char('\\'))) {
#ifdef HAS_SERIALPORT
        // Serial
#ifdef Q_OS_WIN
        const QString fullPort = QextSerialPort::fullPortNameWin(m_address);
#else
        const QString fullPort = m_address;
#endif
        const QSharedPointer<QextSerialPort>
                serialPort(new QextSerialPort(fullPort, QextSerialPort::EventDriven));
        std::printf("Opening port %s...\n", qPrintable(fullPort));

        // Magic USB serial parameters
        serialPort->setTimeout(2000);
        serialPort->setBaudRate(BAUD115200);
        serialPort->setFlowControl(FLOW_OFF);
        serialPort->setParity(PAR_NONE);
        serialPort->setDataBits(DATA_8);
        serialPort->setStopBits(STOP_1);

        m_trkDevice->setSerialFrame(true);
        m_trkDevice->setDevice(serialPort); // Grab all data from start
        if (!serialPort->open(QIODevice::ReadWrite|QIODevice::Unbuffered)) {
            std::fprintf(stderr, "Cannot open port: %s", qPrintable(serialPort->errorString()));
            return false;
        }
        // Initiate communication
        m_trkDevice->sendSerialPing();
        serialPort->flush();
#else
        std::fprintf(stderr, "Not implemented\n");
        return false;
#endif
    } else {
        // TCP/IP
        const QSharedPointer<QTcpSocket> tcfTrkSocket(new QTcpSocket);
        m_trkDevice->setDevice(tcfTrkSocket);
        tcfTrkSocket->connectToHost(m_address, m_port);
        std::printf("Connecting to %s:%hu...\n", qPrintable(m_address), m_port);
    }
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
    return true;
}

void CodaClientApplication::slotError(const QString &e)
{
    std::fprintf(stderr, "Error: %s\n", qPrintable(e));
    doExit(-1);
}

void CodaClientApplication::slotTrkLogMessage(const QString &m)
{
    std::printf("%s\n", qPrintable(m));
}

void CodaClientApplication::handleCreateProcess(const tcftrk::TcfTrkCommandResult &result)
{
    const bool ok = result.type == tcftrk::TcfTrkCommandResult::SuccessReply;
    if (ok) {
        std::printf("Launch succeeded: %s\n", qPrintable(result.toString()));
        if (!m_launchDebug)
            doExit(0);
    } else {
        std::fprintf(stderr, "Launch failed: %s\n", qPrintable(result.toString()));
        doExit(-1);
    }
}

360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
void CodaClientApplication::handleFileSystemOpen(const tcftrk::TcfTrkCommandResult &result)
{
    if (result.type != tcftrk::TcfTrkCommandResult::SuccessReply) {
        std::fprintf(stderr, "Open remote file failed: %s\n", qPrintable(result.toString()));
        doExit(-1);
        return;
    }

    if (result.values.size() < 1 || result.values.at(0).data().isEmpty()) {
        std::fprintf(stderr, "Internal error: No filehandle obtained\n");
        doExit(-1);
        return;
    }

    m_remoteFileHandle = result.values.at(0).data();

    if (m_mode == Stat) {
        m_trkDevice->sendFileSystemFstatCommand(tcftrk::TcfTrkCallback(this, &CodaClientApplication::handleFileSystemFStat),
                                               m_remoteFileHandle);
        return;
    }
    // Put.
382
383
384
    m_putFile.reset(new QFile(m_putLocalFile));
    if (!m_putFile->open(QIODevice::ReadOnly)) { // Should not fail, was checked before
        std::fprintf(stderr, "Open local file failed: %s\n", qPrintable(m_putFile->errorString()));
385
386
387
        doExit(-1);
        return;
    }
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
    putSendNextChunk();
}

void CodaClientApplication::putSendNextChunk()
{
    // Read and send off next chunk
    const quint64 pos = m_putFile->pos();
    const QByteArray data = m_putFile->read(m_putChunkSize);
    if (data.isEmpty()) {
        m_putWriteOk = true;
        closeRemoteFile();
    } else {
        m_putLastChunkSize = data.size();
        std::printf("Writing %llu bytes to remote file '%s' at %llu\n",
                    m_putLastChunkSize,
                    m_remoteFileHandle.constData(), pos);
        m_trkDevice->sendFileSystemWriteCommand(tcftrk::TcfTrkCallback(this, &CodaClientApplication::handleFileSystemWrite),
                                                m_remoteFileHandle, data, unsigned(pos));
    }
}

void CodaClientApplication::closeRemoteFile()
{
    m_trkDevice->sendFileSystemCloseCommand(tcftrk::TcfTrkCallback(this, &CodaClientApplication::handleFileSystemClose),
                                            m_remoteFileHandle);
413
414
415
416
417
}

void CodaClientApplication::handleFileSystemWrite(const tcftrk::TcfTrkCommandResult &result)
{
    // Close remote file even if copy fails
418
    m_putWriteOk = result;
419
420
    if (!m_putWriteOk)
        std::fprintf(stderr, "Writing data failed: %s\n", qPrintable(result.toString()));
421
422
423
424
425
    if (!m_putWriteOk || m_putLastChunkSize < m_putChunkSize) {
        closeRemoteFile();
    } else {
        putSendNextChunk();
    }
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
}

void CodaClientApplication::handleFileSystemFStat(const tcftrk::TcfTrkCommandResult &result)
{
    m_statFstatOk = result.type == tcftrk::TcfTrkCommandResult::SuccessReply;
    // Close remote file even if copy fails
    if (m_statFstatOk) {
        const tcftrk::TcfTrkStatResponse statr = tcftrk::TcfTrkDevice::parseStat(result);
        std::printf("File: %s\nSize: %llu bytes\nAccessed: %s\nModified: %s\n",
                    qPrintable(m_statRemoteFile), statr.size,
                    qPrintable(statr.accessTime.toString(Qt::LocalDate)),
                    qPrintable(statr.modTime.toString(Qt::LocalDate)));
    } else {
        std::fprintf(stderr, "FStat failed: %s\n", qPrintable(result.toString()));
    }
441
    closeRemoteFile();
442
443
444
445
446
}

void CodaClientApplication::handleFileSystemClose(const tcftrk::TcfTrkCommandResult &result)
{
    if (result.type == tcftrk::TcfTrkCommandResult::SuccessReply) {
447
        std::printf("File closed.\n");
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
        const bool ok = m_mode == Put ? m_putWriteOk : m_statFstatOk;
        doExit(ok ? 0 : -1);
    } else {
        std::fprintf(stderr, "File close failed: %s\n", qPrintable(result.toString()));
        doExit(-1);
    }
}

void CodaClientApplication::handleSymbianInstall(const tcftrk::TcfTrkCommandResult &result)
{
    if (result.type == tcftrk::TcfTrkCommandResult::SuccessReply) {
        std::printf("Installation succeeded\n.");
        doExit(0);
    } else {
        std::fprintf(stderr, "Installation failed: %s\n", qPrintable(result.toString()));
        doExit(-1);
    }
}

467
468
469
470
471
472
473
474
475
476
477
void CodaClientApplication::slotTcftrkEvent (const tcftrk::TcfTrkEvent &ev)
{
    std::printf("Event: %s\n", qPrintable(ev.toString()));
    switch (ev.type()) {
    case tcftrk::TcfTrkEvent::LocatorHello: // Commands accepted now
        switch (m_mode) {
        case Launch:
            m_trkDevice->sendProcessStartCommand(tcftrk::TcfTrkCallback(this, &CodaClientApplication::handleCreateProcess),
                                                 m_launchBinary, m_launchUID, m_launchArgs, QString(), m_launchDebug);
            break;
        case Install:
478
479
480
481
482
483
484
            if (m_installSilently) {
                m_trkDevice->sendSymbianInstallSilentInstallCommand(tcftrk::TcfTrkCallback(this, &CodaClientApplication::handleSymbianInstall),
                                                                    m_installSisFile.toAscii(), m_installTargetDrive.toAscii());
            } else {
                m_trkDevice->sendSymbianInstallUIInstallCommand(tcftrk::TcfTrkCallback(this, &CodaClientApplication::handleSymbianInstall),
                                                                m_installSisFile.toAscii());
            }
485
            break;
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
        case Put: {
            const unsigned flags =
                    tcftrk::TcfTrkDevice::FileSystem_TCF_O_WRITE
                    |tcftrk::TcfTrkDevice::FileSystem_TCF_O_CREAT
                    |tcftrk::TcfTrkDevice::FileSystem_TCF_O_TRUNC;
            m_putWriteOk = false;
            m_trkDevice->sendFileSystemOpenCommand(tcftrk::TcfTrkCallback(this, &CodaClientApplication::handleFileSystemOpen),
                                                   m_putRemoteFile.toAscii(), flags);
}
            break;
        case Stat: {
            const unsigned flags = tcftrk::TcfTrkDevice::FileSystem_TCF_O_READ;
            m_statFstatOk = false;
            m_trkDevice->sendFileSystemOpenCommand(tcftrk::TcfTrkCallback(this, &CodaClientApplication::handleFileSystemOpen),
                                                   m_statRemoteFile.toAscii(), flags);
}
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
            break;
        case Invalid:
            break;
        }
        break;
    case tcftrk::TcfTrkEvent::RunControlModuleLoadSuspended:  {
        // Debug mode start: Continue:
        const tcftrk::TcfTrkRunControlModuleLoadContextSuspendedEvent &me =
                static_cast<const tcftrk::TcfTrkRunControlModuleLoadContextSuspendedEvent &>(ev);
        if (me.info().requireResume) {
            std::printf("Continuing...\n");
            m_trkDevice->sendRunControlResumeCommand(tcftrk::TcfTrkCallback(), me.id());
        }
    }
        break;
    case tcftrk::TcfTrkEvent::RunControlContextRemoved: // App terminated in debug mode
        doExit(0);
        break;
    default:
        break;
    }
}

void CodaClientApplication::doExit(int ex)
{
527
528
    std::printf("Operation took %4.2f second(s)\n", m_startTime.elapsed()/1000.);

529
530
    if (!m_trkDevice.isNull()) {
        const QSharedPointer<QIODevice> dev = m_trkDevice->device();
531
532
533
534
535
536
537
538
        if (!dev.isNull()) {
            if (QAbstractSocket *socket = qobject_cast<QAbstractSocket *>(dev.data())) {
                if (socket->state() == QAbstractSocket::ConnectedState)
                    socket->disconnectFromHost();
            } else {
                if (dev->isOpen())
                    dev->close();
            }
539
540
541
542
543
        }
    }
    std::printf("Exiting (%d)\n", ex);
    exit(ex);
}