Join/Login

Business Software

Open Source Software

For Vendors

Blog

About

More

Articles

Create

SourceForge Podcast

Site Documentation

Subscribe to our Newsletter

Support Request

For Vendors Help Create Join Login

Business Software

Open Source Software

SourceForge Podcast

Resources

Articles

Case Studies

Blog

Menu

Help

Create

Join

Login

Home

Browse

AMSerialPort

Code

AMSerialPort Code

Brought to you by: harmless-de

Summary

Files

Reviews

Support

Wiki

Code

Menu ▾ ▴

Browse Commits

Browse Files

[r42]: / trunk / SharedCode / AMSerialPort.m  Maximize  Restore  History

Download this file

947 lines (797 with data), 24.6 kB

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

//

// AMSerialPort.m

//

// Created by Andreas on 2002-04-24.

// Copyright (c) 2001-2014 Andreas Mayer. All rights reserved.

//

// 2002-09-18 Andreas Mayer

// - added available & owner

// 2002-10-10 Andreas Mayer

// - some log messages changed

// 2002-10-25 Andreas Mayer

// - additional locks and other changes for reading and writing in background

// 2003-11-26 James Watson

// - in dealloc [self close] reordered to execute before releasing closeLock

// 2007-05-22 Nick Zitzmann

// - added -hash and -isEqual: methods

// 2007-07-18 Sean McBride

// - behaviour change: -open and -close must now always be matched, -dealloc checks this

// - added -debugDescription so gdb's 'po' command gives something useful

// 2007-07-25 Andreas Mayer

// - replaced -debugDescription by -description; works for both, gdb's 'po' and NSLog()

// 2007-10-26 Sean McBride

// - made code 64 bit and garbage collection clean

// 2008-10-21 Sean McBride

// - Added an API to open a serial port for exclusive use

// - fixed some memory management issues

// 2009-08-06 Sean McBride

// - no longer compare BOOL against YES (dangerous!)

// - renamed method to start with lowercase letter, as per Cocoa convention

// 2011-10-14 Sean McBride

// - very minor cleanup

// 2011-10-18 Andreas Mayer

// - added ARC compatibility

// - added accessors for ISIG, ECHOE, XON/XOFF as well as Start and Stop characters

// - options dictionary will cover more settings; fixed handling of some flags

// 2011-10-19 Sean McBride

// - code review of ARC changes

// - changed delegate semantics to match Cocoa conventions: the delegate is no longer retained!

// 2012-06-20 Sean McBride

// - fixed possible out of range exception and compiler warning

#import "AMSDKCompatibility.h"

#include <sys/ioctl.h>

#import "AMSerialPort.h"

#import "AMSerialErrors.h"

#import <IOKit/serial/IOSerialKeys.h>

#if defined(MAC_OS_X_VERSION_10_4) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_4)

#import <IOKit/serial/ioss.h>

#endif

NSString *const AMSerialErrorDomain = @"de.harmless.AMSerial.ErrorDomain";

@implementation AMSerialPort

// Designated initializer

- (instancetype)init:(NSString *)path withName:(NSString *)name type:(NSString *)type

// path is a bsdPath

// name is an IOKit service name

{

if ((self = [super init])) {

_bsdPath = [path copy];

_serviceName = [name copy];

_serviceType = [type copy];

_optionsDictionary = [[NSMutableDictionary alloc] initWithCapacity:8];

_options = (struct termios *)malloc(sizeof(*_options));

_originalOptions = (struct termios *)malloc(sizeof(*_originalOptions));

_buffer = (char *)malloc(AMSER_MAXBUFSIZE);

_readfds = (fd_set *)malloc(sizeof(*_readfds));

_fileDescriptor = -1;

_writeLock = [[NSLock alloc] init];

_readLock = [[NSLock alloc] init];

_closeLock = [[NSLock alloc] init];

// By default blocking read attempts will timeout after 1 second

[self setReadTimeout:1.0];

// These are used by the AMSerialPortAdditions category only; pretend to use them here to silence warnings by the clang static analyzer.

(void)_am_readTarget;

(void)_am_readSelector;

(void)_stopWriteInBackground;

(void)_countWriteInBackgroundThreads;

(void)_stopReadInBackground;

(void)_countReadInBackgroundThreads;

}

return self;

}

#ifndef __OBJC_GC__

- (void)dealloc

