示例代码

更新时间:2024-04-26 10:19:39下载pdf

本文介绍扫地机 SDK P2P 相关操作的示例代码。

示例代码

#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 数据通道

- (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 连接成功");
            strongif(self)
            [self startObserverSweeperDataByP2P:self.devId downloadType:self.downloadType];
        } failure:^(NSError * _Nullable error) {
            NSLog(@"P2P 连接失败:%@",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(@"关闭数据下载成功");
    } failure:^(NSError * _Nullable error) {
        NSLog(@"关闭数据下载失败:%@",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 {
    // 断开 P2P 通道
    [self.p2pDevice onDestroyP2P];
}

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

@end