-
Notifications
You must be signed in to change notification settings - Fork 3
/
DuoGamerSDK.m
230 lines (186 loc) · 8.1 KB
/
DuoGamerSDK.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
//
//
//
/*
* Copyright (C) 2013 by Matthias Ringwald
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY MATTHIAS RINGWALD AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
* RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
#import "DuoGamerSDK.h"
NSString * duoGamerProtocolString = @"com.discoverybaygames.v2";
NSString * duoGamerName = @"Duo Gamer";
#define SINGLE_PACKET_SIZE 11
@interface NSString (BTstack)
+(NSString*) stringForData:(const uint8_t*) data withSize:(uint16_t) size;
@end
@interface DuoGamer (private)
-(void) openSession:(EAAccessory *) accessor;
- (void)closeSession;
@end
static inline BOOL isBitSet(int data, int bit){
if (data & (1<<bit)) return 1;
return 0;
}
@implementation NSString (BTstatck)
+(NSString*) stringForData:(const uint8_t*) data withSize:(uint16_t) size{
NSMutableString *output = [NSMutableString stringWithCapacity:size * 3];
for(int i = 0; i < size; i++){
[output appendFormat:@"%02x ",data[i]];
}
return output;
}
@end
@implementation DuoGamer
@synthesize accessory;
@synthesize session;
@synthesize delegate;
-(id) init {
self = [super init];
readData = [[NSMutableData alloc] init];
// try to find already connected accessory
NSArray * accessories = [[EAAccessoryManager sharedAccessoryManager] connectedAccessories];
for (EAAccessory * connectedAccessory in accessories){
if (![connectedAccessory.name hasPrefix:duoGamerName]) continue;
[self openSession:connectedAccessory];
}
// register for notifications
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_accessoryDidConnect:) name:EAAccessoryDidConnectNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_accessoryDidDisconnect:) name:EAAccessoryDidDisconnectNotification object:nil];
[[EAAccessoryManager sharedAccessoryManager] registerForLocalNotifications];
return self;
}
-(void) dealloc {
self.delegate = nil;
[self closeSession];
// unregister from notifications
[[EAAccessoryManager sharedAccessoryManager] unregisterForLocalNotifications];
[[NSNotificationCenter defaultCenter] removeObserver:self name:EAAccessoryDidConnectNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:EAAccessoryDidDisconnectNotification object:nil];
[super dealloc];
}
-(void) openSession:(EAAccessory *) connectedAccessory{
if (accessory){
NSLog(@"DuoGamer: already connected");
}
self.accessory = connectedAccessory;
[accessory setDelegate:self];
self.session = [[EASession alloc] initWithAccessory:accessory forProtocol:duoGamerProtocolString];
if (!session) {
NSLog(@"DuoGamer: creating session failed");
self.accessory = nil;
return;
}
[[session inputStream] setDelegate:self];
[[session inputStream] scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[[session inputStream] open];
[[session outputStream] setDelegate:self];
[[session outputStream] scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[[session outputStream] open];
if ([delegate respondsToSelector:@selector(connected)]){
[delegate connected];
}
}
// close the session with the accessory.
- (void)closeSession
{
[[session inputStream] close];
[[session inputStream] removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[[session inputStream] setDelegate:nil];
[[session outputStream] close];
[[session outputStream] removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[[session outputStream] setDelegate:nil];
[session release];
session = nil;
[readData release];
readData = nil;
if ([delegate respondsToSelector:@selector(disconnected)]){
[delegate disconnected];
}
}
- (void)_accessoryDidConnect:(NSNotification *)notification {
EAAccessory *connectedAccessory = [[notification userInfo] objectForKey:EAAccessoryKey];
[self openSession:connectedAccessory];
}
- (void)_accessoryDidDisconnect:(NSNotification *)notification {
EAAccessory *disconnectedAccessory = [[notification userInfo] objectForKey:EAAccessoryKey];
if (accessory.connectionID != disconnectedAccessory.connectionID) return;
self.accessory = nil;
}
-(void)processPacket{
// moving analog joystick may send more packets than usual
while ([readData length] >= SINGLE_PACKET_SIZE) {
uint8_t data[SINGLE_PACKET_SIZE];
// valid fixed data, but ignore xor checksum
[readData getBytes:(void *)data range:NSMakeRange(0, SINGLE_PACKET_SIZE)];
if (data[0] != 0x5a) return;
if (data[1] != 0xa5) return;
if (data[2] != 0x04) return;
if (data[9] != 0x00) return;
DuoGamerState state;
uint8_t buttons_1 = data[3];
uint8_t buttons_2 = data[4];
state.buttonA = isBitSet(buttons_1, 0);
state.buttonB = isBitSet(buttons_1, 1);
state.buttonX = isBitSet(buttons_1, 2);
state.buttonY = isBitSet(buttons_1, 3);
state.analogLeftClick = isBitSet(buttons_1, 5);
state.analogRightClick = isBitSet(buttons_1, 6);
state.shoulderRight = isBitSet(buttons_2, 0);
state.shoulderLeft = isBitSet(buttons_2, 1);
state.dpadUp = isBitSet(buttons_2, 2);
state.dpadRight = isBitSet(buttons_2, 3);
state.dpadDown = isBitSet(buttons_2, 4);
state.dpadLeft = isBitSet(buttons_2, 5);
state.analogLeftX = data[5] - 0x80;
state.analogLeftY = data[6] - 0x80;
state.analogRightX = data[7] - 0x80;
state.analogRightY = data[8] - 0x80;
if (![delegate respondsToSelector:@selector(handleState:)]) return;
[delegate handleState:&state];
[readData replaceBytesInRange:NSMakeRange(0, SINGLE_PACKET_SIZE) withBytes:NULL length:0];
}
}
// asynchronous NSStream handleEvent method
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
if (eventCode != NSStreamEventHasBytesAvailable) return;
#define EAD_INPUT_BUFFER_SIZE 128
uint8_t buf[EAD_INPUT_BUFFER_SIZE];
while ([[session inputStream] hasBytesAvailable])
{
NSInteger bytesRead = [[session inputStream] read:buf maxLength:EAD_INPUT_BUFFER_SIZE];
[readData appendBytes:(void *)buf length:bytesRead];
}
[self processPacket];
// NSLog(@"Read data (%u): %@", [readData length],
// [NSString stringForData:(const uint8_t*)[readData bytes] withSize:[readData length]] )
// reset buffer - assumption: controller packet arrives in a single RFCOMM packet
[readData setLength:0];
}
@end
// vim:ft=objc