{

#ifdef AMSerialDebug

if (fileDescriptor != -1)

NSLog(@"It is a programmer error to have not called -close on an AMSerialPort you have opened");

#endif

free(_readfds); _readfds = NULL;

free(_buffer); _buffer = NULL;

free(_originalOptions); _originalOptions = NULL;

free(_options); _options = NULL;

#if !__has_feature(objc_arc)

[_readLock release]; _readLock = nil;

[_writeLock release]; _writeLock = nil;

[_closeLock release]; _closeLock = nil;

[_am_readTarget release]; _am_readTarget = nil;

[_optionsDictionary release]; _optionsDictionary = nil;

[_serviceName release]; _serviceName = nil;

[_serviceType release]; _serviceType = nil;

[_bsdPath release]; _bsdPath = nil;

[super dealloc];

#endif

}

#else

- (void)finalize

{

#ifdef AMSerialDebug

if (fileDescriptor != -1)

NSLog(@"It is a programmer error to have not called -close on an AMSerialPort you have opened");

#endif

assert (fileDescriptor == -1);

free(_readfds); _readfds = NULL;

free(_buffer); _buffer = NULL;

free(_originalOptions); _originalOptions = NULL;

free(_options); _options = NULL;

[super finalize];

}

#endif

// So NSLog and gdb's 'po' command give something useful

- (NSString *)description

{

NSString *result= [NSString stringWithFormat:@"<%@: address: %p, name: %@, path: %@, type: %@, fileHandle: %@, fileDescriptor: %d>", NSStringFromClass([self class]), self, _serviceName, _bsdPath, _serviceType, _fileHandle, _fileDescriptor];

return result;

}

- (NSUInteger)hash

{

return [[self bsdPath] hash];

}

- (BOOL)isEqual:(id)otherObject

{

if ([otherObject isKindOfClass:[AMSerialPort class]])

return [[self bsdPath] isEqualToString:[otherObject bsdPath]];

return NO;

}

- (id<AMSerialDelegate>)delegate

{

return _delegate;

}

- (void)setDelegate:(id<AMSerialDelegate>)newDelegate

{

if (newDelegate != _delegate) {

// As per Cocoa conventions, delegates are not retained.

_delegate = newDelegate;

_delegateHandlesReadInBackground = [_delegate respondsToSelector:@selector(serialPortReadData:)];

_delegateHandlesWriteInBackground = [_delegate respondsToSelector:@selector(serialPortWriteProgress:)];

}

}

- (NSString *)bsdPath

{

return _bsdPath;

}

- (NSString *)name

{

return _serviceName;

}

- (NSString *)type

{

return _serviceType;

}

- (NSDictionary *)properties

{

NSDictionary *result = nil;

kern_return_t kernResult;

CFMutableDictionaryRef matchingDictionary;

io_service_t serialService;

matchingDictionary = IOServiceMatching(kIOSerialBSDServiceValue);

#if __has_feature(objc_arc)

CFDictionarySetValue(matchingDictionary, CFSTR(kIOTTYDeviceKey), (__bridge CFStringRef)[self name]);

#else

CFDictionarySetValue(matchingDictionary, CFSTR(kIOTTYDeviceKey), (CFStringRef)[self name]);

#endif

if (matchingDictionary != NULL) {

CFRetain(matchingDictionary);

// This function decrements the refcount of the dictionary passed it

serialService = IOServiceGetMatchingService(kIOMasterPortDefault, matchingDictionary);

if (serialService) {

CFMutableDictionaryRef propertiesDict = NULL;

kernResult = IORegistryEntryCreateCFProperties(serialService, &propertiesDict, kCFAllocatorDefault, 0);

if (kernResult == KERN_SUCCESS) {

#if __has_feature(objc_arc)

result = [(__bridge NSDictionary*)propertiesDict copy];

#else

result = [[(NSDictionary*)propertiesDict copy] autorelease];

#endif

}

if (propertiesDict) {

CFRelease(propertiesDict);

}

// We have sucked this service dry of information so release it now.

(void)IOObjectRelease(serialService);

} else {

#ifdef AMSerialDebug

NSLog(@"properties: no matching service for %@", matchingDictionary);

#endif

}

CFRelease(matchingDictionary);

}

return result;

}

- (BOOL)isOpen

{

// YES if port is open

return (_fileDescriptor >= 0);

}

- (AMSerialPort *)obtainBy:(id)sender

{

// get this port exclusively; NULL if it's not free

if (_owner == nil) {

_owner = sender;

return self;

} else

return nil;

}

- (void)free

{

// give it back

_owner = nil;

[self close]; // you never know ...

}

- (BOOL)available

{

// check if port is free and can be obtained

return (_owner == nil);

}

- (id)owner

{

// who obtained the port?

return _owner;

}

// Private

- (NSFileHandle *)openWithFlags:(int)flags // use returned file handle to read and write

{

NSFileHandle *result = nil;

#ifdef __OBJC_GC__

__strong const char *path = [_bsdPath fileSystemRepresentation];

#else

const char *path = [_bsdPath fileSystemRepresentation];

#endif

_fileDescriptor = open(path, flags);

#ifdef AMSerialDebug

NSLog(@"open %@ (%d)\n", bsdPath, fileDescriptor);

#endif

if (_fileDescriptor < 0) {

#ifdef AMSerialDebug

NSLog(@"Error opening serial port %@ - %s(%d).\n", bsdPath, strerror(errno), errno);

#endif

} else {

/*

if (fcntl(fileDescriptor, F_SETFL, fcntl(fileDescriptor, F_GETFL, 0) & !O_NONBLOCK) == -1)

{

NSLog(@"Error clearing O_NDELAY %@ - %s(%d).\n", bsdPath, strerror(errno), errno);

} // ... else

*/

// get the current options and save them for later reset

if (tcgetattr(_fileDescriptor, _originalOptions) == -1) {

#ifdef AMSerialDebug

NSLog(@"Error getting tty attributes %@ - %s(%d).\n", bsdPath, strerror(errno), errno);

#endif

} else {

// Make an exact copy of the options

*_options = *_originalOptions;

// This object owns the fileDescriptor and must dispose it later

// In other words, you must balance calls to -open with -close

_fileHandle = [[NSFileHandle alloc] initWithFileDescriptor:_fileDescriptor];

result = _fileHandle;

}

}

if (!result) { // failure

if (_fileDescriptor >= 0) {

close(_fileDescriptor);

}

_fileDescriptor = -1;

}

return result;

}

// TODO: Sean: why is O_NONBLOCK commented? Do we want it or not?

// use returned file handle to read and write

- (NSFileHandle *)open

{

return [self openWithFlags:(O_RDWR | O_NOCTTY)]; // | O_NONBLOCK);

}

// use returned file handle to read and write

- (NSFileHandle *)openExclusively

{

return [self openWithFlags:(O_RDWR | O_NOCTTY | O_EXLOCK | O_NONBLOCK)]; // | O_NONBLOCK);

}

- (void)close

{

// Traditionally it is good to reset a serial port back to

// the state in which you found it. Let's continue that tradition.

if (_fileDescriptor >= 0) {

//NSLog(@"close - attempt closeLock");

[_closeLock lock];

//NSLog(@"close - closeLock locked");

// kill pending read by setting O_NONBLOCK

if (fcntl(_fileDescriptor, F_SETFL, fcntl(_fileDescriptor, F_GETFL, 0) | O_NONBLOCK) == -1) {

#ifdef AMSerialDebug

NSLog(@"Error clearing O_NONBLOCK %@ - %s(%d).\n", bsdPath, strerror(errno), errno);

#endif

}

if (tcsetattr(_fileDescriptor, TCSANOW, _originalOptions) == -1) {

#ifdef AMSerialDebug

NSLog(@"Error resetting tty attributes - %s(%d).\n", strerror(errno), errno);

#endif

}

// Disallows further access to the communications channel

[_fileHandle closeFile];

// Release the fileHandle

#if !__has_feature(objc_arc)

[_fileHandle release];

#endif

_fileHandle = nil;

#ifdef AMSerialDebug

NSLog(@"close (%d)\n", fileDescriptor);

#endif

// Close the fileDescriptor, that is our responsibility since the fileHandle does not own it

close(_fileDescriptor);

_fileDescriptor = -1;

[_closeLock unlock];

//NSLog(@"close - closeLock unlocked");

}

}

- (BOOL)drainInput

{

BOOL result = (tcdrain(_fileDescriptor) != -1);

return result;

}

- (BOOL)flushInput:(BOOL)fIn output:(BOOL)fOut // (fIn or fOut) must be YES

{

int mode = 0;

if (fIn)

mode = TCIFLUSH;

if (fOut)

mode = TCOFLUSH;

if (fIn && fOut)

mode = TCIOFLUSH;

BOOL result = (tcflush(_fileDescriptor, mode) != -1);

return result;

}

- (BOOL)sendBreak

{

BOOL result = (tcsendbreak(_fileDescriptor, 0) != -1);

return result;

}

- (BOOL)setDTR

{

BOOL result = (ioctl(_fileDescriptor, TIOCSDTR) != -1);

return result;

}

- (BOOL)clearDTR

{

BOOL result = (ioctl(_fileDescriptor, TIOCCDTR) != -1);

return result;

}

// read and write serial port settings through a dictionary

- (void)buildOptionsDictionary

{

[_optionsDictionary removeAllObjects];

[_optionsDictionary setObject:[self name] forKey:AMSerialOptionServiceName];

[_optionsDictionary setObject:[NSString stringWithFormat:@"%ld", [self speed]] forKey:AMSerialOptionSpeed];

[_optionsDictionary setObject:[NSString stringWithFormat:@"%lu", [self dataBits]] forKey:AMSerialOptionDataBits];

switch ([self parity]) {

case kAMSerialParityOdd: {

[_optionsDictionary setObject:@"Odd" forKey:AMSerialOptionParity];

break;

}

case kAMSerialParityEven: {

[_optionsDictionary setObject:@"Even" forKey:AMSerialOptionParity];

break;

}

case kAMSerialParityNone:

default: {

break;

}

}

[_optionsDictionary setObject:[NSString stringWithFormat:@"%d", [self stopBits]] forKey:AMSerialOptionStopBits];

[_optionsDictionary setObject:@"None" forKey:AMSerialOptionInputFlowControl];

if ([self RTSInputFlowControl])

[_optionsDictionary setObject:@"RTS" forKey:AMSerialOptionInputFlowControl];

if ([self DTRInputFlowControl])

[_optionsDictionary setObject:@"DTR" forKey:AMSerialOptionInputFlowControl];

[_optionsDictionary setObject:@"None" forKey:AMSerialOptionOutputFlowControl];

if ([self CTSOutputFlowControl])

[_optionsDictionary setObject:@"CTS" forKey:AMSerialOptionOutputFlowControl];

if ([self DSROutputFlowControl])

[_optionsDictionary setObject:@"DSR" forKey:AMSerialOptionOutputFlowControl];

if ([self CAROutputFlowControl])

[_optionsDictionary setObject:@"CAR" forKey:AMSerialOptionOutputFlowControl];

if ([self softwareFlowControl])

[_optionsDictionary setObject:@"YES" forKey:AMSerialOptionSoftwareFlowControl];

if ([self signalsEnabled])

[_optionsDictionary setObject:@"YES" forKey:AMSerialOptionSignals];

if ([self canonicalMode])

[_optionsDictionary setObject:@"YES" forKey:AMSerialOptionCanonicalMode];

if ([self echoEnabled])

[_optionsDictionary setObject:@"YES" forKey:AMSerialOptionEcho];

if ([self echoEraseEnabled])

[_optionsDictionary setObject:@"YES" forKey:AMSerialOptionEchoErase];

if ([self softwareFlowControl])

[_optionsDictionary setObject:@"YES" forKey:AMSerialOptionSoftwareFlowControl];

[_optionsDictionary setObject:[NSString stringWithFormat:@"%c", [self endOfLineCharacter]] forKey:AMSerialOptionEndOfLineCharacter];

[_optionsDictionary setObject:[NSString stringWithFormat:@"%c", [self startCharacter]] forKey:AMSerialOptionStartCharacter];

[_optionsDictionary setObject:[NSString stringWithFormat:@"%c", [self stopCharacter]] forKey:AMSerialOptionStopCharacter];

}

- (NSDictionary *)options

{

// will open the port to get options if neccessary

if ([_optionsDictionary objectForKey:AMSerialOptionServiceName] == nil) {

if (_fileDescriptor < 0) {

[self open];

[self close];

}

[self buildOptionsDictionary];

}

return [NSMutableDictionary dictionaryWithDictionary:_optionsDictionary];

}

- (void)setOptions:(NSDictionary *)newOptions

{

// AMSerialOptionServiceName HAS to match! You may NOT switch ports using this

// method.

NSString *temp;

if ([(NSString *)[newOptions objectForKey:AMSerialOptionServiceName] isEqualToString:[self name]]) {

[self clearError];

[_optionsDictionary addEntriesFromDictionary:newOptions];

// parse dictionary

temp = (NSString *)[_optionsDictionary objectForKey:AMSerialOptionSpeed];

[self setSpeed:[temp intValue]];

temp = (NSString *)[_optionsDictionary objectForKey:AMSerialOptionDataBits];

[self setDataBits:[temp intValue]];

temp = (NSString *)[_optionsDictionary objectForKey:AMSerialOptionParity];

if (temp == nil || [temp isEqualToString:@"None"])

[self setParity:kAMSerialParityNone];

else if ([temp isEqualToString:@"Odd"])

[self setParity:kAMSerialParityOdd];

else

[self setParity:kAMSerialParityEven];

temp = (NSString *)[_optionsDictionary objectForKey:AMSerialOptionStopBits];

int numStopBits = [temp intValue];

[self setStopBits:(AMSerialStopBits)numStopBits];

temp = (NSString *)[_optionsDictionary objectForKey:AMSerialOptionInputFlowControl];

[self setRTSInputFlowControl:[temp isEqualToString:@"RTS"]];

[self setDTRInputFlowControl:[temp isEqualToString:@"DTR"]];

temp = (NSString *)[_optionsDictionary objectForKey:AMSerialOptionOutputFlowControl];

[self setCTSOutputFlowControl:[temp isEqualToString:@"CTS"]];

[self setDSROutputFlowControl:[temp isEqualToString:@"DSR"]];

[self setCAROutputFlowControl:[temp isEqualToString:@"CAR"]];

temp = (NSString *)[_optionsDictionary objectForKey:AMSerialOptionSignals];

[self setSignalsEnabled:(temp != nil && [temp isEqualToString:@"YES"])];

temp = (NSString *)[_optionsDictionary objectForKey:AMSerialOptionCanonicalMode];

[self setCanonicalMode:(temp != nil && [temp isEqualToString:@"YES"])];

temp = (NSString *)[_optionsDictionary objectForKey:AMSerialOptionEcho];

[self setEchoEnabled:(temp != nil && [temp isEqualToString:@"YES"])];

temp = (NSString *)[_optionsDictionary objectForKey:AMSerialOptionEchoErase];

[self setEchoEraseEnabled:(temp != nil && [temp isEqualToString:@"YES"])];

temp = (NSString *)[_optionsDictionary objectForKey:AMSerialOptionSoftwareFlowControl];

[self setSoftwareFlowControl:(temp != nil && [temp isEqualToString:@"YES"])];

temp = (NSString *)[_optionsDictionary objectForKey:AMSerialOptionEndOfLineCharacter];

if ([temp length] > 0) {

unichar character = [temp characterAtIndex:0];

[self setEndOfLineCharacter:(char)character]; // this assumes that the character in question is a single byte char

}

temp = (NSString *)[_optionsDictionary objectForKey:AMSerialOptionStartCharacter];

if ([temp length] > 0) {

unichar character = [temp characterAtIndex:0];

[self setStartCharacter:(char)character]; // this assumes that the character in question is a single byte char

}

temp = (NSString *)[_optionsDictionary objectForKey:AMSerialOptionStopCharacter];

if ([temp length] > 0) {

unichar character = [temp characterAtIndex:0];

[self setStopCharacter:(char)character]; // this assumes that the character in question is a single byte char

}

[self commitChanges];

} else {

#ifdef AMSerialDebug

NSLog(@"Error setting options for port %s (wrong port name: %s).\n", [self name], [newOptions objectForKey:AMSerialOptionServiceName]);

#endif

}

}

- (unsigned long)speed

{

return cfgetospeed(_options); // we should support cfgetispeed too

}

- (BOOL)setSpeed:(unsigned long)speed

{

BOOL result = YES;

// we should support setting input and output speed separately

int errorCode = 0;

// ***NOTE***: This code does not seem to work. It was taken from Apple's sample code:

// <http://developer.apple.com/samplecode/SerialPortSample/listing2.html>

// and that code does not work either. select() times out regularly if this code path is taken.

#if 0 && defined(MAC_OS_X_VERSION_10_4) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_4)

// Starting with Tiger, the IOSSIOSPEED ioctl can be used to set arbitrary baud rates

// other than those specified by POSIX. The driver for the underlying serial hardware

// ultimately determines which baud rates can be used. This ioctl sets both the input

// and output speed.

speed_t newSpeed = speed;

if (fileDescriptor >= 0) {

errorCode = ioctl(fileDescriptor, IOSSIOSPEED, &newSpeed);

} else {

result = NO;

gotError = YES;

lastError = EBADF; // Bad file descriptor

}

#else

// set both the input and output speed

errorCode = cfsetspeed(_options, speed);

#endif

if (errorCode == -1) {

result = NO;

_gotError = YES;

_lastError = errno;

}

return result;

}

- (unsigned long)dataBits

{

return 5 + ((_options->c_cflag & CSIZE) >> 8);

// man ... I *hate* C syntax ...

}

- (void)setDataBits:(unsigned long)bits // 5 to 8 (5 is marked as "(pseudo)")

{

// ?? options->c_oflag &= ~OPOST;

_options->c_cflag &= ~CSIZE;

switch (bits) {

case 5: _options->c_cflag |= CS5; // redundant since CS5 == 0

break;

case 6: _options->c_cflag |= CS6;

break;

case 7: _options->c_cflag |= CS7;

break;

case 8: _options->c_cflag |= CS8;

break;

}

}

- (AMSerialParity)parity

{

AMSerialParity result;

if (_options->c_cflag & PARENB) {

if (_options->c_cflag & PARODD) {

result = kAMSerialParityOdd;

} else {

result = kAMSerialParityEven;

}

} else {

result = kAMSerialParityNone;

}

return result;

}

- (void)setParity:(AMSerialParity)newParity

{

switch (newParity) {

case kAMSerialParityNone: {

_options->c_cflag &= ~PARENB;

break;

}

case kAMSerialParityOdd: {

_options->c_cflag |= PARENB;

_options->c_cflag |= PARODD;

break;

}

case kAMSerialParityEven: {

_options->c_cflag |= PARENB;

_options->c_cflag &= ~PARODD;

break;

}

}

}

- (AMSerialStopBits)stopBits

{

if (_options->c_cflag & CSTOPB)

return kAMSerialStopBitsTwo;

else

return kAMSerialStopBitsOne;

}

- (void)setStopBits:(AMSerialStopBits)numBits

{

if (numBits == kAMSerialStopBitsOne)

_options->c_cflag &= ~CSTOPB;

else if (numBits == kAMSerialStopBitsTwo)

_options->c_cflag |= CSTOPB;

}

- (BOOL)RTSInputFlowControl

{

return (_options->c_cflag & CRTS_IFLOW) != 0;

}

- (void)setRTSInputFlowControl:(BOOL)rts

{

if (rts)

_options->c_cflag |= CRTS_IFLOW;

else

_options->c_cflag &= ~CRTS_IFLOW;

}

- (BOOL)DTRInputFlowControl

{

return (_options->c_cflag & CDTR_IFLOW) != 0;

}

- (void)setDTRInputFlowControl:(BOOL)dtr

{

if (dtr)

_options->c_cflag |= CDTR_IFLOW;

else

_options->c_cflag &= ~CDTR_IFLOW;

}

- (BOOL)CTSOutputFlowControl

{

return (_options->c_cflag & CCTS_OFLOW) != 0;

}

- (void)setCTSOutputFlowControl:(BOOL)cts

{

if (cts)

_options->c_cflag |= CCTS_OFLOW;

else

_options->c_cflag &= ~CCTS_OFLOW;

}

- (BOOL)DSROutputFlowControl

{

return (_options->c_cflag & CDSR_OFLOW) != 0;

}

- (void)setDSROutputFlowControl:(BOOL)dsr

{

if (dsr)

_options->c_cflag |= CDSR_OFLOW;

else

_options->c_cflag &= ~CDSR_OFLOW;

}

- (BOOL)CAROutputFlowControl

{

return (_options->c_cflag & CCAR_OFLOW) != 0;

}

- (void)setCAROutputFlowControl:(BOOL)car

{

if (car)

_options->c_cflag |= CCAR_OFLOW;

else

_options->c_cflag &= ~CCAR_OFLOW;

}

- (BOOL)hangupOnClose

{

return (_options->c_cflag & HUPCL) != 0;

}

- (void)setHangupOnClose:(BOOL)hangup

{

if (hangup)

_options->c_cflag |= HUPCL;

else

_options->c_cflag &= ~HUPCL;

}

- (BOOL)localMode

{

return (_options->c_cflag & CLOCAL) != 0;

}

- (void)setLocalMode:(BOOL)local

{

// YES = ignore modem status lines

if (local)

_options->c_cflag |= CLOCAL;

else

_options->c_cflag &= ~CLOCAL;

}

- (BOOL)signalsEnabled

{

return (_options->c_lflag & ICANON) != 0;

}

- (void)setSignalsEnabled:(BOOL)signals

{

if (signals)

_options->c_lflag |= ISIG;

else

_options->c_lflag &= ~ISIG;

}

- (BOOL)canonicalMode

{

return (_options->c_lflag & ICANON) != 0;

}

- (void)setCanonicalMode:(BOOL)flag

{

if (flag)

_options->c_lflag |= ICANON;

else

_options->c_lflag &= ~ICANON;

}

- (BOOL)echoEnabled

{

return (_options->c_lflag & ECHO);

}

- (void)setEchoEnabled:(BOOL)echo

{

if (echo)

_options->c_lflag |= ECHO;

else

_options->c_lflag &= ~ECHO;

}

- (BOOL)echoEraseEnabled

{

return (_options->c_lflag & ECHO);

}

- (void)setEchoEraseEnabled:(BOOL)echoE

{

if (echoE)

_options->c_lflag |= ECHOE;

else

_options->c_lflag &= ~ECHOE;

}

- (char)endOfLineCharacter

{

return _options->c_cc[VEOL];

}

- (void)setEndOfLineCharacter:(char)eol

{

_options->c_cc[VEOL] = eol;

}

- (char)startCharacter

{

return _options->c_cc[VSTART];

}

- (void)setStartCharacter:(char)start

{

_options->c_cc[VSTART] = start;

}

- (char)stopCharacter

{

return _options->c_cc[VSTOP];

}

- (void)setStopCharacter:(char)stop

{

_options->c_cc[VSTOP] = stop;

}

- (BOOL)softwareFlowControl

{

BOOL xon = (_options->c_iflag & IXON) != 0;

BOOL xoff = (_options->c_iflag & IXOFF) != 0;

return xon || xoff;

}

- (void)setSoftwareFlowControl:(BOOL)xonxoff

{

if (xonxoff) {

_options->c_iflag |= (IXON | IXOFF);

} else {

_options->c_iflag &= ~(IXON | IXOFF);

}

}

- (BOOL)remoteEchoEnabled

{

BOOL icanon = (_options->c_lflag & ICANON) != 0;

BOOL echo = (_options->c_lflag & ECHO) != 0;

return icanon && echo;

}

- (void)setRemoteEchoEnabled:(BOOL)remoteEcho

{

if (remoteEcho) {

_options->c_lflag |= (ICANON | ECHO | ECHOE);

} else {

_options->c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);

}

}

- (void)clearError

{

// call this before changing any settings

_gotError = NO;

}

- (BOOL)commitChanges

{

// call this after using any of the setters above

if (_gotError)

return NO;

if (tcsetattr(_fileDescriptor, TCSANOW, _options) == -1) {

// something went wrong

_gotError = YES;

_lastError = errno;

return NO;

} else {

[self buildOptionsDictionary];

return YES;

}

}

- (int)errorCode

{

// if -commitChanges returns NO, look here for further info

return _lastError;

}

- (NSTimeInterval)readTimeout

{

return _readTimeout;

}

- (void)setReadTimeout:(NSTimeInterval)aReadTimeout

{

_readTimeout = aReadTimeout;

}

- (void)readTimeoutAsTimeval:(struct timeval*)timeout

{

NSTimeInterval timeoutInterval = [self readTimeout];

double numSecs = trunc(timeoutInterval);

double numUSecs = (timeoutInterval-numSecs)*1000000.0;

timeout->tv_sec = (time_t)lrint(numSecs);

timeout->tv_usec = (suseconds_t)lrint(numUSecs);

}

@end

SourceForge

Create a Project

Open Source Software

Business Software

Top Downloaded Projects

Company

About

Team

SourceForge Headquarters
225 Broadway Suite 1600
San Diego, CA 92101
+1 (858) 422-6466

Resources

Support

Site Documentation

Site Status

SourceForge Reviews

© 2025 Slashdot Media. All Rights Reserved.

Terms Privacy Opt Out Advertise

×
Want the latest updates on software, tech news, and AI?

Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.

Submit