hid.m 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 2021 Valve Corporation
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "../../SDL_internal.h"
  19. #ifdef SDL_JOYSTICK_HIDAPI
  20. #include <CoreBluetooth/CoreBluetooth.h>
  21. #include <QuartzCore/QuartzCore.h>
  22. #import <UIKit/UIKit.h>
  23. #import <mach/mach_time.h>
  24. #include <pthread.h>
  25. #include <sys/time.h>
  26. #include <unistd.h>
  27. #include "../hidapi/hidapi.h"
  28. #define VALVE_USB_VID 0x28DE
  29. #define D0G_BLE2_PID 0x1106
  30. typedef uint32_t uint32;
  31. typedef uint64_t uint64;
  32. // enables detailed NSLog logging of feature reports
  33. #define FEATURE_REPORT_LOGGING 0
  34. #define REPORT_SEGMENT_DATA_FLAG 0x80
  35. #define REPORT_SEGMENT_LAST_FLAG 0x40
  36. #define VALVE_SERVICE @"100F6C32-1735-4313-B402-38567131E5F3"
  37. // (READ/NOTIFICATIONS)
  38. #define VALVE_INPUT_CHAR @"100F6C33-1735-4313-B402-38567131E5F3"
  39. //  (READ/WRITE)
  40. #define VALVE_REPORT_CHAR @"100F6C34-1735-4313-B402-38567131E5F3"
  41. // TODO: create CBUUID's in __attribute__((constructor)) rather than doing [CBUUID UUIDWithString:...] everywhere
  42. #pragma pack(push,1)
  43. typedef struct
  44. {
  45. uint8_t segmentHeader;
  46. uint8_t featureReportMessageID;
  47. uint8_t length;
  48. uint8_t settingIdentifier;
  49. union {
  50. uint16_t usPayload;
  51. uint32_t uPayload;
  52. uint64_t ulPayload;
  53. uint8_t ucPayload[15];
  54. };
  55. } bluetoothSegment;
  56. typedef struct {
  57. uint8_t id;
  58. union {
  59. bluetoothSegment segment;
  60. struct {
  61. uint8_t segmentHeader;
  62. uint8_t featureReportMessageID;
  63. uint8_t length;
  64. uint8_t settingIdentifier;
  65. union {
  66. uint16_t usPayload;
  67. uint32_t uPayload;
  68. uint64_t ulPayload;
  69. uint8_t ucPayload[15];
  70. };
  71. };
  72. };
  73. } hidFeatureReport;
  74. #pragma pack(pop)
  75. size_t GetBluetoothSegmentSize(bluetoothSegment *segment)
  76. {
  77. return segment->length + 3;
  78. }
  79. #define RingBuffer_cbElem 19
  80. #define RingBuffer_nElem 4096
  81. typedef struct {
  82. int _first, _last;
  83. uint8_t _data[ ( RingBuffer_nElem * RingBuffer_cbElem ) ];
  84. pthread_mutex_t accessLock;
  85. } RingBuffer;
  86. static void RingBuffer_init( RingBuffer *this )
  87. {
  88. this->_first = -1;
  89. this->_last = 0;
  90. pthread_mutex_init( &this->accessLock, 0 );
  91. }
  92. static bool RingBuffer_write( RingBuffer *this, const uint8_t *src )
  93. {
  94. pthread_mutex_lock( &this->accessLock );
  95. memcpy( &this->_data[ this->_last ], src, RingBuffer_cbElem );
  96. if ( this->_first == -1 )
  97. {
  98. this->_first = this->_last;
  99. }
  100. this->_last = ( this->_last + RingBuffer_cbElem ) % (RingBuffer_nElem * RingBuffer_cbElem);
  101. if ( this->_last == this->_first )
  102. {
  103. this->_first = ( this->_first + RingBuffer_cbElem ) % (RingBuffer_nElem * RingBuffer_cbElem);
  104. pthread_mutex_unlock( &this->accessLock );
  105. return false;
  106. }
  107. pthread_mutex_unlock( &this->accessLock );
  108. return true;
  109. }
  110. static bool RingBuffer_read( RingBuffer *this, uint8_t *dst )
  111. {
  112. pthread_mutex_lock( &this->accessLock );
  113. if ( this->_first == -1 )
  114. {
  115. pthread_mutex_unlock( &this->accessLock );
  116. return false;
  117. }
  118. memcpy( dst, &this->_data[ this->_first ], RingBuffer_cbElem );
  119. this->_first = ( this->_first + RingBuffer_cbElem ) % (RingBuffer_nElem * RingBuffer_cbElem);
  120. if ( this->_first == this->_last )
  121. {
  122. this->_first = -1;
  123. }
  124. pthread_mutex_unlock( &this->accessLock );
  125. return true;
  126. }
  127. #pragma mark HIDBLEDevice Definition
  128. typedef enum
  129. {
  130. BLEDeviceWaitState_None,
  131. BLEDeviceWaitState_Waiting,
  132. BLEDeviceWaitState_Complete,
  133. BLEDeviceWaitState_Error
  134. } BLEDeviceWaitState;
  135. @interface HIDBLEDevice : NSObject <CBPeripheralDelegate>
  136. {
  137. RingBuffer _inputReports;
  138. uint8_t _featureReport[20];
  139. BLEDeviceWaitState _waitStateForReadFeatureReport;
  140. BLEDeviceWaitState _waitStateForWriteFeatureReport;
  141. }
  142. @property (nonatomic, readwrite) bool connected;
  143. @property (nonatomic, readwrite) bool ready;
  144. @property (nonatomic, strong) CBPeripheral *bleSteamController;
  145. @property (nonatomic, strong) CBCharacteristic *bleCharacteristicInput;
  146. @property (nonatomic, strong) CBCharacteristic *bleCharacteristicReport;
  147. - (id)initWithPeripheral:(CBPeripheral *)peripheral;
  148. @end
  149. @interface HIDBLEManager : NSObject <CBCentralManagerDelegate>
  150. @property (nonatomic) int nPendingScans;
  151. @property (nonatomic) int nPendingPairs;
  152. @property (nonatomic, strong) CBCentralManager *centralManager;
  153. @property (nonatomic, strong) NSMapTable<CBPeripheral *, HIDBLEDevice *> *deviceMap;
  154. @property (nonatomic, retain) dispatch_queue_t bleSerialQueue;
  155. + (instancetype)sharedInstance;
  156. - (void)startScan:(int)duration;
  157. - (void)stopScan;
  158. - (int)updateConnectedSteamControllers:(BOOL) bForce;
  159. - (void)appWillResignActiveNotification:(NSNotification *)note;
  160. - (void)appDidBecomeActiveNotification:(NSNotification *)note;
  161. @end
  162. // singleton class - access using HIDBLEManager.sharedInstance
  163. @implementation HIDBLEManager
  164. + (instancetype)sharedInstance
  165. {
  166. static HIDBLEManager *sharedInstance = nil;
  167. static dispatch_once_t onceToken;
  168. dispatch_once(&onceToken, ^{
  169. sharedInstance = [HIDBLEManager new];
  170. sharedInstance.nPendingScans = 0;
  171. sharedInstance.nPendingPairs = 0;
  172. [[NSNotificationCenter defaultCenter] addObserver:sharedInstance selector:@selector(appWillResignActiveNotification:) name: UIApplicationWillResignActiveNotification object:nil];
  173. [[NSNotificationCenter defaultCenter] addObserver:sharedInstance selector:@selector(appDidBecomeActiveNotification:) name:UIApplicationDidBecomeActiveNotification object:nil];
  174. // receive reports on a high-priority serial-queue. optionally put writes on the serial queue to avoid logical
  175. // race conditions talking to the controller from multiple threads, although BLE fragmentation/assembly means
  176. // that we can still screw this up.
  177. // most importantly we need to consume reports at a high priority to avoid the OS thinking we aren't really
  178. // listening to the BLE device, as iOS on slower devices may stop delivery of packets to the app WITHOUT ACTUALLY
  179. // DISCONNECTING FROM THE DEVICE if we don't react quickly enough to their delivery.
  180. // see also the error-handling states in the peripheral delegate to re-open the device if it gets closed
  181. sharedInstance.bleSerialQueue = dispatch_queue_create( "com.valvesoftware.steamcontroller.ble", DISPATCH_QUEUE_SERIAL );
  182. dispatch_set_target_queue( sharedInstance.bleSerialQueue, dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_HIGH, 0 ) );
  183. // creating a CBCentralManager will always trigger a future centralManagerDidUpdateState:
  184. // where any scanning gets started or connecting to existing peripherals happens, it's never already in a
  185. // powered-on state for a newly launched application.
  186. sharedInstance.centralManager = [[CBCentralManager alloc] initWithDelegate:sharedInstance queue:sharedInstance.bleSerialQueue];
  187. sharedInstance.deviceMap = [[NSMapTable alloc] initWithKeyOptions:NSMapTableWeakMemory valueOptions:NSMapTableStrongMemory capacity:4];
  188. });
  189. return sharedInstance;
  190. }
  191. // called for NSNotification UIApplicationWillResignActiveNotification
  192. - (void)appWillResignActiveNotification:(NSNotification *)note
  193. {
  194. // we'll get resign-active notification if pairing is happening.
  195. if ( self.nPendingPairs > 0 )
  196. return;
  197. for ( CBPeripheral *peripheral in self.deviceMap )
  198. {
  199. HIDBLEDevice *steamController = [self.deviceMap objectForKey:peripheral];
  200. if ( steamController )
  201. {
  202. steamController.connected = NO;
  203. steamController.ready = NO;
  204. [self.centralManager cancelPeripheralConnection:peripheral];
  205. }
  206. }
  207. [self.deviceMap removeAllObjects];
  208. }
  209. // called for NSNotification UIApplicationDidBecomeActiveNotification
  210. // whenever the application comes back from being inactive, trigger a 20s pairing scan and reconnect
  211. // any devices that may have paired while we were inactive.
  212. - (void)appDidBecomeActiveNotification:(NSNotification *)note
  213. {
  214. [self updateConnectedSteamControllers:true];
  215. [self startScan:20];
  216. }
  217. - (int)updateConnectedSteamControllers:(BOOL) bForce
  218. {
  219. static uint64_t s_unLastUpdateTick = 0;
  220. static mach_timebase_info_data_t s_timebase_info;
  221. if (s_timebase_info.denom == 0)
  222. {
  223. mach_timebase_info( &s_timebase_info );
  224. }
  225. uint64_t ticksNow = mach_approximate_time();
  226. if ( !bForce && ( ( (ticksNow - s_unLastUpdateTick) * s_timebase_info.numer ) / s_timebase_info.denom ) < (5ull * NSEC_PER_SEC) )
  227. return (int)self.deviceMap.count;
  228. // we can see previously connected BLE peripherals but can't connect until the CBCentralManager
  229. // is fully powered up - only do work when we are in that state
  230. if ( self.centralManager.state != CBManagerStatePoweredOn )
  231. return (int)self.deviceMap.count;
  232. // only update our last-check-time if we actually did work, otherwise there can be a long delay during initial power-up
  233. s_unLastUpdateTick = mach_approximate_time();
  234. // if a pair is in-flight, the central manager may still give it back via retrieveConnected... and
  235. // cause the SDL layer to attempt to initialize it while some of its endpoints haven't yet been established
  236. if ( self.nPendingPairs > 0 )
  237. return (int)self.deviceMap.count;
  238. NSArray<CBPeripheral *> *peripherals = [self.centralManager retrieveConnectedPeripheralsWithServices: @[ [CBUUID UUIDWithString:@"180A"]]];
  239. for ( CBPeripheral *peripheral in peripherals )
  240. {
  241. // we already know this peripheral
  242. if ( [self.deviceMap objectForKey: peripheral] != nil )
  243. continue;
  244. NSLog( @"connected peripheral: %@", peripheral );
  245. if ( [peripheral.name isEqualToString:@"SteamController"] )
  246. {
  247. self.nPendingPairs += 1;
  248. HIDBLEDevice *steamController = [[HIDBLEDevice alloc] initWithPeripheral:peripheral];
  249. [self.deviceMap setObject:steamController forKey:peripheral];
  250. [self.centralManager connectPeripheral:peripheral options:nil];
  251. }
  252. }
  253. return (int)self.deviceMap.count;
  254. }
  255. // manual API for folks to start & stop scanning
  256. - (void)startScan:(int)duration
  257. {
  258. NSLog( @"BLE: requesting scan for %d seconds", duration );
  259. @synchronized (self)
  260. {
  261. if ( _nPendingScans++ == 0 )
  262. {
  263. [self.centralManager scanForPeripheralsWithServices:nil options:nil];
  264. }
  265. }
  266. if ( duration != 0 )
  267. {
  268. dispatch_after( dispatch_time( DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  269. [self stopScan];
  270. });
  271. }
  272. }
  273. - (void)stopScan
  274. {
  275. NSLog( @"BLE: stopping scan" );
  276. @synchronized (self)
  277. {
  278. if ( --_nPendingScans <= 0 )
  279. {
  280. _nPendingScans = 0;
  281. [self.centralManager stopScan];
  282. }
  283. }
  284. }
  285. #pragma mark CBCentralManagerDelegate Implementation
  286. // called whenever the BLE hardware state changes.
  287. - (void)centralManagerDidUpdateState:(CBCentralManager *)central
  288. {
  289. switch ( central.state )
  290. {
  291. case CBCentralManagerStatePoweredOn:
  292. {
  293. NSLog( @"CoreBluetooth BLE hardware is powered on and ready" );
  294. // at startup, if we have no already attached peripherals, do a 20s scan for new unpaired devices,
  295. // otherwise callers should occaisionally do additional scans. we don't want to continuously be
  296. // scanning because it drains battery, causes other nearby people to have a hard time pairing their
  297. // Steam Controllers, and may also trigger firmware weirdness when a device attempts to start
  298. // the pairing sequence multiple times concurrently
  299. if ( [self updateConnectedSteamControllers:false] == 0 )
  300. {
  301. // TODO: we could limit our scan to only peripherals supporting the SteamController service, but
  302. // that service doesn't currently fit in the base advertising packet, we'd need to put it into an
  303. // extended scan packet. Useful optimization downstream, but not currently necessary
  304. // NSArray *services = @[[CBUUID UUIDWithString:VALVE_SERVICE]];
  305. [self startScan:20];
  306. }
  307. break;
  308. }
  309. case CBCentralManagerStatePoweredOff:
  310. NSLog( @"CoreBluetooth BLE hardware is powered off" );
  311. break;
  312. case CBCentralManagerStateUnauthorized:
  313. NSLog( @"CoreBluetooth BLE state is unauthorized" );
  314. break;
  315. case CBCentralManagerStateUnknown:
  316. NSLog( @"CoreBluetooth BLE state is unknown" );
  317. break;
  318. case CBCentralManagerStateUnsupported:
  319. NSLog( @"CoreBluetooth BLE hardware is unsupported on this platform" );
  320. break;
  321. case CBCentralManagerStateResetting:
  322. NSLog( @"CoreBluetooth BLE manager is resetting" );
  323. break;
  324. }
  325. }
  326. - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
  327. {
  328. HIDBLEDevice *steamController = [_deviceMap objectForKey:peripheral];
  329. steamController.connected = YES;
  330. self.nPendingPairs -= 1;
  331. }
  332. - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
  333. {
  334. NSLog( @"Failed to connect: %@", error );
  335. [_deviceMap removeObjectForKey:peripheral];
  336. self.nPendingPairs -= 1;
  337. }
  338. - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
  339. {
  340. NSString *localName = [advertisementData objectForKey:CBAdvertisementDataLocalNameKey];
  341. NSString *log = [NSString stringWithFormat:@"Found '%@'", localName];
  342. if ( [localName isEqualToString:@"SteamController"] )
  343. {
  344. NSLog( @"%@ : %@ - %@", log, peripheral, advertisementData );
  345. self.nPendingPairs += 1;
  346. HIDBLEDevice *steamController = [[HIDBLEDevice alloc] initWithPeripheral:peripheral];
  347. [self.deviceMap setObject:steamController forKey:peripheral];
  348. [self.centralManager connectPeripheral:peripheral options:nil];
  349. }
  350. }
  351. - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
  352. {
  353. HIDBLEDevice *steamController = [self.deviceMap objectForKey:peripheral];
  354. if ( steamController )
  355. {
  356. steamController.connected = NO;
  357. steamController.ready = NO;
  358. [self.deviceMap removeObjectForKey:peripheral];
  359. }
  360. }
  361. @end
  362. // Core Bluetooth devices calling back on event boundaries of their run-loops. so annoying.
  363. static void process_pending_events()
  364. {
  365. CFRunLoopRunResult res;
  366. do
  367. {
  368. res = CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0.001, FALSE );
  369. }
  370. while( res != kCFRunLoopRunFinished && res != kCFRunLoopRunTimedOut );
  371. }
  372. @implementation HIDBLEDevice
  373. - (id)init
  374. {
  375. if ( self = [super init] )
  376. {
  377. RingBuffer_init( &_inputReports );
  378. self.bleSteamController = nil;
  379. self.bleCharacteristicInput = nil;
  380. self.bleCharacteristicReport = nil;
  381. _connected = NO;
  382. _ready = NO;
  383. }
  384. return self;
  385. }
  386. - (id)initWithPeripheral:(CBPeripheral *)peripheral
  387. {
  388. if ( self = [super init] )
  389. {
  390. RingBuffer_init( &_inputReports );
  391. _connected = NO;
  392. _ready = NO;
  393. self.bleSteamController = peripheral;
  394. if ( peripheral )
  395. {
  396. peripheral.delegate = self;
  397. }
  398. self.bleCharacteristicInput = nil;
  399. self.bleCharacteristicReport = nil;
  400. }
  401. return self;
  402. }
  403. - (void)setConnected:(bool)connected
  404. {
  405. _connected = connected;
  406. if ( _connected )
  407. {
  408. [_bleSteamController discoverServices:nil];
  409. }
  410. else
  411. {
  412. NSLog( @"Disconnected" );
  413. }
  414. }
  415. - (size_t)read_input_report:(uint8_t *)dst
  416. {
  417. if ( RingBuffer_read( &_inputReports, dst+1 ) )
  418. {
  419. *dst = 0x03;
  420. return 20;
  421. }
  422. return 0;
  423. }
  424. - (int)send_report:(const uint8_t *)data length:(size_t)length
  425. {
  426. [_bleSteamController writeValue:[NSData dataWithBytes:data length:length] forCharacteristic:_bleCharacteristicReport type:CBCharacteristicWriteWithResponse];
  427. return (int)length;
  428. }
  429. - (int)send_feature_report:(hidFeatureReport *)report
  430. {
  431. #if FEATURE_REPORT_LOGGING
  432. uint8_t *reportBytes = (uint8_t *)report;
  433. NSLog( @"HIDBLE:send_feature_report (%02zu/19) [%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x]", GetBluetoothSegmentSize( report->segment ),
  434. reportBytes[1], reportBytes[2], reportBytes[3], reportBytes[4], reportBytes[5], reportBytes[6],
  435. reportBytes[7], reportBytes[8], reportBytes[9], reportBytes[10], reportBytes[11], reportBytes[12],
  436. reportBytes[13], reportBytes[14], reportBytes[15], reportBytes[16], reportBytes[17], reportBytes[18],
  437. reportBytes[19] );
  438. #endif
  439. int sendSize = (int)GetBluetoothSegmentSize( &report->segment );
  440. if ( sendSize > 20 )
  441. sendSize = 20;
  442. #if 1
  443. // fire-and-forget - we are going to not wait for the response here because all Steam Controller BLE send_feature_report's are ignored,
  444. // except errors.
  445. [_bleSteamController writeValue:[NSData dataWithBytes:&report->segment length:sendSize] forCharacteristic:_bleCharacteristicReport type:CBCharacteristicWriteWithResponse];
  446. // pretend we received a result anybody cares about
  447. return 19;
  448. #else
  449. // this is technically the correct send_feature_report logic if you want to make sure it gets through and is
  450. // acknowledged or errors out
  451. _waitStateForWriteFeatureReport = BLEDeviceWaitState_Waiting;
  452. [_bleSteamController writeValue:[NSData dataWithBytes:&report->segment length:sendSize
  453. ] forCharacteristic:_bleCharacteristicReport type:CBCharacteristicWriteWithResponse];
  454. while ( _waitStateForWriteFeatureReport == BLEDeviceWaitState_Waiting )
  455. {
  456. process_pending_events();
  457. }
  458. if ( _waitStateForWriteFeatureReport == BLEDeviceWaitState_Error )
  459. {
  460. _waitStateForWriteFeatureReport = BLEDeviceWaitState_None;
  461. return -1;
  462. }
  463. _waitStateForWriteFeatureReport = BLEDeviceWaitState_None;
  464. return 19;
  465. #endif
  466. }
  467. - (int)get_feature_report:(uint8_t)feature into:(uint8_t *)buffer
  468. {
  469. _waitStateForReadFeatureReport = BLEDeviceWaitState_Waiting;
  470. [_bleSteamController readValueForCharacteristic:_bleCharacteristicReport];
  471. while ( _waitStateForReadFeatureReport == BLEDeviceWaitState_Waiting )
  472. process_pending_events();
  473. if ( _waitStateForReadFeatureReport == BLEDeviceWaitState_Error )
  474. {
  475. _waitStateForReadFeatureReport = BLEDeviceWaitState_None;
  476. return -1;
  477. }
  478. memcpy( buffer, _featureReport, sizeof(_featureReport) );
  479. _waitStateForReadFeatureReport = BLEDeviceWaitState_None;
  480. #if FEATURE_REPORT_LOGGING
  481. NSLog( @"HIDBLE:get_feature_report (19) [%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x]",
  482. buffer[1], buffer[2], buffer[3], buffer[4], buffer[5], buffer[6],
  483. buffer[7], buffer[8], buffer[9], buffer[10], buffer[11], buffer[12],
  484. buffer[13], buffer[14], buffer[15], buffer[16], buffer[17], buffer[18],
  485. buffer[19] );
  486. #endif
  487. return 19;
  488. }
  489. #pragma mark CBPeripheralDelegate Implementation
  490. - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
  491. {
  492. for (CBService *service in peripheral.services)
  493. {
  494. NSLog( @"Found Service: %@", service );
  495. if ( [service.UUID isEqual:[CBUUID UUIDWithString:VALVE_SERVICE]] )
  496. {
  497. [peripheral discoverCharacteristics:nil forService:service];
  498. }
  499. }
  500. }
  501. - (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
  502. {
  503. // nothing yet needed here, enable for logging
  504. if ( /* DISABLES CODE */ (0) )
  505. {
  506. for ( CBDescriptor *descriptor in characteristic.descriptors )
  507. {
  508. NSLog( @" - Descriptor '%@'", descriptor );
  509. }
  510. }
  511. }
  512. - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
  513. {
  514. if ([service.UUID isEqual:[CBUUID UUIDWithString:VALVE_SERVICE]])
  515. {
  516. for (CBCharacteristic *aChar in service.characteristics)
  517. {
  518. NSLog( @"Found Characteristic %@", aChar );
  519. if ( [aChar.UUID isEqual:[CBUUID UUIDWithString:VALVE_INPUT_CHAR]] )
  520. {
  521. self.bleCharacteristicInput = aChar;
  522. }
  523. else if ( [aChar.UUID isEqual:[CBUUID UUIDWithString:VALVE_REPORT_CHAR]] )
  524. {
  525. self.bleCharacteristicReport = aChar;
  526. [self.bleSteamController discoverDescriptorsForCharacteristic: aChar];
  527. }
  528. }
  529. }
  530. }
  531. - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
  532. {
  533. static uint64_t s_ticksLastOverflowReport = 0;
  534. // receiving an input report is the final indicator that the user accepted a pairing
  535. // request and that we successfully established notification. CoreBluetooth has no
  536. // notification of the pairing acknowledgement, which is a bad oversight.
  537. if ( self.ready == NO )
  538. {
  539. self.ready = YES;
  540. HIDBLEManager.sharedInstance.nPendingPairs -= 1;
  541. }
  542. if ( [characteristic.UUID isEqual:_bleCharacteristicInput.UUID] )
  543. {
  544. NSData *data = [characteristic value];
  545. if ( data.length != 19 )
  546. {
  547. NSLog( @"HIDBLE: incoming data is %lu bytes should be exactly 19", (unsigned long)data.length );
  548. }
  549. if ( !RingBuffer_write( &_inputReports, (const uint8_t *)data.bytes ) )
  550. {
  551. uint64_t ticksNow = mach_approximate_time();
  552. if ( ticksNow - s_ticksLastOverflowReport > (5ull * NSEC_PER_SEC / 10) )
  553. {
  554. NSLog( @"HIDBLE: input report buffer overflow" );
  555. s_ticksLastOverflowReport = ticksNow;
  556. }
  557. }
  558. }
  559. else if ( [characteristic.UUID isEqual:_bleCharacteristicReport.UUID] )
  560. {
  561. memset( _featureReport, 0, sizeof(_featureReport) );
  562. if ( error != nil )
  563. {
  564. NSLog( @"HIDBLE: get_feature_report error: %@", error );
  565. _waitStateForReadFeatureReport = BLEDeviceWaitState_Error;
  566. }
  567. else
  568. {
  569. NSData *data = [characteristic value];
  570. if ( data.length != 20 )
  571. {
  572. NSLog( @"HIDBLE: incoming data is %lu bytes should be exactly 20", (unsigned long)data.length );
  573. }
  574. memcpy( _featureReport, data.bytes, MIN( data.length, sizeof(_featureReport) ) );
  575. _waitStateForReadFeatureReport = BLEDeviceWaitState_Complete;
  576. }
  577. }
  578. }
  579. - (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
  580. {
  581. if ( [characteristic.UUID isEqual:[CBUUID UUIDWithString:VALVE_REPORT_CHAR]] )
  582. {
  583. if ( error != nil )
  584. {
  585. NSLog( @"HIDBLE: write_feature_report error: %@", error );
  586. _waitStateForWriteFeatureReport = BLEDeviceWaitState_Error;
  587. }
  588. else
  589. {
  590. _waitStateForWriteFeatureReport = BLEDeviceWaitState_Complete;
  591. }
  592. }
  593. }
  594. - (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
  595. {
  596. NSLog( @"didUpdateNotifcationStateForCharacteristic %@ (%@)", characteristic, error );
  597. }
  598. @end
  599. #pragma mark hid_api implementation
  600. struct hid_device_ {
  601. void *device_handle;
  602. int blocking;
  603. hid_device *next;
  604. };
  605. int HID_API_EXPORT HID_API_CALL hid_init(void)
  606. {
  607. return ( HIDBLEManager.sharedInstance == nil ) ? -1 : 0;
  608. }
  609. int HID_API_EXPORT HID_API_CALL hid_exit(void)
  610. {
  611. return 0;
  612. }
  613. void HID_API_EXPORT HID_API_CALL hid_ble_scan( bool bStart )
  614. {
  615. HIDBLEManager *bleManager = HIDBLEManager.sharedInstance;
  616. if ( bStart )
  617. {
  618. [bleManager startScan:0];
  619. }
  620. else
  621. {
  622. [bleManager stopScan];
  623. }
  624. }
  625. hid_device * HID_API_EXPORT hid_open_path( const char *path, int bExclusive /* = false */ )
  626. {
  627. hid_device *result = NULL;
  628. NSString *nssPath = [NSString stringWithUTF8String:path];
  629. HIDBLEManager *bleManager = HIDBLEManager.sharedInstance;
  630. NSEnumerator<HIDBLEDevice *> *devices = [bleManager.deviceMap objectEnumerator];
  631. for ( HIDBLEDevice *device in devices )
  632. {
  633. // we have the device but it hasn't found its service or characteristics until it is connected
  634. if ( !device.ready || !device.connected || !device.bleCharacteristicInput )
  635. continue;
  636. if ( [device.bleSteamController.identifier.UUIDString isEqualToString:nssPath] )
  637. {
  638. result = (hid_device *)malloc( sizeof( hid_device ) );
  639. memset( result, 0, sizeof( hid_device ) );
  640. result->device_handle = (void*)CFBridgingRetain( device );
  641. result->blocking = NO;
  642. // enable reporting input events on the characteristic
  643. [device.bleSteamController setNotifyValue:YES forCharacteristic:device.bleCharacteristicInput];
  644. return result;
  645. }
  646. }
  647. return result;
  648. }
  649. void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs)
  650. {
  651. /* This function is identical to the Linux version. Platform independent. */
  652. struct hid_device_info *d = devs;
  653. while (d) {
  654. struct hid_device_info *next = d->next;
  655. free(d->path);
  656. free(d->serial_number);
  657. free(d->manufacturer_string);
  658. free(d->product_string);
  659. free(d);
  660. d = next;
  661. }
  662. }
  663. int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock)
  664. {
  665. /* All Nonblocking operation is handled by the library. */
  666. dev->blocking = !nonblock;
  667. return 0;
  668. }
  669. struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)
  670. { @autoreleasepool {
  671. struct hid_device_info *root = NULL;
  672. if ( ( vendor_id == 0 && product_id == 0 ) ||
  673. ( vendor_id == VALVE_USB_VID && product_id == D0G_BLE2_PID ) )
  674. {
  675. HIDBLEManager *bleManager = HIDBLEManager.sharedInstance;
  676. [bleManager updateConnectedSteamControllers:false];
  677. NSEnumerator<HIDBLEDevice *> *devices = [bleManager.deviceMap objectEnumerator];
  678. for ( HIDBLEDevice *device in devices )
  679. {
  680. // there are several brief windows in connecting to an already paired device and
  681. // one long window waiting for users to confirm pairing where we don't want
  682. // to consider a device ready - if we hand it back to SDL or another
  683. // Steam Controller consumer, their additional SC setup work will fail
  684. // in unusual/silent ways and we can actually corrupt the BLE stack for
  685. // the entire system and kill the appletv remote's Menu button (!)
  686. if ( device.bleSteamController.state != CBPeripheralStateConnected ||
  687. device.connected == NO || device.ready == NO )
  688. {
  689. if ( device.ready == NO && device.bleCharacteristicInput != nil )
  690. {
  691. // attempt to register for input reports. this call will silently fail
  692. // until the pairing finalizes with user acceptance. oh, apple.
  693. [device.bleSteamController setNotifyValue:YES forCharacteristic:device.bleCharacteristicInput];
  694. }
  695. continue;
  696. }
  697. struct hid_device_info *device_info = (struct hid_device_info *)malloc( sizeof(struct hid_device_info) );
  698. memset( device_info, 0, sizeof(struct hid_device_info) );
  699. device_info->next = root;
  700. root = device_info;
  701. device_info->path = strdup( device.bleSteamController.identifier.UUIDString.UTF8String );
  702. device_info->vendor_id = VALVE_USB_VID;
  703. device_info->product_id = D0G_BLE2_PID;
  704. device_info->product_string = wcsdup( L"Steam Controller" );
  705. device_info->manufacturer_string = wcsdup( L"Valve Corporation" );
  706. }
  707. }
  708. return root;
  709. }}
  710. int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)
  711. {
  712. static wchar_t s_wszManufacturer[] = L"Valve Corporation";
  713. wcsncpy( string, s_wszManufacturer, sizeof(s_wszManufacturer)/sizeof(s_wszManufacturer[0]) );
  714. return 0;
  715. }
  716. int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
  717. {
  718. static wchar_t s_wszProduct[] = L"Steam Controller";
  719. wcsncpy( string, s_wszProduct, sizeof(s_wszProduct)/sizeof(s_wszProduct[0]) );
  720. return 0;
  721. }
  722. int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
  723. {
  724. static wchar_t s_wszSerial[] = L"12345";
  725. wcsncpy( string, s_wszSerial, sizeof(s_wszSerial)/sizeof(s_wszSerial[0]) );
  726. return 0;
  727. }
  728. int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length)
  729. {
  730. HIDBLEDevice *device_handle = (__bridge HIDBLEDevice *)dev->device_handle;
  731. if ( !device_handle.connected )
  732. return -1;
  733. return [device_handle send_report:data length:length];
  734. }
  735. void HID_API_EXPORT hid_close(hid_device *dev)
  736. {
  737. HIDBLEDevice *device_handle = CFBridgingRelease( dev->device_handle );
  738. // disable reporting input events on the characteristic
  739. if ( device_handle.connected ) {
  740. [device_handle.bleSteamController setNotifyValue:NO forCharacteristic:device_handle.bleCharacteristicInput];
  741. }
  742. free( dev );
  743. }
  744. int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
  745. {
  746. HIDBLEDevice *device_handle = (__bridge HIDBLEDevice *)dev->device_handle;
  747. if ( !device_handle.connected )
  748. return -1;
  749. return [device_handle send_feature_report:(hidFeatureReport *)(void *)data];
  750. }
  751. int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
  752. {
  753. HIDBLEDevice *device_handle = (__bridge HIDBLEDevice *)dev->device_handle;
  754. if ( !device_handle.connected )
  755. return -1;
  756. size_t written = [device_handle get_feature_report:data[0] into:data];
  757. return written == length-1 ? (int)length : (int)written;
  758. }
  759. int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)
  760. {
  761. HIDBLEDevice *device_handle = (__bridge HIDBLEDevice *)dev->device_handle;
  762. if ( !device_handle.connected )
  763. return -1;
  764. return hid_read_timeout(dev, data, length, 0);
  765. }
  766. int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
  767. {
  768. HIDBLEDevice *device_handle = (__bridge HIDBLEDevice *)dev->device_handle;
  769. if ( !device_handle.connected )
  770. return -1;
  771. if ( milliseconds != 0 )
  772. {
  773. NSLog( @"hid_read_timeout with non-zero wait" );
  774. }
  775. int result = (int)[device_handle read_input_report:data];
  776. #if FEATURE_REPORT_LOGGING
  777. NSLog( @"HIDBLE:hid_read_timeout (%d) [%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x]", result,
  778. data[1], data[2], data[3], data[4], data[5], data[6],
  779. data[7], data[8], data[9], data[10], data[11], data[12],
  780. data[13], data[14], data[15], data[16], data[17], data[18],
  781. data[19] );
  782. #endif
  783. return result;
  784. }
  785. #endif /* SDL_JOYSTICK_HIDAPI */