Commit b4a32da2 authored by Max Model's avatar Max Model

ios fix

parent 828eb02a
File added
This diff is collapsed.
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1010"
version = "1.3">
<BuildAction
parallelizeBuildables = "NO"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "69CA06021CC43C2900AF6479"
BuildableName = "libRCTBluetoothSerial.a"
BlueprintName = "RCTBluetoothSerial"
ReferencedContainer = "container:RCTBluetoothSerial.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "69CA06021CC43C2900AF6479"
BuildableName = "libRCTBluetoothSerial.a"
BlueprintName = "RCTBluetoothSerial"
ReferencedContainer = "container:RCTBluetoothSerial.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "69CA06021CC43C2900AF6479"
BuildableName = "libRCTBluetoothSerial.a"
BlueprintName = "RCTBluetoothSerial"
ReferencedContainer = "container:RCTBluetoothSerial.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>SchemeUserState</key>
<dict>
<key>RCTBluetoothSerial.xcscheme_^#shared#^_</key>
<dict>
<key>orderHint</key>
<integer>2</integer>
</dict>
</dict>
</dict>
</plist>
/*
Edited by Nuttawut Malee on 10.11.18
Copyright (c) 2013 RedBearLab
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#import <Foundation/Foundation.h>
#if TARGET_OS_IPHONE
#import <CoreBluetooth/CoreBluetooth.h>
#else
#import <IOBluetooth/IOBluetooth.h>
#endif
#import "CBPeripheral+BTSExtensions.h"
typedef void (^CentralManagerDiscoverPeripheralsCallback) (NSMutableArray *peripherals);
/*!
* BLE delegate event to send data
* to delegate class.
*/
@protocol BLEDelegate
@required
/*!
* @method didPowerOn
*
* @discussion Delegate bluetooth enabled.
*
*/
- (void)didPowerOn;
/*!
* @method didPowerOff
*
* @discussion Delegate bluetooth disabled.
*
*/
- (void)didPowerOff;
/*!
* @method didError
*
* @param error The error that will be delegated to delegate class.
*
*/
- (void)didError:(NSError *)error;
/*!
* @method didConnect
*
* @param peripheral The connected peripheral.
*
*/
- (void)didConnect:(CBPeripheral *) peripheral;
/*!
* @method didFailToConnect
*
* @param peripheral The connected peripheral.
*
*/
- (void)didFailToConnect:(CBPeripheral *) peripheral;
/*!
* @method didConnectionLost
*
* @param peripheral The connected peripheral.
*
*/
- (void)didConnectionLost:(CBPeripheral *) peripheral;
/*!
* @method didReceiveData:length:
*
* @param uuid The UUID string of the peripheral.
* @param data The received data from peripheral buffer.
* @param length The length of received data.
*
*/
- (void)didReceiveData:(NSString *)uuid data:(unsigned char *) data length:(NSInteger) length;
@end
/*!
* BLE wrapper class that implement
* common central manager and peripheral instance.
*/
@interface BLE : NSObject <CBCentralManagerDelegate, CBPeripheralDelegate>
/*!
* The delegate object that will receive BLE central events.
*/
@property (nonatomic, assign) id<BLEDelegate> delegate;
/*!
* Core bluetooth's Central manager, for implementing central role.
*/
@property (strong, nonatomic) CBCentralManager *manager;
/*!
* Peripherals that are nearby (sorted descending by RSSI values).
*/
@property (weak, nonatomic, readonly) NSArray *peripherals;
/*!
* List of scanned peripherals.
*/
@property (strong, nonatomic) NSMutableArray *scannedPeripherals;
/*!
* The active peripherals that each has been paired and connected.
*/
@property (nonatomic, copy) NSMutableDictionary *activePeripherals;
/*!
* CBCentralManager's state updated by centralManagerDidUpdateState:
*/
@property(nonatomic) CBCentralManagerState cbCentralManagerState;
/*!
* Threshould to stop scanning for peripherals.
* When the number of discovered peripherals exceeds this value, scanning will be
* stopped even before the scan-interval.
*/
@property (assign, nonatomic) NSUInteger peripheralsCountToStop;
/*!
* Indicates if central manager is ready for core bluetooth tasks. KVO observable.
*/
@property (assign, nonatomic, readonly, getter = isCentralReady) BOOL centralReady;
/*!
* Available BLE services, read and write characteristics.
*/
@property (strong, nonatomic) NSDictionary *bleServices;
/*!
* Completion block for peripheral scanning.
*/
@property (copy, nonatomic) CentralManagerDiscoverPeripheralsCallback scanBlock;
/*!
* KVO for centralReady and centralNotReadyReason
*/
+ (NSSet *)keyPathsForValuesAffectingCentralReady;
+ (NSSet *)keyPathsForValuesAffectingCentralNotReadyReason;
/*!
* @method isConnected
*
* @param uuid
*
* @discussion Indicates selected peripheral connection status.
*
*/
- (BOOL)isConnected:(NSString *)uuid;
/*!
* @method peripheralToDictionary
*
* @param peripheral
*
* @discussion Get NSMutableDictionary info of a peripheral.
*
*/
- (NSMutableDictionary *)peripheralToDictionary:(CBPeripheral *)peripheral;
/*!
* @method readActivePeripheralRSSI
*
* @param uuid CBPeripheral id.
*
* @discussion Retrieves and delegate current RSSI of current
* active peripheral that connected to central manager.
*
*/
- (void)readActivePeripheralRSSI:(NSString *)uuid;
/*!
* @method enableReadNotification
*
* @param peripheral
*
* @discussion Notify peripheral read for a certain characteristic.
*/
- (void)enableReadNotification:(CBPeripheral *)peripheral;
/*!
* @method read
*
* @param uuid Id of one of the active peripherals.
*
* @discussion Read value from active peripheral
* for a certain characteristic.
*/
- (void)read:(NSString *)uuid;
/*!
* @method write
*
* @param uuid Id of one of the active peripherals.
* @param data Data to be written to an active peripheral.
*
* @discussion Write value to active peripheral
* for a certain characteristic.
*
*/
- (void)write:(NSString *)uuid data:(NSData *)data;
/*!
* @method scanForPeripheralsByInterval
*
* @param interval Interval by which scan will be stopped.
* @param callback Completion block will be called after
* <i>interval</i> with nearby peripherals.
*
* @discussion Scans for nearby peripherals
* and fills the - NSArray *peripherals.
* Scan will be stoped after input interaval.
*
*/
- (void)scanForPeripheralsByInterval:(NSUInteger)interval
completion:(CentralManagerDiscoverPeripheralsCallback)callback;
/*!
* @method stopScanForPeripheral
*
* @discussion Stops ongoing scan proccess
*
*/
- (void)stopScanForPeripherals;
/*!
* @method connectToPeripheral
*
* @param peripheral
*
* @discussion Connect to certain peripheral
* and assign activePeripheral to it.
*
*/
- (void)connectToPeripheral:(CBPeripheral *)peripheral;
/*!
* @method disconnectFromPeripheral
*
* @param peripheral
*
*/
- (void)disconnectFromPeripheral:(CBPeripheral *)peripheral;
/*!
* @method centralManagerSetup
*
* @discussion Request bluetooth enable settings.
*
*/
- (void)centralManagerSetup;
/*!
* @method getActivePeripheral
*
* @discussion Get active peripheral from uuid or the first connected one.
*
*/
- (CBPeripheral *)getActivePeripheral:(NSString *)uuid;
/*!
* @method validateServices
*
* @discussion Validate service object to contain certain keys.
*/
- (BOOL)validateServices:(NSArray *)services;
/*!
* @method servicesArrayToDictionary
*
* @discussion Convert services array to dictionary; key is service.
*/
- (NSDictionary *)servicesArrayToDictionary:(NSArray *)services;
/*!
* @method servicesDictionaryToArray
*
* @discussion Convert services dictionary to array.
*/
- (NSArray *)servicesDictionaryToArray:(NSDictionary *)services;
/*!
* @method getDefaultServices
*
* @discussion Get default BLE service array from BLEDefines.h.
*/
- (NSArray *)getDefaultServices;
/*!
* @method includeDefaultServices.
*
* @discussion Include default BLE service array from BLEDefines.h into services array.
*/
- (NSArray *)includeDefaultServices:(NSArray *)services;
@end
This diff is collapsed.
/*
Copyright (c) 2013 RedBearLab
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// BlueGiga Service
#define BLUEGIGA_SERVICE_UUID "1D5688DE-866D-3AA4-EC46-A1BDDB37ECF6"
#define BLUEGIGA_CHAR_TX_UUID "AF20fBAC-2518-4998-9AF7-AF42540731B3"
#define BLUEGIGA_CHAR_RX_UUID "AF20fBAC-2518-4998-9AF7-AF42540731B3"
// RBL Service
#define RBL_SERVICE_UUID "713D0000-503E-4C75-BA94-3148F18D941E"
#define RBL_CHAR_TX_UUID "713D0002-503E-4C75-BA94-3148F18D941E"
#define RBL_CHAR_RX_UUID "713D0003-503E-4C75-BA94-3148F18D941E"
// Adafruit BLE
// http://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout/adding-app-support
// Adafruit | Nordic's TX and RX are the opposite of RBL. This code uses RBL perspective for naming.
#define ADAFRUIT_SERVICE_UUID "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"
#define ADAFRUIT_CHAR_TX_UUID "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
#define ADAFRUIT_CHAR_RX_UUID "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
// Laird Virtual Serial Port (vSP) service for BL600 http://www.lairdtech.com/DownloadAsset.aspx?id=2147489885
#define LAIRD_SERVICE_UUID "569a1101-b87f-490c-92cb-11ba5ea5167c"
#define LAIRD_CHAR_TX_UUID "569a2000-b87f-490c-92cb-11ba5ea5167c"
#define LAIRD_CHAR_RX_UUID "569a2001-b87f-490c-92cb-11ba5ea5167c"
#define RONGTA_SERVICE_UUID "E7810A71-73AE-499D-8C15-FAA9AEF0C3F2"
#define RONGTA_CHAR_TX_UUID "BEF8D6C9-9C21-4C9E-B632-BD58C1009F9F"
#define RONGTA_CHAR_RX_UUID "BEF8D6C9-9C21-4C9E-B632-BD58C1009F9F"
#define POSNET_SERVICE_UUID "53544D54-4552-494F-5345-525631303030"
#define POSNET_CHAR_TX_UUID "53544F55-4152-5449-4E20-205630303031"
#define POSNET_CHAR_RX_UUID "53544F55-4152-5449-4E20-205630303031"
#define RBL_BLE_FRAMEWORK_VER 0x0200
//
// CBPeripheral+BTSExtensions.h
// BluetoothSerial Cordova Plugin
//
// (c) 2103-2015 Don Coleman
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#import <objc/runtime.h>
#import <Foundation/Foundation.h>
#import <CoreBluetooth/CoreBluetooth.h>
@interface CBPeripheral(com_megster_bluetoothserial_extension)
@property (nonatomic, retain) NSString *btsAdvertising;
@property (nonatomic, retain) NSNumber *btsAdvertisementRSSI;
-(void)bts_setAdvertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber*)rssi;
@end
//
// CBPeripheral+BTSExtensions.m
// BluetoothSerial Cordova Plugin
//
// (c) 2103-2015 Don Coleman
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#import "CBPeripheral+BTSExtensions.h"
static char BTS_ADVERTISING_IDENTIFER;
static char BTS_ADVERTISEMENT_RSSI_IDENTIFER;
@implementation CBPeripheral(com_megster_bluetoothserial_extension)
// AdvertisementData and RSSI are from didDiscoverPeripheral.
// Save the manufacturerData so we can pass to Cordova in the peripheral
-(void)bts_setAdvertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)rssi{
if (advertisementData) {
id manufacturerData = [advertisementData objectForKey:CBAdvertisementDataManufacturerDataKey];
if (manufacturerData) {
const uint8_t *bytes = [manufacturerData bytes];
long len = [manufacturerData length];
// skip manufacturer uuid
NSData *data = [NSData dataWithBytes:bytes+2 length:len-2];
[self setBtsAdvertising: [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]];
}
}
[self setBtsAdvertisementRSSI: rssi];
}
-(void)setBtsAdvertising:(NSString *)newAdvertisingValue{
objc_setAssociatedObject(self, &BTS_ADVERTISING_IDENTIFER, newAdvertisingValue, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(NSString*)btsAdvertising{
return objc_getAssociatedObject(self, &BTS_ADVERTISING_IDENTIFER);
}
-(void)setBtsAdvertisementRSSI:(NSNumber *)newAdvertisementRSSIValue {
objc_setAssociatedObject(self, &BTS_ADVERTISEMENT_RSSI_IDENTIFER, newAdvertisementRSSIValue, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(NSString*)btsAdvertisementRSSI{
return objc_getAssociatedObject(self, &BTS_ADVERTISEMENT_RSSI_IDENTIFER);
}
@end
/*
File: EADSessionController.h
Abstract: n/a
Version: 1.1
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple
Inc. ("Apple") in consideration of your agreement to the following
terms, and your use, installation, modification or redistribution of
this Apple software constitutes acceptance of these terms. If you do
not agree with these terms, please do not use, install, modify or
redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the
"Apple Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may
be used to endorse or promote products derived from the Apple Software
without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or
implied, are granted by Apple herein, including but not limited to any
patent rights that may be infringed by your derivative works or by other
works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 2010 Apple Inc. All Rights Reserved.
*/
#import <Foundation/Foundation.h>
#import <ExternalAccessory/ExternalAccessory.h>
extern NSString *EADSessionDataReceivedNotification;
// NOTE: EADSessionController is not threadsafe, calling methods from different threads will lead to unpredictable results
@interface EADSessionController : NSObject <EAAccessoryDelegate, NSStreamDelegate> {
EAAccessory *_accessory;
EASession *_session;
NSString *_protocolString;
NSMutableData *_writeData;
NSMutableData *_readData;
}
+ (EADSessionController *)sharedController;
- (void)setupControllerForAccessory:(EAAccessory *)accessory withProtocolString:(NSString *)protocolString;
- (BOOL)openSession;
- (void)closeSession;
- (void)writeData:(NSData *)data;
- (NSUInteger)readBytesAvailable;
- (NSData *)readData:(NSUInteger)bytesToRead;
@property (nonatomic, readonly) EAAccessory *accessory;
@property (nonatomic, readonly) NSString *protocolString;
@end
/*
File: EADSessionController.m
Abstract: n/a
Version: 1.1
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple
Inc. ("Apple") in consideration of your agreement to the following
terms, and your use, installation, modification or redistribution of
this Apple software constitutes acceptance of these terms. If you do
not agree with these terms, please do not use, install, modify or
redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the
"Apple Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may
be used to endorse or promote products derived from the Apple Software
without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or
implied, are granted by Apple herein, including but not limited to any
patent rights that may be infringed by your derivative works or by other
works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 2010 Apple Inc. All Rights Reserved.
*/
#import "EADSessionController.h"
NSString *EADSessionDataReceivedNotification = @"EADSessionDataReceivedNotification";
@implementation EADSessionController
@synthesize accessory = _accessory;
@synthesize protocolString = _protocolString;
#pragma mark Internal
// low level write method - write data to the accessory while there is space available and data to write
- (void)_writeData {
if(_session == nil)
{
NSLog(@"No session!");
}
if(![[_session outputStream] hasSpaceAvailable])
{
NSLog(@"Has no space");
}
while (([[_session outputStream] hasSpaceAvailable]) && ([_writeData length] > 0))
{
NSInteger bytesWritten = [[_session outputStream] write:[_writeData bytes] maxLength:[_writeData length]];
if (bytesWritten == -1)
{
NSLog( @"write error");
break;
}
else if (bytesWritten > 0)
{
[_writeData replaceBytesInRange:NSMakeRange(0, bytesWritten) withBytes:NULL length:0];
NSLog(@"Written!%d",(int)bytesWritten);
}
}
}
// low level read method - read data while there is data and space available in the input buffer
- (void)_readData {
#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];
if (_readData == nil) {
_readData = [[NSMutableData alloc] init];
}
[_readData appendBytes:(void *)buf length:bytesRead];
//NSLog(@"read %d bytes from input stream", bytesRead);
}
[[NSNotificationCenter defaultCenter] postNotificationName:EADSessionDataReceivedNotification object:self userInfo:nil];
}
#pragma mark Public Methods
+ (EADSessionController *)sharedController
{
static EADSessionController *sessionController = nil;
if (sessionController == nil) {
sessionController = [[EADSessionController alloc] init];
}
return sessionController;
}
- (void)dealloc
{
[self closeSession];
[self setupControllerForAccessory:nil withProtocolString:nil];
}
// initialize the accessory with the protocolString
- (void)setupControllerForAccessory:(EAAccessory *)accessory withProtocolString:(NSString *)protocolString
{
_protocolString = [protocolString copy];
_accessory = accessory;
}
// open a session with the accessory and set up the input and output stream on the default run loop
- (BOOL)openSession
{
[_accessory setDelegate:self];
_session = [[EASession alloc] initWithAccessory:_accessory forProtocol:_protocolString];
if (_session)
{
[[_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];
}
else
{
NSLog(@"creating session failed");
}
return (_session != nil);
}
// 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 = nil;
_writeData = nil;
_readData = nil;
}
// high level write data method
- (void)writeData:(NSData *)data
{
if (_writeData == nil) {
_writeData = [[NSMutableData alloc] init];
}
[_writeData appendData:data];
[self _writeData];
}
// high level read method
- (NSData *)readData:(NSUInteger)bytesToRead
{
NSData *data = nil;
if ([_readData length] >= bytesToRead) {
NSRange range = NSMakeRange(0, bytesToRead);
data = [_readData subdataWithRange:range];
[_readData replaceBytesInRange:range withBytes:NULL length:0];
}
return data;
}
// get number of bytes read into local buffer
- (NSUInteger)readBytesAvailable
{
return [_readData length];
}
#pragma mark EAAccessoryDelegate
- (void)accessoryDidDisconnect:(EAAccessory *)accessory
{
// do something ...
}
#pragma mark NSStreamDelegateEventExtensions
// asynchronous NSStream handleEvent method
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
switch (eventCode) {
case NSStreamEventNone:
break;
case NSStreamEventOpenCompleted:
break;
case NSStreamEventHasBytesAvailable:
[self _readData];
break;
case NSStreamEventHasSpaceAvailable:
[self _writeData];
break;
case NSStreamEventErrorOccurred:
break;
case NSStreamEventEndEncountered:
break;
default:
break;
}
}
@end
/*
Created by Nuttawut Malee on 10.11.18.
Copyright © 2016 Nuttawut Malee. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>
#import "BLE.h"
#import "EADSessionController.h"
#import <ExternalAccessory/ExternalAccessory.h>
typedef void (^RCTBluetoothSerialPeripheralCallback) (CBPeripheral *_Nullable peripheral);
/*!
* RCTBluetoothSerial is an abstract base class to be used for module that connect,
* read and write data from active peripheral.
*/
@interface RCTBluetoothSerial : RCTEventEmitter <RCTBridgeModule, BLEDelegate, EAAccessoryDelegate>
/*!
* BLE central manager, for scanning and connection events.
*/
@property (strong, nonatomic, readonly) BLE *ble;
/*!
* Indicates if there are at least one listeners from RCTEventEmitter.
*/
@property (assign, nonatomic) BOOL doesHaveListeners;
/*!
* Dictionary of buffer from each active peripherals read value.
*/
@property (strong, nonatomic) NSMutableDictionary *buffers;
/*!
* Dictionary of certain delimiter to indicate the end of sliced buffer.
*/
@property (strong, nonatomic) NSMutableDictionary *delimiters;
/*!
* Resolvers an rejectors for connection related function.
*/
@property (strong, nonatomic) NSMutableDictionary *connectionPromises;
/**
* @method bluetoothPowerStateTimer
*
* @param timer
*
* @discussion Indicates central manager power state.
*
*/
- (void)bluetoothPowerStateTimer:(NSTimer *)timer;
@property (strong, nonatomic) NSMutableArray *accessoryList;
@property(nonatomic,retain)EADSessionController *glucoseEADSessionController;
@end
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment