virtualserialdevice_posix.cpp 9.53 KB
Newer Older
1
2
3
4
5
6
7
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <QtCore/QSocketNotifier>
#include <QtCore/QTimer>
8
9
#include <QtCore/QThread>
#include <QtCore/QWaitCondition>
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
#include "virtualserialdevice.h"

namespace SymbianUtils {

class VirtualSerialDevicePrivate
{
public:
    int portHandle;
    QSocketNotifier* readNotifier;
    QSocketNotifier* writeUnblockedNotifier;
};

void VirtualSerialDevice::platInit()
{
    d = new VirtualSerialDevicePrivate;
    d->portHandle = -1;
    d->readNotifier = NULL;
    d->writeUnblockedNotifier = NULL;
    connect(this, SIGNAL(AsyncCall_emitBytesWrittenIfNeeded(qint64)), this, SIGNAL(bytesWritten(qint64)), Qt::QueuedConnection);
}

bool VirtualSerialDevice::open(OpenMode mode)
{
    if (isOpen()) return true;

    d->portHandle = ::open(portName.toAscii().constData(), O_RDWR | O_NONBLOCK | O_NOCTTY);
    if (d->portHandle == -1) {
        setErrorString(QString("Posix error %1 opening %2").arg(errno).arg(portName));
        return false;
        }

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
    struct termios termInfo;
    if (tcgetattr(d->portHandle, &termInfo) < 0) {
        setErrorString(QString::fromLatin1("Unable to retrieve terminal settings: %1 %2").arg(errno).arg(QString::fromAscii(strerror(errno))));
        close();
        return false;
    }
    cfmakeraw(&termInfo);
    // Turn off terminal echo as not get messages back, among other things
    termInfo.c_cflag |= CREAD|CLOCAL;
    termInfo.c_cc[VTIME] = 0;
    termInfo.c_lflag &= (~(ICANON|ECHO|ECHOE|ECHOK|ECHONL|ISIG));
    termInfo.c_iflag &= (~(INPCK|IGNPAR|PARMRK|ISTRIP|ICRNL|IXANY|IXON|IXOFF));
    termInfo.c_oflag &= (~OPOST);
    termInfo.c_cc[VMIN]  = 0;
    termInfo.c_cc[VINTR] = _POSIX_VDISABLE;
    termInfo.c_cc[VQUIT] = _POSIX_VDISABLE;
    termInfo.c_cc[VSTART] = _POSIX_VDISABLE;
    termInfo.c_cc[VSTOP] = _POSIX_VDISABLE;
    termInfo.c_cc[VSUSP] = _POSIX_VDISABLE;

    if (tcsetattr(d->portHandle, TCSAFLUSH, &termInfo) < 0) {
        setErrorString(QString::fromLatin1("Unable to apply terminal settings: %1 %2").arg(errno).arg(QString::fromAscii(strerror(errno))));
        close();
        return false;
    }

67
68
69
70
71
72
73
    d->readNotifier = new QSocketNotifier(d->portHandle, QSocketNotifier::Read);
    connect(d->readNotifier, SIGNAL(activated(int)), this, SIGNAL(readyRead()));

    d->writeUnblockedNotifier = new QSocketNotifier(d->portHandle, QSocketNotifier::Write);
    d->writeUnblockedNotifier->setEnabled(false);
    connect(d->writeUnblockedNotifier, SIGNAL(activated(int)), this, SLOT(writeHasUnblocked(int)));

74
    bool ok = QIODevice::open(mode | QIODevice::Unbuffered);
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
    if (!ok) close();
    return ok;
}

void VirtualSerialDevice::platClose()
{
    delete d->readNotifier;
    d->readNotifier = NULL;

    delete d->writeUnblockedNotifier;
    d->writeUnblockedNotifier = NULL;

    ::close(d->portHandle);
    d->portHandle = -1;
}

VirtualSerialDevice::~VirtualSerialDevice()
{
    close();
    delete d;
}

qint64 VirtualSerialDevice::bytesAvailable() const
{
    QMutexLocker locker(&lock);
    if (!isOpen()) return 0;

    int avail = 0;
    if (ioctl(d->portHandle, FIONREAD, &avail) == -1) {
        return 0;
    }
    return (qint64)avail + QIODevice::bytesAvailable();
}

qint64 VirtualSerialDevice::readData(char *data, qint64 maxSize)
{
    QMutexLocker locker(&lock);
    int result = ::read(d->portHandle, data, maxSize);
113
114
    if (result == -1 && errno == EAGAIN)
        result = 0; // To Qt, 0 here means nothing ready right now, and -1 is reserved for permanent errors
115
116
117
118
119
120
121
122
123
124
    return result;
}

qint64 VirtualSerialDevice::writeData(const char *data, qint64 maxSize)
{
    QMutexLocker locker(&lock);
    qint64 bytesWritten;
    bool needToWait = tryFlushPendingBuffers(locker, EmitBytesWrittenAsync);
    if (!needToWait) {
        needToWait = tryWrite(data, maxSize, bytesWritten);
125
126
127
128
129
        if (needToWait && bytesWritten > 0) {
            // Wrote some of the buffer, adjust pointers to point to the remainder that needs queueing
            data += bytesWritten;
            maxSize -= bytesWritten;
        }
130
131
132
133
134
135
    }

    if (needToWait) {
        pendingWrites.append(QByteArray(data, maxSize));
        d->writeUnblockedNotifier->setEnabled(true);
        // Now wait for the writeUnblocked signal or for a call to waitForBytesWritten
136
        return bytesWritten + maxSize;
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
    } else {
        //emitBytesWrittenIfNeeded(locker, bytesWritten);
        // Can't emit bytesWritten directly from writeData - means clients end up recursing
        emit AsyncCall_emitBytesWrittenIfNeeded(bytesWritten);
        return bytesWritten;
    }
}

/* Returns true if EAGAIN encountered.
 * if error occurred (other than EAGAIN) returns -1 in bytesWritten
 * lock must be held. Doesn't emit signals or set notifiers.
 */
bool VirtualSerialDevice::tryWrite(const char *data, qint64 maxSize, qint64& bytesWritten)
{
    // Must be locked
152
153
154
155
    bytesWritten = 0;
    while (maxSize > 0) {
        int result = ::write(d->portHandle, data, maxSize);
        if (result == -1) {
156
157
158
159
160
            if (errno == EAGAIN)
                return true; // Need to wait
            setErrorString(QString("Posix error %1 from write to %2").arg(errno).arg(portName));
            bytesWritten = -1;
            return false;
161
        } else {
162
163
164
165
166
            if (result == 0)
                qWarning("Zero bytes written to port!");
            bytesWritten += result;
            maxSize -= result;
            data += result;
167
168
        }
    }
169
    return false; // If we reach here we've successfully written all the data without blocking
170
171
172
173
174
175
176
}

/* Returns true if EAGAIN encountered. Emits (or queues) bytesWritten for any buffers written.
 * If stopAfterWritingOneBuffer is true, return immediately if a single buffer is written, rather than
 * attempting to drain the whole queue.
 * Doesn't modify notifier.
 */
177
bool VirtualSerialDevice::tryFlushPendingBuffers(QMutexLocker& locker, FlushPendingOptions flags)
178
179
180
181
182
183
184
{
    while (pendingWrites.count() > 0) {
        // Try writing everything we've got, until we hit EAGAIN
        const QByteArray& data = pendingWrites[0];
        qint64 bytesWritten;
        bool needToWait = tryWrite(data.constData(), data.size(), bytesWritten);
        if (needToWait) {
185
186
187
188
189
190
            if (bytesWritten > 0) {
                // We wrote some of the data, update the pending queue
                QByteArray remainder = data.mid(bytesWritten);
                pendingWrites.removeFirst();
                pendingWrites.insert(0, remainder);
            }
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
            return needToWait;
        } else {
            pendingWrites.removeFirst();
            if (flags & EmitBytesWrittenAsync) {
                emit AsyncCall_emitBytesWrittenIfNeeded(bytesWritten);
            } else {
                emitBytesWrittenIfNeeded(locker, bytesWritten);
            }
            if (flags & StopAfterWritingOneBuffer) return false;
            // Otherwise go round loop again
        }
    }
    return false; // no EAGAIN encountered
}

void VirtualSerialDevice::writeHasUnblocked(int fileHandle)
{
    Q_ASSERT(fileHandle == d->portHandle);
    (void)fileHandle; // Compiler shutter-upper
    d->writeUnblockedNotifier->setEnabled(false);

    QMutexLocker locker(&lock);
    bool needToWait = tryFlushPendingBuffers(locker);
    if (needToWait) d->writeUnblockedNotifier->setEnabled(true);
}

217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
// Copy of qt_safe_select from /qt/src/corelib/kernel/qeventdispatcher_unix.cpp
// But without the timeout correction
int safe_select(int nfds, fd_set *fdread, fd_set *fdwrite, fd_set *fdexcept,
                   const struct timeval *orig_timeout)
{
    if (!orig_timeout) {
        // no timeout -> block forever
        register int ret;
        do {
            ret = select(nfds, fdread, fdwrite, fdexcept, 0);
        } while (ret == -1 && errno == EINTR);
        return ret;
    }

    timeval timeout = *orig_timeout;

    int ret;
    forever {
        ret = ::select(nfds, fdread, fdwrite, fdexcept, &timeout);
        if (ret != -1 || errno != EINTR)
            return ret;
    }
}

241
242
243
244
245
bool VirtualSerialDevice::waitForBytesWritten(int msecs)
{
    QMutexLocker locker(&lock);
    if (pendingWrites.count() == 0) return false;

246
247
248
249
250
251
252
253
254
    if (QThread::currentThread() != thread()) {
        // Wait for signal from main thread
        unsigned long timeout = msecs;
        if (msecs == -1) timeout = ULONG_MAX;
        if (waiterForBytesWritten == NULL)
            waiterForBytesWritten = new QWaitCondition;
        return waiterForBytesWritten->wait(&lock, timeout);
    }

255
256
257
258
259
260
261
262
263
264
265
    d->writeUnblockedNotifier->setEnabled(false);
    forever {
        fd_set writeSet;
        FD_ZERO(&writeSet);
        FD_SET(d->portHandle, &writeSet);

        struct timeval timeout;
        if (msecs != -1) {
            timeout.tv_sec = msecs / 1000;
            timeout.tv_usec = (msecs % 1000) * 1000;
        }
266
        int ret = safe_select(d->portHandle+1, NULL, &writeSet, NULL, msecs == -1 ? NULL : &timeout);
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

        if (ret == 0) {
            // Timeout
            return false;
        } else if (ret < 0) {
            setErrorString(QString("Posix error %1 returned from select in waitForBytesWritten").arg(errno));
            return false;
        } else {
            bool needToWait = tryFlushPendingBuffers(locker, StopAfterWritingOneBuffer);
            if (needToWait) {
                // go round the select again
            } else {
                return true;
            }
        }
    }
}

void VirtualSerialDevice::flush()
{
    while (waitForBytesWritten(-1)) { /* loop */ }
    tcflush(d->portHandle, TCIOFLUSH);
}

bool VirtualSerialDevice::waitForReadyRead(int msecs)
{
    return QIODevice::waitForReadyRead(msecs); //TODO
}

} // namespace SymbianUtils