// // ConnectingAquarVC.m // Ifish // // Created by wbzhan on 2019/9/20. // Copyright © 2019 lianlian. All rights reserved. // #import "ConnectingAquarVC.h" #import "HKPieChartView.h" #import "dataContorl.h" #import #import "IFishHotpotUDPHelper.h" #import "ESPTouchResult.h" #import "ESPTouchTask.h" #import "IfishDataUnity.h" #import "MyMD5.h" #import @interface ConnectingAquarVC () Strong HKPieChartView *progressView; Strong UILabel *titleL; Strong ESPTouchTask* epTask; Strong NSMutableString *trackString; Strong MBProgressHUD *HUD; Strong NSTimer *timer; Strong UITapGestureRecognizer*tap; /** 设备返回的mac地址 */ Copy NSString *macAddress; /** 是否正在绑定设备 */ Assign BOOL isBindingDevice; Strong NSTimer *bindTimer; Assign NSInteger retryTimes; Copy NSString *deviceId; @end @implementation ConnectingAquarVC - (void)viewDidLoad { [super viewDidLoad]; [self addTitleViewWithTitle:@"尝试与设备建立连接"]; [self.view addSubview:self.progressView]; UITapGestureRecognizer*tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tryBindAgain:)]; [self.progressView addGestureRecognizer:tap]; self.tap=tap; self.tap.enabled=NO; [self.view addSubview:self.titleL]; [self.titleL mas_makeConstraints:^(MASConstraintMaker *make) { make.top.mas_equalTo(self.progressView.mas_bottom).offset(kSizeFrom750(80)); make.centerX.mas_equalTo(self.view); make.width.mas_equalTo(kSizeFrom750(700)); }]; [self.progressView updatePercent:100 animation:YES]; [self.progressView endProgressWithString:@"设备连接中..."]; // self.HUD.labelText = @"正在绑定设备"; // // if ( [GWP2PClient sharedClient].linkStatus==P2PLinkStatusOK) { // [self connectDevice]; // }else{ // UserModel *model=[dataContorl getUserInfo]; // [self loginGewellWith:model]; // } //传入设备要连接的wifi名称和密码 [self sendToDeviceWithSSIDName:self.wifiName andSSIDPWD:self.wifiPassword]; // // Do any additional setup after loading the view. self.timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes]; } //AP模式配网 -(void)connectDevice{ [[GWP2PDeviceLinker shareInstance] p2pStopAPLink]; [[GWP2PDeviceLinker shareInstance] p2pAPLinkDeviceWithWiFiSSID:self.wifiName wifiPassword:self.wifiPassword devicePassword:@"" deviceReceive:^(NSString *deviceId, BOOL isSupport) { //已经连接到设备,此处回调之后,会断开热点,重新连接到路由器wifi NSLog(@"设备%@收到WiFi,isSupport:%d",deviceId,isSupport); self.HUD.labelText = @"设备WiFi配置成功,之后会断开设备热点,连接设备到路由器"; self.deviceId = deviceId; } deviceLinkIn:^(NSDictionary *deviceDict) { //AP模式配网成功//连接到路由器wifi成功之后,会走此回调方法 if (IsEmptyStr(self.deviceId)) { [self bindDeviceWithDeviceId:self.deviceId]; } }]; } //P2P连线 -(void)loginGwellWith:(UserModel *)model { NSString *accountId =[NSString stringWithFormat:@"%d",(int)[model.gwellUserID integerValue]&0x7fffffff]; if ([accountId isEqualToString:@"0"]) { [self.view makeToast:@"暂未检测到设备"]; return; } if ([model.P2PVerifyCode1 isEqualToString:@""]) { [self.view makeToast:@"暂未检测到设备"]; return; } if ([model.P2PVerifyCode2 isEqualToString:@""]) { [self.view makeToast:@"暂未检测到设备"]; return; } if ([GWP2PClient sharedClient]!=P2PLinkStatusOK) { [[GWP2PClient sharedClient] connectWithAccount:accountId codeStr1:model.P2PVerifyCode1 codeStr2:model.P2PVerifyCode2 sessionID1:model.sessionID sessionID2:model.sessionID2 customerIDs:nil]; [self connectDevice]; } //loginResult.contactId 用户ID号 NSLog(@"%@%@%@",accountId,model.P2PVerifyCode1,model.P2PVerifyCode2,model.sessionID,model.sessionID2); } -(void)bindDeviceWithDeviceId:(NSString*)deviceId{ NSLog(@"设备bssid_%@",deviceId); [self appendTrakContent:@"=================进入绑定函数================="]; NSString *userId = [dataContorl dataControlGetUserIdInfo]; self.HUD.labelText = @"正在绑定设备"; [self appendTrakContent:[NSString stringWithFormat:@"绑定参数 userID:%@", userId]]; [self appendTrakContent:[NSString stringWithFormat:@"绑定参数 macaddress:%@", deviceId]]; [AFHttpTool bindDeviceWithUserId:userId macAddress:deviceId success:^(id response) { [self endProgress]; self.isBindingDevice = NO; self.macAddress = nil; NSDictionary*resultDic=[NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:nil]; NSLog(@"data:%@",resultDic[@"data"]); [self appendTrakContent:[NSString stringWithFormat:@"绑定请求成功。返回数据为:%@", resultDic]]; if ([resultDic[@"result"] isEqualToString:@"100"]) { // 保存设备信息 NSDictionary*dataDic=resultDic[@"data"]; DeviceModel*devicemodel=[[DeviceModel alloc] initWithDict:dataDic]; [self appendTrakContent:[NSString stringWithFormat:@"绑定返回状态码正确。设备信息为:%@", dataDic]]; if (!devicemodel.type){ self.HUD.labelText = @"用户绑定设备成功,但设备初次入网失败请重新登陆"; }else{ NSMutableArray * _deviceArry=[[DataCenter defaultDtacenter]valueForKey:@"deviceInfo"]; [_deviceArry insertObject:devicemodel atIndex:0]; [[DataCenter defaultDtacenter]setValue:_deviceArry forKey:@"deviceInfo"]; if ([devicemodel.type isEqual:[NSNull null]]){ //进入此循环 可能因为设备所在服务器 不在 本程序所在 服务器 self.HUD.labelText = @"设备不在服务器"; }else{ self.HUD.labelText = @"设备绑定成功"; [[IfishDataUnity shareDataInstance] initAppCenterVcWith:devicemodel addWithdissMisVc:nil]; //绑定成功 加 经验值 [[IfishUserObsever sharedInstance] xinZengJingYanZhi:IFISHADDEXP_BIDDEVICE addType:IFISHADDEXPTYPE1]; } } }else if ([resultDic[@"result"] isEqualToString:@"101"]){ [self appendTrakContent:@"绑定返回状态码错误。设备信息为:%@"]; self.bakbutton.userInteractionEnabled=YES; NSString*msg= resultDic[@"data"]; if ([msg isKindOfClass:[NSString class]]&&msg.length&&![msg isEqualToString:@"null"]) { } else { msg=@"设备类型不匹配,请重新选择入口绑定"; } [self.HUD hide:YES]; [self.view makeToast:msg]; }else if ([resultDic[@"result"] isEqualToString:@"301"]){ [self appendTrakContent:@"绑定返回状态码错误。设备信息为:%@"]; self.HUD.labelText = @"请求验证失败,请重新登录"; self.bakbutton.userInteractionEnabled=YES; }else if ([resultDic[@"result"] isEqualToString:@"302"]){ // 请求被舍弃未执行 [self appendTrakContent:@"绑定返回状态码错误。设备信息为:%@"]; self.bakbutton.userInteractionEnabled=YES; self.HUD.labelText = @"绑定失败"; [self.HUD hide:YES afterDelay:2]; } } failure:^(NSError *err) { if (self.retryTimes < 10) { [self bindDeviceWithDeviceId:self.deviceId]; self.retryTimes += 1; } else { [self endProgress]; self.isBindingDevice = NO; self.HUD.labelText = @"请求异常"; [self.HUD hide:YES afterDelay:2]; [self appendTrakContent:[NSString stringWithFormat:@"绑定网络请求错误:%@", err.localizedDescription]]; self.bakbutton.userInteractionEnabled=YES; } }]; } - (void)dealloc { if (!self.timer) { return; } [self.timer invalidate]; self.timer = nil; } - (HKPieChartView *)progressView { if (!_progressView) { _progressView = [[HKPieChartView alloc]initWithFrame:RECT((screen_width - 100)/2, 100, 100, 100)]; } return _progressView; } - (UILabel *)titleL { if (!_titleL) { _titleL = InitObject(UILabel); _titleL.text = @"设备连接中\n尽量使您的路由器、手机和设备互相靠近"; _titleL.textAlignment = NSTextAlignmentCenter; _titleL.font = FontSize(16); _titleL.numberOfLines = 2; _titleL.textColor = RGB_92; } return _titleL; } -(void)timerAction{ [self.progressView updatePercent:100 animation:YES]; } #pragma mark - UDP related - (void)sendToDeviceWithSSIDName:(NSString *)name andSSIDPWD:(NSString *)pwd { [IFishHotpotUDPHelper sharedInstance].delegate = self; [[IFishHotpotUDPHelper sharedInstance] broadCastHotspotConnectCommandWith:name pwd:pwd]; } #pragma mark - IFishHotpotUDPHelperDelegate //这里是连接到设备的路由器之后的回调方法 - (void)udpHelperCommandExecutedSuccess:(IFishUDPHelperBackMsgModel *)backModel { self.ssid = backModel.senderMacAddress; [self.view resignFirstResponder]; self.HUD.labelText = @"请稍后"; self.trackString = [NSMutableString string]; [self appendTrakContent:@"=================收到设备答复==================="]; [self appendTrakContent:[NSString stringWithFormat:@"答复状态码:%@", backModel.result]]; [self appendTrakContent:[NSString stringWithFormat:@"答复Mac地址:%@", backModel.senderMacAddress]]; self.macAddress = backModel.senderMacAddress; [IFishHotpotUDPHelper sharedInstance].delegate = nil; [[IFishHotpotUDPHelper sharedInstance] broadCastRestartCommand]; //这里需要连接到之前的路由器,才能绑定设备到 self.bindTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(startBinding) userInfo:nil repeats:YES]; } - (void)startBinding { [CommonUtils getNetworkTypeComplete:^(NSString *netconnType, NSString *BSSID, NSString *SSID) { if ([netconnType isEqualToString:@"no network"]||([netconnType isEqualToString:@"Wifi"]&&[SSID.lowercaseString hasPrefix:@"ifish"])) { //无网络 或者连接的还是设备的热点 } else { if (self.isBindingDevice||self.storeNameView) { return; } if (self.macAddress.length == 0) { return; } self.retryTimes = 0; if (self.deviceType==DEVICEPETS) { [self showStoreNameView]; } else { [self bindDeviceWithSsid:self.macAddress]; } } }]; } - (void)udpHelperMessage:(NSString *)msg { if (!self.timer) { return; } [MBProgressHUD hideHUDForView:self.view animated:YES]; self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES]; self.HUD.mode = MBProgressHUDModeIndeterminate; self.HUD.labelText = msg; if ([msg containsString:@"Socket连接失败"]) { [self.HUD hide:YES afterDelay:3]; [self endProgress]; if (self.retryTimes<10) { self.retryTimes++; [self.progressView endProgressWithString:@"自动重试..."]; WEAK_SELF; [[IFishHotpotUDPHelper sharedInstance] closeComplete:^{ [weakSelf sendToDeviceWithSSIDName:weakSelf.wifiName andSSIDPWD:weakSelf.wifiPassword]; }]; } else { [self.progressView endProgressWithString:@"连接结束"]; } } } -(void)endProgress{ [self.progressView endProgressWithString:@"连接结束"]; [self.timer invalidate]; self.timer = nil; } -(UIView *)mask { if (!_mask) { UIView*mask=[[UIView alloc]initWithFrame:self.view.bounds]; mask.backgroundColor=[UIColor lightGrayColor]; mask.alpha=0.5; _mask=mask; UITapGestureRecognizer*tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismissStore)]; //[mask addGestureRecognizer:tap]; } return _mask; } -(void)dismissStore { [self.storeNameView removeFromSuperview]; [self.mask removeFromSuperview]; self.storeNameView =nil; [self.progressView endProgressWithString:@"绑定已经取消..."]; } -(void)showStoreNameView { [self.HUD hide:YES]; [self.storeNameView removeFromSuperview]; if (self.bindTimer) { [self.bindTimer invalidate]; self.bindTimer = nil; } StoreNameView*store=[[[NSBundle mainBundle] loadNibNamed:@"StoreNameView" owner:self options:nil] lastObject]; store.frame=CGRectMake((SCREEN_WIDTH-280)/2.0, 100, 280, 280); self.storeNameView=store; WEAK_SELF; store.cancelBlock=^(){ [weakSelf.mask removeFromSuperview]; [weakSelf.storeNameView removeFromSuperview]; weakSelf.storeNameView =nil; [weakSelf.HUD show:YES]; [weakSelf.progressView endProgressWithString:@"绑定已经取消..."]; }; store.sureBlock=^(NSString*name) { if (!name.length) { [weakSelf.view makeToast:@"请设置或者选择名称!"]; return ; } [weakSelf.mask removeFromSuperview]; [weakSelf.storeNameView removeFromSuperview]; weakSelf.storeNameView =nil; weakSelf.storeName=name; [self bindDeviceWithSsid:self.macAddress]; [weakSelf.HUD show:YES]; }; [self.view addSubview:self.mask]; [self.view addSubview:self.storeNameView]; } #pragma mark - bind -(void)tryBindAgain:(UITapGestureRecognizer*)tap { [self bindDeviceWithSsid:self.macAddress]; } -(void)bindDeviceWithSsid:(NSString*)bssid{ NSLog(@"设备bssid_%@",bssid); if (self.isBindingDevice) { return; } else { self.isBindingDevice = YES; if (self.bindTimer) { [self.bindTimer invalidate]; self.bindTimer = nil; } } [self appendTrakContent:@"=================进入绑定函数================="]; NSString *userId = [dataContorl dataControlGetUserIdInfo]; self.HUD.labelText = @"正在绑定设备"; [self appendTrakContent:[NSString stringWithFormat:@"绑定参数 userID:%@", userId]]; [self appendTrakContent:[NSString stringWithFormat:@"绑定参数 macaddress:%@", bssid]]; NSString*url=[NSString stringWithFormat:@"%@%@",kBindDevice,userId]; NSMutableDictionary*bind=[[NSMutableDictionary alloc]initWithDictionary:@{@"macAddress":bssid}]; NSString* timestamp=[NSString stringWithFormat:@"%lld",[[NSDate date] timeIntervalSince1970]*1000]; NSString*token=[MyMD5 md5:[NSString stringWithFormat:@"%@%@ifish8",userId,timestamp]]; if (self.deviceType==DEVICEPETS) { url=[NSString stringWithFormat:@"%@",[NSString stringWithFormat:@"%@/api/user/bindPetDevice.do",JIEKOUPORT]]; bind[@"token"]=token; bind[@"timestamp"]=timestamp; bind[@"storeName"]=self.storeName.length?self.storeName:@"宠物店"; bind[@"userId"]=userId; } [AFHttpTool requestWihtMethod:RequestMethodTypePost url:url params:bind success:^(id response) { [self endProgress]; self.isBindingDevice = NO; self.macAddress = nil; NSDictionary*resultDic=[NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:nil]; NSLog(@"data:%@",resultDic[@"data"]); [self appendTrakContent:[NSString stringWithFormat:@"绑定请求成功。返回数据为:%@", resultDic]]; if ([resultDic[@"result"] isEqualToString:@"100"]) { [self endProgress]; // 保存设备信息 NSDictionary*dataDic=resultDic[@"data"]; DeviceModel*devicemodel=[[DeviceModel alloc] initWithDict:dataDic]; [self appendTrakContent:[NSString stringWithFormat:@"绑定返回状态码正确。设备信息为:%@", dataDic]]; if (!devicemodel.type){ self.HUD.labelText = @"用户绑定设备成功,但设备初次入网失败请重新登陆"; }else{ NSMutableArray * _deviceArry=[[DataCenter defaultDtacenter]valueForKey:@"deviceInfo"]; [_deviceArry insertObject:devicemodel atIndex:0]; [[DataCenter defaultDtacenter]setValue:_deviceArry forKey:@"deviceInfo"]; if ([devicemodel.type isEqual:[NSNull null]]){ //进入此循环 可能因为设备所在服务器 不在 本程序所在 服务器 self.HUD.labelText = @"设备不在服务器"; }else{ self.HUD.labelText = @"设备绑定成功"; [[IfishDataUnity shareDataInstance] initAppCenterVcWith:devicemodel addWithdissMisVc:nil]; //绑定成功 加 经验值 [[IfishUserObsever sharedInstance] xinZengJingYanZhi:IFISHADDEXP_BIDDEVICE addType:IFISHADDEXPTYPE1]; } } }else if ([resultDic[@"result"] isEqualToString:@"101"]){ [self appendTrakContent:@"绑定返回状态码错误。设备信息为:%@"]; self.bakbutton.userInteractionEnabled=YES; NSString*msg= resultDic[@"data"]; if ([msg isKindOfClass:[NSString class]]&&msg.length&&![msg isEqualToString:@"null"]) { } else { msg=@"设备类型不匹配,请重新选择入口绑定"; } [self.HUD hide:YES]; [self.view makeToast:msg]; }else if ([resultDic[@"result"] isEqualToString:@"301"]){ [self appendTrakContent:@"绑定返回状态码错误。设备信息为:%@"]; self.HUD.labelText = @"请求验证失败,请重新登录"; self.bakbutton.userInteractionEnabled=YES; }else if ([resultDic[@"result"] isEqualToString:@"302"]){ // 请求被舍弃未执行 [self appendTrakContent:@"绑定返回状态码错误。设备信息为:%@"]; self.bakbutton.userInteractionEnabled=YES; self.HUD.labelText = @"绑定失败"; [self.HUD hide:YES afterDelay:2]; } else { [self appendTrakContent:@"绑定返回状态码错误。设备信息为:%@"]; self.bakbutton.userInteractionEnabled=YES; self.HUD.labelText = [NSString stringWithFormat:@"绑定失败:%@",resultDic[@"result"]]; [self.HUD hide:YES afterDelay:2]; } } failure:^(NSError *err) { self.isBindingDevice=NO; if (self.retryTimes < 10) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ self.HUD.labelText = @"自动重连..."; [self bindDeviceWithSsid:self.macAddress]; self.retryTimes += 1; }); } else { [self endProgress]; [self.progressView endProgressWithString:@"点击重试"]; self.tap.enabled=YES; self.isBindingDevice = NO; self.HUD.labelText = err.localizedDescription; [self.HUD hide:YES afterDelay:2]; [self appendTrakContent:[NSString stringWithFormat:@"绑定网络请求错误:%@", err.localizedDescription]]; self.bakbutton.userInteractionEnabled=YES; } }]; } #pragma mark - Private - (void)appendTrakContent:(NSString *)msg { NSLog(@"msg=%@",msg); [self.trackString appendString:msg]; [self.trackString appendString:@"\n"]; } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ @end