代码拉取完成,页面将自动刷新
//
// BluetoothManager.m
// 蓝牙
//
// Created by 赵鹏宇 on 16/1/25.
// Copyright © 2016年 赵鹏宇. All rights reserved.
//
#import <CoreBluetooth/CoreBluetooth.h>
#import "BluetoothManager.h"
#import "ProgressHUD.h"
#define ServiceUUID @"FFF0"
#define NewCharacteristicUUID @"FFF1"
@interface BluetoothManager ()<CBCentralManagerDelegate,CBPeripheralDelegate>
@property (nonatomic,strong) CBCentralManager *manager;
@property (nonatomic,strong) CBPeripheral *peripherals;
@property (nonatomic,strong) CBCharacteristic *characteristics;
@property (nonatomic,strong) NSMutableArray *address;
@property (nonatomic,strong) NSMutableArray *peripheralsArray;
@property (nonatomic,strong) NSMutableArray *chars;
@property (nonatomic,strong) NSMutableDictionary *charMap;
@property (nonatomic,strong) NSMutableDictionary *charMapOne;
@property (nonatomic,strong) NSMutableDictionary *flagMap;
@property (nonatomic,strong) NSMutableDictionary *successMap;
@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic,assign) BOOL isIn;
@property (nonatomic,strong) GWPeripheral *currentPModel;
@property (strong, nonatomic) NSMutableSet *connectPerpherals;
@end
@implementation BluetoothManager
+ (instancetype)standardManager
{
static BluetoothManager *m = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
m = [[BluetoothManager alloc] init];
});
return m;
}
- (instancetype)init
{
self = [super init];
if (self) {
self.address=[NSMutableArray array];
self.charMapOne=[NSMutableDictionary dictionary];
self.charMap=[NSMutableDictionary dictionary];
self.peripheralsArray = [NSMutableArray array];
self.peripheralsNameArray = [NSMutableArray array];
self.connectedPeripherals = [NSMutableArray array];
self.connectPerpherals = [NSMutableSet set];
self.chars=[NSMutableArray array];
self.successMap=[NSMutableDictionary dictionary];
self.flagMap=[NSMutableDictionary dictionary];
//订阅键盘通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopScanPeripheral) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startScanPeripheral) name:UIKeyboardWillHideNotification object:nil];
}
return self;
}
- (void)stopScanPeripheral
{
[self.manager stopScan];
}
- (void)startScanPeripheral
{
[self.manager scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey:@YES}];
}
- (void)startDiscoverPeripheral
{
NSMutableArray *connectedArray = [NSMutableArray array];
for (GWPeripheral *gwPeriph in self.connectedPeripherals) {
[connectedArray addObject:gwPeriph];
}
[self.peripheralsArray removeAllObjects];
[self.peripheralsNameArray removeAllObjects];
if (connectedArray.count > 0) {
[self.peripheralsNameArray addObjectsFromArray:connectedArray];
[self.peripheralsArray addObject:[connectedArray valueForKeyPath:@"peripheral"]];
}
if ([self.delegate respondsToSelector:@selector(didUpdatePeripheralsArray:)]) {
[self.delegate performSelector:@selector(didUpdatePeripheralsArray:) withObject:self.peripheralsNameArray];
}
if (!self.manager) {//不存在则初始化
self.manager = [[CBCentralManager alloc]initWithDelegate:self queue:nil];
}else{//存在 只有在蓝牙打开的情况下搜索外设
if (self.manager.state == 5) {
[self.manager scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey:@YES}];
}
}
}
#pragma mark -- 蓝牙状态
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
if (central.state == 5) {
[self.manager scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey:@YES}];
}
}
- (void)setFalgWithAddress:(NSString *)address withFlag:(NSString *)flag
{
[self.flagMap setObject:flag forKey:address];
}
//1 连接成功 0 连接失败
- (NSString *)getFlagWithAddress:(NSString *)address
{
return [self.flagMap objectForKey:address];
}
#pragma mark -- 找到外围设备
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI
{
NSData *manufacturerData = [advertisementData objectForKey:@"kCBAdvDataManufacturerData"];
if (manufacturerData) {
self.isIn = NO;
NSString *macAddress = [NSString stringWithFormat:@"%@",manufacturerData];
for (GWPeripheral *model in self.peripheralsNameArray) {
if ([macAddress isEqualToString:model.macAddress]) {
self.isIn = YES;
break;
}
}
Byte *resultByte = (Byte*)[manufacturerData bytes];//取出字节数组
NSMutableArray *tempArray = [NSMutableArray array];
for (int i = 0; i < manufacturerData.length; i++) {
int number = (int)resultByte[i];
[tempArray addObject:@(number)];
}
NSArray *resultArray = [[tempArray reverseObjectEnumerator] allObjects];
NSString *actulMacAddress = @"";
if (resultArray.count >= 8) {
for (int i = 0; i < 6; i ++) {
actulMacAddress = [actulMacAddress stringByAppendingFormat:@"%02x:",[resultArray[i] intValue]];
}
actulMacAddress = [actulMacAddress substringToIndex:actulMacAddress.length - 1];
}
//防止重复
if (peripheral.name && self.isIn == NO) {
//添加外设
GWPeripheral *model = [GWPeripheral new];
model.name = peripheral.name;
model.RSSI = RSSI;
model.peripheral = peripheral;
model.actulMacAddress = [actulMacAddress uppercaseString];
if (manufacturerData) {
model.macAddress = [NSString stringWithFormat:@"%@",manufacturerData];
}else{
model.macAddress = @"0";
}
if ([peripheral.name hasPrefix:@"CoolLED"] || [peripheral.name hasPrefix:@"FS"]){
[self.peripheralsNameArray addObject:model];
[self.peripheralsArray addObject:peripheral];
NSArray *connectedDevices = [[NSUserDefaults standardUserDefaults] objectForKey:kLastConnectedPeripheral];
if ([connectedDevices isKindOfClass:[NSString class]]) {
connectedDevices = @[connectedDevices];
}
if ([connectedDevices containsObject:model.macAddress]) {
[self startConnectPeripheralWithName:model.macAddress];
}
if ([self.delegate respondsToSelector:@selector(didUpdatePeripheralsArray:)]) {
[self.delegate performSelector:@selector(didUpdatePeripheralsArray:) withObject:self.peripheralsNameArray];
}
}
} else if (self.isIn == YES){
self.isIn = NO;
}
}
}
#pragma mark -- 开始连接外围设备
- (void)startConnectPeripheralWithName:(NSString *)peripheralMacAds
{
NSString *flag=[self.successMap objectForKey:peripheralMacAds];
if(flag){
if([flag isEqualToString:@"1"]){
return;
}
}
else{
[self.successMap setObject:@"0" forKey:peripheralMacAds];
}
for (GWPeripheral *peripheralModel in self.peripheralsNameArray) {
if ([peripheralModel.macAddress isEqualToString:peripheralMacAds]) {
if (peripheralModel.peripheral) {
//添加保存外围设备,注意如果这里不保存外围设备(或者说peripheral没有一个强引用,无法到达连接成功(或失败)的代理方法,因为在此方法调用完就会被销毁
[self.connectPerpherals addObject:peripheralModel.peripheral];
self.peripherals = peripheralModel.peripheral;
[self.charMap setObject:peripheralModel.peripheral forKey:peripheralMacAds];
self.currentPModel = peripheralModel;
[ProgressHUD show:showText(@"连接中")];
if (self.timer) {
[self.timer invalidate];
self.timer = nil;
}
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeOut) userInfo:nil repeats:YES];
[self.manager connectPeripheral:peripheralModel.peripheral options:nil];
}
}
}
}
- (void)cancelPeripheralConnection:(NSString *)peripheralMacAds
{
NSString *flag=[self.successMap objectForKey:peripheralMacAds];
if(!flag || [flag isEqualToString:@"0"]){
return;
}
for (GWPeripheral *peripheralModel in self.peripheralsNameArray) {
if ([peripheralModel.macAddress isEqualToString:peripheralMacAds]) {
[self.manager cancelPeripheralConnection:peripheralModel.peripheral];
NSArray *connectedDevices = [[NSUserDefaults standardUserDefaults] objectForKey:kLastConnectedPeripheral];
if ([connectedDevices isKindOfClass:[NSString class]]) {
connectedDevices = @[connectedDevices];
}
NSMutableArray *arrayM = [NSMutableArray arrayWithArray:connectedDevices];
[arrayM removeObject:peripheralModel.macAddress];
[[NSUserDefaults standardUserDefaults] setObject:arrayM forKey:kLastConnectedPeripheral];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
}
- (void)timeOut
{
static int count = 0;
if (count!=15) {
count++;
} else {
[self.timer invalidate];
self.timer = nil;
[ProgressHUD showError:showText(@"超时")];
count = 0;
}
}
-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
peripheral.delegate = self;
//外围设备开始寻找服务
[peripheral discoverServices:nil];
}
-(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
[self.timer invalidate];
self.timer = nil;
for (GWPeripheral *peripheralModel in self.peripheralsNameArray) {
if(peripheralModel.peripheral==peripheral){
[self.flagMap setObject:@"0" forKey:peripheralModel.macAddress];
[self.successMap setObject:@"0" forKey:peripheralModel.macAddress];
if([self.address containsObject:peripheralModel.macAddress]){
[self.address removeObject:peripheralModel.macAddress];
}
[ProgressHUD showError:showText(@"断开连接")];
if ([self.delegate respondsToSelector:@selector(didDisconnectPeripheral:)]) {
[self.delegate performSelector:@selector(didDisconnectPeripheral:) withObject:peripheralModel];
}
if ([self.delegate respondsToSelector:@selector(didUpdatePeripheralsArray:)]) {
[self.delegate performSelector:@selector(didUpdatePeripheralsArray:) withObject:self.peripheralsNameArray];
}
[[NSNotificationCenter defaultCenter] postNotificationName:kConnectedDeviceListChange object:nil];
}
}
[self.connectedPeripherals enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
GWPeripheral *peripheralModel = (GWPeripheral *)obj;
if (peripheralModel.peripheral == peripheral) {
[self.connectedPeripherals removeObject:peripheralModel];
}
}];
}
-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
[self.timer invalidate];
self.timer = nil;
[ProgressHUD showError:showText(@"连接失败")];
for (GWPeripheral *peripheralModel in self.peripheralsNameArray) {
if(peripheralModel.peripheral==peripheral){
[self.flagMap setObject:@"0" forKey:peripheralModel.macAddress];
[self.successMap setObject:@"0" forKey:peripheralModel.macAddress];
}if ([self.delegate respondsToSelector:@selector(didFailToConnectPeripheral:)]) {
[self.delegate performSelector:@selector(didFailToConnectPeripheral:) withObject:peripheralModel];
}
}
self.currentPModel = nil;
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
if (error)
{
[self.timer invalidate];
self.timer = nil;
[ProgressHUD showError:@"连接失败"];
for (GWPeripheral *peripheralModel in self.peripheralsNameArray) {
if(peripheralModel.peripheral==peripheral){
[self.flagMap setObject:@"0" forKey:peripheralModel.macAddress];
[self.successMap setObject:@"0" forKey:peripheralModel.macAddress];
if ([self.delegate respondsToSelector:@selector(didFailToConnectPeripheral:)]) {
[self.delegate performSelector:@selector(didFailToConnectPeripheral:) withObject:peripheralModel];
}
}
}
return;
}
for (CBService *service in peripheral.services)
{
if ([service.UUID isEqual:[CBUUID UUIDWithString:ServiceUUID]])
{
[peripheral discoverCharacteristics:nil forService:service];
break;
}
}
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
if (error)
{
[self.timer invalidate];
self.timer = nil;
[ProgressHUD showError:showText(@"连接失败")];
for (GWPeripheral *peripheralModel in self.peripheralsNameArray) {
if(peripheralModel.peripheral==peripheral){
[self.flagMap setObject:@"0" forKey:peripheralModel.macAddress];
[self.successMap setObject:@"0" forKey:peripheralModel.macAddress];
if ([self.delegate respondsToSelector:@selector(didFailToConnectPeripheral:)]) {
[self.delegate performSelector:@selector(didFailToConnectPeripheral:) withObject:peripheralModel];
}
}
}
return;
}
for (CBCharacteristic *characteristic in service.characteristics)
{
if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:NewCharacteristicUUID]])
{
[self.timer invalidate];
self.timer = nil;
[ProgressHUD showSuccess:showText(@"连接成功")];
for (GWPeripheral *peripheralModel in self.peripheralsNameArray) {
if(peripheralModel.peripheral == peripheral){
[self.flagMap setObject:@"1" forKey:peripheralModel.macAddress];
[self.successMap setObject:@"1" forKey:peripheralModel.macAddress];
if(![self.address containsObject:peripheralModel.macAddress]){
[self.address addObject:peripheralModel.macAddress];
}
[self.charMapOne setObject:characteristic forKey:peripheralModel.macAddress];
self.characteristics = characteristic;
if (_ConnectedPeripheralBlock) {
_ConnectedPeripheralBlock(YES);
}
[self.connectedPeripherals addObject:peripheralModel];
NSArray *connectedDevices = [[NSUserDefaults standardUserDefaults] objectForKey:kLastConnectedPeripheral];
if ([connectedDevices isKindOfClass:[NSString class]]) {
connectedDevices = @[connectedDevices];
}
NSMutableArray *arrayM = [NSMutableArray arrayWithArray:connectedDevices];
[arrayM addObject:peripheralModel.macAddress];
[[NSUserDefaults standardUserDefaults] setObject:arrayM forKey:kLastConnectedPeripheral];
[[NSUserDefaults standardUserDefaults] synchronize];
// 设置通知, 数据会进入 peripheral:didUpdateValueForCharacteristic:error:方法
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
if ([self.delegate respondsToSelector:@selector(didConnectedPeripheral:)]) {
[self.delegate performSelector:@selector(didConnectedPeripheral:)withObject:peripheralModel];
}
[[NSNotificationCenter defaultCenter] postNotificationName:kConnectedDeviceListChange object:nil];
}
}
// 如果这一次连接的设备与上一次连接的设备不一样,则抛出通知
if ([peripheral.name hasPrefix:@"CoolLED"]) {
if (self.peripheralType != BTPeripheralTypeCrosby) {
self.peripheralType = BTPeripheralTypeCrosby;
[[NSNotificationCenter defaultCenter] postNotificationName:kConnectedPeriphTypeDidChangeNotification object:@(BTPeripheralTypeCrosby)];
}
// 删除已经连接的另一种类型的设备
NSMutableArray *connectedMacAddress = [NSMutableArray array];
NSMutableArray *connectedModels = [NSMutableArray arrayWithArray:self.connectedPeripherals];
for (GWPeripheral *peripheralModel in self.connectedPeripherals) {
if ([peripheralModel.name hasPrefix:@"FS"]) {
[self cancelPeripheralConnection:peripheralModel.macAddress];
[connectedModels removeObject:peripheralModel];
} else {
[connectedMacAddress addObject:peripheralModel.macAddress];
}
}
self.connectedPeripherals = connectedModels;
[[NSUserDefaults standardUserDefaults] setObject:connectedMacAddress forKey:kLastConnectedPeripheral];
} else if ([peripheral.name hasPrefix:@"FS"]) {
if (self.peripheralType != BTPeripheralTypeGlowaler) {
self.peripheralType = BTPeripheralTypeGlowaler;
[[NSNotificationCenter defaultCenter] postNotificationName:kConnectedPeriphTypeDidChangeNotification object:@(BTPeripheralTypeGlowaler)];
}
// 删除已经连接的另一种类型的设备
NSMutableArray *connectedMacAddress = [NSMutableArray array];
NSMutableArray *connectedModels = [NSMutableArray arrayWithArray:self.connectedPeripherals];
for (GWPeripheral *peripheralModel in self.connectedPeripherals) {
if ([peripheralModel.name hasPrefix:@"CoolLED"]) {
[self cancelPeripheralConnection:peripheralModel.macAddress];
[connectedModels removeObject:peripheralModel];
} else {
[connectedMacAddress addObject:peripheralModel.macAddress];
}
}
self.connectedPeripherals = connectedModels;
[[NSUserDefaults standardUserDefaults] setObject:connectedMacAddress forKey:kLastConnectedPeripheral];
}
break;
}
}
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
// NSData *data = characteristic.value;
//只是适用于灯的开关解析 别的响应判断第一个字节的命令
Byte *resultByte = (Byte*)[characteristic.value bytes];//取出字节数组
// NSLog(@"获取灯的状态:%hhu",resultByte[1]);
int length = sizeof(resultByte);
for (int i = 0; i < length; i++) {
NSLog(@"获取灯的数据:%hhu",resultByte[i]);
}
if (resultByte[0] == 240) {//灯的开关响应解析
if (resultByte[1] == 1) {//数组中的第二个字符是开关状态 0 关闭 1 开启状态
if (_lampStateBlock) {
self.lampStateBlock(YES);
}
}else if (resultByte[1] == 0){
if (_lampStateBlock) {
self.lampStateBlock(NO);
}
}
}
}
//订阅通知
//写数据
- (void)writCommad:(NSString *)commad
{
GWLog(@"--- write commad: %@",commad);
NSMutableArray *arr = [NSMutableArray array];
NSMutableString *mCommad = [NSMutableString stringWithString:commad];
while (mCommad.length>=38) {
NSString *str = [mCommad substringWithRange:NSMakeRange(0, 38)];
[mCommad deleteCharactersInRange:NSMakeRange(0, 38)];
[arr addObject:str];
}
NSString *str = [mCommad substringWithRange:NSMakeRange(0, mCommad.length)];
[arr addObject:str];
for(NSString *ad in self.address){
NSMutableData *data = [NSMutableData data];
for (NSString *strTemp in arr)
{
for (int i=0; i<strTemp.length; i+=2)
{
NSString *temp = [strTemp substringWithRange:NSMakeRange(i, 2)];
[data appendData:[self stringToByte:temp]];
}
NSString *flag= [self.flagMap objectForKey:ad];
NSString *successFlag=[self.successMap objectForKey:ad];
GWLog(@"---address:%@--- falg strig:%@---successFlag:%@",ad,flag,successFlag);
GWLog(@"data:%@",data);
if([successFlag isEqualToString:@"1"]&&[flag isEqualToString:@"1"]){
[[self.charMap objectForKey:ad] writeValue:data forCharacteristic:[self.charMapOne objectForKey:ad] type:CBCharacteristicWriteWithoutResponse];
[data resetBytesInRange:NSMakeRange(0, [data length])];
[data setLength:0];
}
}
}
}
- (void)writeCommad:(NSString *)commad onDevice:(NSString *)peripheralMacAds
{
NSMutableArray *arr = [NSMutableArray array];
NSMutableString *mCommad = [NSMutableString stringWithString:commad];
while (mCommad.length>=38) {
NSString *str = [mCommad substringWithRange:NSMakeRange(0, 38)];
[mCommad deleteCharactersInRange:NSMakeRange(0, 38)];
[arr addObject:str];
}
NSString *str = [mCommad substringWithRange:NSMakeRange(0, mCommad.length)];
[arr addObject:str];
if (![self.address containsObject:peripheralMacAds]) {
return;
}
NSString *flag= [self.flagMap objectForKey:peripheralMacAds];
NSString *successFlag=[self.successMap objectForKey:peripheralMacAds];
if (![successFlag isEqualToString:@"1"] || ![flag isEqualToString:@"1"]) {
return;
}
NSMutableData *data = [NSMutableData data];
for (NSString *strTemp in arr)
{
for (int i=0; i<strTemp.length; i+=2)
{
NSString *temp = [strTemp substringWithRange:NSMakeRange(i, 2)];
[data appendData:[self stringToByte:temp]];
}
GWLog(@"---address:%@--- falg strig:%@---successFlag:%@",peripheralMacAds,flag,successFlag);
GWLog(@"data:%@",data);
[[self.charMap objectForKey:peripheralMacAds] writeValue:data forCharacteristic:[self.charMapOne objectForKey:peripheralMacAds] type:CBCharacteristicWriteWithoutResponse];
[data resetBytesInRange:NSMakeRange(0, [data length])];
[data setLength:0];
}
}
-(NSData*)stringToByte:(NSString*)string
{
NSString *hexString=[[string uppercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];
if ([hexString length]%2!=0) {
return nil;
}
Byte tempbyt[1]={0};
NSMutableData* bytes=[NSMutableData data];
for(int i=0;i<[hexString length];i++)
{
unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
int int_ch1;
if(hex_char1 >= '0' && hex_char1 <='9')
int_ch1 = (hex_char1-48)*16; //// 0 的Ascll - 48
else if(hex_char1 >= 'A' && hex_char1 <='F')
int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65
else
return nil;
i++;
unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)
int int_ch2;
if(hex_char2 >= '0' && hex_char2 <='9')
int_ch2 = (hex_char2-48); //// 0 的Ascll - 48
else if(hex_char2 >= 'A' && hex_char2 <='F')
int_ch2 = hex_char2-55; //// A 的Ascll - 65
else
return nil;
tempbyt[0] = int_ch1+int_ch2; ///将转化后的数放入Byte数组里
[bytes appendBytes:tempbyt length:1];
}
return bytes;
}
@end
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。