cocoa - How to build commands for use with writeAsync over RFCOMMChannel? -
i have communicate on bluetooth device, device expects commands separated carriage return + linefeed. connection established using rfcommchannel.
atm seems code not working since expecting reply device, when send commands using simpel terminal program.
this code run after connection established (this definately working since can log data coming in external device)
nsstring *clockrequest = @"c\r\n"; void *clockrequestdata = (__bridge void *)([clockrequest datausingencoding:nsasciistringencoding]); nslog(@"data buffer write: %@", clockrequestdata); [rfcommchannel writeasync: clockrequestdata length:100 refcon:null]; //writing data rfcomm - (void)rfcommchannelwritecomplete:(iobluetoothrfcommchannel*)rfcommchannel refcon:(void*)refcon status:(ioreturn)error { nslog(@"macbook wrote timecube, status: %d", error); }
the code establishing connection taken , adjusted https://gist.github.com/crazycoder1999/3139668
thx in advance
add category nsstringhextobytes 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 implementation file import nsstring+nsstringhextobytes.h , 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];
Comments
Post a Comment