-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
serialcomm.cpp
699 lines (632 loc) · 22.6 KB
/
serialcomm.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
// SPDX-License-Identifier: GPL-3.0-or-later
//
// Copyright (c) 2013-2024 plan44.ch / Lukas Zeller, Zurich, Switzerland
//
// Author: Lukas Zeller <luz@plan44.ch>
//
// This file is part of p44utils.
//
// p44utils is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// p44utils is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with p44utils. If not, see <http://www.gnu.org/licenses/>.
//
// File scope debugging options
// - Set ALWAYS_DEBUG to 1 to enable DBGLOG output even in non-DEBUG builds of this file
#define ALWAYS_DEBUG 0
// - set FOCUSLOGLEVEL to non-zero log level (usually, 5,6, or 7==LOG_DEBUG) to get focus (extensive logging) for this file
// Note: must be before including "logger.hpp" (or anything that includes "logger.hpp")
#define FOCUSLOGLEVEL 7
#include "serialcomm.hpp"
using namespace p44;
#if ENABLE_SERIAL_SCRIPT_FUNCS
#include "application.hpp" // for userlevel check
using namespace P44Script;
#endif
#if defined(__linux__)
#include <linux/serial.h>
#endif
#define DEFAULT_OPEN_FLAGS (O_RDWR)
SerialComm::SerialComm(MainLoop &aMainLoop) :
inherited(aMainLoop),
mConnectionPort(0),
mBaudRate(9600),
mCharSize(8),
mParityEnable(false),
mEvenParity(false),
mTwoStopBits(false),
mHardwareHandshake(false),
mConnectionOpen(false),
mReconnecting(false),
mUnknownReadyBytes(false),
mDeviceOpenFlags(DEFAULT_OPEN_FLAGS)
{
}
SerialComm::~SerialComm()
{
closeConnection();
}
bool SerialComm::parseConnectionSpecification(
const char* aConnectionSpec, uint16_t aDefaultPort, const char *aDefaultCommParams,
string &aConnectionPath,
int &aBaudRate,
int &aCharSize,
bool &aParityEnable,
bool &aEvenParity,
bool &aTwoStopBits,
bool &aHardwareHandshake,
uint16_t &aConnectionPort
)
{
// device or IP host?
aConnectionPort = 0; // means: serial
aConnectionPath.clear();
aBaudRate = 9600;
aCharSize = 8;
aParityEnable = false;
aEvenParity = false;
aTwoStopBits = false;
aHardwareHandshake = false;
if (aConnectionSpec && *aConnectionSpec) {
aConnectionPath = aConnectionSpec;
if (aConnectionSpec[0]=='/') {
// serial device
string opt = nonNullCStr(aDefaultCommParams);
size_t n = aConnectionPath.find(":");
if (n!=string::npos) {
// explicit specification of communication params: baudrate, bits, parity
opt = aConnectionPath.substr(n+1,string::npos);
aConnectionPath.erase(n,string::npos);
}
if (opt.size()>0) {
// get communication options : [baud rate][,[bits][,[parity][,[stopbits][,[H]]]]]
// or for not doing any termio setting : none
string part;
const char *p = opt.c_str();
if (nextPart(p, part, ',')) {
// baud rate
if (uequals("none", part)) {
// just char device, do not do any termios
aBaudRate = -1; // signal "no termios" via negative baud rate
}
else {
sscanf(part.c_str(), "%d", &aBaudRate);
if (nextPart(p, part, ',')) {
// bits
sscanf(part.c_str(), "%d", &aCharSize);
if (nextPart(p, part, ',')) {
// parity: O,E,N
if (part.size()>0) {
aParityEnable = false;
if (part[0]=='E') {
aParityEnable = true;
aEvenParity = true;
}
else if (part[0]=='O') {
aParityEnable = false;
aEvenParity = false;
}
}
if (nextPart(p, part, ',')) {
// stopbits: 1 or 2
if (part.size()>0) {
aTwoStopBits = part[0]=='2';
}
if (nextPart(p, part, ',')) {
// hardware handshake?
if (part.size()>0) {
aHardwareHandshake = part[0]=='H';
}
}
}
}
}
}
}
}
return true; // real serial
}
else {
// IP host
aConnectionPort = aDefaultPort; // set default in case aConnectionSpec does not have a path number
splitHost(aConnectionSpec, &aConnectionPath, &aConnectionPort);
return false; // no real serial
}
}
return false; // no real serial either
}
void SerialComm::setConnectionSpecification(const char* aConnectionSpec, uint16_t aDefaultPort, const char *aDefaultCommParams)
{
parseConnectionSpecification(
aConnectionSpec, aDefaultPort, aDefaultCommParams,
mConnectionPath,
mBaudRate,
mCharSize,
mParityEnable,
mEvenParity,
mTwoStopBits,
mHardwareHandshake,
mConnectionPort
);
closeConnection();
}
void SerialComm::setDeviceOpParams(int aDeviceOpenFlags, bool aUnknownReadyBytes)
{
mDeviceOpenFlags = aDeviceOpenFlags!=0 ? aDeviceOpenFlags : DEFAULT_OPEN_FLAGS;
mUnknownReadyBytes = aUnknownReadyBytes;
}
// Setting baud rate on Linux, see sample code at the bottom of the tty_ioctl man page:
// https://www.man7.org/linux/man-pages/man4/tty_ioctl.4.html
#if defined(BOTHER)
#define OTHERBAUDRATE (BOTHER)
#elif P44_BUILD_OW
#define OTHERBAUDRATE (CBAUDEX)
#endif
ErrorPtr SerialComm::establishConnection()
{
if (!mConnectionOpen) {
// Open connection to bridge
mConnectionFd = 0;
int res;
#if USE_TERMIOS2
struct termios2 newTermIO;
#else
struct termios newTermIO;
#endif
// check type of connection
mDeviceConnection = mConnectionPath[0]=='/';
if (mDeviceConnection) {
// char device code
int baudRateCode = -1; // invalid
if (nativeSerialPort()) {
// actual serial port we want to set termios params
// - convert the baudrate
switch (mBaudRate) {
case 50 : baudRateCode = B50; break;
case 75 : baudRateCode = B75; break;
case 110 : baudRateCode = B110; break;
case 134 : baudRateCode = B134; break;
case 150 : baudRateCode = B150; break;
case 200 : baudRateCode = B200; break;
case 300 : baudRateCode = B300; break;
case 600 : baudRateCode = B600; break;
case 1200 : baudRateCode = B1200; break;
case 1800 : baudRateCode = B1800; break;
case 2400 : baudRateCode = B2400; break;
case 4800 : baudRateCode = B4800; break;
case 9600 : baudRateCode = B9600; break;
case 19200 : baudRateCode = B19200; break;
case 38400 : baudRateCode = B38400; break;
case 57600 : baudRateCode = B57600; break;
case 115200 : baudRateCode = B115200; break;
case 230400 : baudRateCode = B230400; break;
#if defined(__linux__)
case 460800 : baudRateCode = B460800; break;
case 500000 : baudRateCode = B500000; break;
case 576000 : baudRateCode = B576000; break;
case 921600 : baudRateCode = B921600; break;
case 1000000 : baudRateCode = B1000000; break;
case 1152000 : baudRateCode = B1152000; break;
case 1500000 : baudRateCode = B1500000; break;
case 2000000 : baudRateCode = B2000000; break;
case 2500000 : baudRateCode = B2500000; break;
case 3000000 : baudRateCode = B3000000; break;
case 3500000 : baudRateCode = B3500000; break;
case 4000000 : baudRateCode = B4000000; break;
#endif
#ifdef OTHERBAUDRATE
default : baudRateCode = OTHERBAUDRATE; break;
#endif
}
if (baudRateCode<=0) {
return ErrorPtr(new SerialCommError(SerialCommError::UnknownBaudrate));
}
}
// assume it's a serial port
mConnectionFd = open(mConnectionPath.c_str(), mDeviceOpenFlags|O_NOCTTY);
if (mConnectionFd<0) {
return SysError::errNo("Cannot open serial port: ");
}
if (nativeSerialPort()) {
// actual serial port we want to set termios params
// - save current port settings
#if USE_TERMIOS2
ioctl(mConnectionFd, TCGETS2, &mOldTermIO);
#elif defined(TCGETS)
ioctl(mConnectionFd, TCGETS, &mOldTermIO);
#else
tcgetattr(mConnectionFd, &mOldTermIO); // save current port settings
#endif
// see "man termios" for details
memset(&newTermIO, 0, sizeof(newTermIO));
// - 8-N-1,
newTermIO.c_cflag =
CLOCAL | CREAD | // no modem control lines (local), reading enabled
(mCharSize==5 ? CS5 : (mCharSize==6 ? CS6 : (mCharSize==7 ? CS7 : CS8))) | // char size
(mTwoStopBits ? CSTOPB : 0) | // stop bits
(mParityEnable ? PARENB | (mEvenParity ? 0 : PARODD) : 0) | // parity
(mHardwareHandshake ? CRTSCTS : 0); // hardware handshake
// - ignore parity errors
newTermIO.c_iflag =
mParityEnable ? INPCK : IGNPAR; // check or ignore parity
// - no output control
newTermIO.c_oflag = 0;
// - no input control (non-canonical)
newTermIO.c_lflag = 0;
// - no inter-char time
newTermIO.c_cc[VTIME] = 0; /* inter-character timer unused */
// - receive every single char seperately
newTermIO.c_cc[VMIN] = 1; /* blocking read until 1 chars received */
// - baud rate
#ifdef OTHERBAUDRATE
if (baudRateCode==OTHERBAUDRATE) {
// we have a non-standard baudrate
#if defined(BOTHER)
FOCUSLOG("SerialComm: requested custom baud rate = %d -> setting with BOTHER to c_ispeed/c_ospeed", mBaudRate);
// Linux: set the baudrate directly via BOTHER
// - output
newTermIO.c_cflag &= ~CBAUD; // not necessary because we cleared all flags
newTermIO.c_cflag |= BOTHER;
newTermIO.c_ospeed = mBaudRate;
// - input
#ifdef IBSHIFT
newTermIO.c_cflag &= ~(CBAUD << IBSHIFT); // not necessary because we cleared all flags
newTermIO.c_cflag |= BOTHER << IBSHIFT;
#endif
newTermIO.c_ispeed = mBaudRate;
#elif P44_BUILD_OW
// try the alias trick
newTermIO.c_cflag &= ~(CBAUD | CBAUDEX);
newTermIO.c_cflag |= B38400;
// - actual baud rate magic happens after tcsetattr(), see below
#endif // P44_BUILD_OW
}
else
#endif // OTHERBAUDRATE
{
// Most compatible way to set standard baudrates
// Note: as this ors into c_cflag, this must be after setting c_cflag initial value
cfsetspeed(&newTermIO, baudRateCode);
}
// - set new params
tcflush(mConnectionFd, TCIFLUSH);
#if USE_TERMIOS2
res = ioctl(mConnectionFd, TCSETS2, &newTermIO);
#elif defined(TCGETS)
res = ioctl(mConnectionFd, TCSETS, &newTermIO);
#else
res = tcsetattr(mConnectionFd, TCSANOW, &newTermIO);
#endif
if (res<0) {
return SysError::errNo("Error setting serial port parameters: ");
}
// - baud rate settings needed after tcsetattr()
#ifdef OTHERBAUDRATE
if (baudRateCode==OTHERBAUDRATE && mBaudRate>0) {
#if P44_BUILD_OW
struct serial_struct serial;
if (ioctl(mConnectionFd, TIOCGSERIAL, &serial)) return SysError::errNo("Error getting with TIOCGSERIAL: ");
serial.flags &= ~ASYNC_SPD_MASK;
serial.flags |= ASYNC_SPD_CUST;
serial.custom_divisor = serial.baud_base / mBaudRate;
FOCUSLOG("SerialComm: requested custom baud rate = %d, serial.baud_base = %d -> serial.custom_divisor = %d, ACTUAL baud = %d",
mBaudRate, serial.baud_base, serial.custom_divisor, serial.baud_base/serial.custom_divisor
);
if (ioctl(mConnectionFd, TIOCSSERIAL, &serial)) return SysError::errNo("Error setting with TIOCSSERIAL: ");
#endif // P44_BUILD_OW
}
#endif
}
}
else {
// assume it's an IP address or hostname
struct sockaddr_in conn_addr;
if ((mConnectionFd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
return SysError::errNo("Cannot create socket: ");
}
// prepare IP address
memset(&conn_addr, '0', sizeof(conn_addr));
conn_addr.sin_family = AF_INET;
conn_addr.sin_port = htons(mConnectionPort);
struct hostent *server;
server = gethostbyname(mConnectionPath.c_str());
if (server == NULL) {
close(mConnectionFd);
return ErrorPtr(new SerialCommError(SerialCommError::InvalidHost));
}
memcpy((void *)&conn_addr.sin_addr.s_addr, (void *)(server->h_addr), sizeof(in_addr_t));
if ((res = connect(mConnectionFd, (struct sockaddr *)&conn_addr, sizeof(conn_addr))) < 0) {
close(mConnectionFd);
return SysError::errNo("Cannot open socket: ");
}
}
// successfully opened
mConnectionOpen = true;
// now set FD for FdComm to monitor
setFd(mConnectionFd, mUnknownReadyBytes);
}
mReconnecting = false; // successfully opened, don't try to reconnect any more
return ErrorPtr(); // ok
}
bool SerialComm::requestConnection()
{
ErrorPtr err = establishConnection();
if (Error::notOK(err)) {
if (!mReconnecting) {
LOG(LOG_ERR, "SerialComm: requestConnection() could not open connection now: %s -> entering background retry mode", err->text());
mReconnecting = true;
mReconnectTicket.executeOnce(boost::bind(&SerialComm::reconnectHandler, this), 5*Second);
}
return false;
}
return true;
}
void SerialComm::closeConnection()
{
mReconnecting = false; // explicit close, don't try to reconnect any more
if (mConnectionOpen) {
// stop monitoring
setFd(-1);
// restore IO settings
if (nativeSerialPort()) {
#if USE_TERMIOS2
ioctl(mConnectionFd, TCSETS2, &mOldTermIO);
#elif defined(TCGETS)
ioctl(mConnectionFd, TCSETS, &mOldTermIO);
#else
tcsetattr(mConnectionFd, TCSANOW, &mOldTermIO);
#endif
}
// close
close(mConnectionFd);
// closed
mConnectionOpen = false;
}
}
bool SerialComm::connectionIsOpen()
{
return mConnectionOpen;
}
// MARK: - break
#define SENDBREAK_WORKS_WITH_SHORT_BREAK (!P44_BUILD_OW) // assume it does, normally - but does not on OpenWrt Linux for MT7688 SoC
void SerialComm::sendBreak(MLMicroSeconds aDuration)
{
if (!connectionIsOpen() || !nativeSerialPort()) return; // ignore
#if SENDBREAK_WORKS_WITH_SHORT_BREAK || !defined(TIOCGSERIAL)
// tcsendbreak accepts duration (or we don't have means to mess with baud rate)
int breaklen = 0; // standard break, which should be >=0.25sec and <=0.5sec
if (aDuration>0) breaklen = static_cast<int>((aDuration+MilliSecond-1)/MilliSecond);
FOCUSLOG("- tcsendbreak with duration=%d", breaklen);
tcsendbreak(mConnectionFd, breaklen);
#else
if (aDuration==0) {
// standard break, which should be >=0.25sec and <=0.5sec
FOCUSLOG("- tcsendbreak with standard duration");
tcsendbreak(mConnectionFd, 0);
}
else {
// non-standard duration, need to fake it
// - drain
FOCUSLOG("- will drain before break");
tcdrain(mConnectionFd);
FOCUSLOG("- did drain before break");
// - manipulate baud rate
struct serial_struct oldserial;
struct serial_struct serial;
if (ioctl(mConnectionFd, TIOCGSERIAL, &serial)) return;
memcpy(&oldserial, &serial, sizeof(struct serial_struct));
serial.flags &= ~ASYNC_SPD_MASK;
serial.flags |= ASYNC_SPD_CUST;
// start
serial.custom_divisor = (int)((MLMicroSeconds)serial.baud_base / 9 * aDuration / Second);
FOCUSLOG("- will set fake baud for break: serial.custom_divisor = %d", serial.custom_divisor);
if (ioctl(mConnectionFd, TIOCSSERIAL, &serial)) return;
FOCUSLOG("- did set fake baud rate");
// send one 0x00 with slower baudrate to fake a BREAK
uint8_t b = 0;
write(mConnectionFd, &b, 1);
FOCUSLOG("- did write a 0x00 byte");
// Note: do NOT drain here, it consumes enormous time on MT7688. Just wait long enough, we drained
// already above, so timing should be ok with just waiting
// await break to go out
MainLoop::sleep(aDuration);
FOCUSLOG("- did sleep for the break duration");
// restore actual baud rate
FOCUSLOG("- will restore actual baud rate after break: serial.custom_divisor = %d", oldserial.custom_divisor)
if (ioctl(mConnectionFd, TIOCSSERIAL, &oldserial)) return;
FOCUSLOG("- did restore the original baud rate");
}
#endif
}
// MARK: - handshake signal control
void SerialComm::setDTR(bool aActive)
{
if (!connectionIsOpen() || !nativeSerialPort()) return; // ignore
int iFlags = TIOCM_DTR;
ioctl(mConnectionFd, aActive ? TIOCMBIS : TIOCMBIC, &iFlags);
}
void SerialComm::setRTS(bool aActive)
{
if (!connectionIsOpen() || !nativeSerialPort()) return; // ignore
int iFlags = TIOCM_RTS;
ioctl(mConnectionFd, aActive ? TIOCMBIS : TIOCMBIC, &iFlags);
}
// MARK: - handling data exception
void SerialComm::dataExceptionHandler(int aFd, int aPollFlags)
{
DBGLOG(LOG_DEBUG, "SerialComm::dataExceptionHandler(fd==%d, pollflags==0x%X)", aFd, aPollFlags);
bool reEstablish = false;
if (aPollFlags & POLLHUP) {
// other end has closed connection
LOG(LOG_ERR, "SerialComm: serial connection was hung up unexpectely");
reEstablish = true;
}
else if (aPollFlags & POLLIN) {
// Note: on linux a socket closed server side does not return POLLHUP, but POLLIN with no data
// alerted for read, but nothing to read any more: assume connection closed
LOG(LOG_ERR, "SerialComm: serial connection returns POLLIN with no data: assuming connection broken");
reEstablish = true;
}
else if (aPollFlags & POLLERR) {
// error
LOG(LOG_ERR, "SerialComm: error on serial connection: assuming connection broken");
reEstablish = true;
}
// in case of error, close and re-open connection
if (reEstablish && !mReconnecting) {
LOG(LOG_ERR, "SerialComm: closing and re-opening connection in attempt to re-establish it after error");
closeConnection();
// try re-opening right now
mReconnecting = true;
reconnectHandler();
}
}
void SerialComm::reconnectHandler()
{
if (mReconnecting) {
ErrorPtr err = establishConnection();
if (Error::notOK(err)) {
LOG(LOG_ERR, "SerialComm: re-connect failed: %s -> retry again later", err->text());
mReconnecting = true;
mReconnectTicket.executeOnce(boost::bind(&SerialComm::reconnectHandler, this), 15*Second);
}
else {
LOG(LOG_NOTICE, "SerialComm: successfully reconnected to %s", mConnectionPath.c_str());
}
}
}
#if ENABLE_SERIAL_SCRIPT_FUNCS
// MARK: - midi scripting
// received()
static void received_func(BuiltinFunctionContextPtr f)
{
EventSource* es = dynamic_cast<EventSource*>(f->thisObj().get());
assert(es);
f->finish(new OneShotEventNullValue(es, "serial data"));
}
// send(senddata)
FUNC_ARG_DEFS(send, { anyvalid });
static void send_func(BuiltinFunctionContextPtr f)
{
SerialCommObj* o = dynamic_cast<SerialCommObj*>(f->thisObj().get());
assert(o);
o->serialComm()->sendString(f->arg(0)->stringValue());
f->finish();
}
// rts(on)
// dtr(on)
FUNC_ARG_DEFS(boolarg, { numeric } );
static void rts_func(BuiltinFunctionContextPtr f)
{
SerialCommObj* o = dynamic_cast<SerialCommObj*>(f->thisObj().get());
assert(o);
o->serialComm()->setRTS(f->arg(0)->boolValue());
f->finish();
}
static void dtr_func(BuiltinFunctionContextPtr f)
{
SerialCommObj* o = dynamic_cast<SerialCommObj*>(f->thisObj().get());
assert(o);
o->serialComm()->setDTR(f->arg(0)->boolValue());
f->finish();
}
// sendbreak()
static void sendbreak_func(BuiltinFunctionContextPtr f)
{
SerialCommObj* o = dynamic_cast<SerialCommObj*>(f->thisObj().get());
assert(o);
o->serialComm()->sendBreak();
f->finish();
}
static const BuiltinMemberDescriptor serialCommMembers[] = {
FUNC_DEF_W_ARG(send, executable|null),
FUNC_DEF_NOARG(received, executable|null),
FUNC_DEF_C_ARG(dtr, executable|null, boolarg),
FUNC_DEF_C_ARG(rts, executable|null, boolarg),
FUNC_DEF_NOARG(sendbreak, executable|null),
{ NULL } // terminator
};
static BuiltInMemberLookup* sharedSerialCommFunctionLookupP = NULL;
SerialCommObj::SerialCommObj(SerialCommPtr aSerialComm, char aSeparator) :
mSerialComm(aSerialComm)
{
// install the input handler
mSerialComm->setReceiveHandler(boost::bind(&SerialCommObj::hasData, this, _1), aSeparator);
registerSharedLookup(sharedSerialCommFunctionLookupP, serialCommMembers);
}
void SerialCommObj::deactivate()
{
if (mSerialComm) {
mSerialComm->closeConnection();
mSerialComm.reset();
}
}
SerialCommObj::~SerialCommObj()
{
deactivate();
}
void SerialCommObj::hasData(ErrorPtr aStatus)
{
if (Error::isOK(aStatus)) {
// get the data
string data;
if (mSerialComm->mDelimiter) {
// receiving delimited chunks
if (mSerialComm->receiveDelimitedString(data)) {
sendEvent(new StringValue(data));
}
return;
}
else {
// no delimiter, report available data
aStatus = mSerialComm->receiveIntoString(data, 4096);
if (Error::isOK(aStatus)) {
sendEvent(new StringValue(data));
return;
}
}
}
// failed
sendEvent(new ErrorValue(aStatus));
}
// serial(serialconnectionspec)
// serial(serialconnectionspec, delimiter)
FUNC_ARG_DEFS(serial, { text }, { text|numeric|optionalarg } );
static void serial_func(BuiltinFunctionContextPtr f)
{
#if ENABLE_APPLICATION_SUPPORT
if (Application::sharedApplication()->userLevel()<1) { // user level >=1 is needed for IO access
f->finish(new ErrorValue(ScriptError::NoPrivilege, "no IO privileges"));
}
#endif
SerialCommPtr serialComm = new SerialComm;
serialComm->setConnectionSpecification(f->arg(0)->stringValue().c_str(), 2101, "none");
char delimiter = 0;
if (f->arg(1)->hasType(text)) delimiter = *(f->arg(1)->stringValue().c_str()); // one char or NUL
else if (f->arg(1)->boolValue()) delimiter = '\n'; // just true means LF (and removing CRs, too)
SerialCommObjPtr serialObj = new SerialCommObj(serialComm, delimiter);
ErrorPtr err = serialObj->serialComm()->establishConnection();
if (Error::isOK(err)) {
f->finish(serialObj);
}
else {
f->finish(new ErrorValue(err));
}
}
static const BuiltinMemberDescriptor serialGlobals[] = {
FUNC_DEF_W_ARG(serial, executable|null),
{ NULL } // terminator
};
SerialLookup::SerialLookup() :
inherited(serialGlobals)
{
}
#endif // ENABLE_SERIAL_SCRIPT_FUNCS