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

#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <QSocketNotifier>
#include <QTimer>
#include <QThread>
#include <QWaitCondition>
#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(tr("The port %1 could not be opened: %2 (POSIX error %3)").
                       arg(portName, QString::fromLocal8Bit(strerror(errno))).arg(errno));
        return false;
        }

    struct termios termInfo;
    if (tcgetattr(d->portHandle, &termInfo) < 0) {
        setErrorString(tr("Unable to retrieve terminal settings of port %1: %2 (POSIX error %3)").
                       arg(portName, QString::fromLocal8Bit(strerror(errno))).arg(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(tr("Unable to apply terminal settings to port %1: %2 (POSIX error %3)").
                       arg(portName, QString::fromLocal8Bit(strerror(errno))).arg(errno));
        close();
        return false;
    }

    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)));

    bool ok = QIODevice::open(mode | QIODevice::Unbuffered);
    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;
    d->readNotifier->setEnabled(false);
    int res = ioctl(d->portHandle, FIONREAD, &avail);
    d->readNotifier->setEnabled(true);
    if (res == -1) {
        return 0;
    }
    return (qint64)avail + QIODevice::bytesAvailable();
}

qint64 VirtualSerialDevice::readData(char *data, qint64 maxSize)
{
    QMutexLocker locker(&lock);
    d->readNotifier->setEnabled(false);
    int result = ::read(d->portHandle, data, maxSize);
    d->readNotifier->setEnabled(true);
    if (result == -1 && errno == EAGAIN)
        result = 0; // To Qt, 0 here means nothing ready right now, and -1 is reserved for permanent errors
    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);
        if (needToWait && bytesWritten > 0) {
            // Wrote some of the buffer, adjust pointers to point to the remainder that needs queueing
            data += bytesWritten;
            maxSize -= bytesWritten;
        }
    }

    if (needToWait) {
        pendingWrites.append(QByteArray(data, maxSize));
        d->writeUnblockedNotifier->setEnabled(true);
        // Now wait for the writeUnblocked signal or for a call to waitForBytesWritten
        return bytesWritten + maxSize;
    } 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
    bytesWritten = 0;
    while (maxSize > 0) {
        int result = ::write(d->portHandle, data, maxSize);
        if (result == -1) {
            if (errno == EAGAIN)
                return true; // Need to wait
            setErrorString(tr("Cannot write to port %1: %2 (POSIX error %3)").
                           arg(portName, QString::fromLocal8Bit(strerror(errno))).arg(errno));

            bytesWritten = -1;
            return false;
        } else {
            if (result == 0)
                qWarning("%s: Zero bytes written to port %s!", Q_FUNC_INFO, qPrintable(portName));
            bytesWritten += result;
            maxSize -= result;
            data += result;
        }
    }
    return false; // If we reach here we've successfully written all the data without blocking
}

/* 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.
 */
bool VirtualSerialDevice::tryFlushPendingBuffers(QMutexLocker& locker, FlushPendingOptions flags)
{
    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) {
            if (bytesWritten > 0) {
                // We wrote some of the data, update the pending queue
                QByteArray remainder = data.mid(bytesWritten);
                pendingWrites.removeFirst();
                pendingWrites.insert(0, remainder);
            }
            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);
}

// 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;
    }
}

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

    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);
    }

    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;
        }
        int ret = safe_select(d->portHandle+1, NULL, &writeSet, NULL, msecs == -1 ? NULL : &timeout);

        if (ret == 0) {
            // Timeout
            return false;
        } else if (ret < 0) {
            setErrorString(tr("The function select() returned an error on port %1: %2 (POSIX error %3)").
                           arg(portName, QString::fromLocal8Bit(strerror(errno))).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