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

[r50]: / trunk / SharedCode / AMSerialPortList.m  Maximize  Restore  History

Download this file

336 lines (290 with data), 11.1 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

//

// AMSerialPortList.m

//

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

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

//

// 2002-09-09 Andreas Mayer

// - reuse AMSerialPort objects when calling init on an existing AMSerialPortList

// 2002-09-30 Andreas Mayer

// - added +sharedPortList

// 2004-07-05 Andreas Mayer

// - added some log statements

// 2007-05-22 Nick Zitzmann

// - added notifications for when serial ports are added/removed

// 2007-07-18 Sean McBride

// - minor improvements to the added/removed notification support

// - changed singleton creation technique, now matches Apple's sample code

// - removed oldPortList as it is no longer needed

// 2007-10-26 Sean McBride

// - made code 64 bit and garbage collection clean

// 2008-10-21 Sean McBride

// - fixed some memory management issues

// 2010-01-04 Sean McBride

// - fixed some memory management issues

// 2011-08-18 Andreas Mayer

// - minor edits to placate the clang static analyzer

// 2011-10-14 Sean McBride

// - removed one NSRunLoop method in favour of CFRunLoop

// 2011-10-18 Andreas Mayer

// - added ARC compatibility

// 2011-10-19 Sean McBride

// - code review of ARC changes

// - greatly simplified the various singleton implementations

// 2012-03-27

// - use instancetype for singleton return value

#import "AMSDKCompatibility.h"

#import "AMSerialPortList.h"

#import "AMSerialPort.h"

#import "AMStandardEnumerator.h"

#import <termios.h>

#import <CoreFoundation/CoreFoundation.h>

#import <IOKit/IOKitLib.h>

#import <IOKit/serial/IOSerialKeys.h>

#import <IOKit/IOBSD.h>

NSString *const AMSerialPortListDidAddPortsNotification = @"AMSerialPortListDidAddPortsNotification";

NSString *const AMSerialPortListDidRemovePortsNotification = @"AMSerialPortListDidRemovePortsNotification";

NSString *const AMSerialPortListAddedPorts = @"AMSerialPortListAddedPorts";

NSString *const AMSerialPortListRemovedPorts = @"AMSerialPortListRemovedPorts";

@implementation AMSerialPortList

+ (instancetype)sharedPortList {

static AMSerialPortList *sharedPortList = nil;

@synchronized([AMSerialPortList class]) {

if (!sharedPortList) {

sharedPortList = [[self alloc] init];

}

}

return sharedPortList;

}

+ (NSEnumerator *)portEnumerator

{

id ports = [AMSerialPortList sharedPortList];

NSEnumerator *enumerator = [[AMStandardEnumerator alloc] initWithCollection:ports

countSelector:@selector(count)

objectAtIndexSelector:@selector(objectAtIndex:)];

#if !__has_feature(objc_arc)

[enumerator autorelease];

#endif

return enumerator;

}

+ (NSEnumerator *)portEnumeratorForSerialPortsOfType:(NSString *)serialTypeKey

{

id ports = [[AMSerialPortList sharedPortList] serialPortsOfType:serialTypeKey];

NSEnumerator *enumerator = [[AMStandardEnumerator alloc] initWithCollection:ports

countSelector:@selector(count)

objectAtIndexSelector:@selector(objectAtIndex:)];

#if !__has_feature(objc_arc)

[enumerator autorelease];

#endif

return enumerator;

}

- (AMSerialPort *)portByPath:(NSString *)bsdPath

{

AMSerialPort *result = nil;

AMSerialPort *port;

NSEnumerator *enumerator;

enumerator = [_portList objectEnumerator];

while ((port = [enumerator nextObject]) != nil) {

if ([[port bsdPath] isEqualToString:bsdPath]) {

result = port;

break;

}

}

return result;

}

- (AMSerialPort *)getNextSerialPort:(io_iterator_t)serialPortIterator

