forked from RespeQt/RespeQt
-
Notifications
You must be signed in to change notification settings - Fork 1
/
serialport-unix.cpp
980 lines (835 loc) · 25.2 KB
/
serialport-unix.cpp
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
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
440
441
442
443
444
445
446
447
448
449
450
451
452
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
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
735
736
737
738
739
740
741
742
743
744
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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
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
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
/*
* serialport-unix.cpp
*
* Copyright 2015 DrVenkman
* Copyright 2015 Joseph Zatarski
* Copyright 2016, 2017 TheMontezuma
* Copyright 2017 josch1710
* Copyright 2017 blind
*
* This file is copyrighted by either Fatih Aygun, Ray Ataergin, or both.
* However, the years for these copyrights are unfortunately unknown. If you
* know the specific year(s) please let the current maintainer know.
*/
#include "atarisio.h"
#include "respeqtsettings.h"
#include "serialport.h"
#include "sioworker.h"
#include "siorecorder.h"
#include <QTime>
#include <QtDebug>
#include <cerrno>
#include <cstring>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#ifdef Q_OS_UNIX
#ifdef Q_OS_LINUX
//#include <stropts.h>
#include <linux/serial.h>
#include <termio.h>
#endif
#ifdef Q_OS_MAC
#include <sys/ioctl.h>
#include <termios.h>
#define IOSSIOSPEED _IOW('T', 2, speed_t)
#endif
#endif
AbstractSerialPortBackend::AbstractSerialPortBackend(QObject *parent)
: QObject(parent) {
}
AbstractSerialPortBackend::~AbstractSerialPortBackend() {
}
StandardSerialPortBackend::StandardSerialPortBackend(QObject *parent)
: AbstractSerialPortBackend(parent) {
mHandle = -1;
mForceHighSpeed = 0;
}
StandardSerialPortBackend::~StandardSerialPortBackend() {
if (isOpen()) {
close();
}
}
#ifdef Q_OS_LINUX
QString StandardSerialPortBackend::defaultPortName() {
return QString("ttyS0");
}
#endif
#ifdef Q_OS_MAC
QString StandardSerialPortBackend::defaultPortName() {
return QString("tty.usbserial");
}
#endif
bool StandardSerialPortBackend::open() {
if (isOpen()) {
close();
}
QString name(SERIAL_PORT_LOCATION);
name.append(RespeqtSettings::instance()->serialPortName());
mMethod = RespeqtSettings::instance()->serialPortHandshakingMethod();
mWriteDelay = SLEEP_FACTOR * RespeqtSettings::instance()->serialPortWriteDelay();
mCompErrDelay = RespeqtSettings::instance()->serialPortCompErrDelay();
mHandle = ::open(name.toLocal8Bit().constData(), O_RDWR | O_NOCTTY | O_NDELAY);
if (mHandle < 0) {
qCritical() << "!e" << tr("Cannot open serial port '%1': %2").arg(name, lastErrorMessage());
return false;
}
if (mMethod != HANDSHAKE_SOFTWARE) {
int status;
if (ioctl(mHandle, TIOCMGET, &status) < 0) {
qCritical() << "!e" << tr("Cannot get serial port status");
return false;
}
status &= ~(TIOCM_RI | TIOCM_RTS | TIOCM_CTS);
if (ioctl(mHandle, TIOCMSET, &status) < 0) {
qCritical() << "!e" << tr("Cannot clear RI, RTS and CTS lines in serial port '%1': %2").arg(name, lastErrorMessage());
return false;
}
}
mCanceled = false;
if (!setNormalSpeed()) {
close();
return false;
}
QString m;
switch (mMethod) {
case HANDSHAKE_RI:
m = "RI";
break;
case HANDSHAKE_DSR:
m = "DSR";
break;
case HANDSHAKE_CTS:
m = "CTS";
break;
case HANDSHAKE_NO_HANDSHAKE:
m = "NO";
break;
case HANDSHAKE_SOFTWARE:
default:
m = "SOFTWARE (SIO2BT)";
break;
}
/* Notify the user that emulation is started */
qWarning() << "!i" << tr("Emulation started through standard serial port backend on '%1' with %2 handshaking.").arg(RespeqtSettings::instance()->serialPortName()).arg(m);
return true;
}
bool StandardSerialPortBackend::isOpen() {
return mHandle >= 0;
}
void StandardSerialPortBackend::close() {
cancel();
if (::close(mHandle)) {
qCritical() << "!e" << tr("Cannot close serial port: %1").arg(lastErrorMessage());
}
mHandle = -1;
}
void StandardSerialPortBackend::cancel() {
mCanceled = true;
}
int StandardSerialPortBackend::speedByte() {
if (RespeqtSettings::instance()->serialPortHandshakingMethod() == HANDSHAKE_SOFTWARE) {
return 0x28;// standard speed (19200)
} else if (mForceHighSpeed != 0) {
return baudToDivisor(mForceHighSpeed);// speed when SuperArchiver/BitWriter is active
} else if (RespeqtSettings::instance()->serialPortUsePokeyDivisors()) {
return RespeqtSettings::instance()->serialPortPokeyDivisor();
} else {
int speed = 0x08;
switch (RespeqtSettings::instance()->serialPortMaximumSpeed()) {
case 0:
speed = 0x28;
break;
case 1:
speed = 0x10;
break;
case 2:
speed = 0x08;
break;
}
return speed;
}
}
void StandardSerialPortBackend::forceHighSpeed(int speed) {
mForceHighSpeed = speed;
}
bool StandardSerialPortBackend::setNormalSpeed() {
mHighSpeed = false;
return setSpeed(19200);
}
bool StandardSerialPortBackend::setHighSpeed() {
mHighSpeed = true;
if (mForceHighSpeed != 0) {
return setSpeed(mForceHighSpeed);// used to force 52400 when SuperArchiver/BitWriter is active
} else if (RespeqtSettings::instance()->serialPortUsePokeyDivisors()) {
return setSpeed(divisorToBaud(RespeqtSettings::instance()->serialPortPokeyDivisor()));
} else {
int speed = 57600;
switch (RespeqtSettings::instance()->serialPortMaximumSpeed()) {
case 0:
speed = 19200;
break;
case 1:
speed = 38400;
break;
case 2:
speed = 57600;
break;
}
return setSpeed(speed);
}
}
#ifdef Q_OS_LINUX
bool StandardSerialPortBackend::setSpeed(int speed) {
termios tios;
struct serial_struct ss;
tcgetattr(mHandle, &tios);
tios.c_cflag &= ~CSTOPB;
cfmakeraw(&tios);
switch (speed) {
case 600:
cfsetispeed(&tios, B600);
cfsetospeed(&tios, B600);
break;
case 19200:
cfsetispeed(&tios, B19200);
cfsetospeed(&tios, B19200);
break;
case 38400:
// reset special handling of 38400bps back to 38400
ioctl(mHandle, TIOCGSERIAL, &ss);
ss.flags &= ~ASYNC_SPD_MASK;
ioctl(mHandle, TIOCSSERIAL, &ss);
cfsetispeed(&tios, B38400);
cfsetospeed(&tios, B38400);
break;
case 57600:
cfsetispeed(&tios, B57600);
cfsetospeed(&tios, B57600);
break;
default:
// configure port to use custom speed instead of 38400
ioctl(mHandle, TIOCGSERIAL, &ss);
ss.flags = (ss.flags & ~ASYNC_SPD_MASK) | ASYNC_SPD_CUST;
ss.custom_divisor = (ss.baud_base + (speed / 2)) / speed;
int customSpeed = ss.baud_base / ss.custom_divisor;
if (customSpeed < speed * 98 / 100 || customSpeed > speed * 102 / 100) {
qCritical() << "!e" << tr("Cannot set serial port speed to %1: %2").arg(speed).arg(tr("Closest possible speed is %2.").arg(customSpeed));
return false;
}
ioctl(mHandle, TIOCSSERIAL, &ss);
cfsetispeed(&tios, B38400);
cfsetospeed(&tios, B38400);
break;
}
/* Set serial port state */
if (tcsetattr(mHandle, TCSANOW, &tios) != 0) {
qCritical() << "!e" << tr("Cannot set serial port speed to %1: %2").arg(speed).arg(lastErrorMessage());
return false;
}
emit statusChanged(tr("%1 bits/sec").arg(speed));
qWarning() << "!i" << tr("Serial port speed set to %1.").arg(speed);
mSpeed = speed;
return true;
}
#endif
#ifdef Q_OS_MAC
bool StandardSerialPortBackend::setSpeed(int speed) {
termios tios;
tcgetattr(mHandle, &tios);
tios.c_cflag &= ~CSTOPB;
cfmakeraw(&tios);
tios.c_cflag |= CREAD | CLOCAL;// turn on READ
tios.c_cflag |= CS8;
tios.c_cc[VMIN] = 0;
tios.c_cc[VTIME] = 10;// 1 sec timeout
/* Default speed */
cfsetispeed(&tios, B19200);
cfsetospeed(&tios, B19200);
/* Set serial port state */
if (tcsetattr(mHandle, TCSANOW, &tios) != 0) {
qCritical() << "!e" << tr("Cannot set serial port speed to %1: %2").arg(19200).arg(lastErrorMessage());
return false;
}
/* Set requested speed */
speed_t spd = speed;
if (ioctl(mHandle, IOSSIOSPEED, &spd) < 0) {
qCritical() << "!e" << tr("Failed to set serial port speed to %1").arg(speed);
return false;
}
emit statusChanged(tr("%1 bits/sec").arg(speed));
qWarning() << "!i" << tr("Serial port speed set to %1.").arg(speed);
mSpeed = speed;
return true;
}
#endif
int StandardSerialPortBackend::speed() {
return mSpeed;
}
QByteArray StandardSerialPortBackend::readCommandFrame() {
QByteArray data;
if (mMethod == HANDSHAKE_SOFTWARE) {
if (tcflush(mHandle, TCIFLUSH) != 0) {
qCritical() << "!e" << tr("Cannot clear serial port read buffer: %1").arg(lastErrorMessage());
return data;
}
const int size = 4;
quint8 expected = 0;
quint8 got = 1;
do {
char c;
if (1 == ::read(mHandle, &c, 1)) {
data.append(c);
if (data.size() == size + 2) {
data.remove(0, 1);
}
if (data.size() == size + 1) {
for (int i = 0; i < mSioDevices.size(); i++) {
if (data.at(0) == mSioDevices[i]) {
expected = (quint8) data.at(size);
got = sioChecksum(data, size);
break;
}
}
}
} else {
// avoid high CPU load in idle state
#if defined Q_OS_UNIX || defined Q_OS_MAC
QThread::usleep(300);
#endif
}
} while (got != expected && !mCanceled);
if (got == expected) {
data.resize(size);
auto recorder = SioRecorder::instance();
if (recorder->isSnapshotRunning())
recorder->writeSnapshotCommandFrame(data[0], data[1], data[2], data[3]);
// After sending the last byte of the command frame
// ATARI does not drop the command line immediately.
// Within this small time window ATARI is not able to process the ACK byte.
// For the "software handshake" approach, we need to wait here a little bit.
QThread::usleep(500);
} else {
data.clear();
}
} else {
// RI/DSR/CTS/- handshake
int mask;
switch (mMethod) {
case HANDSHAKE_RI:
mask = TIOCM_RI;
break;
case HANDSHAKE_DSR:
mask = TIOCM_DSR;
break;
case HANDSHAKE_CTS:
default:
mask = TIOCM_CTS;
break;
}
int status;
int retries = 0, totalRetries = 0;
do {
data.clear();
if (mMethod == HANDSHAKE_NO_HANDSHAKE) {
int bytes;
do {
ioctl(mHandle, FIONREAD, &bytes);
#ifdef Q_OS_UNIX
QThread::yieldCurrentThread();
#endif
#ifdef Q_OS_MAC
QThread::usleep(300);
#endif
} while ((bytes == 0) && !mCanceled);
} else {
// RI/DSR/CTS handshake
/* First, wait until command line goes off */
do {
if (ioctl(mHandle, TIOCMGET, &status) < 0) {
qCritical() << "!e" << tr("Cannot retrieve serial port status: %1").arg(lastErrorMessage());
return data;
}
if (status & mask) {
#ifdef Q_OS_UNIX
QThread::yieldCurrentThread();// Venkman 07132015 OS definition blocks added
#endif
#ifdef Q_OS_MAC
QThread::usleep(500);
#endif
}
} while ((status & mask) && !mCanceled);
/* Now wait for it to go on again */
do {
if (ioctl(mHandle, TIOCMGET, &status) < 0) {
qCritical() << "!e" << tr("Cannot retrieve serial port status: %1").arg(lastErrorMessage());
return data;
}
if (!(status & mask)) {
#ifdef Q_OS_UNIX
QThread::yieldCurrentThread();// Venkman 07132015 OS definition blocks added
#endif
#ifdef Q_OS_MAC
QThread::usleep(500);
#endif
}
} while (!(status & mask) && !mCanceled);
if (tcflush(mHandle, TCIFLUSH) != 0) {
qCritical() << "!e" << tr("Cannot clear serial port read buffer: %1").arg(lastErrorMessage());
return data;
}
}
if (mCanceled) {
return data;
}
data = readDataFrame(4, true);
if (!data.isEmpty()) {
if (mMethod != HANDSHAKE_NO_HANDSHAKE) {
// wait for command line to go off
do {
if (ioctl(mHandle, TIOCMGET, &status) < 0) {
qCritical() << "!e" << tr("Cannot retrieve serial port status: %1").arg(lastErrorMessage());
return data;
}
} while ((status & mask) && !mCanceled);
} else {
// After sending the last byte of the command frame
// ATARI does not drop the command line immediately.
// Within this small time window ATARI is not able to process the ACK byte.
// For the "no handshake" approach, we need to wait here a little bit.
QThread::usleep(500);
}
break;
} else {
retries++;
totalRetries++;
if (retries == 2) {
retries = 0;
if (mHighSpeed) {
setNormalSpeed();
} else {
setHighSpeed();
}
}
}
// } while (totalRetries < 100);
} while (1);
}
return data;
}
QByteArray StandardSerialPortBackend::readDataFrame(uint size, bool isCommandFrame, bool verbose) {
QByteArray data = readRawFrame(size + 1, verbose);
if (data.isEmpty()) {
return data;
}
auto expected = (quint8) data.at(size);
auto got = sioChecksum(data, size);
if (expected == got) {
data.resize(size);
auto recorder = SioRecorder::instance();
if (recorder->isSnapshotRunning()) {
if (isCommandFrame) {
recorder->writeSnapshotCommandFrame(data[0], data[1], data[2], data[3]);
} else {
recorder->writeSnapshotDataFrame(data);
}
}
return data;
} else {
if (verbose) {
qWarning() << "!w" << tr("Data frame checksum error, expected: %1, got: %2. (%3)").arg(expected).arg(got).arg(QString(data.toHex()));
}
data.clear();
return data;
}
}
bool StandardSerialPortBackend::writeDataFrame(const QByteArray &data) {
QByteArray copy(data);
copy.resize(copy.size() + 1);
copy[copy.size() - 1] = sioChecksum(copy, copy.size() - 1);
if (mMethod == HANDSHAKE_SOFTWARE) SioWorker::usleep(mWriteDelay);
SioWorker::usleep(50);
return writeRawFrame(copy);
}
bool StandardSerialPortBackend::writeCommandAck() {
return writeRawFrame(QByteArray(1, SIO_ACK));
}
bool StandardSerialPortBackend::writeCommandNak() {
return writeRawFrame(QByteArray(1, SIO_NACK));
}
bool StandardSerialPortBackend::writeDataAck() {
return writeRawFrame(QByteArray(1, SIO_ACK));
}
bool StandardSerialPortBackend::writeDataNak() {
return writeRawFrame(QByteArray(1, SIO_NACK));
}
bool StandardSerialPortBackend::writeComplete() {
if (mMethod == HANDSHAKE_SOFTWARE) SioWorker::usleep(mWriteDelay);
else
SioWorker::usleep(mCompErrDelay);
return writeRawFrame(QByteArray(1, SIO_COMPLETE));
}
bool StandardSerialPortBackend::writeError() {
if (mMethod == HANDSHAKE_SOFTWARE) SioWorker::usleep(mWriteDelay);
else
SioWorker::usleep(mCompErrDelay);
return writeRawFrame(QByteArray(1, SIO_ERROR));
}
quint8 StandardSerialPortBackend::sioChecksum(const QByteArray &data, uint size) {
uint i;
uint sum = 0;
for (i = 0; i < size; i++) {
sum += (quint8) data.at(i);
if (sum > 255) {
sum -= 255;
}
}
return sum;
}
QByteArray StandardSerialPortBackend::readRawFrame(uint size, bool /*verbose*/) {
QByteArray data;
int result;
uint total, rest;
data.resize(size);
total = 0;
rest = size;
QTime startTime = QTime::currentTime();
int timeOut = data.count() * 12000 / mSpeed + 100;
if (mMethod == HANDSHAKE_SOFTWARE) {
timeOut += 100;
}
int elapsed;
do {
result = ::read(mHandle, data.data() + total, rest);
if (result < 0 && errno != EAGAIN) {
qCritical() << "!e" << tr("Cannot read from serial port: %1").arg(lastErrorMessage());
data.clear();
return data;
}
if (result < 0) {
result = 0;
}
total += result;
rest -= result;
elapsed = startTime.msecsTo(QTime::currentTime());
} while (total < size && elapsed < timeOut);
if ((uint) total != size) {
qCritical() << "!e" << tr("Serial port read timeout. %1 of %2 read in %3 ms").arg(total).arg(data.count()).arg(elapsed);
data.clear();
return data;
}
return data;
}
bool StandardSerialPortBackend::writeRawFrame(const QByteArray &data) {
int result;
uint total, rest;
total = 0;
rest = data.count();
QTime startTime = QTime::currentTime();
int timeOut = data.count() * 12000 / mSpeed + 100;
if (mMethod == HANDSHAKE_SOFTWARE) {
timeOut += 100;
}
int elapsed;
do {
result = ::write(mHandle, data.constData() + total, rest);
if (result < 0 && errno != EAGAIN) {
qCritical() << "!e" << tr("Cannot read from serial port: %1").arg(lastErrorMessage());
return false;
}
if (result < 0) {
result = 0;
}
total += result;
rest -= result;
elapsed = startTime.msecsTo(QTime::currentTime());
} while (total < (uint) data.count() && elapsed < timeOut);
if (total != (uint) data.count()) {
qCritical() << "!e" << tr("Serial port write timeout. %1 of %2 written in %3 ms").arg(total).arg(data.count()).arg(elapsed);
return false;
}
if (tcdrain(mHandle) != 0) {
qCritical() << "!e" << tr("Cannot flush serial port write buffer: %1").arg(lastErrorMessage());
return false;
}
return true;
}
QString StandardSerialPortBackend::lastErrorMessage() {
return QString::fromUtf8(strerror(errno)) + ".";
}
void StandardSerialPortBackend::setActiveSioDevices(const QByteArray &data) {
mSioDevices = data;
}
AtariSioBackend::AtariSioBackend(QObject *parent)
: AbstractSerialPortBackend(parent) {
mHandle = -1;
}
AtariSioBackend::~AtariSioBackend() {
if (isOpen()) {
close();
}
}
QString AtariSioBackend::defaultPortName() {
return QString("atarisio0");
}
bool AtariSioBackend::open() {
if (isOpen()) {
close();
}
QString name(SERIAL_PORT_LOCATION);
name.append(RespeqtSettings::instance()->atariSioDriverName());
mHandle = ::open(name.toLocal8Bit().constData(), O_RDWR);
if (mHandle < 0) {
qCritical() << "!e" << tr("Cannot open serial port '%1': %2").arg(name, lastErrorMessage());
return false;
}
int version;
version = ioctl(mHandle, ATARISIO_IOC_GET_VERSION);
if (version < 0) {
qCritical() << "!e" << tr("Cannot open AtariSio driver '%1': %2").arg(name).arg("Cannot determine AtariSio version.");
close();
return false;
}
if ((version >> 8) != (ATARISIO_VERSION >> 8) ||
(version & 0xff) < (ATARISIO_VERSION & 0xff)) {
qCritical() << "!e" << tr("Cannot open AtariSio driver '%1': %2").arg(name).arg("Incompatible AtariSio version.");
close();
return false;
}
int mode;
mMethod = RespeqtSettings::instance()->atariSioHandshakingMethod();
switch (mMethod) {
case HANDSHAKE_RI:
mode = ATARISIO_MODE_SIOSERVER;
break;
case HANDSHAKE_DSR:
mode = ATARISIO_MODE_SIOSERVER_DSR;
break;
default:
case HANDSHAKE_CTS:
mode = ATARISIO_MODE_SIOSERVER_CTS;
break;
}
if (ioctl(mHandle, ATARISIO_IOC_SET_MODE, mode) < 0) {
qCritical() << "!e" << tr("Cannot set AtariSio driver mode: %1").arg(lastErrorMessage());
close();
return false;
}
if (ioctl(mHandle, ATARISIO_IOC_SET_AUTOBAUD, true) < 0) {
qCritical() << "!e" << tr("Cannot set AtariSio to autobaud mode: %1").arg(lastErrorMessage());
close();
return false;
}
if (pipe(mCancelHandles) != 0) {
qCritical() << "!e" << tr("Cannot create the cancel pipe");
}
QString m;
switch (mMethod) {
case HANDSHAKE_RI:
m = "RI";
break;
case HANDSHAKE_DSR:
m = "DSR";
break;
default:
case HANDSHAKE_CTS:
m = "CTS";
break;
}
/* Notify the user that emulation is started */
qWarning() << "!i" << tr("Emulation started through AtariSIO backend on '%1' with %2 handshaking.").arg(RespeqtSettings::instance()->atariSioDriverName()).arg(m);
return true;
}
bool AtariSioBackend::isOpen() {
return mHandle >= 0;
}
void AtariSioBackend::close() {
cancel();
if (::close(mHandle)) {
qCritical() << "!e" << tr("Cannot close serial port: %1").arg(lastErrorMessage());
}
::close(mCancelHandles[0]);
::close(mCancelHandles[1]);
mHandle = -1;
}
void AtariSioBackend::cancel() {
if (::write(mCancelHandles[1], "C", 1) < 1) {
qCritical() << "!e" << tr("Cannot stop AtariSio backend.");
}
}
void AtariSioBackend::forceHighSpeed(int) {
}
bool AtariSioBackend::setSpeed(int speed) {
if (ioctl(mHandle, ATARISIO_IOC_SET_BAUDRATE, speed) < 0) {
qCritical() << "!e" << tr("Cannot set AtariSio speed to %1: %2").arg(speed).arg(lastErrorMessage());
return false;
} else {
emit statusChanged(tr("%1 bits/sec").arg(speed));
qWarning() << "!i" << tr("Serial port speed set to %1.").arg(speed);
return true;
}
}
QByteArray AtariSioBackend::readCommandFrame() {
QByteArray data;
fd_set read_set;
fd_set except_set;
int ret;
int maxfd = mHandle;
FD_ZERO(&except_set);
FD_SET(mHandle, &except_set);
if (mCancelHandles[0] > maxfd) {
maxfd = mCancelHandles[0];
}
FD_ZERO(&read_set);
FD_SET(mCancelHandles[0], &read_set);
ret = select(maxfd + 1, &read_set, nullptr, &except_set, 0);
if (ret == -1 || ret == 0) {
return data;
}
if (FD_ISSET(mCancelHandles[0], &read_set)) {
return data;
}
if (FD_ISSET(mHandle, &except_set)) {
SIO_command_frame frame;
if (ioctl(mHandle, ATARISIO_IOC_GET_COMMAND_FRAME, &frame) < 0) {
return data;
}
data.resize(4);
data[0] = frame.device_id;
data[1] = frame.command;
data[2] = frame.aux1;
data[3] = frame.aux2;
auto recorder = SioRecorder::instance();
if (recorder->isSnapshotRunning())
recorder->writeSnapshotCommandFrame(data[0], data[1], data[2], data[3]);
int sp = ioctl(mHandle, ATARISIO_IOC_GET_BAUDRATE);
if (sp >= 0 && mSpeed != sp) {
emit statusChanged(tr("%1 bits/sec").arg(sp));
qWarning() << "!i" << tr("Serial port speed set to %1.").arg(sp);
mSpeed = sp;
}
return data;
}
qCritical() << "!e" << tr("Illegal condition using select!");
return data;
}
int AtariSioBackend::speedByte() {
return 0x08;
}
int AtariSioBackend::speed() {
return mSpeed;
}
QByteArray AtariSioBackend::readDataFrame(uint size, bool isCommandFrame, bool verbose) {
QByteArray data;
SIO_data_frame frame;
data.resize(size);
auto recorder = SioRecorder::instance();
if (recorder->isSnapshotRunning()) {
if (isCommandFrame) {
recorder->writeSnapshotCommandFrame(data[0], data[1], data[2], data[3]);
} else {
recorder->writeSnapshotDataFrame(data);
}
}
frame.data_buffer = (unsigned char *) data.data();
frame.data_length = size;
if (ioctl(mHandle, ATARISIO_IOC_RECEIVE_DATA_FRAME, &frame) < 0) {
if (verbose) {
qCritical() << "!e" << tr("Cannot read data frame: %1").arg(lastErrorMessage());
}
data.clear();
}
return data;
}
bool AtariSioBackend::writeDataFrame(const QByteArray &data) {
SIO_data_frame frame;
frame.data_buffer = (unsigned char *) data.constData();
frame.data_length = data.size();
if (ioctl(mHandle, ATARISIO_IOC_SEND_DATA_FRAME, &frame) < 0) {
qCritical() << "!e" << tr("Cannot write data frame: %1").arg(lastErrorMessage());
return false;
}
return true;
}
bool AtariSioBackend::writeCommandAck() {
if (ioctl(mHandle, ATARISIO_IOC_SEND_COMMAND_ACK) < 0) {
if (errno != EATARISIO_COMMAND_TIMEOUT) {
qCritical() << "!e" << tr("Cannot write command ACK: %1").arg(lastErrorMessage());
}
return false;
}
return true;
}
bool AtariSioBackend::writeCommandNak() {
if (ioctl(mHandle, ATARISIO_IOC_SEND_COMMAND_NAK) < 0) {
qCritical() << "!e" << tr("Cannot write command NAK: %1").arg(lastErrorMessage());
return false;
}
return true;
}
bool AtariSioBackend::writeDataAck() {
if (ioctl(mHandle, ATARISIO_IOC_SEND_DATA_ACK) < 0) {
qCritical() << "!e" << tr("Cannot write data ACK: %1").arg(lastErrorMessage());
return false;
}
return true;
}
bool AtariSioBackend::writeDataNak() {
if (ioctl(mHandle, ATARISIO_IOC_SEND_DATA_NAK) < 0) {
qCritical() << "!e" << tr("Cannot write data NAK: %1").arg(lastErrorMessage());
return false;
}
return true;
}
bool AtariSioBackend::writeComplete() {
if (ioctl(mHandle, ATARISIO_IOC_SEND_COMPLETE) < 0) {
qCritical() << "!e" << tr("Cannot write COMPLETE byte: %1").arg(lastErrorMessage());
return false;
}
return true;
}
bool AtariSioBackend::writeError() {
if (ioctl(mHandle, ATARISIO_IOC_SEND_ERROR) < 0) {
qCritical() << "!e" << tr("Cannot write ERROR byte: %1").arg(lastErrorMessage());
return false;
}
return true;
}
bool AtariSioBackend::writeRawFrame(const QByteArray &data) {
SIO_data_frame frame;
frame.data_buffer = (unsigned char *) data.constData();
frame.data_length = data.size();
if (ioctl(mHandle, ATARISIO_IOC_SEND_RAW_FRAME, &frame) < 0) {
qCritical() << "!e" << tr("Cannot write raw frame: %1").arg(lastErrorMessage());
return false;
}
return true;
}
QString AtariSioBackend::lastErrorMessage() {
switch (errno) {
case EATARISIO_ERROR_BLOCK_TOO_LONG:
return tr("Block too long.");
break;
case EATARISIO_COMMAND_NAK:
return tr("Command not acknowledged.");
break;
case EATARISIO_COMMAND_TIMEOUT:
return tr("Command timeout.");
break;
case EATARISIO_CHECKSUM_ERROR:
return tr("Checksum error.");
break;
case EATARISIO_COMMAND_COMPLETE_ERROR:
return tr("Device error.");
break;
case EATARISIO_DATA_NAK:
return tr("Data frame not acknowledged.");
break;
case EATARISIO_UNKNOWN_ERROR:
return tr("Unknown AtariSio driver error.");
break;
default:
return QString::fromUtf8(strerror(errno)) + ".";
}
}
void AtariSioBackend::setActiveSioDevices(const QByteArray &) {}