objective c - Why does ORSSerialPort serialPort:didReceiveData NSData only have single byte? -


from arduino, i'm writing multi-byte data serial serial.print("blah"), in objective-c, -serialport:didreceivedata: (provided orsserialport) gets data 1 byte @ time. occasionally, it'll grab 2 bytes @ once, never 4. expected? if so, how can make receive 4 bytes @ once?

arduino:

void loop() {     serial.print("blah");     delay(1000); } 

obj-c:

- (void)serialport:(orsserialport *)serialport didreceivedata:(nsdata *)data {    nsstring *string = [[nsstring alloc] initwithdata:data encoding:nsutf8stringencoding];    nslog(@"%@",string); } 

setting breakpoint inside method shows data holds 1 byte.

this normal, expected behavior. underlying serial hardware , software has no way of knowing how many bytes you're waiting for, or complete packet looks like, delivers data comes in. you'll have buffer data in objective-c code. fundamentally, pretty simple. create nsmutabledata can use buffer:

@property (strong) nsmutabledata *incomingdatabuffer; 

initialize (e.g. in -init):

_incomingdatabuffer = [[nsmutabledata alloc] init]; 

then, in -serialport:didreceivedata::

- (void)serialport:(orsserialport *)serialport didreceivedata:(nsdata *)data {    [self.incomingdatabuffer appenddata:data];     if ([self databufferhascompletepacket]) { // check see if buffer contains complete, valid packet        [self processreceiveddatapacket:self.incomingdatabuffer]; // whatever need received data        [self.incomingdatabuffer replacebytesinrange:nsmakerange(0, [self.incomingdatabuffer length]) withbytes:null length:0]; // clear data buffer    } } 

this start. has flaws, namely stall , never figure out data has stopped coming in if e.g. corrupt packet comes on wire followed valid one, or serial cable unplugged right in middle of packet. these flaws can fixed combination of designed packet format, including example unique header, checksum and/or end sequence , timeouts cause receiver reset state.

i've had in mind enhancements address issue in orsserialport itself. there's discussion of stuff in issue on github. feel free add comments , suggestions on issue if you're interested in.


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -