Sample Code

Last Updated on : 2024-04-26 10:19:39download

This topic describes sample code related to the P2P operation based on the robot vacuum SDK.

Sample code

#import "ThingSmartSweeperBestPractices.h"
#import <ThingSmartSweeperKit/ThingSmartSweeperKit.h>

@interface ThingSmartSweeperP2PBestPractices()

@property (nonatomic,strong)  ThingSmartSweeperDevice *p2pDevice;
@property (nonatomic, copy)   NSString        *devId;
@property (nonatomic,assign)  NSInteger downloadType;

@end

@implementation ThingSmartSweeperP2PBestPractices

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - P2P data channel

- (void)initP2PSDK:(NSString*)devId {
    [self initConfig];
    self.devId = devId;
    self.p2pDevice = [ThingSmartSweeperDevice deviceWithDeviceId:devId];
}

- (void)connectDeviceByP2P{
    if (![self.p2pDevice P2PActiveCheck]){
         weakify(self)
        [self.p2pDevice connectDeviceByP2P:^{
            NSLog(@"P2P connection was successful");
            strongif(self)
            [self startObserverSweeperDataByP2P:self.devId downloadType:self.downloadType];
        } failure:^(NSError * _Nullable error) {
            NSLog(@"P2P connection failed: %@",error);
        }];
    }
}

- (void)startObserverSweeperDataByP2P:(NSString*)devId downloadType:(NSInteger)downloadType{
    self.downloadType = downloadType;
    weakify(self);
    [self.p2pDevice startObserverSweeperDataByP2P:downloadType receiveP2PData:^(NSDictionary * _Nonnull data) {
        if (data) {
            NSLog(@"onMapDataReceiveByP2P is %@",data);
        }
    } failure:^(NSError * _Nullable error) {
        NSLog(@"onP2PError is %@",error);
    }];
}

- (void)stopObserverSweeperDataByP2P{
    [self.p2pDevice stopObserverSweeperDataByP2P:^{
        NSLog(@"Data download was closed successfully");
    } failure:^(NSError * _Nullable error) {
        NSLog(@"Failed to close data download: %@",error);
    }];
}

- (void)deInitP2PSDK:(NSString*)devId {
    [self.p2pDevice onDestroyP2P];
}

#pragma mark - private

-(void)initConfig {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(p2p_cancelDownload) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(p2p_startDownload) name:UIApplicationWillEnterForegroundNotification object:nil];
    weakify(self)
    NetworkStatusChanged(self, ^(NetworkStatus status) {
        strongif(self)
        if (status == NetworkStatusUnknown || status == NetworkStatusUnreachable) {
            [self p2p_cancelDownload];
        } else {
            [self p2p_startDownload];
        }
    });
}



-(void)p2p_cancelDownload {
    // Disconnect the P2P channel
    [self.p2pDevice onDestroyP2P];
}

-(void)p2p_startDownload {
    [self connectDeviceByP2P];
}
@end