{

AMSerialPort *serialPort = nil;

io_object_t serialService = IOIteratorNext(serialPortIterator);

if (serialService != 0) {

CFStringRef modemName = (CFStringRef)IORegistryEntryCreateCFProperty(serialService, CFSTR(kIOTTYDeviceKey), kCFAllocatorDefault, 0);

CFStringRef bsdPath = (CFStringRef)IORegistryEntryCreateCFProperty(serialService, CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);

CFStringRef serviceType = (CFStringRef)IORegistryEntryCreateCFProperty(serialService, CFSTR(kIOSerialBSDTypeKey), kCFAllocatorDefault, 0);

if (modemName && bsdPath) {

// If the port already exists in the list of ports, we want that one. We only create a new one as a last resort.

#if __has_feature(objc_arc)

serialPort = [self portByPath:(__bridge NSString*)bsdPath];

if (serialPort == nil) {

serialPort = [[AMSerialPort alloc] init:(__bridge NSString*)bsdPath withName:(__bridge NSString*)modemName type:(__bridge NSString*)serviceType];

}

#else

serialPort = [self portByPath:(NSString*)bsdPath];

if (serialPort == nil) {

serialPort = [[[AMSerialPort alloc] init:(NSString*)bsdPath withName:(NSString*)modemName type:(NSString*)serviceType] autorelease];

}

#endif

}

if (modemName) {

CFRelease(modemName);

}

if (bsdPath) {

CFRelease(bsdPath);

}

if (serviceType) {

CFRelease(serviceType);

}

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

(void)IOObjectRelease(serialService);

}

return serialPort;

}

- (void)portsWereAdded:(io_iterator_t)iterator

{

AMSerialPort *serialPort;

NSMutableArray *addedPorts = [NSMutableArray array];

while ((serialPort = [self getNextSerialPort:iterator]) != nil) {

[addedPorts addObject:serialPort];

[_portList addObject:serialPort];

}

NSNotificationCenter* notifCenter = [NSNotificationCenter defaultCenter];

NSDictionary* userInfo = [NSDictionary dictionaryWithObject:addedPorts forKey:AMSerialPortListAddedPorts];

[notifCenter postNotificationName:AMSerialPortListDidAddPortsNotification object:self userInfo:userInfo];

}

- (void)portsWereRemoved:(io_iterator_t)iterator

{

AMSerialPort *serialPort;

NSMutableArray *removedPorts = [NSMutableArray array];

while ((serialPort = [self getNextSerialPort:iterator]) != nil) {

// Since the port was removed, one should obviously not attempt to use it anymore -- so 'close' it.

// -close does nothing if the port was never opened.

[serialPort close];

[removedPorts addObject:serialPort];

[_portList removeObject:serialPort];

}

NSNotificationCenter* notifCenter = [NSNotificationCenter defaultCenter];

NSDictionary* userInfo = [NSDictionary dictionaryWithObject:removedPorts forKey:AMSerialPortListRemovedPorts];

[notifCenter postNotificationName:AMSerialPortListDidRemovePortsNotification object:self userInfo:userInfo];

}

static void AMSerialPortWasAddedNotification(void *refcon, io_iterator_t iterator)

{

(void)refcon;

[[AMSerialPortList sharedPortList] portsWereAdded:iterator];

}

static void AMSerialPortWasRemovedNotification(void *refcon, io_iterator_t iterator)

{

(void)refcon;

[[AMSerialPortList sharedPortList] portsWereRemoved:iterator];

}

- (void)registerForSerialPortChangeNotifications

