armadsen / ORSSerialPort

Serial port library for Objective-C and Swift macOS apps
MIT License
751 stars 183 forks source link

Add initializer to ORSSerialPacketDescriptor to allow for choosing matching options on a regular expression #160

Closed SpencerCurtis closed 4 years ago

SpencerCurtis commented 4 years ago

Context: I'm using ORSSerialPort to communicate with a home audio controller. The problem is that the responses come with the # prefix. The NSMatchingAnchored option prevents me from using a regular expression on responses that are returned on more than a single line. Or at least I haven't found a regular expression that will let me.

In creating a new initializer that takes in the matching options, the user of ORSSerialPort can choose which options fit their use case. To maintain compatibility, the existing initializer that takes in a regular expression has been converted into a convenience initializer that calls the new initializer with NSMatchingAnchored.

armadsen commented 4 years ago

Hi Spencer, thanks for the pull request.

I have to think about this change a little more. It's intentional that ORSSerialPacketDescriptor requires matches to match at the beginning of the string, which is why NSMatchingAnchored was specified. It may be that we're OK without that. In any case, I'd like to add some tests to verify behavior around this change (and the existing code).

Can you tell me what the packets you're trying to receive actually look like?

SpencerCurtis commented 4 years ago

Sure, I wanted to get this entire string back as a single packet and parse it from there.

#?10
#>1100010000190707100200

#>1200000000320707100200

#>1300000000020707100100

#>1400000000120707100100

#>1500000000200707100100

#>1600010000160707100600

#
armadsen commented 4 years ago

Does it always have the same prefix and is it always the same length? What regex are you trying to match it with?

SpencerCurtis commented 4 years ago

Looks like I was just tired and didn't quite write the regular expression correctly. Thanks for taking the time to look at the PR anyway!

NSString *string = @"#>1100010000190707100200\r\r\n#>1200000000320707100200\r\r\n#>1300000000020707100100\r\r\n#>1400000000120707100100\r\r\n#>1500000000200707100100\r\r\n#>1600010000160707100600\r\r\n#";

NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:@"(#>.+\r\r\n{0,}){6}#" options:0 error:nil];

BOOL found = [regex numberOfMatchesInString:string options:NSMatchingAnchored range:NSMakeRange(0, [string length])] > 0;
NSLog(@"%i", found);