Commit 2095658e authored by Friedemann Kleint's avatar Friedemann Kleint

Trk: Factor out write queue using a functor.

parent d79e8dc3
This diff is collapsed.
......@@ -70,27 +70,11 @@ private slots:
void handleResult(const TrkResult &data);
private:
void sendTrkMessage(unsigned char code,
TrkCallBack callBack = 0,
const QByteArray &data = QByteArray(),
const QVariant &cookie = QVariant());
// adds message to 'send' queue
void queueTrkMessage(const TrkMessage &msg);
void tryTrkWrite();
void tryTrkRead();
// actually writes a message to the device
void trkWrite(const TrkMessage &msg);
void trkWriteRawMessage(const TrkMessage &msg);
// convienience messages
void sendTrkInitialPing();
void sendTrkAck(unsigned char token);
// kill process and breakpoints
void cleanUp();
void timerEvent(QTimerEvent *ev);
unsigned char nextTrkWriteToken();
void handleFileCreation(const TrkResult &result);
void handleFileCreated(const TrkResult &result);
void handleInstallPackageFinished(const TrkResult &result);
......
......@@ -32,6 +32,9 @@
#include <QtCore/QString>
#include <QtCore/QDebug>
#include <QtCore/QQueue>
#include <QtCore/QHash>
#include <QtCore/QMap>
#ifdef Q_OS_WIN
# include <windows.h>
......@@ -194,6 +197,7 @@ void TrkDevice::close()
}
#ifdef Q_OS_WIN
CloseHandle(d->hdevice);
d->hdevice = INVALID_HANDLE_VALUE;
#else
d->file.close();
#endif
......@@ -287,8 +291,8 @@ void TrkDevice::tryTrkRead()
return;
const ushort len = isValidTrkResult(d->trkReadBuffer, d->serialFrame);
if (!len) {
d->errorString = QString::fromLatin1("Partial message: %1").arg(stringFromArray(d->trkReadBuffer));
qWarning("%s\n", qPrintable(d->errorString));
const QString msg = QString::fromLatin1("Partial message: %1").arg(stringFromArray(d->trkReadBuffer));
emitError(msg);
return;
}
#else
......@@ -300,9 +304,9 @@ void TrkDevice::tryTrkRead()
const ushort len = isValidTrkResult(d->trkReadBuffer, d->serialFrame);
if (!len) {
if (d->trkReadBuffer.size() > 10) {
d->errorString = QString::fromLatin1("Unable to extract message from '%1' '%2'").
const QString msg = QString::fromLatin1("Unable to extract message from '%1' '%2'").
arg(QLatin1String(d->trkReadBuffer.toHex())).arg(QString::fromAscii(d->trkReadBuffer));
qWarning("%s\n", qPrintable(d->errorString));
emitError(msg);
}
return;
}
......@@ -320,4 +324,166 @@ void TrkDevice::timerEvent(QTimerEvent *)
tryTrkRead();
}
} // namespace trk
void TrkDevice::emitError(const QString &s)
{
d->errorString = s;
qWarning("%s\n", qPrintable(s));
emit error(s);
}
/* A message to be send to TRK, triggering a callback on receipt
* of the answer. */
struct TrkMessage {
typedef TrkFunctor1<const TrkResult &> Callback;
explicit TrkMessage(unsigned char code = 0u,
unsigned char token = 0u,
Callback callback = Callback());
unsigned char code;
unsigned char token;
QByteArray data;
QVariant cookie;
Callback callback;
bool invokeOnNAK;
};
TrkMessage::TrkMessage(unsigned char c,
unsigned char t,
Callback cb) :
code(c),
token(t),
callback(cb),
invokeOnNAK(false)
{
}
// ------- TrkWriteQueueDevice
struct TrkWriteQueueDevicePrivate {
typedef QMap<unsigned char, TrkMessage> TokenMessageMap;
TrkWriteQueueDevicePrivate();
unsigned char trkWriteToken;
QQueue<TrkMessage> trkWriteQueue;
TokenMessageMap writtenTrkMessages;
bool trkWriteBusy;
};
TrkWriteQueueDevicePrivate::TrkWriteQueueDevicePrivate() :
trkWriteToken(0),
trkWriteBusy(false)
{
}
TrkWriteQueueDevice::TrkWriteQueueDevice(QObject *parent) :
TrkDevice(parent),
qd(new TrkWriteQueueDevicePrivate)
{
connect(this, SIGNAL(messageReceived(TrkResult)), this, SLOT(slotHandleResult(TrkResult)));
}
TrkWriteQueueDevice::~TrkWriteQueueDevice()
{
delete qd;
}
unsigned char TrkWriteQueueDevice::nextTrkWriteToken()
{
++qd->trkWriteToken;
if (qd->trkWriteToken == 0)
++qd->trkWriteToken;
return qd->trkWriteToken;
}
void TrkWriteQueueDevice::sendTrkMessage(unsigned char code, Callback callback,
const QByteArray &data, const QVariant &cookie,
bool invokeOnNAK)
{
TrkMessage msg(code, nextTrkWriteToken(), callback);
msg.data = data;
msg.cookie = cookie;
msg.invokeOnNAK = invokeOnNAK;
queueTrkMessage(msg);
}
void TrkWriteQueueDevice::sendTrkInitialPing()
{
const TrkMessage msg(0, 0); // Ping, reset sequence count
queueTrkMessage(msg);
}
bool TrkWriteQueueDevice::sendTrkAck(unsigned char token)
{
TrkMessage msg(0x80, token);
msg.token = token;
msg.data.append('\0');
// The acknowledgement must not be queued!
return trkWriteRawMessage(msg);
// 01 90 00 07 7e 80 01 00 7d 5e 7e
}
void TrkWriteQueueDevice::queueTrkMessage(const TrkMessage &msg)
{
qd->trkWriteQueue.append(msg);
}
void TrkWriteQueueDevice::tryTrkWrite()
{
// Invoked from timer, try to flush out message queue
if (qd->trkWriteBusy)
return;
if (qd->trkWriteQueue.isEmpty())
return;
const TrkMessage msg = qd->trkWriteQueue.dequeue();
trkWrite(msg);
}
bool TrkWriteQueueDevice::trkWriteRawMessage(const TrkMessage &msg)
{
const QByteArray ba = frameMessage(msg.code, msg.token, msg.data, serialFrame());
if (verbose())
qDebug() << ("WRITE: " + stringFromArray(ba));
QString errorMessage;
const bool rc = write(ba, &errorMessage);
if (!rc)
emitError(errorMessage);
return rc;
}
bool TrkWriteQueueDevice::trkWrite(const TrkMessage &msg)
{
qd->writtenTrkMessages.insert(msg.token, msg);
qd->trkWriteBusy = true;
return trkWriteRawMessage(msg);
}
void TrkWriteQueueDevice::timerEvent(QTimerEvent *ev)
{
tryTrkWrite();
TrkDevice::timerEvent(ev);
}
void TrkWriteQueueDevice::slotHandleResult(const TrkResult &result)
{
qd->trkWriteBusy = false;
if (result.code != TrkNotifyAck && result.code != TrkNotifyNak)
return;
// Find which request the message belongs to and invoke callback
// if ACK or on NAK if desired.
const TrkWriteQueueDevicePrivate::TokenMessageMap::iterator it = qd->writtenTrkMessages.find(result.token);
if (it == qd->writtenTrkMessages.end())
return;
const bool invokeCB = it.value().callback
&& (result.code == TrkNotifyAck || it.value().invokeOnNAK);
if (invokeCB) {
TrkResult result1 = result;
result1.cookie = it.value().cookie;
it.value().callback(result1);
}
qd->writtenTrkMessages.erase(it);
}
} // namespace tr
......@@ -30,6 +30,8 @@
#ifndef TRKDEVICE_H
#define TRKDEVICE_H
#include "trkfunctor.h"
#include <QtCore/QObject>
#include <QtCore/QVariant>
#include <QtCore/QByteArray>
......@@ -37,7 +39,9 @@
namespace trk {
struct TrkResult;
struct TrkMessage;
struct TrkDevicePrivate;
struct TrkWriteQueueDevicePrivate;
/* TrkDevice: Implements a Windows COM or Linux device for
* Trk communications. Provides synchronous write and asynchronous
......@@ -71,14 +75,62 @@ public:
signals:
void messageReceived(const TrkResult&);
void error(const QString &s);
protected:
void emitError(const QString &);
virtual void timerEvent(QTimerEvent *ev);
private:
void tryTrkRead();
virtual void timerEvent(QTimerEvent *ev);
TrkDevicePrivate *d;
};
/* TrkWriteQueueDevice: Extends TrkDevice by write message queue allowing
* for queueing messages with a notification callback. If the message receives
* an ACK, the callback is invoked. */
class TrkWriteQueueDevice : public TrkDevice
{
Q_OBJECT
public:
explicit TrkWriteQueueDevice(QObject *parent = 0);
virtual ~TrkWriteQueueDevice();
// Construct as 'TrkWriteQueueDevice::Callback(instance, &Klass::method);'
typedef TrkFunctor1<const TrkResult &> Callback;
// Enqueue a message with a notification callback.
void sendTrkMessage(unsigned char code,
Callback callBack = Callback(),
const QByteArray &data = QByteArray(),
const QVariant &cookie = QVariant(),
// Invoke callback on receiving NAK, too.
bool invokeOnNAK = false);
// Enqeue an initial ping
void sendTrkInitialPing();
// Send an Ack synchronously, bypassing the queue
bool sendTrkAck(unsigned char token);
private slots:
void slotHandleResult(const TrkResult &);
protected:
virtual void timerEvent(QTimerEvent *ev);
private:
unsigned char nextTrkWriteToken();
void queueTrkMessage(const TrkMessage &msg);
void tryTrkWrite();
bool trkWriteRawMessage(const TrkMessage &msg);
bool trkWrite(const TrkMessage &msg);
TrkWriteQueueDevicePrivate *qd;
};
} // namespace trk
#endif // TRKDEVICE_H
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 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.
**
**************************************************************************/
#ifndef _TRK_FUNCTOR_H_
#define _TRK_FUNCTOR_H_
#include <QtGlobal>
namespace trk {
namespace Internal {
/* Helper class for the 1-argument functor:
* Cloneable base class for the implementation which is
* invokeable with the argument. */
template <class Argument>
class TrkFunctor1ImplBase {
Q_DISABLE_COPY(TrkFunctor1ImplBase)
public:
TrkFunctor1ImplBase() {}
virtual TrkFunctor1ImplBase *clone() const = 0;
virtual void invoke(Argument a) = 0;
virtual ~TrkFunctor1ImplBase() {}
};
/* Helper class for the 1-argument functor: Implementation for
* a class instance with a member function pointer. */
template <class Klass, class Argument>
class TrkFunctor1MemberPtrImpl : public TrkFunctor1ImplBase<Argument> {
public:
typedef void (Klass::*MemberFuncPtr)(Argument);
explicit TrkFunctor1MemberPtrImpl(Klass *instance,
MemberFuncPtr memberFunc) :
m_instance(instance),
m_memberFunc(memberFunc) {}
virtual TrkFunctor1ImplBase<Argument> *clone() const
{
return new TrkFunctor1MemberPtrImpl<Klass, Argument>(m_instance, m_memberFunc);
}
virtual void invoke(Argument a)
{ (m_instance->*m_memberFunc)(a); }
private:
Klass *m_instance;
MemberFuncPtr m_memberFunc;
};
} // namespace Internal
/* Default-constructible, copyable 1-argument functor providing an
* operator()(Argument) that invokes a member function of a class:
* \code
class Foo {
public:
void print(const std::string &);
};
...
Foo foo;
TrkFunctor1<const std::string &> f1(&foo, &Foo::print);
f1("test");
\endcode */
template <class Argument>
class TrkFunctor1 {
public:
TrkFunctor1() : m_impl(0) {}
template <class Klass>
TrkFunctor1(Klass *instance,
void (Klass::*memberFunc)(Argument)) :
m_impl(new Internal::TrkFunctor1MemberPtrImpl<Klass,Argument>(instance, memberFunc)) {}
~TrkFunctor1()
{
clean();
}
TrkFunctor1(const TrkFunctor1 &rhs) :
m_impl(0)
{
if (rhs.m_impl)
m_impl = rhs.m_impl->clone();
}
TrkFunctor1 &operator=(const TrkFunctor1 &rhs)
{
if (this != &rhs) {
clean();
if (rhs.m_impl)
m_impl = rhs.m_impl->clone();
}
return *this;
}
inline bool isNull() const { return m_impl == 0; }
operator bool() const { return !isNull(); }
void operator()(Argument a)
{
if (m_impl)
m_impl->invoke(a);
}
private:
void clean()
{
if (m_impl) {
delete m_impl;
m_impl = 0;
}
}
Internal::TrkFunctor1ImplBase<Argument> *m_impl;
};
} // namespace trk
#endif // _TRK_FUNCTOR_H_
......@@ -4,5 +4,6 @@ SOURCES += $$PWD/launcher.cpp \
$$PWD/trkutils.cpp \
$$PWD/trkdevice.cpp
HEADERS += $$PWD/trkutils.h \
$$PWD/trkfunctor.h \
$$PWD/trkdevice.h \
$$PWD/launcher.h
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment