Project Background:

Bluetooth or WiFi projects typically exchange data according to a customized protocol. For example, data is received from BLE: 0x01. Data is resolved according to the protocol. 0x01 means that the device has been opened, and we need to do the corresponding business logic processing on the client side.

In the project background above, we can extract the following development keywords:

  • Bluetooth (WiFi) Interactive data: NSData sent by the client can be obtained from the corresponding agent or Block
  • agreement: Defines the meaning of data exchanged between the client and the hardware, for example0x01: turn on the light. If the protocol is complex, try to model the protocol.

So our usual process during development is:Where: distribute data according to the analytical results. The conventional approach is:The result is transmitted to each interface through proxy, notification and BLCOK to complete the corresponding business logic.

But with AOP, we don’t need to use a lot of notifications, proxies, and BLCOk. We just need to intercept the results of parsing where data is needed to get the data we need, as follows:

Implementation of data interception library: Based on the encapsulation callback method of Appects framework, it can achieve the corresponding analysis results can be seen as Aspects

Code snippet:

Receive data

+ (void)receiveData:(NSData *)data{
    
    NSString *dataString =  [NSString convertDataToHexStr:[data subdataWithRange:NSMakeRange(0.1)]];
   
   int backCode = [[NSString hexStringToDecima:dataString] intValue];

    switch (backCode) {
        case 0x1: {}break;
        case 0x2: {}case 0x0F: {}default:
            break; }}Copy the code
Data parsing

The data transfer model can be handled by writing a Runtime utility class.

+ (HNGetDeviceInfoCode *)getDeviceInfoModel:(NSData *)data{
   HNGetDeviceInfoCode *code = [HNGetDeviceInfoCode AnalysisDataToModel:data BytesArray:@[@1The @1The @1The @1The @6The @1The @1]];
    DLog(@ "% @",code);
    return code;
}
Copy the code
Data interception library
+ (void)getDeviceUpdateStatus:(void(^) (BOOL isSuccess))handlerBlock{
    
    [object_getClass([HNBLEDataManager class]) aspect_hookSelector:@selector(getDeviceUpdataStatus:) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo,NSData *data){
        BOOL isSuccess;
        [aspectInfo.originalInvocation getReturnValue:&isSuccess];
        if (handlerBlock) {
            handlerBlock(isSuccess);
        }
    } error:NULL];
}
Copy the code

Aspects [A brief discussion on the architecture of iOS in Internet of Things Application](