-
Notifications
You must be signed in to change notification settings - Fork 0
/
AMSerialPortList.m
357 lines (303 loc) · 10.9 KB
/
AMSerialPortList.m
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
//
// AMSerialPortList.m
//
// Created by Andreas on 2002-04-24.
// Copyright (c) 2001-2010 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
#import "AMSDKCompatibility.h"
#import "AMSerialPortList.h"
#import "AMSerialPort.h"
#import "AMStandardEnumerator.h"
#include <termios.h>
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/serial/IOSerialKeys.h>
#include <IOKit/IOBSD.h>
static AMSerialPortList *AMSerialPortListSingleton = nil;
NSString *const AMSerialPortListDidAddPortsNotification = @"AMSerialPortListDidAddPortsNotification";
NSString *const AMSerialPortListDidRemovePortsNotification = @"AMSerialPortListDidRemovePortsNotification";
NSString *const AMSerialPortListAddedPorts = @"AMSerialPortListAddedPorts";
NSString *const AMSerialPortListRemovedPorts = @"AMSerialPortListRemovedPorts";
@implementation AMSerialPortList
+ (AMSerialPortList *)sharedPortList
{
@synchronized(self) {
if (AMSerialPortListSingleton == nil) {
#ifndef __OBJC_GC__
[[self alloc] init]; // assignment not done here
#else
// Singleton creation is easy in the GC case, just create it if it hasn't been created yet,
// it won't get collected since globals are strongly referenced.
AMSerialPortListSingleton = [[self alloc] init];
#endif
}
}
return AMSerialPortListSingleton;
}
#ifndef __OBJC_GC__
+ (id)allocWithZone:(NSZone *)zone
{
id result = nil;
@synchronized(self) {
if (AMSerialPortListSingleton == nil) {
AMSerialPortListSingleton = [super allocWithZone:zone];
result = AMSerialPortListSingleton; // assignment and return on first allocation
//on subsequent allocation attempts return nil
}
}
return result;
}
- (id)copyWithZone:(NSZone *)zone
{
(void)zone;
return self;
}
- (id)retain
{
return self;
}
- (NSUInteger)retainCount
{
return NSUIntegerMax; //denotes an object that cannot be released
}
- (oneway void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
- (void)dealloc
{
[portList release]; portList = nil;
[super dealloc];
}
#endif
+ (NSEnumerator *)portEnumerator
{
return [[[AMStandardEnumerator alloc] initWithCollection:[AMSerialPortList sharedPortList]
countSelector:@selector(count) objectAtIndexSelector:@selector(objectAtIndex:)] autorelease];
}
+ (NSEnumerator *)portEnumeratorForSerialPortsOfType:(NSString *)serialTypeKey
{
return [[[AMStandardEnumerator alloc] initWithCollection:[[AMSerialPortList sharedPortList]
serialPortsOfType:serialTypeKey] countSelector:@selector(count) objectAtIndexSelector:@selector(objectAtIndex:)] autorelease];
}
- (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.
serialPort = [self portByPath:(NSString*)bsdPath];
if (serialPort == nil) {
serialPort = [[[AMSerialPort alloc] init:(NSString*)bsdPath withName:(NSString*)modemName type:(NSString*)serviceType] autorelease];
}
}
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([[NSRunLoop currentRunLoop] getCFRunLoop], 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 irrelevent 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
}
}
- (id)init
{
if ((self = [super init])) {
portList = [[NSMutableArray array] retain];
[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
{
return [[portList copy] autorelease];
}
- (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