Skip to content

Commit

Permalink
Added BLE Chat (Peripheral Role) example for iOS.
Browse files Browse the repository at this point in the history
  • Loading branch information
Cheong2K committed Mar 9, 2014
1 parent 196eca2 commit 0019f50
Show file tree
Hide file tree
Showing 15 changed files with 903 additions and 0 deletions.

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIdentifier</key>
<string>com.redbear.${PRODUCT_NAME:rfc1034identifier}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
</array>
</dict>
</plist>
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
//
// Prefix header
//
// The contents of this file are implicitly included at the beginning of every source file.
//

#import <Availability.h>

#ifndef __IPHONE_5_0
#warning "This project uses features only available in iOS SDK 5.0 and later."
#endif

#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#endif
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<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">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="3747"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="ufC-wZ-h7g">
<objects>
<viewController id="vXZ-lx-hvc" customClass="RBLViewController" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="6qn-dw-sKt"/>
<viewControllerLayoutGuide type="bottom" id="64q-Q6-ZeT"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="kh9-bI-dsS">
<rect key="frame" x="0.0" y="0.0" width="320" height="568"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<subviews>
<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">
<rect key="frame" x="20" y="287" width="280" height="30"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<textInputTraits key="textInputTraits" returnKeyType="send"/>
</textField>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
</view>
<connections>
<outlet property="textField" destination="rgl-4C-zHx" id="kwI-Zq-zQT"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="x5A-6p-PRh" sceneMemberID="firstResponder"/>
</objects>
</scene>
</scenes>
<simulatedMetricsContainer key="defaultSimulatedMetrics">
<simulatedStatusBarMetrics key="statusBar"/>
<simulatedOrientationMetrics key="orientation"/>
<simulatedScreenMetrics key="destination" type="retina4"/>
</simulatedMetricsContainer>
</document>
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"images" : [
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "2x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"images" : [
{
"orientation" : "portrait",
"idiom" : "iphone",
"extent" : "full-screen",
"minimum-system-version" : "7.0",
"scale" : "2x"
},
{
"orientation" : "portrait",
"idiom" : "iphone",
"subtype" : "retina4",
"extent" : "full-screen",
"minimum-system-version" : "7.0",
"scale" : "2x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
//
// RBLAppDelegate.h
// BLE peripheral mode
//
// Created by redbear on 14-2-20.
// Copyright (c) 2014年 redbear. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface RBLAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@end
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
//
// RBLAppDelegate.m
// BLE peripheral mode
//
// Created by redbear on 14-2-20.
// Copyright (c) 2014年 redbear. All rights reserved.
//

#import "RBLAppDelegate.h"

@implementation RBLAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
// 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.
// 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.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
// 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.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
// 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.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
// 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.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
//
// RBLViewController.h
// BLE peripheral mode
//
// Created by redbear on 14-2-20.
// Copyright (c) 2014年 redbear. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <CoreBluetooth/CoreBluetooth.h>

@interface RBLViewController : UIViewController <CBPeripheralManagerDelegate, UITextFieldDelegate>
{
CBMutableCharacteristic *rx;
NSMutableString *str;
}

@property (nonatomic, strong) CBPeripheralManager *peripheralManager;

@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) IBOutlet UITextField *textField;

@end
122 changes: 122 additions & 0 deletions Examples/BLEChat_Peripheral_iOS/BLEChat_Peripheral/RBLViewController.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
//
// RBLViewController.m
// BLE peripheral mode
//
// Created by redbear on 14-2-20.
// Copyright (c) 2014年 redbear. All rights reserved.
//

#import "RBLViewController.h"

@interface RBLViewController ()

#define RBL_SERVICE_UUID @"713d0000-503e-4c75-ba94-3148f18d941e"
#define RBL_TX_UUID @"713d0003-503e-4c75-ba94-3148f18d941e"
#define RBL_RX_UUID @"713d0002-503e-4c75-ba94-3148f18d941e"

@end

@implementation RBLViewController

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

self.peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];
self.textField.delegate = self;
[self.textField becomeFirstResponder];

NSString *reqSysVer = @"7.0";
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
BOOL osVersionSupported = ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending);

if (osVersionSupported) {
NSTextStorage* textStorage = [[NSTextStorage alloc] init];
NSLayoutManager* layoutManager = [NSLayoutManager new];
[textStorage addLayoutManager:layoutManager];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:self.view.bounds.size];
[layoutManager addTextContainer:textContainer];
self.textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 20, 320, 203) textContainer:textContainer];
}
else
self.textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 20, 320, 203)];

self.textView.editable = NO;
self.textView.selectable = NO;
self.textView.font = [UIFont fontWithName:@"Arial" size:20.0f];
[self.view addSubview:self.textView];
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral
{
if (peripheral.state != CBPeripheralManagerStatePoweredOn) {
return;
}

NSLog(@"self.peripheralManager powered on.");

CBMutableCharacteristic *tx = [[CBMutableCharacteristic alloc] initWithType:[CBUUID UUIDWithString:RBL_TX_UUID] properties:CBCharacteristicPropertyWriteWithoutResponse value:nil permissions:CBAttributePermissionsWriteable];
rx = [[CBMutableCharacteristic alloc] initWithType:[CBUUID UUIDWithString:RBL_RX_UUID] properties:CBCharacteristicPropertyNotify value:nil permissions:CBAttributePermissionsReadable];

CBMutableService *s = [[CBMutableService alloc] initWithType:[CBUUID UUIDWithString:RBL_SERVICE_UUID] primary:YES];
s.characteristics = @[tx, rx];

[self.peripheralManager addService:s];

NSDictionary *advertisingData = @{CBAdvertisementDataLocalNameKey : @"BLE Shield", CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:RBL_SERVICE_UUID]]};
[self.peripheralManager startAdvertising:advertisingData];
}

- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray *)requests
{
NSLog(@"didReceiveWriteRequests");

CBATTRequest* request = [requests objectAtIndex: 0];
NSData* request_data = request.value;
CBCharacteristic* write_char = request.characteristic;

uint8_t buf[request_data.length];
[request_data getBytes:buf length:request_data.length];

NSMutableString *temp = [[NSMutableString alloc] init];
for (int i = 0; i < request_data.length; i++) {
[temp appendFormat:@"%c", buf[i]];
}

if (str == nil) {
str = [NSMutableString stringWithFormat:@"%@\n", temp];
} else {
[str appendFormat:@"%@\n", temp];
}

self.textView.text = str;
[self scrollOutputToBottom];

//[peripheral respondToRequest:request withResult:CBATTErrorSuccess];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
NSString *text = self.textField.text;

NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];

[self.peripheralManager updateValue:data forCharacteristic:rx onSubscribedCentrals:nil];

return YES;
}

- (void)scrollOutputToBottom {
CGPoint p = [self.textView contentOffset];
[self.textView setContentOffset:p animated:NO];
[self.textView scrollRangeToVisible:NSMakeRange([self.textView.text length], 0)];
}

@end
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/* Localized versions of Info.plist keys */

18 changes: 18 additions & 0 deletions Examples/BLEChat_Peripheral_iOS/BLEChat_Peripheral/main.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
//
// main.m
// BLE peripheral mode
//
// Created by redbear on 14-2-20.
// Copyright (c) 2014年 redbear. All rights reserved.
//

#import <UIKit/UIKit.h>

#import "RBLAppDelegate.h"

int main(int argc, char * argv[])
{
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([RBLAppDelegate class]));
}
}
Loading

0 comments on commit 0019f50

Please sign in to comment.