vendredi 2 janvier 2015

Live monitoring Socket connnection

I'm creating app that can handle live connection between car and iPhone by ELM327 wi-fi device. I used this tutorial to make connection between phone and device - http://ift.tt/KAvOHJ. Everything works fine but now I want to make condition for sending a request. I mean - when car answers to my request at the end of this answer it sends ">" symbol so that means it is ready to take another request. I did Regular Expression to find ">" and tried to make an if statement that it will send next request(live data monitoring) only when ">" appears. Regular Expression works but I have trouble with socket connection because it saves everything to "output" variable with is NSString. That means it always have something in and before next answer comes it still has ">" symbol from last request. It usually saves more than 1 line of answer so it has answer for my request and ">" symbol. Anyway as you see at this moment I can't make live monitoring this when it saves answers to variable. Can you please suggest me what to do to make it work? PS. One of my friends told me to use ReactiveCocoa. Is this a good idea?


This is my code:



- (void)initNetworkCommunication {
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"192.168.0.10", 35000, &readStream, &writeStream);
self.inputStream = objc_unretainedObject(readStream);
self.outputStream = objc_unretainedObject(writeStream);
[self.inputStream setDelegate:self];
[self.outputStream setDelegate:self];
[self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

[self.inputStream open];
[self.outputStream open];
}

- (IBAction)connectObd:(id)sender {
[self initNetworkCommunication];

}

-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
switch (eventCode) {

case NSStreamEventOpenCompleted:
[self.logTextView setText:[self.logTextView.text stringByAppendingString:@"Stream opened\n"]];
break;

case NSStreamEventHasBytesAvailable:
NSLog(@"lol");
if (aStream == self.inputStream) {

uint8_t buffer[1024];
long len;

while ([self.inputStream hasBytesAvailable]) {
len = [self.inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {

NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];

if (nil != output) {
[self.logTextView setText:[self.logTextView.text stringByAppendingString:output]];

}
}

}
}
}
break;

case NSStreamEventErrorOccurred:
[self.logTextView setText:[self.logTextView.text stringByAppendingString:@"Can not connect to the host!"]];
break;

case NSStreamEventEndEncountered:
break;

default:
NSLog(@"Unknown event");
}



Aucun commentaire:

Enregistrer un commentaire