I have to communicate over bluetooth with a device, the device expects commands to be separated by carriage return + linefeed. Connection is established using RFCOMMChannel.
Atm it seems that my code is not working since I am expecting a reply from the device, which it does when I send it commands using a simpel terminal program.
This code is run after the connection is established (this is definately working since I can log data coming in from the external device)
NSString *clockRequest = @"C\r\n";
void *clockRequestData = (__bridge void *)([clockRequest dataUsingEncoding:NSASCIIStringEncoding]);
NSLog(@"Data buffer to write: %@", clockRequestData);
[rfcommChannel writeAsync: clockRequestData length:100 refcon:NULL];
//writing data from rfcomm
- (void)rfcommChannelWriteComplete:(IOBluetoothRFCOMMChannel*)rfcommChannel refcon:(void*)refcon status:(IOReturn)error {
NSLog(@"Macbook wrote to Timecube, status: %d", error);
}
The code for establishing a connection was taken and adjusted from https://gist.github.com/crazycoder1999/3139668
thx in advance
Add category NSStringHexToBytes to Your project:
NSString+NSStringHexToBytes.h
#import <Foundation/Foundation.h>
@interface NSString (NSStringHexToBytes)
+ (NSData *)dataWithString:(NSString *)string;
@end
NSString+NSStringHexToBytes.m
#import "NSString+NSStringHexToBytes.h"
@implementation NSString (NSStringHexToBytes)
+ (NSData *)dataWithString:(NSString *)string
{
//string = [string stringByReplacingOccurrencesOfString:@"0x" withString:@""];
//NSCharacterSet *notAllowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefABCDEF1234567890"] invertedSet];
//string = [[string componentsSeparatedByCharactersInSet:notAllowedCharacters] componentsJoinedByString:@""];
const char *cString = [string cStringUsingEncoding:NSASCIIStringEncoding];
const char *idx = cString;
unsigned char result[[string length] / 2];
size_t count = 0;
for(count = 0; count < sizeof(result)/sizeof(result[0]); count++)
{
sscanf(idx, "%2hhx", &result[count]);
idx += 2 * sizeof(char);
}
return [[NSData alloc] initWithBytes:result length:sizeof(result)];
}
@end
In Your implementation file import NSString+NSStringHexToBytes.h and add method
-(void)sendMessage:(NSData *)data
{
[rfcommChannel writeSync:(void*)data.bytes length:data.length];
}
and then:
NSString* clockRequest = @"C\r\n";
NSData* data = [NSString dataWithString:clockRequest];
[rfcommChannel sendMessage:data];