Commit 771a085a authored by lujunye's avatar lujunye

调整登录状态

parent 1029702b
...@@ -38,6 +38,15 @@ ...@@ -38,6 +38,15 @@
E09B03C32445BD9500211A51 /* NavViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E09B03C22445BD9500211A51 /* NavViewController.swift */; }; E09B03C32445BD9500211A51 /* NavViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E09B03C22445BD9500211A51 /* NavViewController.swift */; };
E09B03C62445BF6700211A51 /* NavBarView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E09B03C52445BF6700211A51 /* NavBarView.swift */; }; E09B03C62445BF6700211A51 /* NavBarView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E09B03C52445BF6700211A51 /* NavBarView.swift */; };
E09B03C82445BF9300211A51 /* SwiftNotice.swift in Sources */ = {isa = PBXBuildFile; fileRef = E09B03C72445BF9300211A51 /* SwiftNotice.swift */; }; E09B03C82445BF9300211A51 /* SwiftNotice.swift in Sources */ = {isa = PBXBuildFile; fileRef = E09B03C72445BF9300211A51 /* SwiftNotice.swift */; };
E0D197BA2448431C002B080C /* BabyDefine.m in Sources */ = {isa = PBXBuildFile; fileRef = E0D197A92448431B002B080C /* BabyDefine.m */; };
E0D197BB2448431C002B080C /* BabyCallback.m in Sources */ = {isa = PBXBuildFile; fileRef = E0D197AB2448431B002B080C /* BabyCallback.m */; };
E0D197BC2448431C002B080C /* BabyPeripheralManager.m in Sources */ = {isa = PBXBuildFile; fileRef = E0D197AD2448431B002B080C /* BabyPeripheralManager.m */; };
E0D197BD2448431C002B080C /* BabySpeaker.m in Sources */ = {isa = PBXBuildFile; fileRef = E0D197AE2448431B002B080C /* BabySpeaker.m */; };
E0D197BE2448431C002B080C /* BabyOptions.m in Sources */ = {isa = PBXBuildFile; fileRef = E0D197B02448431B002B080C /* BabyOptions.m */; };
E0D197BF2448431C002B080C /* BabyBluetooth.m in Sources */ = {isa = PBXBuildFile; fileRef = E0D197B32448431C002B080C /* BabyBluetooth.m */; };
E0D197C02448431C002B080C /* BabyCentralManager.m in Sources */ = {isa = PBXBuildFile; fileRef = E0D197B52448431C002B080C /* BabyCentralManager.m */; };
E0D197C12448431C002B080C /* BabyToy.m in Sources */ = {isa = PBXBuildFile; fileRef = E0D197B82448431C002B080C /* BabyToy.m */; };
E0D197C22448431C002B080C /* BabyRhythm.m in Sources */ = {isa = PBXBuildFile; fileRef = E0D197B92448431C002B080C /* BabyRhythm.m */; };
E0D4165F24482AAF008DCAB4 /* AccountViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E0D4165D24482AAF008DCAB4 /* AccountViewController.swift */; }; E0D4165F24482AAF008DCAB4 /* AccountViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E0D4165D24482AAF008DCAB4 /* AccountViewController.swift */; };
E0D4166024482AAF008DCAB4 /* AccountViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = E0D4165E24482AAF008DCAB4 /* AccountViewController.xib */; }; E0D4166024482AAF008DCAB4 /* AccountViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = E0D4165E24482AAF008DCAB4 /* AccountViewController.xib */; };
E0D4166424483058008DCAB4 /* ChangePassViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E0D4166224483058008DCAB4 /* ChangePassViewController.swift */; }; E0D4166424483058008DCAB4 /* ChangePassViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E0D4166224483058008DCAB4 /* ChangePassViewController.swift */; };
...@@ -102,6 +111,24 @@ ...@@ -102,6 +111,24 @@
E09B03C22445BD9500211A51 /* NavViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NavViewController.swift; sourceTree = "<group>"; }; E09B03C22445BD9500211A51 /* NavViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NavViewController.swift; sourceTree = "<group>"; };
E09B03C52445BF6700211A51 /* NavBarView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NavBarView.swift; sourceTree = "<group>"; }; E09B03C52445BF6700211A51 /* NavBarView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NavBarView.swift; sourceTree = "<group>"; };
E09B03C72445BF9300211A51 /* SwiftNotice.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SwiftNotice.swift; sourceTree = "<group>"; }; E09B03C72445BF9300211A51 /* SwiftNotice.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SwiftNotice.swift; sourceTree = "<group>"; };
E0D197A82448431B002B080C /* BabyCentralManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BabyCentralManager.h; sourceTree = "<group>"; };
E0D197A92448431B002B080C /* BabyDefine.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BabyDefine.m; sourceTree = "<group>"; };
E0D197AA2448431B002B080C /* BabyOptions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BabyOptions.h; sourceTree = "<group>"; };
E0D197AB2448431B002B080C /* BabyCallback.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BabyCallback.m; sourceTree = "<group>"; };
E0D197AC2448431B002B080C /* BabyCallback.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BabyCallback.h; sourceTree = "<group>"; };
E0D197AD2448431B002B080C /* BabyPeripheralManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BabyPeripheralManager.m; sourceTree = "<group>"; };
E0D197AE2448431B002B080C /* BabySpeaker.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BabySpeaker.m; sourceTree = "<group>"; };
E0D197AF2448431B002B080C /* BabyBluetooth.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BabyBluetooth.h; sourceTree = "<group>"; };
E0D197B02448431B002B080C /* BabyOptions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BabyOptions.m; sourceTree = "<group>"; };
E0D197B12448431C002B080C /* BabyToy.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BabyToy.h; sourceTree = "<group>"; };
E0D197B22448431C002B080C /* BabyRhythm.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BabyRhythm.h; sourceTree = "<group>"; };
E0D197B32448431C002B080C /* BabyBluetooth.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BabyBluetooth.m; sourceTree = "<group>"; };
E0D197B42448431C002B080C /* BabyPeripheralManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BabyPeripheralManager.h; sourceTree = "<group>"; };
E0D197B52448431C002B080C /* BabyCentralManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BabyCentralManager.m; sourceTree = "<group>"; };
E0D197B62448431C002B080C /* BabyDefine.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BabyDefine.h; sourceTree = "<group>"; };
E0D197B72448431C002B080C /* BabySpeaker.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BabySpeaker.h; sourceTree = "<group>"; };
E0D197B82448431C002B080C /* BabyToy.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BabyToy.m; sourceTree = "<group>"; };
E0D197B92448431C002B080C /* BabyRhythm.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BabyRhythm.m; sourceTree = "<group>"; };
E0D4165D24482AAF008DCAB4 /* AccountViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccountViewController.swift; sourceTree = "<group>"; }; E0D4165D24482AAF008DCAB4 /* AccountViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccountViewController.swift; sourceTree = "<group>"; };
E0D4165E24482AAF008DCAB4 /* AccountViewController.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = AccountViewController.xib; sourceTree = "<group>"; }; E0D4165E24482AAF008DCAB4 /* AccountViewController.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = AccountViewController.xib; sourceTree = "<group>"; };
E0D4166224483058008DCAB4 /* ChangePassViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChangePassViewController.swift; sourceTree = "<group>"; }; E0D4166224483058008DCAB4 /* ChangePassViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChangePassViewController.swift; sourceTree = "<group>"; };
...@@ -250,6 +277,7 @@ ...@@ -250,6 +277,7 @@
E088CC882446FFA1000DAA8A /* Other */ = { E088CC882446FFA1000DAA8A /* Other */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
E0D197A72448430E002B080C /* 蓝牙 */,
E088CC8B2446FFB5000DAA8A /* 验证码 */, E088CC8B2446FFB5000DAA8A /* 验证码 */,
); );
path = Other; path = Other;
...@@ -366,6 +394,31 @@ ...@@ -366,6 +394,31 @@
path = NavBarView; path = NavBarView;
sourceTree = "<group>"; sourceTree = "<group>";
}; };
E0D197A72448430E002B080C /* 蓝牙 */ = {
isa = PBXGroup;
children = (
E0D197AF2448431B002B080C /* BabyBluetooth.h */,
E0D197B32448431C002B080C /* BabyBluetooth.m */,
E0D197AC2448431B002B080C /* BabyCallback.h */,
E0D197AB2448431B002B080C /* BabyCallback.m */,
E0D197A82448431B002B080C /* BabyCentralManager.h */,
E0D197B52448431C002B080C /* BabyCentralManager.m */,
E0D197B62448431C002B080C /* BabyDefine.h */,
E0D197A92448431B002B080C /* BabyDefine.m */,
E0D197AA2448431B002B080C /* BabyOptions.h */,
E0D197B02448431B002B080C /* BabyOptions.m */,
E0D197B42448431C002B080C /* BabyPeripheralManager.h */,
E0D197AD2448431B002B080C /* BabyPeripheralManager.m */,
E0D197B22448431C002B080C /* BabyRhythm.h */,
E0D197B92448431C002B080C /* BabyRhythm.m */,
E0D197B72448431C002B080C /* BabySpeaker.h */,
E0D197AE2448431B002B080C /* BabySpeaker.m */,
E0D197B12448431C002B080C /* BabyToy.h */,
E0D197B82448431C002B080C /* BabyToy.m */,
);
path = "蓝牙";
sourceTree = "<group>";
};
E0D4165C24482A7D008DCAB4 /* 账号信息 */ = { E0D4165C24482A7D008DCAB4 /* 账号信息 */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
...@@ -454,6 +507,7 @@ ...@@ -454,6 +507,7 @@
TargetAttributes = { TargetAttributes = {
E00D85DA244561FD00F5F816 = { E00D85DA244561FD00F5F816 = {
CreatedOnToolsVersion = 11.3; CreatedOnToolsVersion = 11.3;
LastSwiftMigration = 1130;
}; };
E00D85F0244561FE00F5F816 = { E00D85F0244561FE00F5F816 = {
CreatedOnToolsVersion = 11.3; CreatedOnToolsVersion = 11.3;
...@@ -568,18 +622,26 @@ ...@@ -568,18 +622,26 @@
isa = PBXSourcesBuildPhase; isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
E0D197BA2448431C002B080C /* BabyDefine.m in Sources */,
E09B03B62445B85A00211A51 /* LoginViewController.swift in Sources */, E09B03B62445B85A00211A51 /* LoginViewController.swift in Sources */,
E0D197C12448431C002B080C /* BabyToy.m in Sources */,
E09B03C32445BD9500211A51 /* NavViewController.swift in Sources */, E09B03C32445BD9500211A51 /* NavViewController.swift in Sources */,
E0D197C02448431C002B080C /* BabyCentralManager.m in Sources */,
E00D85DF244561FD00F5F816 /* AppDelegate.swift in Sources */, E00D85DF244561FD00F5F816 /* AppDelegate.swift in Sources */,
E0516F7F244806C500E373CE /* MsgCenterViewController.swift in Sources */, E0516F7F244806C500E373CE /* MsgCenterViewController.swift in Sources */,
E0516F822448086700E373CE /* MsgCenterCell.swift in Sources */, E0516F822448086700E373CE /* MsgCenterCell.swift in Sources */,
E0D197BB2448431C002B080C /* BabyCallback.m in Sources */,
E0D4166424483058008DCAB4 /* ChangePassViewController.swift in Sources */, E0D4166424483058008DCAB4 /* ChangePassViewController.swift in Sources */,
E09B03C62445BF6700211A51 /* NavBarView.swift in Sources */, E09B03C62445BF6700211A51 /* NavBarView.swift in Sources */,
E0D197BD2448431C002B080C /* BabySpeaker.m in Sources */,
E00D85E1244561FD00F5F816 /* SceneDelegate.swift in Sources */, E00D85E1244561FD00F5F816 /* SceneDelegate.swift in Sources */,
E09B03A12445AF7100211A51 /* Define.swift in Sources */, E09B03A12445AF7100211A51 /* Define.swift in Sources */,
E09B03A82445B04E00211A51 /* BaseView.swift in Sources */, E09B03A82445B04E00211A51 /* BaseView.swift in Sources */,
E09B03C02445B96500211A51 /* FgPassViewController.swift in Sources */, E09B03C02445B96500211A51 /* FgPassViewController.swift in Sources */,
E09B03AB2445B0A300211A51 /* LoginModel.swift in Sources */, E09B03AB2445B0A300211A51 /* LoginModel.swift in Sources */,
E0D197BE2448431C002B080C /* BabyOptions.m in Sources */,
E0D197C22448431C002B080C /* BabyRhythm.m in Sources */,
E0D197BF2448431C002B080C /* BabyBluetooth.m in Sources */,
E09B03C82445BF9300211A51 /* SwiftNotice.swift in Sources */, E09B03C82445BF9300211A51 /* SwiftNotice.swift in Sources */,
E0D4165F24482AAF008DCAB4 /* AccountViewController.swift in Sources */, E0D4165F24482AAF008DCAB4 /* AccountViewController.swift in Sources */,
E01C26B62446AF3100ADCC70 /* DemoViewController.swift in Sources */, E01C26B62446AF3100ADCC70 /* DemoViewController.swift in Sources */,
...@@ -588,6 +650,7 @@ ...@@ -588,6 +650,7 @@
E09B03A72445B04E00211A51 /* BaseViewController.swift in Sources */, E09B03A72445B04E00211A51 /* BaseViewController.swift in Sources */,
E088CC932447124D000DAA8A /* BindViewController.swift in Sources */, E088CC932447124D000DAA8A /* BindViewController.swift in Sources */,
E088CC8D24470BF0000DAA8A /* CodeView.swift in Sources */, E088CC8D24470BF0000DAA8A /* CodeView.swift in Sources */,
E0D197BC2448431C002B080C /* BabyPeripheralManager.m in Sources */,
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };
...@@ -753,6 +816,7 @@ ...@@ -753,6 +816,7 @@
baseConfigurationReference = 6FA79EFC99FED0CA28AA1444 /* Pods-GeliBusinessPlatform.debug.xcconfig */; baseConfigurationReference = 6FA79EFC99FED0CA28AA1444 /* Pods-GeliBusinessPlatform.debug.xcconfig */;
buildSettings = { buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_ASSET_PATHS = "\"GeliBusinessPlatform/Preview Content\""; DEVELOPMENT_ASSET_PATHS = "\"GeliBusinessPlatform/Preview Content\"";
DEVELOPMENT_TEAM = K48346UACH; DEVELOPMENT_TEAM = K48346UACH;
...@@ -765,6 +829,7 @@ ...@@ -765,6 +829,7 @@
PRODUCT_BUNDLE_IDENTIFIER = GeliBusinessPlatform.GeliBusinessPlatform; PRODUCT_BUNDLE_IDENTIFIER = GeliBusinessPlatform.GeliBusinessPlatform;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
"SWIFT_OBJC_BRIDGING_HEADER[arch=*]" = "$(SRCROOT)/GeliBusinessPlatform/Define/Bridge_Header.h"; "SWIFT_OBJC_BRIDGING_HEADER[arch=*]" = "$(SRCROOT)/GeliBusinessPlatform/Define/Bridge_Header.h";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0; SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2"; TARGETED_DEVICE_FAMILY = "1,2";
}; };
...@@ -775,6 +840,7 @@ ...@@ -775,6 +840,7 @@
baseConfigurationReference = 073EFCE4E1CBD26A64719EC0 /* Pods-GeliBusinessPlatform.release.xcconfig */; baseConfigurationReference = 073EFCE4E1CBD26A64719EC0 /* Pods-GeliBusinessPlatform.release.xcconfig */;
buildSettings = { buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_ASSET_PATHS = "\"GeliBusinessPlatform/Preview Content\""; DEVELOPMENT_ASSET_PATHS = "\"GeliBusinessPlatform/Preview Content\"";
DEVELOPMENT_TEAM = K48346UACH; DEVELOPMENT_TEAM = K48346UACH;
......
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
<key>GeliBusinessPlatform.xcscheme_^#shared#^_</key> <key>GeliBusinessPlatform.xcscheme_^#shared#^_</key>
<dict> <dict>
<key>orderHint</key> <key>orderHint</key>
<integer>23</integer> <integer>22</integer>
</dict> </dict>
</dict> </dict>
</dict> </dict>
......
...@@ -11,4 +11,5 @@ ...@@ -11,4 +11,5 @@
#import "MJRefresh.h" #import "MJRefresh.h"
#import "WYHead.h" #import "WYHead.h"
#endif /* Bridge_Header_h */ #endif /* Bridge_Header_h */
/*
BabyBluetooth
简单易用的蓝牙ble库,基于CoreBluetooth 作者:刘彦玮
https://github.com/coolnameismy/BabyBluetooth
version:0.7.0
*/
// Created by 刘彦玮 on 15/3/31.
// Copyright (c) 2015年 刘彦玮. All rights reserved.
#import <Foundation/Foundation.h>
#import <CoreBluetooth/CoreBluetooth.h>
#import "BabyCentralManager.h"
#import "BabyPeripheralManager.h"
#import "BabyToy.h"
#import "BabySpeaker.h"
#import "BabyRhythm.h"
#import "BabyDefine.h"
@interface BabyBluetooth : NSObject
#pragma mark - babybluetooth的委托
//默认频道的委托
/**
设备状态改变的block | when CentralManager state changed
*/
- (void)setBlockOnCentralManagerDidUpdateState:(void (^)(CBCentralManager *central))block;
/**
找到Peripherals的block | when find peripheral
*/
- (void)setBlockOnDiscoverToPeripherals:(void (^)(CBCentralManager *central,CBPeripheral *peripheral,NSDictionary *advertisementData, NSNumber *RSSI))block;
/**
连接Peripherals成功的block
| when connected peripheral
*/
- (void)setBlockOnConnected:(void (^)(CBCentralManager *central,CBPeripheral *peripheral))block;
/**
连接Peripherals失败的block
| when fail to connect peripheral
*/
- (void)setBlockOnFailToConnect:(void (^)(CBCentralManager *central,CBPeripheral *peripheral,NSError *error))block;
/**
断开Peripherals的连接的block
| when disconnected peripheral
*/
- (void)setBlockOnDisconnect:(void (^)(CBCentralManager *central,CBPeripheral *peripheral,NSError *error))block;
/**
设置查找服务的block
| when discover services of peripheral
*/
- (void)setBlockOnDiscoverServices:(void (^)(CBPeripheral *peripheral,NSError *error))block;
/**
设置查找到Characteristics的block
| when discovered Characteristics
*/
- (void)setBlockOnDiscoverCharacteristics:(void (^)(CBPeripheral *peripheral,CBService *service,NSError *error))block;
/**
设置获取到最新Characteristics值的block
| when read new characteristics value or notiy a characteristics value
*/
- (void)setBlockOnReadValueForCharacteristic:(void (^)(CBPeripheral *peripheral,CBCharacteristic *characteristic,NSError *error))block;
/**
设置查找到Descriptors名称的block
| when discover descriptors for characteristic
*/
- (void)setBlockOnDiscoverDescriptorsForCharacteristic:(void (^)(CBPeripheral *peripheral,CBCharacteristic *characteristic,NSError *error))block;
/**
设置读取到Descriptors值的block
| when read descriptors for characteristic
*/
- (void)setBlockOnReadValueForDescriptors:(void (^)(CBPeripheral *peripheral,CBDescriptor *descriptor,NSError *error))block;
/**
写Characteristic成功后的block
| when did write value for characteristic successed
*/
- (void)setBlockOnDidWriteValueForCharacteristic:(void (^)(CBCharacteristic *characteristic,NSError *error))block;
/**
写descriptor成功后的block
| when did write value for descriptor successed
*/
- (void)setBlockOnDidWriteValueForDescriptor:(void (^)(CBDescriptor *descriptor,NSError *error))block;
/**
characteristic订阅状态改变的block
| when characteristic notification state changed
*/
- (void)setBlockOnDidUpdateNotificationStateForCharacteristic:(void (^)(CBCharacteristic *characteristic,NSError *error))block;
/**
读取RSSI的委托
| when did read RSSI
*/
- (void)setBlockOnDidReadRSSI:(void (^)(NSNumber *RSSI,NSError *error))block;
/**
discoverIncludedServices的回调,暂时在babybluetooth中无作用
| no used in babybluetooth
*/
- (void)setBlockOnDidDiscoverIncludedServicesForService:(void (^)(CBService *service,NSError *error))block;
/**
外设更新名字后的block
| when peripheral update name
*/
- (void)setBlockOnDidUpdateName:(void (^)(CBPeripheral *peripheral))block;
/**
外设更新服务后的block
| when peripheral update services
*/
- (void)setBlockOnDidModifyServices:(void (^)(CBPeripheral *peripheral,NSArray *invalidatedServices))block;
// channel的委托
/**
设备状态改变的block
| when CentralManager state changed
*/
- (void)setBlockOnCentralManagerDidUpdateStateAtChannel:(NSString *)channel
block:(void (^)(CBCentralManager *central))block;
/**
找到Peripherals的block
| when find peripheral
*/
- (void)setBlockOnDiscoverToPeripheralsAtChannel:(NSString *)channel
block:(void (^)(CBCentralManager *central,CBPeripheral *peripheral,NSDictionary *advertisementData, NSNumber *RSSI))block;
/**
连接Peripherals成功的block
| when connected peripheral
*/
- (void)setBlockOnConnectedAtChannel:(NSString *)channel
block:(void (^)(CBCentralManager *central,CBPeripheral *peripheral))block;
/**
连接Peripherals失败的block
| when fail to connect peripheral
*/
- (void)setBlockOnFailToConnectAtChannel:(NSString *)channel
block:(void (^)(CBCentralManager *central,CBPeripheral *peripheral,NSError *error))block;
/**
断开Peripherals的连接的block
| when disconnected peripheral
*/
- (void)setBlockOnDisconnectAtChannel:(NSString *)channel
block:(void (^)(CBCentralManager *central,CBPeripheral *peripheral,NSError *error))block;
/**
设置查找服务的block
| when discover services of peripheral
*/
- (void)setBlockOnDiscoverServicesAtChannel:(NSString *)channel
block:(void (^)(CBPeripheral *peripheral,NSError *error))block;
/**
设置查找到Characteristics的block
| when discovered Characteristics
*/
- (void)setBlockOnDiscoverCharacteristicsAtChannel:(NSString *)channel
block:(void (^)(CBPeripheral *peripheral,CBService *service,NSError *error))block;
/**
设置获取到最新Characteristics值的block
| when read new characteristics value or notiy a characteristics value
*/
- (void)setBlockOnReadValueForCharacteristicAtChannel:(NSString *)channel
block:(void (^)(CBPeripheral *peripheral,CBCharacteristic *characteristic,NSError *error))block;
/**
设置查找到Characteristics描述的block
| when discover descriptors for characteristic
*/
- (void)setBlockOnDiscoverDescriptorsForCharacteristicAtChannel:(NSString *)channel
block:(void (^)(CBPeripheral *peripheral,CBCharacteristic *service,NSError *error))block;
/**
设置读取到Characteristics描述的值的block
| when read descriptors for characteristic
*/
- (void)setBlockOnReadValueForDescriptorsAtChannel:(NSString *)channel
block:(void (^)(CBPeripheral *peripheral,CBDescriptor *descriptor,NSError *error))block;
/**
写Characteristic成功后的block
| when did write value for characteristic successed
*/
- (void)setBlockOnDidWriteValueForCharacteristicAtChannel:(NSString *)channel
block:(void (^)(CBCharacteristic *characteristic,NSError *error))block;
/**
写descriptor成功后的block
| when did write value for descriptor successed
*/
- (void)setBlockOnDidWriteValueForDescriptorAtChannel:(NSString *)channel
block:(void (^)(CBDescriptor *descriptor,NSError *error))block;
/**
characteristic订阅状态改变的block
| when characteristic notification state changed
*/
- (void)setBlockOnDidUpdateNotificationStateForCharacteristicAtChannel:(NSString *)channel
block:(void (^)(CBCharacteristic *characteristic,NSError *error))block;
/**
读取RSSI的委托
| when did read RSSI
*/
- (void)setBlockOnDidReadRSSIAtChannel:(NSString *)channel
block:(void (^)(NSNumber *RSSI,NSError *error))block;
/**
discoverIncludedServices的回调,暂时在babybluetooth中无作用
| no used in babybluetooth
*/
- (void)setBlockOnDidDiscoverIncludedServicesForServiceAtChannel:(NSString *)channel
block:(void (^)(CBService *service,NSError *error))block;
/**
外设更新名字后的block
| when peripheral update name
*/
- (void)setBlockOnDidUpdateNameAtChannel:(NSString *)channel
block:(void (^)(CBPeripheral *peripheral))block;
/**
外设更新服务后的block
| when peripheral update services
*/
- (void)setBlockOnDidModifyServicesAtChannel:(NSString *)channel
block:(void (^)(CBPeripheral *peripheral,NSArray *invalidatedServices))block;
#pragma mark - babybluetooth filter
/**
设置查找Peripherals的规则
| filter of discover peripherals
*/
- (void)setFilterOnDiscoverPeripherals:(BOOL (^)(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI))filter;
/**
设置连接Peripherals的规则
| setting filter of connect to peripherals peripherals
*/
- (void)setFilterOnConnectToPeripherals:(BOOL (^)(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI))filter;
/**
设置查找Peripherals的规则
| filter of discover peripherals
*/
- (void)setFilterOnDiscoverPeripheralsAtChannel:(NSString *)channel
filter:(BOOL (^)(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI))filter;
/**
设置连接Peripherals的规则
| setting filter of connect to peripherals peripherals
*/
- (void)setFilterOnConnectToPeripheralsAtChannel:(NSString *)channel
filter:(BOOL (^)(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI))filter;
#pragma mark - babybluetooth Special
/**
babyBluettooth cancelScan方法调用后的回调
| when after call cancelScan
*/
- (void)setBlockOnCancelScanBlock:(void(^)(CBCentralManager *centralManager))block;
/**
babyBluettooth cancelAllPeripheralsConnectionBlock 方法执行后并且全部设备断开后的回调
| when did all peripheral disConnect
*/
- (void)setBlockOnCancelAllPeripheralsConnectionBlock:(void(^)(CBCentralManager *centralManager))block;
/**
babyBluettooth cancelScan方法调用后的回调
| when after call cancelScan
*/
- (void)setBlockOnCancelScanBlockAtChannel:(NSString *)channel
block:(void(^)(CBCentralManager *centralManager))block;
/**
babyBluettooth cancelAllPeripheralsConnectionBlock 方法执行后并且全部设备断开后的回调
| when did all peripheral disConnect
*/
- (void)setBlockOnCancelAllPeripheralsConnectionBlockAtChannel:(NSString *)channel
block:(void(^)(CBCentralManager *centralManager))block;
/**
设置蓝牙运行时的参数
| set ble runtime parameters
*/
- (void)setBabyOptionsWithScanForPeripheralsWithOptions:(NSDictionary *) scanForPeripheralsWithOptions
connectPeripheralWithOptions:(NSDictionary *) connectPeripheralWithOptions
scanForPeripheralsWithServices:(NSArray *)scanForPeripheralsWithServices
discoverWithServices:(NSArray *)discoverWithServices
discoverWithCharacteristics:(NSArray *)discoverWithCharacteristics;
/**
设置蓝牙运行时的参数
| set ble runtime parameters
*/
- (void)setBabyOptionsAtChannel:(NSString *)channel
scanForPeripheralsWithOptions:(NSDictionary *) scanForPeripheralsWithOptions
connectPeripheralWithOptions:(NSDictionary *) connectPeripheralWithOptions
scanForPeripheralsWithServices:(NSArray *)scanForPeripheralsWithServices
discoverWithServices:(NSArray *)discoverWithServices
discoverWithCharacteristics:(NSArray *)discoverWithCharacteristics;
#pragma mark - 链式函数
/**
查找Peripherals
*/
- (BabyBluetooth *) scanForPeripherals;
/**
连接Peripherals
*/
- (BabyBluetooth *) connectToPeripherals;
/**
发现Services
*/
- (BabyBluetooth *) discoverServices;
/**
获取Characteristics
*/
- (BabyBluetooth *) discoverCharacteristics;
/**
更新Characteristics的值
*/
- (BabyBluetooth *) readValueForCharacteristic;
/**
获取Characteristics的名称
*/
- (BabyBluetooth *) discoverDescriptorsForCharacteristic;
/**
获取Descriptors的值
*/
- (BabyBluetooth *) readValueForDescriptors;
/**
开始执行
*/
- (BabyBluetooth *) begin;
/**
sec秒后停止
*/
- (BabyBluetooth *) stop:(int)sec;
/**
持有对象
*/
- (BabyBluetooth *) having:(NSObject *)obj;
/**
切换委托的频道
*/
- (BabyBluetooth *) channel: (NSString *)channel;
/**
谓词,返回self
*/
- (BabyBluetooth *) and;
/**
谓词,返回self
*/
- (BabyBluetooth *) then;
/**
谓词,返回self
*/
- (BabyBluetooth *) with;
/**
* enjoy 祝你使用愉快,
*
* 说明:enjoy是蓝牙全套串行方法的简写(发现服务,发现特征,读取特征,读取特征描述),前面可以必须有scanForPeripherals或having方法,channel可以选择添加。
enjoy() 等同于 connectToPeripherals().discoverServices().discoverCharacteristics().readValueForCharacteristic().discoverDescriptorsForCharacteristic().readValueForDescriptors().begin();
它可以让你少敲很多代码
## 例子:
- 扫描后来个全套(发现服务,发现特征,读取特征,读取特征描述)
` baby.scanForPeripherals().connectToPeripherals().discoverServices().discoverCharacteristics()
.readValueForCharacteristic().discoverDescriptorsForCharacteristic().readValueForDescriptors().begin();
`
- 直接使用已有的外设连接后全套(发现服务,发现特征,读取特征,读取特征描述)
` baby.having(self.peripheral).connectToPeripherals().discoverServices().discoverCharacteristics()
.readValueForCharacteristic().discoverDescriptorsForCharacteristic().readValueForDescriptors().begin();
`
enjoy后面也可以加stop()方法
*/
- (BabyBluetooth *) enjoy;
#pragma mark - 工具方法
/**
* 单例构造方法
* @return BabyBluetooth共享实例
*/
+ (instancetype)shareBabyBluetooth;
/**
断开连接
*/
- (void)cancelPeripheralConnection:(CBPeripheral *)peripheral;
/**
断开所有连接
*/
- (void)cancelAllPeripheralsConnection;
/**
停止扫描
*/
- (void)cancelScan;
/**
更新Characteristics的值
*/
- (BabyBluetooth *(^)(CBPeripheral *peripheral,CBCharacteristic *characteristic)) characteristicDetails;
/**
设置characteristic的notify
*/
- (void)notify:(CBPeripheral *)peripheral
characteristic:(CBCharacteristic *)characteristic
block:(void(^)(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error))block;
/**
取消characteristic的notify
*/
- (void)cancelNotify:(CBPeripheral *)peripheral
characteristic:(CBCharacteristic *)characteristic;
/**
获取当前连接的peripherals
*/
- (NSArray *)findConnectedPeripherals;
/**
获取当前连接的peripheral
*/
- (CBPeripheral *)findConnectedPeripheral:(NSString *)peripheralName;
/**
获取当前corebluetooth的centralManager对象
*/
- (CBCentralManager *)centralManager;
/**
添加断开自动重连的外设
*/
- (void)AutoReconnect:(CBPeripheral *)peripheral;
/**
删除断开自动重连的外设
*/
- (void)AutoReconnectCancel:(CBPeripheral *)peripheral;
/**
根据外设UUID对应的string获取已配对的外设
通过方法获取外设后可以直接连接外设,跳过扫描过程
*/
- (CBPeripheral *)retrievePeripheralWithUUIDString:(NSString *)UUIDString;
#pragma mark - peripheral model
//进入外设模式
- (BabyPeripheralManager *(^)()) bePeripheral;
- (BabyPeripheralManager *(^)(NSString *localName)) bePeripheralWithName;
@property (nonatomic, readonly) CBPeripheralManager *peripheralManager;
//peripheral model block
/**
PeripheralManager did update state block
*/
- (void)peripheralModelBlockOnPeripheralManagerDidUpdateState:(void(^)(CBPeripheralManager *peripheral))block;
/**
PeripheralManager did add service block
*/
- (void)peripheralModelBlockOnDidAddService:(void(^)(CBPeripheralManager *peripheral,CBService *service,NSError *error))block;
/**
PeripheralManager did start advertising block
*/
- (void)peripheralModelBlockOnDidStartAdvertising:(void(^)(CBPeripheralManager *peripheral,NSError *error))block;
/**
peripheralManager did receive read request block
*/
- (void)peripheralModelBlockOnDidReceiveReadRequest:(void(^)(CBPeripheralManager *peripheral,CBATTRequest *request))block;
/**
peripheralManager did receive write request block
*/
- (void)peripheralModelBlockOnDidReceiveWriteRequests:(void(^)(CBPeripheralManager *peripheral,NSArray *requests))block;
/**
peripheralManager did subscribe to characteristic block
*/
- (void)peripheralModelBlockOnDidSubscribeToCharacteristic:(void(^)(CBPeripheralManager *peripheral,CBCentral *central,CBCharacteristic *characteristic))block;
/**
peripheralManager did subscribe to characteristic block
*/
- (void)peripheralModelBlockOnDidUnSubscribeToCharacteristic:(void(^)(CBPeripheralManager *peripheral,CBCentral *central,CBCharacteristic *characteristic))block;
@end
/*
BabyBluetooth
简单易用的蓝牙ble库,基于CoreBluetooth 作者:刘彦玮
https://github.com/coolnameismy/BabyBluetooth
*/
// Created by 刘彦玮 on 15/3/31.
// Copyright (c) 2015年 刘彦玮. All rights reserved.
#import "BabyBluetooth.h"
@implementation BabyBluetooth{
BabyCentralManager *babyCentralManager;
BabyPeripheralManager *babyPeripheralManager;
BabySpeaker *babySpeaker;
int CENTRAL_MANAGER_INIT_WAIT_TIMES;
NSTimer *timerForStop;
}
//单例模式
+ (instancetype)shareBabyBluetooth {
static BabyBluetooth *share = nil;
static dispatch_once_t oneToken;
dispatch_once(&oneToken, ^{
share = [[BabyBluetooth alloc]init];
});
return share;
}
- (instancetype)init {
self = [super init];
if (self) {
//初始化对象
babyCentralManager = [[BabyCentralManager alloc]init];
babySpeaker = [[BabySpeaker alloc]init];
babyCentralManager->babySpeaker = babySpeaker;
babyPeripheralManager = [[BabyPeripheralManager alloc]init];
babyPeripheralManager->babySpeaker = babySpeaker;
}
return self;
}
#pragma mark - babybluetooth的委托
/*
默认频道的委托
*/
//设备状态改变的委托
- (void)setBlockOnCentralManagerDidUpdateState:(void (^)(CBCentralManager *central))block {
[[babySpeaker callback]setBlockOnCentralManagerDidUpdateState:block];
}
//找到Peripherals的委托
- (void)setBlockOnDiscoverToPeripherals:(void (^)(CBCentralManager *central,CBPeripheral *peripheral,NSDictionary *advertisementData, NSNumber *RSSI))block{
[[babySpeaker callback]setBlockOnDiscoverPeripherals:block];
}
//连接Peripherals成功的委托
- (void)setBlockOnConnected:(void (^)(CBCentralManager *central,CBPeripheral *peripheral))block {
[[babySpeaker callback]setBlockOnConnectedPeripheral:block];
}
//连接Peripherals失败的委托
- (void)setBlockOnFailToConnect:(void (^)(CBCentralManager *central,CBPeripheral *peripheral,NSError *error))block {
[[babySpeaker callback]setBlockOnFailToConnect:block];
}
//断开Peripherals的连接
- (void)setBlockOnDisconnect:(void (^)(CBCentralManager *central,CBPeripheral *peripheral,NSError *error))block {
[[babySpeaker callback]setBlockOnDisconnect:block];
}
//设置查找服务回叫
- (void)setBlockOnDiscoverServices:(void (^)(CBPeripheral *peripheral,NSError *error))block {
[[babySpeaker callback]setBlockOnDiscoverServices:block];
}
//设置查找到Characteristics的block
- (void)setBlockOnDiscoverCharacteristics:(void (^)(CBPeripheral *peripheral,CBService *service,NSError *error))block {
[[babySpeaker callback]setBlockOnDiscoverCharacteristics:block];
}
//设置获取到最新Characteristics值的block
- (void)setBlockOnReadValueForCharacteristic:(void (^)(CBPeripheral *peripheral,CBCharacteristic *characteristic,NSError *error))block {
[[babySpeaker callback]setBlockOnReadValueForCharacteristic:block];
}
//设置查找到Characteristics描述的block
- (void)setBlockOnDiscoverDescriptorsForCharacteristic:(void (^)(CBPeripheral *peripheral,CBCharacteristic *service,NSError *error))block {
[[babySpeaker callback]setBlockOnDiscoverDescriptorsForCharacteristic:block];
}
//设置读取到Characteristics描述的值的block
- (void)setBlockOnReadValueForDescriptors:(void (^)(CBPeripheral *peripheral,CBDescriptor *descriptor,NSError *error))block {
[[babySpeaker callback]setBlockOnReadValueForDescriptors:block];
}
//写Characteristic成功后的block
- (void)setBlockOnDidWriteValueForCharacteristic:(void (^)(CBCharacteristic *characteristic,NSError *error))block {
[[babySpeaker callback]setBlockOnDidWriteValueForCharacteristic:block];
}
//写descriptor成功后的block
- (void)setBlockOnDidWriteValueForDescriptor:(void (^)(CBDescriptor *descriptor,NSError *error))block {
[[babySpeaker callback]setBlockOnDidWriteValueForDescriptor:block];
}
//characteristic订阅状态改变的block
- (void)setBlockOnDidUpdateNotificationStateForCharacteristic:(void (^)(CBCharacteristic *characteristic,NSError *error))block {
[[babySpeaker callback]setBlockOnDidUpdateNotificationStateForCharacteristic:block];
}
//读取RSSI的委托
- (void)setBlockOnDidReadRSSI:(void (^)(NSNumber *RSSI,NSError *error))block {
[[babySpeaker callback]setBlockOnDidReadRSSI:block];
}
//discoverIncludedServices的回调,暂时在babybluetooth中无作用
- (void)setBlockOnDidDiscoverIncludedServicesForService:(void (^)(CBService *service,NSError *error))block {
[[babySpeaker callback]setBlockOnDidDiscoverIncludedServicesForService:block];
}
//外设更新名字后的block
- (void)setBlockOnDidUpdateName:(void (^)(CBPeripheral *peripheral))block {
[[babySpeaker callback]setBlockOnDidUpdateName:block];
}
//外设更新服务后的block
- (void)setBlockOnDidModifyServices:(void (^)(CBPeripheral *peripheral,NSArray *invalidatedServices))block {
[[babySpeaker callback]setBlockOnDidModifyServices:block];
}
//设置蓝牙使用的参数参数
- (void)setBabyOptionsWithScanForPeripheralsWithOptions:(NSDictionary *) scanForPeripheralsWithOptions
connectPeripheralWithOptions:(NSDictionary *) connectPeripheralWithOptions
scanForPeripheralsWithServices:(NSArray *)scanForPeripheralsWithServices
discoverWithServices:(NSArray *)discoverWithServices
discoverWithCharacteristics:(NSArray *)discoverWithCharacteristics {
BabyOptions *option = [[BabyOptions alloc]initWithscanForPeripheralsWithOptions:scanForPeripheralsWithOptions connectPeripheralWithOptions:connectPeripheralWithOptions scanForPeripheralsWithServices:scanForPeripheralsWithServices discoverWithServices:discoverWithServices discoverWithCharacteristics:discoverWithCharacteristics];
[[babySpeaker callback]setBabyOptions:option];
}
/*
channel的委托
*/
//设备状态改变的委托
- (void)setBlockOnCentralManagerDidUpdateStateAtChannel:(NSString *)channel
block:(void (^)(CBCentralManager *central))block {
[[babySpeaker callbackOnChnnel:channel createWhenNotExist:YES] setBlockOnCentralManagerDidUpdateState:block];
}
//找到Peripherals的委托
- (void)setBlockOnDiscoverToPeripheralsAtChannel:(NSString *)channel
block:(void (^)(CBCentralManager *central,CBPeripheral *peripheral,NSDictionary *advertisementData, NSNumber *RSSI))block {
[[babySpeaker callbackOnChnnel:channel createWhenNotExist:YES] setBlockOnDiscoverPeripherals:block];
}
//连接Peripherals成功的委托
- (void)setBlockOnConnectedAtChannel:(NSString *)channel
block:(void (^)(CBCentralManager *central,CBPeripheral *peripheral))block {
[[babySpeaker callbackOnChnnel:channel createWhenNotExist:YES] setBlockOnConnectedPeripheral:block];
}
//连接Peripherals失败的委托
- (void)setBlockOnFailToConnectAtChannel:(NSString *)channel
block:(void (^)(CBCentralManager *central,CBPeripheral *peripheral,NSError *error))block {
[[babySpeaker callbackOnChnnel:channel createWhenNotExist:YES] setBlockOnFailToConnect:block];
}
//断开Peripherals的连接
- (void)setBlockOnDisconnectAtChannel:(NSString *)channel
block:(void (^)(CBCentralManager *central,CBPeripheral *peripheral,NSError *error))block {
[[babySpeaker callbackOnChnnel:channel createWhenNotExist:YES] setBlockOnDisconnect:block];
}
//设置查找服务回叫
- (void)setBlockOnDiscoverServicesAtChannel:(NSString *)channel
block:(void (^)(CBPeripheral *peripheral,NSError *error))block {
[[babySpeaker callbackOnChnnel:channel createWhenNotExist:YES] setBlockOnDiscoverServices:block];
}
//设置查找到Characteristics的block
- (void)setBlockOnDiscoverCharacteristicsAtChannel:(NSString *)channel
block:(void (^)(CBPeripheral *peripheral,CBService *service,NSError *error))block {
[[babySpeaker callbackOnChnnel:channel createWhenNotExist:YES] setBlockOnDiscoverCharacteristics:block];
}
//设置获取到最新Characteristics值的block
- (void)setBlockOnReadValueForCharacteristicAtChannel:(NSString *)channel
block:(void (^)(CBPeripheral *peripheral,CBCharacteristic *characteristic,NSError *error))block {
[[babySpeaker callbackOnChnnel:channel createWhenNotExist:YES] setBlockOnReadValueForCharacteristic:block];
}
//设置查找到Characteristics描述的block
- (void)setBlockOnDiscoverDescriptorsForCharacteristicAtChannel:(NSString *)channel
block:(void (^)(CBPeripheral *peripheral,CBCharacteristic *service,NSError *error))block {
[[babySpeaker callbackOnChnnel:channel createWhenNotExist:YES] setBlockOnDiscoverDescriptorsForCharacteristic:block];
}
//设置读取到Characteristics描述的值的block
- (void)setBlockOnReadValueForDescriptorsAtChannel:(NSString *)channel
block:(void (^)(CBPeripheral *peripheral,CBDescriptor *descriptor,NSError *error))block {
[[babySpeaker callbackOnChnnel:channel createWhenNotExist:YES] setBlockOnReadValueForDescriptors:block];
}
//写Characteristic成功后的block
- (void)setBlockOnDidWriteValueForCharacteristicAtChannel:(NSString *)channel
block:(void (^)(CBCharacteristic *characteristic,NSError *error))block {
[[babySpeaker callbackOnChnnel:channel createWhenNotExist:YES]setBlockOnDidWriteValueForCharacteristic:block];
}
//写descriptor成功后的block
- (void)setBlockOnDidWriteValueForDescriptorAtChannel:(NSString *)channel
block:(void (^)(CBDescriptor *descriptor,NSError *error))block {
[[babySpeaker callbackOnChnnel:channel createWhenNotExist:YES]setBlockOnDidWriteValueForDescriptor:block];
}
//characteristic订阅状态改变的block
- (void)setBlockOnDidUpdateNotificationStateForCharacteristicAtChannel:(NSString *)channel
block:(void (^)(CBCharacteristic *characteristic,NSError *error))block {
[[babySpeaker callbackOnChnnel:channel createWhenNotExist:YES]setBlockOnDidUpdateNotificationStateForCharacteristic:block];
}
//读取RSSI的委托
- (void)setBlockOnDidReadRSSIAtChannel:(NSString *)channel
block:(void (^)(NSNumber *RSSI,NSError *error))block {
[[babySpeaker callbackOnChnnel:channel createWhenNotExist:YES]setBlockOnDidReadRSSI:block];
}
//discoverIncludedServices的回调,暂时在babybluetooth中无作用
- (void)setBlockOnDidDiscoverIncludedServicesForServiceAtChannel:(NSString *)channel
block:(void (^)(CBService *service,NSError *error))block {
[[babySpeaker callbackOnChnnel:channel createWhenNotExist:YES]setBlockOnDidDiscoverIncludedServicesForService:block];
}
//外设更新名字后的block
- (void)setBlockOnDidUpdateNameAtChannel:(NSString *)channel
block:(void (^)(CBPeripheral *peripheral))block {
[[babySpeaker callbackOnChnnel:channel createWhenNotExist:YES]setBlockOnDidUpdateName:block];
}
//外设更新服务后的block
- (void)setBlockOnDidModifyServicesAtChannel:(NSString *)channel
block:(void (^)(CBPeripheral *peripheral,NSArray *invalidatedServices))block {
[[babySpeaker callbackOnChnnel:channel createWhenNotExist:YES]setBlockOnDidModifyServices:block];
}
//设置蓝牙运行时的参数
- (void)setBabyOptionsAtChannel:(NSString *)channel
scanForPeripheralsWithOptions:(NSDictionary *) scanForPeripheralsWithOptions
connectPeripheralWithOptions:(NSDictionary *) connectPeripheralWithOptions
scanForPeripheralsWithServices:(NSArray *)scanForPeripheralsWithServices
discoverWithServices:(NSArray *)discoverWithServices
discoverWithCharacteristics:(NSArray *)discoverWithCharacteristics {
BabyOptions *option = [[BabyOptions alloc]initWithscanForPeripheralsWithOptions:scanForPeripheralsWithOptions connectPeripheralWithOptions:connectPeripheralWithOptions scanForPeripheralsWithServices:scanForPeripheralsWithServices discoverWithServices:discoverWithServices discoverWithCharacteristics:discoverWithCharacteristics];
[[babySpeaker callbackOnChnnel:channel createWhenNotExist:YES]setBabyOptions:option];
}
#pragma mark - babybluetooth filter委托
//设置查找Peripherals的规则
- (void)setFilterOnDiscoverPeripherals:(BOOL (^)(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI))filter {
[[babySpeaker callback]setFilterOnDiscoverPeripherals:filter];
}
//设置连接Peripherals的规则
- (void)setFilterOnConnectToPeripherals:(BOOL (^)(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI))filter {
[[babySpeaker callback]setFilterOnconnectToPeripherals:filter];
}
//设置查找Peripherals的规则
- (void)setFilterOnDiscoverPeripheralsAtChannel:(NSString *)channel
filter:(BOOL (^)(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI))filter {
[[babySpeaker callbackOnChnnel:channel createWhenNotExist:YES] setFilterOnDiscoverPeripherals:filter];
}
//设置连接Peripherals的规则
- (void)setFilterOnConnectToPeripheralsAtChannel:(NSString *)channel
filter:(BOOL (^)(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI))filter {
[[babySpeaker callbackOnChnnel:channel createWhenNotExist:YES] setFilterOnconnectToPeripherals:filter];
}
#pragma mark - babybluetooth Special
//babyBluettooth cancelScan方法调用后的回调
- (void)setBlockOnCancelScanBlock:(void(^)(CBCentralManager *centralManager))block {
[[babySpeaker callback]setBlockOnCancelScan:block];
}
//babyBluettooth cancelAllPeripheralsConnectionBlock 方法调用后的回调
- (void)setBlockOnCancelAllPeripheralsConnectionBlock:(void(^)(CBCentralManager *centralManager))block{
[[babySpeaker callback]setBlockOnCancelAllPeripheralsConnection:block];
}
//babyBluettooth cancelScan方法调用后的回调
- (void)setBlockOnCancelScanBlockAtChannel:(NSString *)channel
block:(void(^)(CBCentralManager *centralManager))block {
[[babySpeaker callbackOnChnnel:channel createWhenNotExist:YES] setBlockOnCancelScan:block];
}
//babyBluettooth cancelAllPeripheralsConnectionBlock 方法调用后的回调
- (void)setBlockOnCancelAllPeripheralsConnectionBlockAtChannel:(NSString *)channel
block:(void(^)(CBCentralManager *centralManager))block {
[[babySpeaker callbackOnChnnel:channel createWhenNotExist:YES] setBlockOnCancelAllPeripheralsConnection:block];
}
#pragma mark - 链式函数
//查找Peripherals
- (BabyBluetooth *) scanForPeripherals {
[babyCentralManager->pocket setObject:@"YES" forKey:@"needScanForPeripherals"];
return self;
}
//连接Peripherals
- (BabyBluetooth *) connectToPeripherals {
[babyCentralManager->pocket setObject:@"YES" forKey:@"needConnectPeripheral"];
return self;
}
//发现Services
- (BabyBluetooth *) discoverServices {
[babyCentralManager->pocket setObject:@"YES" forKey:@"needDiscoverServices"];
return self;
}
//获取Characteristics
- (BabyBluetooth *) discoverCharacteristics {
[babyCentralManager->pocket setObject:@"YES" forKey:@"needDiscoverCharacteristics"];
return self;
}
//更新Characteristics的值
- (BabyBluetooth *) readValueForCharacteristic {
[babyCentralManager->pocket setObject:@"YES" forKey:@"needReadValueForCharacteristic"];
return self;
}
//设置查找到Descriptors名称的block
- (BabyBluetooth *) discoverDescriptorsForCharacteristic {
[babyCentralManager->pocket setObject:@"YES" forKey:@"needDiscoverDescriptorsForCharacteristic"];
return self;
}
//设置读取到Descriptors值的block
- (BabyBluetooth *) readValueForDescriptors {
[babyCentralManager->pocket setObject:@"YES" forKey:@"needReadValueForDescriptors"];
return self;
}
//开始并执行
- (BabyBluetooth *) begin {
//取消未执行的stop定时任务
[timerForStop invalidate];
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self resetSeriseParmeter];
//处理链式函数缓存的数据
if ([[babyCentralManager->pocket valueForKey:@"needScanForPeripherals"] isEqualToString:@"YES"]) {
babyCentralManager->needScanForPeripherals = YES;
}
if ([[babyCentralManager->pocket valueForKey:@"needConnectPeripheral"] isEqualToString:@"YES"]) {
babyCentralManager->needConnectPeripheral = YES;
}
if ([[babyCentralManager->pocket valueForKey:@"needDiscoverServices"] isEqualToString:@"YES"]) {
babyCentralManager->needDiscoverServices = YES;
}
if ([[babyCentralManager->pocket valueForKey:@"needDiscoverCharacteristics"] isEqualToString:@"YES"]) {
babyCentralManager->needDiscoverCharacteristics = YES;
}
if ([[babyCentralManager->pocket valueForKey:@"needReadValueForCharacteristic"] isEqualToString:@"YES"]) {
babyCentralManager->needReadValueForCharacteristic = YES;
}
if ([[babyCentralManager->pocket valueForKey:@"needDiscoverDescriptorsForCharacteristic"] isEqualToString:@"YES"]) {
babyCentralManager->needDiscoverDescriptorsForCharacteristic = YES;
}
if ([[babyCentralManager->pocket valueForKey:@"needReadValueForDescriptors"] isEqualToString:@"YES"]) {
babyCentralManager->needReadValueForDescriptors = YES;
}
//调整委托方法的channel,如果没设置默认为缺省频道
NSString *channel = [babyCentralManager->pocket valueForKey:@"channel"];
[babySpeaker switchChannel:channel];
//缓存的peripheral
CBPeripheral *cachedPeripheral = [babyCentralManager->pocket valueForKey:NSStringFromClass([CBPeripheral class])];
//校验series合法性
[self validateProcess];
//清空pocjet
babyCentralManager->pocket = [[NSMutableDictionary alloc]init];
//开始扫描或连接设备
[self start:cachedPeripheral];
});
return self;
}
//私有方法,扫描或连接设备
- (void)start:(CBPeripheral *)cachedPeripheral {
if (babyCentralManager->centralManager.state == CBCentralManagerStatePoweredOn) {
CENTRAL_MANAGER_INIT_WAIT_TIMES = 0;
//扫描后连接
if (babyCentralManager->needScanForPeripherals) {
//开始扫描peripherals
[babyCentralManager scanPeripherals];
}
//直接连接
else {
if (cachedPeripheral) {
[babyCentralManager connectToPeripheral:cachedPeripheral];
}
}
return;
}
//尝试重新等待CBCentralManager打开
CENTRAL_MANAGER_INIT_WAIT_TIMES ++;
if (CENTRAL_MANAGER_INIT_WAIT_TIMES >= KBABY_CENTRAL_MANAGER_INIT_WAIT_TIMES ) {
BabyLog(@">>> 第%d次等待CBCentralManager 打开任然失败,请检查你蓝牙使用权限或检查设备问题。",CENTRAL_MANAGER_INIT_WAIT_TIMES);
return;
//[NSException raise:@"CBCentralManager打开异常" format:@"尝试等待打开CBCentralManager5次,但任未能打开"];
}
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, KBABY_CENTRAL_MANAGER_INIT_WAIT_SECOND * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self start:cachedPeripheral];
});
BabyLog(@">>> 第%d次等待CBCentralManager打开",CENTRAL_MANAGER_INIT_WAIT_TIMES);
}
//sec秒后停止
- (BabyBluetooth *) stop:(int)sec {
BabyLog(@">>> stop in %d sec",sec);
//听见定时器执行babyStop
timerForStop = [NSTimer timerWithTimeInterval:sec target:self selector:@selector(babyStop) userInfo:nil repeats:NO];
[timerForStop setFireDate: [[NSDate date]dateByAddingTimeInterval:sec]];
[[NSRunLoop currentRunLoop] addTimer:timerForStop forMode:NSRunLoopCommonModes];
return self;
}
//私有方法,停止扫描和断开连接,清空pocket
- (void)babyStop {
BabyLog(@">>>did stop");
[timerForStop invalidate];
[self resetSeriseParmeter];
babyCentralManager->pocket = [[NSMutableDictionary alloc]init];
//停止扫描,断开连接
[babyCentralManager cancelScan];
[babyCentralManager cancelAllPeripheralsConnection];
}
//重置串行方法参数
- (void)resetSeriseParmeter {
babyCentralManager->needScanForPeripherals = NO;
babyCentralManager->needConnectPeripheral = NO;
babyCentralManager->needDiscoverServices = NO;
babyCentralManager->needDiscoverCharacteristics = NO;
babyCentralManager->needReadValueForCharacteristic = NO;
babyCentralManager->needDiscoverDescriptorsForCharacteristic = NO;
babyCentralManager->needReadValueForDescriptors = NO;
}
//持有对象
- (BabyBluetooth *) having:(NSObject *)obj {
[babyCentralManager->pocket setObject:obj forKey:NSStringFromClass([obj class])];
return self;
}
//切换委托频道
- (BabyBluetooth *) channel: (NSString *)channel {
//先缓存数据,到begin方法统一处理
[babyCentralManager->pocket setValue:channel forKey:@"channel"];
return self;
}
- (void)validateProcess {
NSMutableArray *faildReason = [[NSMutableArray alloc]init];
//规则:不执行discoverDescriptorsForCharacteristic()时,不能执行readValueForDescriptors()
if (!babyCentralManager->needDiscoverDescriptorsForCharacteristic) {
if (babyCentralManager->needReadValueForDescriptors) {
[faildReason addObject:@"未执行discoverDescriptorsForCharacteristic()不能执行readValueForDescriptors()"];
}
}
//规则:不执行discoverCharacteristics()时,不能执行readValueForCharacteristic()或者是discoverDescriptorsForCharacteristic()
if (!babyCentralManager->needDiscoverCharacteristics) {
if (babyCentralManager->needReadValueForCharacteristic||babyCentralManager->needDiscoverDescriptorsForCharacteristic) {
[faildReason addObject:@"未执行discoverCharacteristics()不能执行readValueForCharacteristic()或discoverDescriptorsForCharacteristic()"];
}
}
//规则: 不执行discoverServices()不能执行discoverCharacteristics()、readValueForCharacteristic()、discoverDescriptorsForCharacteristic()、readValueForDescriptors()
if (!babyCentralManager->needDiscoverServices) {
if (babyCentralManager->needDiscoverCharacteristics||babyCentralManager->needDiscoverDescriptorsForCharacteristic ||babyCentralManager->needReadValueForCharacteristic ||babyCentralManager->needReadValueForDescriptors) {
[faildReason addObject:@"未执行discoverServices()不能执行discoverCharacteristics()、readValueForCharacteristic()、discoverDescriptorsForCharacteristic()、readValueForDescriptors()"];
}
}
//规则:不执行connectToPeripherals()时,不能执行discoverServices()
if(!babyCentralManager->needConnectPeripheral) {
if (babyCentralManager->needDiscoverServices) {
[faildReason addObject:@"未执行connectToPeripherals()不能执行discoverServices()"];
}
}
//规则:不执行needScanForPeripherals(),那么执行connectToPeripheral()方法时必须用having(peripheral)传入peripheral实例
if (!babyCentralManager->needScanForPeripherals) {
CBPeripheral *peripheral = [babyCentralManager->pocket valueForKey:NSStringFromClass([CBPeripheral class])];
if (!peripheral) {
[faildReason addObject:@"若不执行scanForPeripherals()方法,则必须执行connectToPeripheral方法并且需要传入参数(CBPeripheral *)peripheral"];
}
}
//抛出异常
if ([faildReason lastObject]) {
NSException *e = [NSException exceptionWithName:@"BadyBluetooth usage exception" reason:[faildReason lastObject] userInfo:nil];
@throw e;
}
}
- (BabyBluetooth *) and {
return self;
}
- (BabyBluetooth *) then {
return self;
}
- (BabyBluetooth *) with {
return self;
}
- (BabyBluetooth *) enjoy {
[[[[[[[self connectToPeripherals]discoverServices]discoverCharacteristics]readValueForCharacteristic]discoverDescriptorsForCharacteristic]readValueForDescriptors]begin];
return self;
}
#pragma mark - 工具方法
//断开连接
- (void)cancelPeripheralConnection:(CBPeripheral *)peripheral {
[babyCentralManager cancelPeripheralConnection:peripheral];
}
//断开所有连接
- (void)cancelAllPeripheralsConnection {
[babyCentralManager cancelAllPeripheralsConnection];
}
//停止扫描
- (void)cancelScan{
[babyCentralManager cancelScan];
}
//读取Characteristic的详细信息
- (BabyBluetooth *(^)(CBPeripheral *peripheral,CBCharacteristic *characteristic)) characteristicDetails {
//切换频道
[babySpeaker switchChannel:[babyCentralManager->pocket valueForKey:@"channel"]];
babyCentralManager->pocket = [[NSMutableDictionary alloc]init];
return ^(CBPeripheral *peripheral,CBCharacteristic *characteristic) {
//判断连接状态
if (peripheral.state == CBPeripheralStateConnected) {
self->babyCentralManager->oneReadValueForDescriptors = YES;
[peripheral readValueForCharacteristic:characteristic];
[peripheral discoverDescriptorsForCharacteristic:characteristic];
}
else {
BabyLog(@"!!!设备当前处于非连接状态");
}
return self;
};
}
- (void)notify:(CBPeripheral *)peripheral
characteristic:(CBCharacteristic *)characteristic
block:(void(^)(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error))block {
//设置通知
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
[babySpeaker addNotifyCallback:characteristic withBlock:block];
}
- (void)cancelNotify:(CBPeripheral *)peripheral
characteristic:(CBCharacteristic *)characteristic {
[peripheral setNotifyValue:NO forCharacteristic:characteristic];
[babySpeaker removeNotifyCallback:characteristic];
}
//获取当前连接的peripherals
- (NSArray *)findConnectedPeripherals {
return [babyCentralManager findConnectedPeripherals];
}
//获取当前连接的peripheral
- (CBPeripheral *)findConnectedPeripheral:(NSString *)peripheralName {
return [babyCentralManager findConnectedPeripheral:peripheralName];
}
//获取当前corebluetooth的centralManager对象
- (CBCentralManager *)centralManager {
return babyCentralManager->centralManager;
}
/**
添加断开自动重连的外设
*/
- (void)AutoReconnect:(CBPeripheral *)peripheral{
[babyCentralManager sometimes_ever:peripheral];
}
/**
删除断开自动重连的外设
*/
- (void)AutoReconnectCancel:(CBPeripheral *)peripheral{
[babyCentralManager sometimes_never:peripheral];
}
- (CBPeripheral *)retrievePeripheralWithUUIDString:(NSString *)UUIDString {
CBPeripheral *p = nil;
@try {
NSUUID *uuid = [[NSUUID alloc]initWithUUIDString:UUIDString];
p = [self.centralManager retrievePeripheralsWithIdentifiers:@[uuid]][0];
} @catch (NSException *exception) {
BabyLog(@">>> retrievePeripheralWithUUIDString error:%@",exception)
} @finally {
}
return p;
}
#pragma mark - peripheral model
//进入外设模式
- (CBPeripheralManager *)peripheralManager {
return babyPeripheralManager.peripheralManager;
}
- (BabyPeripheralManager *(^)()) bePeripheral {
return ^BabyPeripheralManager* () {
return babyPeripheralManager;
};
}
- (BabyPeripheralManager *(^)(NSString *localName)) bePeripheralWithName {
return ^BabyPeripheralManager* (NSString *localName) {
babyPeripheralManager.localName = localName;
return babyPeripheralManager;
};
}
- (void)peripheralModelBlockOnPeripheralManagerDidUpdateState:(void(^)(CBPeripheralManager *peripheral))block {
[[babySpeaker callback]setBlockOnPeripheralModelDidUpdateState:block];
}
- (void)peripheralModelBlockOnDidAddService:(void(^)(CBPeripheralManager *peripheral,CBService *service,NSError *error))block {
[[babySpeaker callback]setBlockOnPeripheralModelDidAddService:block];
}
- (void)peripheralModelBlockOnDidStartAdvertising:(void(^)(CBPeripheralManager *peripheral,NSError *error))block {
[[babySpeaker callback]setBlockOnPeripheralModelDidStartAdvertising:block];
}
- (void)peripheralModelBlockOnDidReceiveReadRequest:(void(^)(CBPeripheralManager *peripheral,CBATTRequest *request))block {
[[babySpeaker callback]setBlockOnPeripheralModelDidReceiveReadRequest:block];
}
- (void)peripheralModelBlockOnDidReceiveWriteRequests:(void(^)(CBPeripheralManager *peripheral,NSArray *requests))block {
[[babySpeaker callback]setBlockOnPeripheralModelDidReceiveWriteRequests:block];
}
- (void)peripheralModelBlockOnDidSubscribeToCharacteristic:(void(^)(CBPeripheralManager *peripheral,CBCentral *central,CBCharacteristic *characteristic))block {
[[babySpeaker callback]setBlockOnPeripheralModelDidSubscribeToCharacteristic:block];
}
- (void)peripheralModelBlockOnDidUnSubscribeToCharacteristic:(void(^)(CBPeripheralManager *peripheral,CBCentral *central,CBCharacteristic *characteristic))block {
[[babySpeaker callback]setBlockOnPeripheralModelDidUnSubscribeToCharacteristic:block];
}
@end
/*
BabyBluetooth
简单易用的蓝牙ble库,基于CoreBluetooth 作者:刘彦玮
https://github.com/coolnameismy/BabyBluetooth
@brief babybluetooth 的block定义和储存
*/
// Created by 刘彦玮 on 15/9/2.
// Copyright (c) 2015年 刘彦玮. All rights reserved.
//
#import <CoreBluetooth/CoreBluetooth.h>
#import "BabyOptions.h"
//设备状态改变的委托
typedef void (^BBCentralManagerDidUpdateStateBlock)(CBCentralManager *central);
//找到设备的委托
typedef void (^BBDiscoverPeripheralsBlock)(CBCentralManager *central,CBPeripheral *peripheral,NSDictionary *advertisementData, NSNumber *RSSI);
//连接设备成功的block
typedef void (^BBConnectedPeripheralBlock)(CBCentralManager *central,CBPeripheral *peripheral);
//连接设备失败的block
typedef void (^BBFailToConnectBlock)(CBCentralManager *central,CBPeripheral *peripheral,NSError *error);
//断开设备连接的bock
typedef void (^BBDisconnectBlock)(CBCentralManager *central,CBPeripheral *peripheral,NSError *error);
//找到服务的block
typedef void (^BBDiscoverServicesBlock)(CBPeripheral *peripheral,NSError *error);
//找到Characteristics的block
typedef void (^BBDiscoverCharacteristicsBlock)(CBPeripheral *peripheral,CBService *service,NSError *error);
//更新(获取)Characteristics的value的block
typedef void (^BBReadValueForCharacteristicBlock)(CBPeripheral *peripheral,CBCharacteristic *characteristic,NSError *error);
//获取Characteristics的名称
typedef void (^BBDiscoverDescriptorsForCharacteristicBlock)(CBPeripheral *peripheral,CBCharacteristic *service,NSError *error);
//获取Descriptors的值
typedef void (^BBReadValueForDescriptorsBlock)(CBPeripheral *peripheral,CBDescriptor *descriptor,NSError *error);
//babyBluettooth cancelScanBlock方法调用后的回调
typedef void (^BBCancelScanBlock)(CBCentralManager *centralManager);
//babyBluettooth cancelAllPeripheralsConnection 方法调用后的回调
typedef void (^BBCancelAllPeripheralsConnectionBlock)(CBCentralManager *centralManager);
typedef void (^BBDidWriteValueForCharacteristicBlock)(CBCharacteristic *characteristic,NSError *error);
typedef void (^BBDidWriteValueForDescriptorBlock)(CBDescriptor *descriptor,NSError *error);
typedef void (^BBDidUpdateNotificationStateForCharacteristicBlock)(CBCharacteristic *characteristic,NSError *error);
typedef void (^BBDidReadRSSIBlock)(NSNumber *RSSI,NSError *error);
typedef void (^BBDidDiscoverIncludedServicesForServiceBlock)(CBService *service,NSError *error);
typedef void (^BBDidUpdateNameBlock)(CBPeripheral *peripheral);
typedef void (^BBDidModifyServicesBlock)(CBPeripheral *peripheral,NSArray *invalidatedServices);
//peripheral model
typedef void (^BBPeripheralModelDidUpdateState)(CBPeripheralManager *peripheral);
typedef void (^BBPeripheralModelDidAddService)(CBPeripheralManager *peripheral,CBService *service,NSError *error);
typedef void (^BBPeripheralModelDidStartAdvertising)(CBPeripheralManager *peripheral,NSError *error);
typedef void (^BBPeripheralModelDidReceiveReadRequest)(CBPeripheralManager *peripheral,CBATTRequest *request);
typedef void (^BBPeripheralModelDidReceiveWriteRequests)(CBPeripheralManager *peripheral,NSArray *requests);
typedef void (^BBPeripheralModelDidSubscribeToCharacteristic)(CBPeripheralManager *peripheral,CBCentral *central,CBCharacteristic *characteristic);
typedef void (^BBPeripheralModelDidUnSubscribeToCharacteristic)(CBPeripheralManager *peripheral,CBCentral *central,CBCharacteristic *characteristic);
@interface BabyCallback : NSObject
#pragma mark - callback block
//设备状态改变的委托
@property (nonatomic, copy) BBCentralManagerDidUpdateStateBlock blockOnCentralManagerDidUpdateState;
//发现peripherals
@property (nonatomic, copy) BBDiscoverPeripheralsBlock blockOnDiscoverPeripherals;
//连接callback
@property (nonatomic, copy) BBConnectedPeripheralBlock blockOnConnectedPeripheral;
//连接设备失败的block
@property (nonatomic, copy) BBFailToConnectBlock blockOnFailToConnect;
//断开设备连接的bock
@property (nonatomic, copy) BBDisconnectBlock blockOnDisconnect;
//发现services
@property (nonatomic, copy) BBDiscoverServicesBlock blockOnDiscoverServices;
//发现Characteristics
@property (nonatomic, copy) BBDiscoverCharacteristicsBlock blockOnDiscoverCharacteristics;
//发现更新Characteristics的
@property (nonatomic, copy) BBReadValueForCharacteristicBlock blockOnReadValueForCharacteristic;
//获取Characteristics的名称
@property (nonatomic, copy) BBDiscoverDescriptorsForCharacteristicBlock blockOnDiscoverDescriptorsForCharacteristic;
//获取Descriptors的值
@property (nonatomic,copy) BBReadValueForDescriptorsBlock blockOnReadValueForDescriptors;
@property (nonatomic, copy) BBDidWriteValueForCharacteristicBlock blockOnDidWriteValueForCharacteristic;
@property (nonatomic, copy) BBDidWriteValueForDescriptorBlock blockOnDidWriteValueForDescriptor;
@property (nonatomic, copy) BBDidUpdateNotificationStateForCharacteristicBlock blockOnDidUpdateNotificationStateForCharacteristic;
@property (nonatomic, copy) BBDidReadRSSIBlock blockOnDidReadRSSI;
@property (nonatomic, copy) BBDidDiscoverIncludedServicesForServiceBlock blockOnDidDiscoverIncludedServicesForService;
@property (nonatomic, copy) BBDidUpdateNameBlock blockOnDidUpdateName;
@property (nonatomic, copy) BBDidModifyServicesBlock blockOnDidModifyServices;
//babyBluettooth stopScan方法调用后的回调
@property(nonatomic,copy) BBCancelScanBlock blockOnCancelScan;
//babyBluettooth stopConnectAllPerihperals 方法调用后的回调
@property(nonatomic,copy) BBCancelAllPeripheralsConnectionBlock blockOnCancelAllPeripheralsConnection;
//babyBluettooth 蓝牙使用的参数参数
@property(nonatomic,strong) BabyOptions *babyOptions;
#pragma mark - 过滤器Filter
//发现peripherals规则
@property (nonatomic, copy) BOOL (^filterOnDiscoverPeripherals)(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI);
//连接peripherals规则
@property (nonatomic, copy) BOOL (^filterOnconnectToPeripherals)(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI);
#pragma mark - peripheral model
//peripheral model
@property (nonatomic, copy) BBPeripheralModelDidUpdateState blockOnPeripheralModelDidUpdateState;
@property (nonatomic, copy) BBPeripheralModelDidAddService blockOnPeripheralModelDidAddService;
@property (nonatomic, copy) BBPeripheralModelDidStartAdvertising blockOnPeripheralModelDidStartAdvertising;
@property (nonatomic, copy) BBPeripheralModelDidReceiveReadRequest blockOnPeripheralModelDidReceiveReadRequest;
@property (nonatomic, copy) BBPeripheralModelDidReceiveWriteRequests blockOnPeripheralModelDidReceiveWriteRequests;
@property (nonatomic, copy) BBPeripheralModelDidSubscribeToCharacteristic blockOnPeripheralModelDidSubscribeToCharacteristic;
@property (nonatomic, copy) BBPeripheralModelDidUnSubscribeToCharacteristic blockOnPeripheralModelDidUnSubscribeToCharacteristic;
@end
/*
BabyBluetooth
简单易用的蓝牙ble库,基于CoreBluetooth 作者:刘彦玮
https://github.com/coolnameismy/BabyBluetooth
*/
// Created by 刘彦玮 on 15/9/2.
// Copyright (c) 2015年 刘彦玮. All rights reserved.
//
#import "BabyCallback.h"
@implementation BabyCallback
- (instancetype)init {
self = [super init];
if (self) {
[self setFilterOnDiscoverPeripherals:^BOOL(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI) {
if (![peripheralName isEqualToString:@""]) {
return YES;
}
return NO;
}];
[self setFilterOnconnectToPeripherals:^BOOL(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI) {
if (![peripheralName isEqualToString:@""]) {
return YES;
}
return NO;
}];
}
return self;
}
@end
/*
BabyBluetooth
简单易用的蓝牙ble库,基于CoreBluetooth 作者:刘彦玮
https://github.com/coolnameismy/BabyBluetooth
@brief 蓝牙中心模式实现类
*/
// Created by 刘彦玮 on 15/7/30.
// Copyright (c) 2015年 刘彦玮. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreBluetooth/CoreBluetooth.h>
#import "BabyToy.h"
#import "BabySpeaker.h"
#import "BabyDefine.h"
@interface BabyCentralManager : NSObject<CBCentralManagerDelegate,CBPeripheralDelegate> {
@public
//方法是否处理
BOOL needScanForPeripherals;//是否扫描Peripherals
BOOL needConnectPeripheral;//是否连接Peripherals
BOOL needDiscoverServices;//是否发现Services
BOOL needDiscoverCharacteristics;//是否获取Characteristics
BOOL needReadValueForCharacteristic;//是否获取(更新)Characteristics的值
BOOL needDiscoverDescriptorsForCharacteristic;//是否获取Characteristics的描述
BOOL needReadValueForDescriptors;//是否获取Descriptors的值
//一次性处理
BOOL oneReadValueForDescriptors;
//方法执行时间
int executeTime;
NSTimer *connectTimer;
//pocket
NSMutableDictionary *pocket;
//主设备
CBCentralManager *centralManager;
//回叫方法
BabySpeaker *babySpeaker;
@private
//已经连接的设备
NSMutableArray *connectedPeripherals;
//已经连接的设备
NSMutableArray *discoverPeripherals;
//需要自动重连的外设
NSMutableArray *reConnectPeripherals;
}
//扫描Peripherals
- (void)scanPeripherals;
//连接Peripherals
- (void)connectToPeripheral:(CBPeripheral *)peripheral;
//断开设备连接
- (void)cancelPeripheralConnection:(CBPeripheral *)peripheral;
//断开所有已连接的设备
- (void)cancelAllPeripheralsConnection;
//停止扫描
- (void)cancelScan;
//获取当前连接的peripherals
- (NSArray *)findConnectedPeripherals;
//获取当前连接的peripheral
- (CBPeripheral *)findConnectedPeripheral:(NSString *)peripheralName;
/**
sometimes ever,sometimes never. 相聚有时,后会无期
this is center with peripheral's story
**/
//sometimes ever:添加断开重连接的设备
- (void)sometimes_ever:(CBPeripheral *)peripheral ;
//sometimes never:删除需要重连接的设备
- (void)sometimes_never:(CBPeripheral *)peripheral ;
@end
/*
BabyBluetooth
简单易用的蓝牙ble库,基于CoreBluetooth 作者:刘彦玮
https://github.com/coolnameismy/BabyBluetooth
*/
// Created by 刘彦玮 on 15/7/30.
// Copyright (c) 2015年 刘彦玮. All rights reserved.
//
#import "BabyCentralManager.h"
#import "BabyCallback.h"
@implementation BabyCentralManager
#define currChannel [babySpeaker callbackOnCurrChannel]
- (instancetype)init {
self = [super init];
if (self) {
#if __IPHONE_OS_VERSION_MIN_REQUIRED > __IPHONE_6_0
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
//蓝牙power没打开时alert提示框
[NSNumber numberWithBool:YES],CBCentralManagerOptionShowPowerAlertKey,
//重设centralManager恢复的IdentifierKey
@"babyBluetoothRestore",CBCentralManagerOptionRestoreIdentifierKey,
nil];
#else
NSDictionary *options = nil;
#endif
NSArray *backgroundModes = [[[NSBundle mainBundle] infoDictionary]objectForKey:@"UIBackgroundModes"];
if ([backgroundModes containsObject:@"bluetooth-central"]) {
//后台模式
centralManager = [[CBCentralManager alloc]initWithDelegate:self queue:nil options:options];
}
else {
//非后台模式
centralManager = [[CBCentralManager alloc]initWithDelegate:self queue:nil];
}
//pocket
pocket = [[NSMutableDictionary alloc]init];
connectedPeripherals = [[NSMutableArray alloc]init];
discoverPeripherals = [[NSMutableArray alloc]init];
reConnectPeripherals = [[NSMutableArray alloc]init];
}
return self;
}
#pragma mark - 接收到通知
//扫描Peripherals
- (void)scanPeripherals {
[centralManager scanForPeripheralsWithServices:[currChannel babyOptions].scanForPeripheralsWithServices options:[currChannel babyOptions].scanForPeripheralsWithOptions];
}
//连接Peripherals
- (void)connectToPeripheral:(CBPeripheral *)peripheral{
[centralManager connectPeripheral:peripheral options:[currChannel babyOptions].connectPeripheralWithOptions];
}
//断开设备连接
- (void)cancelPeripheralConnection:(CBPeripheral *)peripheral {
[centralManager cancelPeripheralConnection:peripheral];
}
//断开所有已连接的设备
- (void)cancelAllPeripheralsConnection {
for (int i=0;i<connectedPeripherals.count;i++) {
[centralManager cancelPeripheralConnection:connectedPeripherals[i]];
}
}
//停止扫描
- (void)cancelScan {
[centralManager stopScan];
//停止扫描callback
if([currChannel blockOnCancelScan]) {
[currChannel blockOnCancelScan](centralManager);
}
}
#pragma mark - CBCentralManagerDelegate委托方法
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
//发送通知
[[NSNotificationCenter defaultCenter]postNotificationName:BabyNotificationAtCentralManagerDidUpdateState object:@{@"central":central}];
switch (central.state) {
case CBCentralManagerStateUnknown:
BabyLog(@">>>CBCentralManagerStateUnknown");
break;
case CBCentralManagerStateResetting:
BabyLog(@">>>CBCentralManagerStateResetting");
break;
case CBCentralManagerStateUnsupported:
BabyLog(@">>>CBCentralManagerStateUnsupported");
break;
case CBCentralManagerStateUnauthorized:
BabyLog(@">>>CBCentralManagerStateUnauthorized");
break;
case CBCentralManagerStatePoweredOff:
BabyLog(@">>>CBCentralManagerStatePoweredOff");
break;
case CBCentralManagerStatePoweredOn:
BabyLog(@">>>CBCentralManagerStatePoweredOn");
[[NSNotificationCenter defaultCenter]postNotificationName:BabyNotificationAtCentralManagerEnable object:@{@"central":central}];
break;
default:
break;
}
//状态改变callback
if ([currChannel blockOnCentralManagerDidUpdateState]) {
[currChannel blockOnCentralManagerDidUpdateState](central);
}
}
- (void)centralManager:(CBCentralManager *)central willRestoreState:(NSDictionary *)dict {
}
//扫描到Peripherals
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
//日志
//BabyLog(@"当扫描到设备:%@",peripheral.name);
[self addDiscoverPeripheral:peripheral];
//发出通知
[[NSNotificationCenter defaultCenter]postNotificationName:BabyNotificationAtDidDiscoverPeripheral
object:@{@"central":central,@"peripheral":peripheral,@"advertisementData":advertisementData,@"RSSI":RSSI}];
//扫描到设备callback
if ([currChannel filterOnDiscoverPeripherals]) {
if ([currChannel filterOnDiscoverPeripherals](peripheral.name,advertisementData,RSSI)) {
if ([currChannel blockOnDiscoverPeripherals]) {
[[babySpeaker callbackOnCurrChannel] blockOnDiscoverPeripherals](central,peripheral,advertisementData,RSSI);
}
}
}
//处理连接设备
if (needConnectPeripheral) {
if ([currChannel filterOnconnectToPeripherals](peripheral.name,advertisementData,RSSI)) {
[centralManager connectPeripheral:peripheral options:[currChannel babyOptions].connectPeripheralWithOptions];
//开一个定时器监控连接超时的情况
connectTimer = [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(disconnect:) userInfo:peripheral repeats:NO];
}
}
}
//停止扫描
- (void)disconnect:(id)sender {
[centralManager stopScan];
}
//连接到Peripherals-成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
//发出通知
[[NSNotificationCenter defaultCenter]postNotificationName:BabyNotificationAtDidConnectPeripheral
object:@{@"central":central,@"peripheral":peripheral}];
//设置委托
[peripheral setDelegate:self];
//BabyLog(@">>>连接到名称为(%@)的设备-成功",peripheral.name);
[connectTimer invalidate];//停止时钟
[self addPeripheral:peripheral];
//执行回叫
//扫描到设备callback
if ([currChannel blockOnConnectedPeripheral]) {
[currChannel blockOnConnectedPeripheral](central,peripheral);
}
//扫描外设的服务
if (needDiscoverServices) {
[peripheral discoverServices:[currChannel babyOptions].discoverWithServices];
//discoverIncludedServices
}
}
//连接到Peripherals-失败
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
//发出通知
[[NSNotificationCenter defaultCenter]postNotificationName:BabyNotificationAtDidFailToConnectPeripheral
object:@{@"central":central,@"peripheral":peripheral,@"error":error?error:@""}];
// BabyLog(@">>>连接到名称为(%@)的设备-失败,原因:%@",[peripheral name],[error localizedDescription]);
if ([currChannel blockOnFailToConnect]) {
[currChannel blockOnFailToConnect](central,peripheral,error);
}
}
//Peripherals断开连接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
//发出通知
[[NSNotificationCenter defaultCenter]postNotificationName:BabyNotificationAtDidDisconnectPeripheral
object:@{@"central":central,@"peripheral":peripheral,@"error":error?error:@""}];
// BabyLog(@">>>外设连接断开连接 %@: %@\n", [peripheral name], [error localizedDescription]);
if (error)
{
BabyLog(@">>> didDisconnectPeripheral for %@ with error: %@", peripheral.name, [error localizedDescription]);
}
[self deletePeripheral:peripheral];
if ([currChannel blockOnDisconnect]) {
[currChannel blockOnDisconnect](central,peripheral,error);
}
//判断是否全部链接都已经段开,调用blockOnCancelAllPeripheralsConnection委托
if ([self findConnectedPeripherals].count == 0) {
//停止扫描callback
if ([currChannel blockOnCancelAllPeripheralsConnection]) {
[currChannel blockOnCancelAllPeripheralsConnection](centralManager);
}
// BabyLog(@">>> stopConnectAllPerihperals");
}
//检查并重新连接需要重连的设备
if ([reConnectPeripherals containsObject:peripheral]) {
[self connectToPeripheral:peripheral];
}
}
//扫描到服务
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
//发出通知
[[NSNotificationCenter defaultCenter]postNotificationName:BabyNotificationAtDidDiscoverServices
object:@{@"peripheral":peripheral,@"error":error?error:@""}];
// BabyLog(@">>>扫描到服务:%@",peripheral.services);
if (error) {
BabyLog(@">>>didDiscoverServices for %@ with error: %@", peripheral.name, [error localizedDescription]);
}
//回叫block
if ([currChannel blockOnDiscoverServices]) {
[currChannel blockOnDiscoverServices](peripheral,error);
}
//discover characteristics
if (needDiscoverCharacteristics) {
for (CBService *service in peripheral.services) {
[peripheral discoverCharacteristics:[currChannel babyOptions].discoverWithCharacteristics forService:service];
}
}
}
//发现服务的Characteristics
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
//发出通知
[[NSNotificationCenter defaultCenter]postNotificationName:BabyNotificationAtDidDiscoverCharacteristicsForService
object:@{@"peripheral":peripheral,@"service":service,@"error":error?error:@""}];
if (error) {
BabyLog(@"error didDiscoverCharacteristicsForService for %@ with error: %@", service.UUID, [error localizedDescription]);
// return;
}
//回叫block
if ([currChannel blockOnDiscoverCharacteristics]) {
[currChannel blockOnDiscoverCharacteristics](peripheral,service,error);
}
//如果需要更新Characteristic的值
if (needReadValueForCharacteristic) {
for (CBCharacteristic *characteristic in service.characteristics) {
[peripheral readValueForCharacteristic:characteristic];
//判断读写权限
// if (characteristic.properties & CBCharacteristicPropertyRead ) {
// [peripheral readValueForCharacteristic:characteristic];
// }
}
}
//如果搜索Characteristic的Descriptors
if (needDiscoverDescriptorsForCharacteristic) {
for (CBCharacteristic *characteristic in service.characteristics) {
[peripheral discoverDescriptorsForCharacteristic:characteristic];
}
}
}
//读取Characteristics的值
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
//发出通知
[[NSNotificationCenter defaultCenter]postNotificationName:BabyNotificationAtDidUpdateValueForCharacteristic
object:@{@"peripheral":peripheral,@"characteristic":characteristic,@"error":error?error:@""}];
if (error) {
BabyLog(@"error didUpdateValueForCharacteristic %@ with error: %@", characteristic.UUID, [error localizedDescription]);
// return;
}
//查找字段订阅
if ([babySpeaker notifyCallback:characteristic]) {
[babySpeaker notifyCallback:characteristic](peripheral,characteristic,error);
return;
}
//回叫block
if ([currChannel blockOnReadValueForCharacteristic]) {
[currChannel blockOnReadValueForCharacteristic](peripheral,characteristic,error);
}
}
//发现Characteristics的Descriptors
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
if (error) {
BabyLog(@"error Discovered DescriptorsForCharacteristic for %@ with error: %@", characteristic.UUID, [error localizedDescription]);
// return;
}
//回叫block
if ([currChannel blockOnDiscoverDescriptorsForCharacteristic]) {
[currChannel blockOnDiscoverDescriptorsForCharacteristic](peripheral,characteristic,error);
}
//如果需要更新Characteristic的Descriptors
if (needReadValueForDescriptors) {
for (CBDescriptor *d in characteristic.descriptors) {
[peripheral readValueForDescriptor:d];
}
}
//执行一次的方法
if (oneReadValueForDescriptors) {
for (CBDescriptor *d in characteristic.descriptors) {
[peripheral readValueForDescriptor:d];
}
oneReadValueForDescriptors = NO;
}
}
//读取Characteristics的Descriptors的值
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error {
if (error) {
BabyLog(@"error didUpdateValueForDescriptor for %@ with error: %@", descriptor.UUID, [error localizedDescription]);
// return;
}
//回叫block
if ([currChannel blockOnReadValueForDescriptors]) {
[currChannel blockOnReadValueForDescriptors](peripheral,descriptor,error);
}
}
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
[[NSNotificationCenter defaultCenter]postNotificationName:BabyNotificationAtDidWriteValueForCharacteristic object:@{@"characteristic":characteristic,@"error":error?error:@""}];
// BabyLog(@">>>didWriteValueForCharacteristic");
// BabyLog(@">>>uuid:%@,new value:%@",characteristic.UUID,characteristic.value);
if ([currChannel blockOnDidWriteValueForCharacteristic]) {
[currChannel blockOnDidWriteValueForCharacteristic](characteristic,error);
}
}
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error {
// BabyLog(@">>>didWriteValueForCharacteristic");
// BabyLog(@">>>uuid:%@,new value:%@",descriptor.UUID,descriptor.value);
if ([currChannel blockOnDidWriteValueForDescriptor]) {
[currChannel blockOnDidWriteValueForDescriptor](descriptor,error);
}
}
//characteristic.isNotifying 状态改变
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
[[NSNotificationCenter defaultCenter]postNotificationName:BabyNotificationAtDidUpdateNotificationStateForCharacteristic object:@{@"characteristic":characteristic,@"error":error?error:@""}];
BabyLog(@">>>didUpdateNotificationStateForCharacteristic");
BabyLog(@">>>uuid:%@,isNotifying:%@",characteristic.UUID,characteristic.isNotifying?@"isNotifying":@"Notifying");
if ([currChannel blockOnDidUpdateNotificationStateForCharacteristic]) {
[currChannel blockOnDidUpdateNotificationStateForCharacteristic](characteristic,error);
}
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverIncludedServicesForService:(CBService *)service error:(NSError *)error {
if ([currChannel blockOnDidDiscoverIncludedServicesForService]) {
[currChannel blockOnDidDiscoverIncludedServicesForService](service,error);
}
}
# if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_8_0
- (void)peripheralDidUpdateRSSI:(CBPeripheral *)peripheral error:(nullable NSError *)error {
[[NSNotificationCenter defaultCenter]postNotificationName:BabyNotificationAtDidReadRSSI object:@{@"peripheral":peripheral,@"RSSI":peripheral.RSSI,@"error":error?error:@""}];
BabyLog(@">>>peripheralDidUpdateRSSI -> RSSI:%@",peripheral.RSSI);
if ([currChannel blockOnDidReadRSSI]) {
[currChannel blockOnDidReadRSSI](peripheral.RSSI,error);
}
}
#else
- (void)peripheral:(CBPeripheral *)peripheral didReadRSSI:(NSNumber *)RSSI error:(NSError *)error {
[[NSNotificationCenter defaultCenter]postNotificationName:BabyNotificationAtDidReadRSSI object:@{@"peripheral":peripheral,@"RSSI":RSSI,@"error":error?error:@""}];
BabyLog(@">>>peripheralDidUpdateRSSI -> RSSI:%@",RSSI);
if ([currChannel blockOnDidReadRSSI]) {
[currChannel blockOnDidReadRSSI](RSSI,error);
}
}
#endif
- (void)peripheralDidUpdateName:(CBPeripheral *)peripheral {
if ([currChannel blockOnDidUpdateName]) {
[currChannel blockOnDidUpdateName](peripheral);
}
}
- (void)peripheral:(CBPeripheral *)peripheral didModifyServices:(NSArray *)invalidatedServices {
if ([currChannel blockOnDidModifyServices]) {
[currChannel blockOnDidModifyServices](peripheral,invalidatedServices);
}
}
/**
sometimes ever,sometimes never. 相聚有时,后会无期
this is center with peripheral's story
**/
//sometimes ever:添加断开重连接的设备
- (void)sometimes_ever:(CBPeripheral *)peripheral {
if (![reConnectPeripherals containsObject:peripheral]) {
[reConnectPeripherals addObject:peripheral];
}
}
//sometimes never:删除需要重连接的设备
- (void)sometimes_never:(CBPeripheral *)peripheral {
[reConnectPeripherals removeObject:peripheral];
}
#pragma mark - 私有方法
#pragma mark - 设备list管理
- (void)addDiscoverPeripheral:(CBPeripheral *)peripheral{
if (![discoverPeripherals containsObject:peripheral]) {
[discoverPeripherals addObject:peripheral];
}
}
- (void)addPeripheral:(CBPeripheral *)peripheral {
if (![connectedPeripherals containsObject:peripheral]) {
[connectedPeripherals addObject:peripheral];
}
}
- (void)deletePeripheral:(CBPeripheral *)peripheral{
[connectedPeripherals removeObject:peripheral];
}
- (CBPeripheral *)findConnectedPeripheral:(NSString *)peripheralName {
for (CBPeripheral *p in connectedPeripherals) {
if ([p.name isEqualToString:peripheralName]) {
return p;
}
}
return nil;
}
- (NSArray *)findConnectedPeripherals{
return connectedPeripherals;
}
@end
/*
BabyBluetooth
简单易用的蓝牙ble库,基于CoreBluetooth 作者:刘彦玮
https://github.com/coolnameismy/BabyBluetooth
@brief 预定义一些库的执行行为和配置
*/
// Created by 刘彦玮 on 6/4/19.
// Copyright © 2016年 liuyanwei. All rights reserved.
//
#import <Foundation/Foundation.h>
# pragma mark - baby 行为定义
//Baby if show log 是否打印日志,默认1:打印 ,0:不打印
#define KBABY_IS_SHOW_LOG 1
//CBcentralManager等待设备打开次数
# define KBABY_CENTRAL_MANAGER_INIT_WAIT_TIMES 5
//CBcentralManager等待设备打开间隔时间
# define KBABY_CENTRAL_MANAGER_INIT_WAIT_SECOND 2.0
//BabyRhythm默认心跳时间间隔
#define KBABYRHYTHM_BEATS_DEFAULT_INTERVAL 3;
//Baby默认链式方法channel名称
#define KBABY_DETAULT_CHANNEL @"babyDefault"
# pragma mark - baby通知
//蓝牙系统通知
//centralManager status did change notification
#define BabyNotificationAtCentralManagerDidUpdateState @"BabyNotificationAtCentralManagerDidUpdateState"
//did discover peripheral notification
#define BabyNotificationAtDidDiscoverPeripheral @"BabyNotificationAtDidDiscoverPeripheral"
//did connection peripheral notification
#define BabyNotificationAtDidConnectPeripheral @"BabyNotificationAtDidConnectPeripheral"
//did filed connect peripheral notification
#define BabyNotificationAtDidFailToConnectPeripheral @"BabyNotificationAtDidFailToConnectPeripheral"
//did disconnect peripheral notification
#define BabyNotificationAtDidDisconnectPeripheral @"BabyNotificationAtDidDisconnectPeripheral"
//did discover service notification
#define BabyNotificationAtDidDiscoverServices @"BabyNotificationAtDidDiscoverServices"
//did discover characteristics notification
#define BabyNotificationAtDidDiscoverCharacteristicsForService @"BabyNotificationAtDidDiscoverCharacteristicsForService"
//did read or notify characteristic when received value notification
#define BabyNotificationAtDidUpdateValueForCharacteristic @"BabyNotificationAtDidUpdateValueForCharacteristic"
//did write characteristic and response value notification
#define BabyNotificationAtDidWriteValueForCharacteristic @"BabyNotificationAtDidWriteValueForCharacteristic"
//did change characteristis notify status notification
#define BabyNotificationAtDidUpdateNotificationStateForCharacteristic @"BabyNotificationAtDidUpdateNotificationStateForCharacteristic"
//did read rssi and receiced value notification
#define BabyNotificationAtDidReadRSSI @"BabyNotificationAtDidReadRSSI"
//蓝牙扩展通知
// did centralManager enable notification
#define BabyNotificationAtCentralManagerEnable @"BabyNotificationAtCentralManagerEnable"
# pragma mark - baby 定义的方法
//Baby log
#define BabyLog(fmt, ...) if(KBABY_IS_SHOW_LOG) { NSLog(fmt,##__VA_ARGS__); }
@interface BabyDefine : NSObject
@end
//
// BabyBlueDefine.m
// BabyTestProject
//
// Created by xuanyan.lyw on 16/4/19.
// Copyright © 2016年 liuyanwei. All rights reserved.
//
#import "BabyDefine.h"
@implementation BabyDefine
@end
/*
BabyBluetooth
简单易用的蓝牙ble库,基于CoreBluetooth 作者:刘彦玮
https://github.com/coolnameismy/BabyBluetooth
@brief babybluetooth 封装蓝牙外设模式的运行时参数,可以实现后台模式,重复接收广播,查找service参数,查找characteristic参数
*/
// Created by 刘彦玮 on 15/9/27.
// Copyright © 2015年 刘彦玮. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreBluetooth/CoreBluetooth.h>
@interface BabyOptions : NSObject
#pragma mark - 属性
/*!
* 扫描参数,centralManager:scanForPeripheralsWithServices:self.scanForPeripheralsWithServices options:self.scanForPeripheralsWithOptions
* @param An optional dictionary specifying options for the scan.
* @see centralManager:scanForPeripheralsWithServices
* @seealso CBCentralManagerScanOptionAllowDuplicatesKey :忽略同一个Peripheral端的多个发现事件被聚合成一个发现事件
* @seealso CBCentralManagerScanOptionSolicitedServiceUUIDsKey
*/
@property (nonatomic, copy) NSDictionary *scanForPeripheralsWithOptions;
/*!
* 连接设备的参数
* @method connectPeripheral:options:
* @param An optional dictionary specifying connection behavior options.
* @see centralManager:didConnectPeripheral:
* @see centralManager:didFailToConnectPeripheral:error:
* @seealso CBConnectPeripheralOptionNotifyOnConnectionKey
* @seealso CBConnectPeripheralOptionNotifyOnDisconnectionKey
* @seealso CBConnectPeripheralOptionNotifyOnNotificationKey
*/
@property (nonatomic, copy) NSDictionary *connectPeripheralWithOptions;
/*!
* 扫描参数,centralManager:scanForPeripheralsWithServices:self.scanForPeripheralsWithServices options:self.scanForPeripheralsWithOptions
*@param serviceUUIDs A list of <code>CBUUID</code> objects representing the service(s) to scan for.
*@see centralManager:scanForPeripheralsWithServices
*/
@property (nonatomic, copy) NSArray *scanForPeripheralsWithServices;
// [peripheral discoverServices:self.discoverWithServices];
@property (nonatomic, copy) NSArray *discoverWithServices;
// [peripheral discoverCharacteristics:self.discoverWithCharacteristics forService:service];
@property (nonatomic, copy) NSArray *discoverWithCharacteristics;
#pragma mark - 构造方法
- (instancetype)initWithscanForPeripheralsWithOptions:(NSDictionary *)scanForPeripheralsWithOptions
connectPeripheralWithOptions:(NSDictionary *)connectPeripheralWithOptions;
- (instancetype)initWithscanForPeripheralsWithOptions:(NSDictionary *)scanForPeripheralsWithOptions
connectPeripheralWithOptions:(NSDictionary *)connectPeripheralWithOptions
scanForPeripheralsWithServices:(NSArray *)scanForPeripheralsWithServices
discoverWithServices:(NSArray *)discoverWithServices
discoverWithCharacteristics:(NSArray *)discoverWithCharacteristics;
@end
//
// BabyClothes.m
// BabyBluetoothAppDemo
//
// Created by 刘彦玮 on 15/9/27.
// Copyright © 2015年 刘彦玮. All rights reserved.
//
#import "BabyOptions.h"
@implementation BabyOptions
- (instancetype)init {
self = [super init];
if (self) {
_scanForPeripheralsWithOptions = nil;
_connectPeripheralWithOptions = nil;
_scanForPeripheralsWithServices = nil;
_discoverWithServices = nil;
_discoverWithCharacteristics = nil;
}
return self;
}
- (instancetype)initWithscanForPeripheralsWithOptions:(NSDictionary *)scanForPeripheralsWithOptions
connectPeripheralWithOptions:(NSDictionary *)connectPeripheralWithOptions
{
self = [super init];
if (self) {
[self setScanForPeripheralsWithOptions:scanForPeripheralsWithOptions];
[self setConnectPeripheralWithOptions:connectPeripheralWithOptions];
}
return self;
}
- (instancetype)initWithscanForPeripheralsWithOptions:(NSDictionary *)scanForPeripheralsWithOptions
connectPeripheralWithOptions:(NSDictionary *)connectPeripheralWithOptions
scanForPeripheralsWithServices:(NSArray *)scanForPeripheralsWithServices
discoverWithServices:(NSArray *)discoverWithServices
discoverWithCharacteristics:(NSArray *)discoverWithCharacteristics
{
self = [self initWithscanForPeripheralsWithOptions:scanForPeripheralsWithOptions connectPeripheralWithOptions:connectPeripheralWithOptions];
if (self) {
[self setScanForPeripheralsWithServices:scanForPeripheralsWithServices];
[self setDiscoverWithServices:discoverWithServices];
[self setDiscoverWithCharacteristics:discoverWithCharacteristics];
}
return self;
}
@end
/*
BabyBluetooth
简单易用的蓝牙ble库,基于CoreBluetooth 作者:刘彦玮
https://github.com/coolnameismy/BabyBluetooth
@brief 蓝牙外设模式实现类
*/
// Created by 刘彦玮 on 15/12/12.
// Copyright © 2015年 刘彦玮. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreBluetooth/CoreBluetooth.h>
#import "BabyToy.h"
#import "BabySpeaker.h"
@interface BabyPeripheralManager : NSObject<CBPeripheralManagerDelegate> {
@public
//回叫方法
BabySpeaker *babySpeaker;
}
/**
添加服务
*/
- (BabyPeripheralManager *(^)(NSArray *array))addServices;
/**
启动广播
*/
- (BabyPeripheralManager *(^)())startAdvertising;
//外设管理器
@property (nonatomic, strong) CBPeripheralManager *peripheralManager;
@property (nonatomic, copy) NSString *localName;
@property (nonatomic, strong) NSMutableArray *services;
@end
/**
* 构造Characteristic,并加入service
* service:CBService
* param`ter for properties :option 'r' | 'w' | 'n' or combination
* r CBCharacteristicPropertyRead
* w CBCharacteristicPropertyWrite
* n CBCharacteristicPropertyNotify
* default value is rw Read-Write
* paramter for descriptor:be uesd descriptor for characteristic
*/
void makeCharacteristicToService(CBMutableService *service,NSString *UUID,NSString *properties,NSString *descriptor);
/**
* 构造一个包含初始值的Characteristic,并加入service,包含了初值的characteristic必须设置permissions和properties都为只读
* make characteristic then add to service, a static characteristic mean it has a initial value .according apple rule, it must set properties and permissions to CBCharacteristicPropertyRead and CBAttributePermissionsReadable
*/
void makeStaticCharacteristicToService(CBMutableService *service,NSString *UUID,NSString *descriptor,NSData *data);
/**
生成CBService
*/
CBMutableService* makeCBService(NSString *UUID);
/**
生成UUID
*/
NSString* genUUID();
//
// BabyPeripheralManager.m
// BluetoothStubOnIOS
//
// Created by 刘彦玮 on 15/12/12.
// Copyright © 2015年 刘彦玮. All rights reserved.
//
#import "BabyPeripheralManager.h"
#import "BabyDefine.h"
#define callbackBlock(...) if ([[babySpeaker callback] __VA_ARGS__]) [[babySpeaker callback] __VA_ARGS__ ]
@implementation BabyPeripheralManager {
int PERIPHERAL_MANAGER_INIT_WAIT_TIMES;
int didAddServices;
NSTimer *addServiceTask;
}
- (instancetype)init {
self = [super init];
if (self) {
_localName = @"baby-default-name";
_peripheralManager = [[CBPeripheralManager alloc]initWithDelegate:self queue:nil options:nil];
}
return self;
}
- (BabyPeripheralManager *(^)())startAdvertising {
return ^BabyPeripheralManager *() {
if ([self canStartAdvertising]) {
PERIPHERAL_MANAGER_INIT_WAIT_TIMES = 0;
NSMutableArray *UUIDS = [NSMutableArray array];
for (CBMutableService *s in _services) {
[UUIDS addObject:s.UUID];
}
//启动广播
[_peripheralManager startAdvertising:
@{
CBAdvertisementDataServiceUUIDsKey : UUIDS
,CBAdvertisementDataLocalNameKey : _localName
}];
}
else {
PERIPHERAL_MANAGER_INIT_WAIT_TIMES++;
if (PERIPHERAL_MANAGER_INIT_WAIT_TIMES > 5) {
BabyLog(@">>>error: 第%d次等待peripheralManager打开任然失败,请检查蓝牙设备是否可用",PERIPHERAL_MANAGER_INIT_WAIT_TIMES);
}
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 3.0 * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
self.startAdvertising();
});
BabyLog(@">>> 第%d次等待peripheralManager打开",PERIPHERAL_MANAGER_INIT_WAIT_TIMES);
}
return self;
};
}
- (BOOL)canStartAdvertising {
if (_peripheralManager.state != CBPeripheralManagerStatePoweredOn) {
return NO;
}
if (didAddServices != _services.count) {
return NO;
}
return YES;
}
- (BOOL)isPoweredOn {
if (_peripheralManager.state != CBPeripheralManagerStatePoweredOn) {
return NO;
}
return YES;
}
- (BabyPeripheralManager *(^)(NSArray *array))addServices {
return ^BabyPeripheralManager*(NSArray *array) {
_services = [NSMutableArray arrayWithArray:array];
[self addServicesToPeripheral];
return self;
};
}
- (void)addServicesToPeripheral {
if ([self isPoweredOn]) {
for (CBMutableService *s in _services) {
[_peripheralManager addService:s];
}
}
else {
[addServiceTask setFireDate:[NSDate distantPast]];
addServiceTask = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(addServicesToPeripheral) userInfo:nil repeats:NO];
}
}
#pragma mark - peripheralManager delegate
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral {
switch (peripheral.state) {
case CBPeripheralManagerStateUnknown:
BabyLog(@">>>CBPeripheralManagerStateUnknown");
break;
case CBPeripheralManagerStateResetting:
BabyLog(@">>>CBPeripheralManagerStateResetting");
break;
case CBPeripheralManagerStateUnsupported:
BabyLog(@">>>CBPeripheralManagerStateUnsupported");
break;
case CBPeripheralManagerStateUnauthorized:
BabyLog(@">>>CBPeripheralManagerStateUnauthorized");
break;
case CBPeripheralManagerStatePoweredOff:
BabyLog(@">>>CBPeripheralManagerStatePoweredOff");
break;
case CBPeripheralManagerStatePoweredOn:
BabyLog(@">>>CBPeripheralManagerStatePoweredOn");
//发送centralManagerDidUpdateState通知
[[NSNotificationCenter defaultCenter]postNotificationName:@"CBPeripheralManagerStatePoweredOn" object:nil];
break;
default:
break;
}
// if([babySpeaker callback] blockOnPeripheralModelDidUpdateState) {
// [currChannel blockOnCancelScan](centralManager);
// }
callbackBlock(blockOnPeripheralModelDidUpdateState)(peripheral);
}
- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error {
didAddServices++;
callbackBlock(blockOnPeripheralModelDidAddService)(peripheral,service,error);
}
- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error {
callbackBlock(blockOnPeripheralModelDidStartAdvertising)(peripheral,error);
}
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request {
callbackBlock(blockOnPeripheralModelDidReceiveReadRequest)(peripheral, request);
}
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray *)requests {
callbackBlock(blockOnPeripheralModelDidReceiveWriteRequests)(peripheral,requests);
}
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic {
callbackBlock(blockOnPeripheralModelDidSubscribeToCharacteristic)(peripheral,central,characteristic);
}
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic {
callbackBlock(blockOnPeripheralModelDidUnSubscribeToCharacteristic)(peripheral,central,characteristic);
}
@end
void makeCharacteristicToService(CBMutableService *service,NSString *UUID,NSString *properties,NSString *descriptor) {
//paramter for properties
CBCharacteristicProperties prop = 0x00;
if ([properties containsString:@"r"]) {
prop = prop | CBCharacteristicPropertyRead;
}
if ([properties containsString:@"w"]) {
prop = prop | CBCharacteristicPropertyWrite;
}
if ([properties containsString:@"n"]) {
prop = prop | CBCharacteristicPropertyNotify;
}
if (properties == nil || [properties isEqualToString:@""]) {
prop = CBCharacteristicPropertyRead | CBCharacteristicPropertyWrite;
}
CBMutableCharacteristic *c = [[CBMutableCharacteristic alloc]initWithType:[CBUUID UUIDWithString:UUID] properties:prop value:nil permissions:CBAttributePermissionsReadable | CBAttributePermissionsWriteable];
//paramter for descriptor
if (!(descriptor == nil || [descriptor isEqualToString:@""])) {
//c设置description对应的haracteristics字段描述
CBUUID *CBUUIDCharacteristicUserDescriptionStringUUID = [CBUUID UUIDWithString:CBUUIDCharacteristicUserDescriptionString];
CBMutableDescriptor *desc = [[CBMutableDescriptor alloc]initWithType: CBUUIDCharacteristicUserDescriptionStringUUID value:descriptor];
[c setDescriptors:@[desc]];
}
if (!service.characteristics) {
service.characteristics = @[];
}
NSMutableArray *cs = [service.characteristics mutableCopy];
[cs addObject:c];
service.characteristics = [cs copy];
}
void makeStaticCharacteristicToService(CBMutableService *service,NSString *UUID,NSString *descriptor,NSData *data) {
CBMutableCharacteristic *c = [[CBMutableCharacteristic alloc]initWithType:[CBUUID UUIDWithString:UUID] properties:CBCharacteristicPropertyRead value:data permissions:CBAttributePermissionsReadable];
//paramter for descriptor
if (!(descriptor == nil || [descriptor isEqualToString:@""])) {
//c设置description对应的haracteristics字段描述
CBUUID *CBUUIDCharacteristicUserDescriptionStringUUID = [CBUUID UUIDWithString:CBUUIDCharacteristicUserDescriptionString];
CBMutableDescriptor *desc = [[CBMutableDescriptor alloc]initWithType: CBUUIDCharacteristicUserDescriptionStringUUID value:descriptor];
[c setDescriptors:@[desc]];
}
if (!service.characteristics) {
service.characteristics = @[];
}
NSMutableArray *cs = [service.characteristics mutableCopy];
[cs addObject:c];
service.characteristics = [cs copy];
}
CBMutableService* makeCBService(NSString *UUID)
{
CBMutableService *s = [[CBMutableService alloc]initWithType:[CBUUID UUIDWithString:UUID] primary:YES];
return s;
}
NSString * genUUID()
{
CFUUIDRef uuid_ref = CFUUIDCreate(NULL);
CFStringRef uuid_string_ref= CFUUIDCreateString(NULL, uuid_ref);
CFRelease(uuid_ref);
NSString *uuid = [NSString stringWithString:(__bridge NSString*)uuid_string_ref];
CFRelease(uuid_string_ref);
return uuid;
}
/*
BabyBluetooth
简单易用的蓝牙ble库,基于CoreBluetooth 作者:刘彦玮
https://github.com/coolnameismy/BabyBluetooth
@brief babybluetooth Rhythm用于检测蓝牙的任务执行情况,处理复杂的蓝牙流程操作
*/
//
// Created by ZTELiuyw on 15/9/15.
// Copyright (c) 2015年 刘彦玮. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "BabyDefine.h"
@interface BabyRhythm : NSObject
typedef void (^BBBeatsBreakBlock)(BabyRhythm *bry);
typedef void (^BBBeatsOverBlock)(BabyRhythm *bry);
//timer for beats
@property (nonatomic, strong) NSTimer *beatsTimer;
//beat interval
@property NSInteger beatsInterval;
#pragma mark beats
//心跳
- (void)beats;
//主动中断心跳
- (void)beatsBreak;
//结束心跳,结束后会进入BlockOnBeatOver,并且结束后再不会在触发BlockOnBeatBreak
- (void)beatsOver;
//恢复心跳,beatsOver操作后可以使用beatsRestart恢复心跳,恢复后又可以进入BlockOnBeatBreak方法
- (void)beatsRestart;
//心跳中断的委托
- (void)setBlockOnBeatsBreak:(void(^)(BabyRhythm *bry))block;
//心跳结束的委托
- (void)setBlockOnBeatsOver:(void(^)(BabyRhythm *bry))block;
@end
//
// BabyBeats.m
// BabyBluetoothAppDemo
//
// Created by ZTELiuyw on 15/9/15.
// Copyright (c) 2015年 刘彦玮. All rights reserved.
//
#import "BabyRhythm.h"
#import "BabyDefine.h"
@implementation BabyRhythm {
BOOL isOver;
BBBeatsBreakBlock blockOnBeatBreak;
BBBeatsOverBlock blockOnBeatOver;
}
- (instancetype)init {
self = [super init];
if (self) {
//beatsInterval
_beatsInterval = KBABYRHYTHM_BEATS_DEFAULT_INTERVAL;
}
return self;
}
- (void)beats {
if (isOver) {
BabyLog(@">>>beats isOver");
return;
}
BabyLog(@">>>beats at :%@",[NSDate date]);
if (self.beatsTimer) {
[self.beatsTimer setFireDate: [[NSDate date]dateByAddingTimeInterval:self.beatsInterval]];
}
else {
self.beatsTimer = [NSTimer timerWithTimeInterval:self.beatsInterval target:self selector:@selector(beatsBreak) userInfo:nil repeats:YES];
[self.beatsTimer setFireDate: [[NSDate date]dateByAddingTimeInterval:self.beatsInterval]];
[[NSRunLoop currentRunLoop] addTimer:self.beatsTimer forMode:NSRunLoopCommonModes];
}
}
- (void)beatsBreak {
BabyLog(@">>>beatsBreak :%@",[NSDate date]);
[self.beatsTimer setFireDate:[NSDate distantFuture]];
if (blockOnBeatBreak) {
blockOnBeatBreak(self);
}
}
- (void)beatsOver {
BabyLog(@">>>beatsOver :%@",[NSDate date]);
[self.beatsTimer setFireDate:[NSDate distantFuture]];
isOver = YES;
if (blockOnBeatOver) {
blockOnBeatOver(self);
}
}
- (void)beatsRestart {
BabyLog(@">>>beatsRestart :%@",[NSDate date]);
isOver = NO;
[self beats];
}
- (void)setBlockOnBeatsBreak:(void(^)(BabyRhythm *bry))block {
blockOnBeatBreak = block;
}
- (void)setBlockOnBeatsOver:(void(^)(BabyRhythm *bry))block {
blockOnBeatOver = block;
}
@end
/*
BabyBluetooth
简单易用的蓝牙ble库,基于CoreBluetooth 作者:刘彦玮
https://github.com/coolnameismy/BabyBluetooth
@brief babybluetooth block查找和channel切换
*/
// Created by 刘彦玮 on 15/9/2.
// Copyright (c) 2015年 刘彦玮. All rights reserved.
//
#import "BabyCallback.h"
#import <CoreBluetooth/CoreBluetooth.h>
@interface BabySpeaker : NSObject
- (BabyCallback *)callback;
- (BabyCallback *)callbackOnCurrChannel;
- (BabyCallback *)callbackOnChnnel:(NSString *)channel;
- (BabyCallback *)callbackOnChnnel:(NSString *)channel
createWhenNotExist:(BOOL)createWhenNotExist;
//切换频道
- (void)switchChannel:(NSString *)channel;
//添加到notify list
- (void)addNotifyCallback:(CBCharacteristic *)c
withBlock:(void(^)(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error))block;
//添加到notify list
- (void)removeNotifyCallback:(CBCharacteristic *)c;
//获取notify list
- (NSMutableDictionary *)notifyCallBackList;
//获取notityBlock
- (void(^)(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error))notifyCallback:(CBCharacteristic *)c;
@end
/*
BabyBluetooth
简单易用的蓝牙ble库,基于CoreBluetooth 作者:刘彦玮
https://github.com/coolnameismy/BabyBluetooth
*/
// Created by 刘彦玮 on 15/9/2.
// Copyright (c) 2015年 刘彦玮. All rights reserved.
//
#import "BabySpeaker.h"
#import "BabyDefine.h"
typedef NS_ENUM(NSUInteger, BabySpeakerType) {
BabySpeakerTypeDiscoverPeripherals,
BabySpeakerTypeConnectedPeripheral,
BabySpeakerTypeDiscoverPeripheralsFailToConnect,
BabySpeakerTypeDiscoverPeripheralsDisconnect,
BabySpeakerTypeDiscoverPeripheralsDiscoverServices,
BabySpeakerTypeDiscoverPeripheralsDiscoverCharacteristics,
BabySpeakerTypeDiscoverPeripheralsReadValueForCharacteristic,
BabySpeakerTypeDiscoverPeripheralsDiscoverDescriptorsForCharacteristic,
BabySpeakerTypeDiscoverPeripheralsReadValueForDescriptorsBlock
};
@implementation BabySpeaker {
//所有委托频道
NSMutableDictionary *channels;
//当前委托频道
NSString *currChannel;
//notifyList
NSMutableDictionary *notifyList;
}
- (instancetype)init {
self = [super init];
if (self) {
BabyCallback *defaultCallback = [[BabyCallback alloc]init];
notifyList = [[NSMutableDictionary alloc]init];
channels = [[NSMutableDictionary alloc]init];
currChannel = KBABY_DETAULT_CHANNEL;
[channels setObject:defaultCallback forKey:KBABY_DETAULT_CHANNEL];
}
return self;
}
- (BabyCallback *)callback {
return [channels objectForKey:KBABY_DETAULT_CHANNEL];
}
- (BabyCallback *)callbackOnCurrChannel {
return [self callbackOnChnnel:currChannel];
}
- (BabyCallback *)callbackOnChnnel:(NSString *)channel {
if (!channel) {
[self callback];
}
return [channels objectForKey:channel];
}
- (BabyCallback *)callbackOnChnnel:(NSString *)channel
createWhenNotExist:(BOOL)createWhenNotExist {
BabyCallback *callback = [channels objectForKey:channel];
if (!callback && createWhenNotExist) {
callback = [[BabyCallback alloc]init];
[channels setObject:callback forKey:channel];
}
return callback;
}
- (void)switchChannel:(NSString *)channel {
if (channel) {
if ([self callbackOnChnnel:channel]) {
currChannel = channel;
BabyLog(@">>>已切换到%@",channel);
}
else {
BabyLog(@">>>所要切换的channel不存在");
}
}
else {
currChannel = KBABY_DETAULT_CHANNEL;
BabyLog(@">>>已切换到默认频道");
}
}
//添加到notify list
- (void)addNotifyCallback:(CBCharacteristic *)c
withBlock:(void(^)(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error))block {
[notifyList setObject:block forKey:c.UUID.description];
}
//添加到notify list
- (void)removeNotifyCallback:(CBCharacteristic *)c {
[notifyList removeObjectForKey:c.UUID.description];
}
//获取notify list
- (NSMutableDictionary *)notifyCallBackList {
return notifyList;
}
//获取notityBlock
- (void(^)(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error))notifyCallback:(CBCharacteristic *)c {
return [notifyList objectForKey:c.UUID.description];
}
@end
/*
BabyBluetooth
简单易用的蓝牙ble库,基于CoreBluetooth 作者:刘彦玮
https://github.com/coolnameismy/BabyBluetooth
@brief babybluetooth 工具类
*/
// Created by 刘彦玮 on 15/8/1.
// Copyright (c) 2015年 刘彦玮. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreBluetooth/CoreBluetooth.h>
@interface BabyToy : NSObject
//十六进制转换为普通字符串的。
+ (NSString *)ConvertHexStringToString:(NSString *)hexString;
//普通字符串转换为十六进制
+ (NSString *)ConvertStringToHexString:(NSString *)string;
//int转data
+(NSData *)ConvertIntToData:(int)i;
//data转int
+(int)ConvertDataToInt:(NSData *)data;
//十六进制转换为普通字符串的。
+ (NSData *)ConvertHexStringToData:(NSString *)hexString;
//根据UUIDString查找CBCharacteristic
+(CBCharacteristic *)findCharacteristicFormServices:(NSMutableArray *)services
UUIDString:(NSString *)UUIDString;
@end
/*
BabyBluetooth
简单易用的蓝牙ble库,基于CoreBluetooth 作者:刘彦玮
https://github.com/coolnameismy/BabyBluetooth
*/
// Created by 刘彦玮 on 15/8/1.
// Copyright (c) 2015年 刘彦玮. All rights reserved.
//
#import "BabyToy.h"
@implementation BabyToy
//十六进制转换为普通字符串的。
+ (NSString *)ConvertHexStringToString:(NSString *)hexString {
char *myBuffer = (char *)malloc((int)[hexString length] / 2 + 1);
bzero(myBuffer, [hexString length] / 2 + 1);
for (int i = 0; i < [hexString length] - 1; i += 2) {
unsigned int anInt;
NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];
NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];
[scanner scanHexInt:&anInt];
myBuffer[i / 2] = (char)anInt;
}
NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:4];
// BabyLog(@"===字符串===%@",unicodeString);
return unicodeString;
}
//普通字符串转换为十六进制
+ (NSString *)ConvertStringToHexString:(NSString *)string {
NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];
Byte *bytes = (Byte *)[myD bytes];
//下面是Byte 转换为16进制。
NSString *hexStr=@"";
for (int i=0;i<[myD length];i++) {
NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
if ([newHexStr length]==1) {
hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
}
else{
hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
}
}
return hexStr;
}
//int转data
+ (NSData *)ConvertIntToData:(int)i {
NSData *data = [NSData dataWithBytes: &i length: sizeof(i)];
return data;
}
//data转int
+ (int)ConvertDataToInt:(NSData *)data {
int i;
[data getBytes:&i length:sizeof(i)];
return i;
}
//十六进制转换为普通字符串的。
+ (NSData *)ConvertHexStringToData:(NSString *)hexString {
NSData *data = [[BabyToy ConvertHexStringToString:hexString] dataUsingEncoding:NSUTF8StringEncoding];
return data;
}
//根据UUIDString查找CBCharacteristic
+ (CBCharacteristic *)findCharacteristicFormServices:(NSMutableArray *)services
UUIDString:(NSString *)UUIDString {
for (CBService *s in services) {
for (CBCharacteristic *c in s.characteristics) {
if ([c.UUID.UUIDString isEqualToString:UUIDString]) {
return c;
}
}
}
return nil;
}
@end
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
import UIKit import UIKit
import Alamofire import Alamofire
import CryptoSwift import CryptoSwift
import LGButton
class LoginViewController: BaseViewController { class LoginViewController: BaseViewController {
...@@ -31,6 +31,7 @@ self.navigationController?.pushViewController(vc, animated: true) ...@@ -31,6 +31,7 @@ self.navigationController?.pushViewController(vc, animated: true)
self.navigationController?.pushViewController(vc, animated: true) self.navigationController?.pushViewController(vc, animated: true)
} }
//MARK: - 输入账号、密码、验证码 //MARK: - 输入账号、密码、验证码
@IBOutlet weak var loginBtn: LGButton!
@IBOutlet weak var codeView: UIView! @IBOutlet weak var codeView: UIView!
@IBOutlet weak var phoneTF: UITextField! @IBOutlet weak var phoneTF: UITextField!
@IBOutlet weak var passTF: UITextField! @IBOutlet weak var passTF: UITextField!
...@@ -60,6 +61,9 @@ self.navigationController?.pushViewController(vc, animated: true) ...@@ -60,6 +61,9 @@ self.navigationController?.pushViewController(vc, animated: true)
make.left.right.equalTo(0) make.left.right.equalTo(0)
make.height.equalTo(60) make.height.equalTo(60)
} }
//登录中状态
// loginBtn.isLoading = true
} }
} }
...@@ -13,6 +13,7 @@ ...@@ -13,6 +13,7 @@
<outlet property="bannerImg" destination="AdE-4p-9iF" id="Eub-F8-pfv"/> <outlet property="bannerImg" destination="AdE-4p-9iF" id="Eub-F8-pfv"/>
<outlet property="codeTF" destination="qfV-go-Nf1" id="dsy-cS-dte"/> <outlet property="codeTF" destination="qfV-go-Nf1" id="dsy-cS-dte"/>
<outlet property="codeView" destination="dgy-iq-Edz" id="6HM-ez-mXt"/> <outlet property="codeView" destination="dgy-iq-Edz" id="6HM-ez-mXt"/>
<outlet property="loginBtn" destination="I08-S6-beg" id="bDZ-w8-CrS"/>
<outlet property="passTF" destination="ipW-Al-eG6" id="P2q-AH-6SO"/> <outlet property="passTF" destination="ipW-Al-eG6" id="P2q-AH-6SO"/>
<outlet property="phoneTF" destination="xEL-ml-rz8" id="wzo-Rz-RWS"/> <outlet property="phoneTF" destination="xEL-ml-rz8" id="wzo-Rz-RWS"/>
<outlet property="shBtn" destination="xgv-CB-GLZ" id="3XV-lQ-3ja"/> <outlet property="shBtn" destination="xgv-CB-GLZ" id="3XV-lQ-3ja"/>
...@@ -257,6 +258,10 @@ ...@@ -257,6 +258,10 @@
<real key="value" value="17"/> <real key="value" value="17"/>
</userDefinedRuntimeAttribute> </userDefinedRuntimeAttribute>
<userDefinedRuntimeAttribute type="string" keyPath="titleFontName" value="PingFang SC Medium"/> <userDefinedRuntimeAttribute type="string" keyPath="titleFontName" value="PingFang SC Medium"/>
<userDefinedRuntimeAttribute type="string" keyPath="loadingString" value="登录中"/>
<userDefinedRuntimeAttribute type="number" keyPath="loadingFontSize">
<real key="value" value="17"/>
</userDefinedRuntimeAttribute>
</userDefinedRuntimeAttributes> </userDefinedRuntimeAttributes>
<connections> <connections>
<action selector="loginAction:" destination="-1" eventType="touchUpInside" id="jlC-gq-qwQ"/> <action selector="loginAction:" destination="-1" eventType="touchUpInside" id="jlC-gq-qwQ"/>
......
...@@ -110,7 +110,7 @@ ...@@ -110,7 +110,7 @@
<key>SVProgressHUD.xcscheme_^#shared#^_</key> <key>SVProgressHUD.xcscheme_^#shared#^_</key>
<dict> <dict>
<key>orderHint</key> <key>orderHint</key>
<integer>22</integer> <integer>21</integer>
</dict> </dict>
<key>SkeletonView.xcscheme</key> <key>SkeletonView.xcscheme</key>
<dict> <dict>
......
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