{

IONotificationPortRef notificationPort = IONotificationPortCreate(kIOMasterPortDefault);

if (notificationPort) {

CFRunLoopSourceRef notificationSource = IONotificationPortGetRunLoopSource(notificationPort);

if (notificationSource) {

// Serial devices are instances of class IOSerialBSDClient

CFMutableDictionaryRef classesToMatch1 = IOServiceMatching(kIOSerialBSDServiceValue);

if (classesToMatch1) {

CFDictionarySetValue(classesToMatch1, CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));

// Copy classesToMatch1 now, while it has a non-zero ref count.

CFMutableDictionaryRef classesToMatch2 = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, classesToMatch1);

// Add to the runloop

CFRunLoopAddSource(CFRunLoopGetCurrent(), notificationSource, kCFRunLoopCommonModes);

// Set up notification for ports being added.

io_iterator_t unused;

kern_return_t kernResult = IOServiceAddMatchingNotification(notificationPort, kIOPublishNotification, classesToMatch1, AMSerialPortWasAddedNotification, NULL, &unused); // consumes a reference to classesToMatch1

if (kernResult != KERN_SUCCESS) {

#ifdef AMSerialDebug

NSLog(@"Error %d when setting up add notifications!", kernResult);

#endif

} else {

while (IOIteratorNext(unused)) {} // arm the notification

}

if (classesToMatch2) {

// Set up notification for ports being removed.

kernResult = IOServiceAddMatchingNotification(notificationPort, kIOTerminatedNotification, classesToMatch2, AMSerialPortWasRemovedNotification, NULL, &unused); // consumes a reference to classesToMatch2

if (kernResult != KERN_SUCCESS) {

#ifdef AMSerialDebug

NSLog(@"Error %d when setting up add notifications!", kernResult);

#endif

} else {

while (IOIteratorNext(unused)) {} // arm the notification

}

}

} else {

#ifdef AMSerialDebug

NSLog(@"IOServiceMatching returned a NULL dictionary.");

#endif

}

}

// Note that IONotificationPortDestroy(notificationPort) is deliberately not called here because if it were our port change notifications would never fire. This minor leak is pretty irrelevant since this object is a singleton that lives for the life of the application anyway.

}

}

- (void)addAllSerialPortsToArray:(NSMutableArray *)array

{

kern_return_t kernResult;

CFMutableDictionaryRef classesToMatch;

io_iterator_t serialPortIterator;

AMSerialPort* serialPort;

// Serial devices are instances of class IOSerialBSDClient

classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue);

if (classesToMatch != NULL) {

CFDictionarySetValue(classesToMatch, CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));

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

kernResult = IOServiceGetMatchingServices(kIOMasterPortDefault, classesToMatch, &serialPortIterator);

if (kernResult == KERN_SUCCESS) {

while ((serialPort = [self getNextSerialPort:serialPortIterator]) != nil) {

[array addObject:serialPort];

}

(void)IOObjectRelease(serialPortIterator);

} else {

#ifdef AMSerialDebug

NSLog(@"IOServiceGetMatchingServices returned %d", kernResult);

#endif

}

} else {

#ifdef AMSerialDebug

NSLog(@"IOServiceMatching returned a NULL dictionary.");

#endif

}

}

- (instancetype)init

{

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

_portList = [[NSMutableArray alloc] init];

[self addAllSerialPortsToArray:_portList];

[self registerForSerialPortChangeNotifications];

}

return self;

}

- (NSUInteger)count

{

return [_portList count];

}

- (AMSerialPort *)objectAtIndex:(NSUInteger)idx

{

return [_portList objectAtIndex:idx];

}

- (AMSerialPort *)objectWithName:(NSString *)name

{

AMSerialPort *result = nil;

NSEnumerator *enumerator = [_portList objectEnumerator];

AMSerialPort *port;

while ((port = [enumerator nextObject]) != nil) {

if ([[port name] isEqualToString:name]) {

result = port;

break;

}

}

return result;

}

- (NSArray *)serialPorts

{

NSArray *ports = [_portList copy];

#if !__has_feature(objc_arc)

[ports autorelease];

#endif

return ports;

}

- (NSArray *)serialPortsOfType:(NSString *)serialTypeKey

{

NSMutableArray *result = [NSMutableArray array];

NSEnumerator *enumerator = [_portList objectEnumerator];

AMSerialPort *port;

while ((port = [enumerator nextObject]) != nil) {

if ([[port type] isEqualToString:serialTypeKey]) {

[result addObject:port];

}

}

return result;

}

@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