您的位置:首页 > 移动开发 > IOS开发

iOS学习,蓝牙,iOS设备模拟BLE发送数据

2014-06-17 13:53 162 查看

写在前面

刚开始学习iOS开发,在此过程中学习到很多知识点,写这些的目的,首先是为了给像我一样的小白提供一些参考资料,其次是对自己所学知识的一个总结与记录。

废话不多说,下面开始。
之前写过一篇总结,是IOS设备对蓝牙数据的接收,之后更新UI。我现在实际中,负责蓝牙模块的同事还没搞定,我如果要继续做蓝牙的相关工作(接收蓝牙数据,之后画图什么的)就要自己制造些数据用来接收。这就涉及蓝牙的外设,也就是蓝牙4.0规范中得BLE,bluetooth smart,下面的工作就是模拟一个这样的设备来一直发送数据。

准备工作

1.导入CoreBluetooth框架
2.实现外设代理(请看下面的.h文件)

正式开始

由于就是用来发数据的,界面简单,就一个switch,如果开,就广播,让别人可以搜索到。storyboard中拖一个switch ,需要action来控制广播开关。

没有多余viewController,就是新建工程时候自己带的那个,点开.h文件,输入如下:
#import <UIKit/UIKit.h>
#import <CoreBluetooth/CoreBluetooth.h>

@interface TBViewController : UIViewController <CBPeripheralManagerDelegate>
@property (nonatomic, strong) CBPeripheralManager *manager;

@end


在编写.m文件之前,新建一个头文件,用来存放service 和 characteristic的UUID,方便管理。当然,你写在刚才的.h中也行。不过我还是推荐用专门的.h来管理,UUID.h
#ifndef SmartBicycle_UUID_h
#define SmartBicycle_UUID_h

#define TRANSFER_SERVICE_UUID           @"FFF0"
#define TRANSFER_CHARACTERISTIC_UUID    @"FFF1"

#endif


俩宏,没啥难度。下面开始真正工作,在viewController的.m文件中:
//  TBViewController.m

#import "TBViewController.h"
#import "UUID.h"

@interface TBViewController () {
}
@property (strong, nonatomic) CBMutableCharacteristic   *customCharacteristic;
@property (strong, nonatomic) CBMutableService   *customService;
@property (strong, nonatomic) NSData                    *dataToSend;
@property (weak, nonatomic) IBOutlet UISwitch *advertisingSwitch;

- (IBAction)switchChanged:(UISwitch *)sender;

@end

@implementation TBViewController

- (void)viewDidLoad
{
[super viewDidLoad];
self.manager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];
}

#pragma -mark 消失,停止广告
- (void)viewWillDisappear:(BOOL)animated
{
[self.manager stopAdvertising];

[super viewWillDisappear:animated];
}

#pragma -mark 检查peripheral状态
//如果状态正确,开始服务
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral
{
switch (peripheral.state) {
case CBPeripheralManagerStatePoweredOn:
[self setupService];
break;
default:
NSLog(@"the peripheralManagerState is not PoweredOn");
break;
}
}

#pragma -mark 开始服务
- (void)setupService
{
//CHARACTERISTIC UUID
CBUUID *characteristicUUID = [CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID];
self.customCharacteristic =  [[CBMutableCharacteristic alloc] initWithType:characteristicUUID properties:CBCharacteristicPropertyNotify value:nil permissions:CBAttributePermissionsReadable];

//SERVICE UUID
CBUUID *serviceUUID = [CBUUID UUIDWithString:TRANSFER_SERVICE_UUID];
self.customService = [[CBMutableService alloc] initWithType:serviceUUID primary:YES];
[self.customService setCharacteristics:@[self.customCharacteristic]];
[self.manager addService:self.customService];
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}

- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic
{
NSLog(@"Central subscribed to characteristic");

int i = rand()%20;
NSString *stringToSend = [NSString stringWithFormat:@"%d", i];
NSLog(@"the random number is ---> %d", i);
NSData *data = [stringToSend dataUsingEncoding:NSUTF8StringEncoding];

if ([self.manager  updateValue:data forCharacteristic:self.customCharacteristic onSubscribedCentrals:nil]) {
NSLog(@"success, send number -- > %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}else{
NSLog(@"failed");
}
}

- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic
{
NSLog(@"Central unsubscribed from characteristic");
}

- (IBAction)switchChanged:(UISwitch *)sender {
if (self.advertisingSwitch.on) {
// All we advertise is our service's UUID
[self.manager startAdvertising:@{ CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]] }];
}

else {
[self.manager stopAdvertising];
}
}
@end


主要都是一些回调,通过方法名字就知道是在何时回调。
如果有IOS中央订阅了某个characteristic,就会回调带didSubscribe的方法,这个方法中实现发送数据。在实际测试中发现,外设会一直回调这个东西,所以会一直发送数据,测试方法就是,产生一个随机数,打印一下,当发生发送数据时,把发送的数据也打印一下,发现两数据一样,回调频率也挺高的。具体多少还没查,跟一般的手环、心率器频率应该差不多,可以达到模拟的目的。
注意发送string时候的编码格式,外设和中央应该一致,不然有些数据可能在中央没法显示。我用的都是UTF8
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: