Skip to content

Commit 0019f50

Browse files
committed
Added BLE Chat (Peripheral Role) example for iOS.
1 parent 196eca2 commit 0019f50

File tree

15 files changed

+903
-0
lines changed

15 files changed

+903
-0
lines changed

Examples/BLEChat_Peripheral_iOS/BLEChat_Peripheral.xcodeproj/project.pbxproj

Lines changed: 478 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+
<plist version="1.0">
4+
<dict>
5+
<key>CFBundleDevelopmentRegion</key>
6+
<string>en</string>
7+
<key>CFBundleDisplayName</key>
8+
<string>${PRODUCT_NAME}</string>
9+
<key>CFBundleExecutable</key>
10+
<string>${EXECUTABLE_NAME}</string>
11+
<key>CFBundleIdentifier</key>
12+
<string>com.redbear.${PRODUCT_NAME:rfc1034identifier}</string>
13+
<key>CFBundleInfoDictionaryVersion</key>
14+
<string>6.0</string>
15+
<key>CFBundleName</key>
16+
<string>${PRODUCT_NAME}</string>
17+
<key>CFBundlePackageType</key>
18+
<string>APPL</string>
19+
<key>CFBundleShortVersionString</key>
20+
<string>1.0</string>
21+
<key>CFBundleSignature</key>
22+
<string>????</string>
23+
<key>CFBundleVersion</key>
24+
<string>1.0</string>
25+
<key>LSRequiresIPhoneOS</key>
26+
<true/>
27+
<key>UIMainStoryboardFile</key>
28+
<string>Main</string>
29+
<key>UIRequiredDeviceCapabilities</key>
30+
<array>
31+
<string>armv7</string>
32+
</array>
33+
<key>UISupportedInterfaceOrientations</key>
34+
<array>
35+
<string>UIInterfaceOrientationPortrait</string>
36+
</array>
37+
</dict>
38+
</plist>
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
//
2+
// Prefix header
3+
//
4+
// The contents of this file are implicitly included at the beginning of every source file.
5+
//
6+
7+
#import <Availability.h>
8+
9+
#ifndef __IPHONE_5_0
10+
#warning "This project uses features only available in iOS SDK 5.0 and later."
11+
#endif
12+
13+
#ifdef __OBJC__
14+
#import <UIKit/UIKit.h>
15+
#import <Foundation/Foundation.h>
16+
#endif
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
2+
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="4514" systemVersion="13C64" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" initialViewController="vXZ-lx-hvc">
3+
<dependencies>
4+
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="3747"/>
5+
</dependencies>
6+
<scenes>
7+
<!--View Controller-->
8+
<scene sceneID="ufC-wZ-h7g">
9+
<objects>
10+
<viewController id="vXZ-lx-hvc" customClass="RBLViewController" sceneMemberID="viewController">
11+
<layoutGuides>
12+
<viewControllerLayoutGuide type="top" id="6qn-dw-sKt"/>
13+
<viewControllerLayoutGuide type="bottom" id="64q-Q6-ZeT"/>
14+
</layoutGuides>
15+
<view key="view" contentMode="scaleToFill" id="kh9-bI-dsS">
16+
<rect key="frame" x="0.0" y="0.0" width="320" height="568"/>
17+
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
18+
<subviews>
19+
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="left" contentVerticalAlignment="center" borderStyle="roundedRect" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="rgl-4C-zHx">
20+
<rect key="frame" x="20" y="287" width="280" height="30"/>
21+
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
22+
<fontDescription key="fontDescription" type="system" pointSize="14"/>
23+
<textInputTraits key="textInputTraits" returnKeyType="send"/>
24+
</textField>
25+
</subviews>
26+
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
27+
</view>
28+
<connections>
29+
<outlet property="textField" destination="rgl-4C-zHx" id="kwI-Zq-zQT"/>
30+
</connections>
31+
</viewController>
32+
<placeholder placeholderIdentifier="IBFirstResponder" id="x5A-6p-PRh" sceneMemberID="firstResponder"/>
33+
</objects>
34+
</scene>
35+
</scenes>
36+
<simulatedMetricsContainer key="defaultSimulatedMetrics">
37+
<simulatedStatusBarMetrics key="statusBar"/>
38+
<simulatedOrientationMetrics key="orientation"/>
39+
<simulatedScreenMetrics key="destination" type="retina4"/>
40+
</simulatedMetricsContainer>
41+
</document>
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
{
2+
"images" : [
3+
{
4+
"idiom" : "iphone",
5+
"size" : "29x29",
6+
"scale" : "2x"
7+
},
8+
{
9+
"idiom" : "iphone",
10+
"size" : "40x40",
11+
"scale" : "2x"
12+
},
13+
{
14+
"idiom" : "iphone",
15+
"size" : "60x60",
16+
"scale" : "2x"
17+
}
18+
],
19+
"info" : {
20+
"version" : 1,
21+
"author" : "xcode"
22+
}
23+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
{
2+
"images" : [
3+
{
4+
"orientation" : "portrait",
5+
"idiom" : "iphone",
6+
"extent" : "full-screen",
7+
"minimum-system-version" : "7.0",
8+
"scale" : "2x"
9+
},
10+
{
11+
"orientation" : "portrait",
12+
"idiom" : "iphone",
13+
"subtype" : "retina4",
14+
"extent" : "full-screen",
15+
"minimum-system-version" : "7.0",
16+
"scale" : "2x"
17+
}
18+
],
19+
"info" : {
20+
"version" : 1,
21+
"author" : "xcode"
22+
}
23+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
//
2+
// RBLAppDelegate.h
3+
// BLE peripheral mode
4+
//
5+
// Created by redbear on 14-2-20.
6+
// Copyright (c) 2014年 redbear. All rights reserved.
7+
//
8+
9+
#import <UIKit/UIKit.h>
10+
11+
@interface RBLAppDelegate : UIResponder <UIApplicationDelegate>
12+
13+
@property (strong, nonatomic) UIWindow *window;
14+
15+
@end
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
//
2+
// RBLAppDelegate.m
3+
// BLE peripheral mode
4+
//
5+
// Created by redbear on 14-2-20.
6+
// Copyright (c) 2014年 redbear. All rights reserved.
7+
//
8+
9+
#import "RBLAppDelegate.h"
10+
11+
@implementation RBLAppDelegate
12+
13+
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
14+
{
15+
// Override point for customization after application launch.
16+
return YES;
17+
}
18+
19+
- (void)applicationWillResignActive:(UIApplication *)application
20+
{
21+
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
22+
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
23+
}
24+
25+
- (void)applicationDidEnterBackground:(UIApplication *)application
26+
{
27+
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
28+
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
29+
}
30+
31+
- (void)applicationWillEnterForeground:(UIApplication *)application
32+
{
33+
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
34+
}
35+
36+
- (void)applicationDidBecomeActive:(UIApplication *)application
37+
{
38+
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
39+
}
40+
41+
- (void)applicationWillTerminate:(UIApplication *)application
42+
{
43+
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
44+
}
45+
46+
@end
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
//
2+
// RBLViewController.h
3+
// BLE peripheral mode
4+
//
5+
// Created by redbear on 14-2-20.
6+
// Copyright (c) 2014年 redbear. All rights reserved.
7+
//
8+
9+
#import <UIKit/UIKit.h>
10+
#import <CoreBluetooth/CoreBluetooth.h>
11+
12+
@interface RBLViewController : UIViewController <CBPeripheralManagerDelegate, UITextFieldDelegate>
13+
{
14+
CBMutableCharacteristic *rx;
15+
NSMutableString *str;
16+
}
17+
18+
@property (nonatomic, strong) CBPeripheralManager *peripheralManager;
19+
20+
@property (nonatomic, strong) UITextView *textView;
21+
@property (nonatomic, strong) IBOutlet UITextField *textField;
22+
23+
@end
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
//
2+
// RBLViewController.m
3+
// BLE peripheral mode
4+
//
5+
// Created by redbear on 14-2-20.
6+
// Copyright (c) 2014年 redbear. All rights reserved.
7+
//
8+
9+
#import "RBLViewController.h"
10+
11+
@interface RBLViewController ()
12+
13+
#define RBL_SERVICE_UUID @"713d0000-503e-4c75-ba94-3148f18d941e"
14+
#define RBL_TX_UUID @"713d0003-503e-4c75-ba94-3148f18d941e"
15+
#define RBL_RX_UUID @"713d0002-503e-4c75-ba94-3148f18d941e"
16+
17+
@end
18+
19+
@implementation RBLViewController
20+
21+
- (void)viewDidLoad
22+
{
23+
[super viewDidLoad];
24+
// Do any additional setup after loading the view, typically from a nib.
25+
26+
self.peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];
27+
self.textField.delegate = self;
28+
[self.textField becomeFirstResponder];
29+
30+
NSString *reqSysVer = @"7.0";
31+
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
32+
BOOL osVersionSupported = ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending);
33+
34+
if (osVersionSupported) {
35+
NSTextStorage* textStorage = [[NSTextStorage alloc] init];
36+
NSLayoutManager* layoutManager = [NSLayoutManager new];
37+
[textStorage addLayoutManager:layoutManager];
38+
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:self.view.bounds.size];
39+
[layoutManager addTextContainer:textContainer];
40+
self.textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 20, 320, 203) textContainer:textContainer];
41+
}
42+
else
43+
self.textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 20, 320, 203)];
44+
45+
self.textView.editable = NO;
46+
self.textView.selectable = NO;
47+
self.textView.font = [UIFont fontWithName:@"Arial" size:20.0f];
48+
[self.view addSubview:self.textView];
49+
}
50+
51+
- (void)didReceiveMemoryWarning
52+
{
53+
[super didReceiveMemoryWarning];
54+
// Dispose of any resources that can be recreated.
55+
}
56+
57+
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral
58+
{
59+
if (peripheral.state != CBPeripheralManagerStatePoweredOn) {
60+
return;
61+
}
62+
63+
NSLog(@"self.peripheralManager powered on.");
64+
65+
CBMutableCharacteristic *tx = [[CBMutableCharacteristic alloc] initWithType:[CBUUID UUIDWithString:RBL_TX_UUID] properties:CBCharacteristicPropertyWriteWithoutResponse value:nil permissions:CBAttributePermissionsWriteable];
66+
rx = [[CBMutableCharacteristic alloc] initWithType:[CBUUID UUIDWithString:RBL_RX_UUID] properties:CBCharacteristicPropertyNotify value:nil permissions:CBAttributePermissionsReadable];
67+
68+
CBMutableService *s = [[CBMutableService alloc] initWithType:[CBUUID UUIDWithString:RBL_SERVICE_UUID] primary:YES];
69+
s.characteristics = @[tx, rx];
70+
71+
[self.peripheralManager addService:s];
72+
73+
NSDictionary *advertisingData = @{CBAdvertisementDataLocalNameKey : @"BLE Shield", CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:RBL_SERVICE_UUID]]};
74+
[self.peripheralManager startAdvertising:advertisingData];
75+
}
76+
77+
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray *)requests
78+
{
79+
NSLog(@"didReceiveWriteRequests");
80+
81+
CBATTRequest* request = [requests objectAtIndex: 0];
82+
NSData* request_data = request.value;
83+
CBCharacteristic* write_char = request.characteristic;
84+
85+
uint8_t buf[request_data.length];
86+
[request_data getBytes:buf length:request_data.length];
87+
88+
NSMutableString *temp = [[NSMutableString alloc] init];
89+
for (int i = 0; i < request_data.length; i++) {
90+
[temp appendFormat:@"%c", buf[i]];
91+
}
92+
93+
if (str == nil) {
94+
str = [NSMutableString stringWithFormat:@"%@\n", temp];
95+
} else {
96+
[str appendFormat:@"%@\n", temp];
97+
}
98+
99+
self.textView.text = str;
100+
[self scrollOutputToBottom];
101+
102+
//[peripheral respondToRequest:request withResult:CBATTErrorSuccess];
103+
}
104+
105+
- (BOOL)textFieldShouldReturn:(UITextField *)textField
106+
{
107+
NSString *text = self.textField.text;
108+
109+
NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
110+
111+
[self.peripheralManager updateValue:data forCharacteristic:rx onSubscribedCentrals:nil];
112+
113+
return YES;
114+
}
115+
116+
- (void)scrollOutputToBottom {
117+
CGPoint p = [self.textView contentOffset];
118+
[self.textView setContentOffset:p animated:NO];
119+
[self.textView scrollRangeToVisible:NSMakeRange([self.textView.text length], 0)];
120+
}
121+
122+
@end
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
/* Localized versions of Info.plist keys */
2+
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
//
2+
// main.m
3+
// BLE peripheral mode
4+
//
5+
// Created by redbear on 14-2-20.
6+
// Copyright (c) 2014年 redbear. All rights reserved.
7+
//
8+
9+
#import <UIKit/UIKit.h>
10+
11+
#import "RBLAppDelegate.h"
12+
13+
int main(int argc, char * argv[])
14+
{
15+
@autoreleasepool {
16+
return UIApplicationMain(argc, argv, nil, NSStringFromClass([RBLAppDelegate class]));
17+
}
18+
}

0 commit comments

Comments
 (0)