سؤال

All,

I have an OBDII device which has a webserver in it. I connect via wifi. I want to create an app to send commands and read the data received from the device.

I first test it using Terminal. I connect using a telnet session and can send a command (0104) and I get the respons. This works fine.

Now, I want to create an app to do the same. I know I can connect using:

- (void)initNetworkCommunication {
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"192.168.0.10", 35000, &readStream, &writeStream);
    inputStream = (NSInputStream *)readStream;
    outputStream = (NSOutputStream *)writeStream;
    [inputStream setDelegate:self];
    [outputStream setDelegate:self];

    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [inputStream open];
    [outputStream open];
}

The connection works fine.
Then, I want to send a command. I use this:

- (IBAction)sendCommand:(id)sender {
    NSString *response  = [NSString stringWithFormat:@"%@", commandText.text];
    NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
    [outputStream write:[data bytes] maxLength:[data length]];   
}

But I don't get a correct answer, I get a ? back. So the device does not recognize the command...
What am I doing wrong? Is it the wrong format? Shouldn't it be a String? Or should it be different than ASCII?

I already tried to put \r at the end of the command, but this does not help.

هل كانت مفيدة؟

المحلول

Solution:

Send the data with addition \r\n. Can also change encoding in UTF encoding but this is not mandatory...

- (IBAction)sendCommand:(id)sender {
    NSString *response  = [NSString stringWithFormat:@"%@\r\n", commandText.text];
    NSLog(@"Response send: %@", response);
    NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSUTF8StringEncoding]];
    NSInteger bytesWritten = [outputStream write:[data bytes] maxLength:[data length]];

}

نصائح أخرى

...has a webserver in it. I connect via wifi...

If that's the case, one would think the best solution would be a high-level one. Use NSURLRequest to send your request, and get the data back in an NSHTTPURLResponse. Let iOS take care of the HTTP stuff for you. If that doesn't work, then your device's server can't really be called a web server.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top