如何在RFCOMMChannel上构建与writeAsync一起使用的命令?

时间:2013-05-14 15:19:55

标签: cocoa iobluetooth

我必须通过蓝牙与设备进行通信,设备需要通过回车+换行来分隔命令。 使用RFCOMMChannel建立连接。

Atm似乎我的代码没有工作,因为我期待设备的回复,当我使用simpel终端程序发送命令时,它会这样做。

此代码在建立连接后运行(由于我可以记录来自外部设备的数据,因此这肯定有效)

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);
}

建立连接的代码已经过调整 https://gist.github.com/crazycoder1999/3139668

事先提前

1 个答案:

答案 0 :(得分:0)

将类别NSStringHexToBytes添加到您的项目中:

的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

在您的实现文件中导入NSString + NSStringHexToBytes.h并添加方法

-(void)sendMessage:(NSData *)data
{
    [rfcommChannel writeSync:(void*)data.bytes length:data.length];
}

然后:

NSString* clockRequest = @"C\r\n";
NSData* data = [NSString dataWithString:clockRequest];
[rfcommChannel sendMessage:data];