// // 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 @interface ConnectingAquarVC () Strong HKPieChartView *progressView; Strong UILabel *titleL; Strong ESPTouchTask* epTask; Strong NSMutableString *trackString; Strong MBProgressHUD *HUD; Strong NSTimer *timer; /** 设备返回的mac地址 */ Copy NSString *macAddress; /** 是否正在绑定设备 */ Assign BOOL isBindingDevice; Strong NSTimer *bindTimer; Assign NSInteger retryTimes; @end @implementation ConnectingAquarVC - (void)viewDidLoad { [super viewDidLoad]; [self addTitleViewWithTitle:@"尝试与设备建立连接"]; [self.view addSubview:self.progressView]; [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:@"设备连接中..."]; //AP模式配网 // [[GWP2PDeviceLinker shareInstance] p2pAPLinkDeviceWithWiFiSSID:self.wifiName wifiPassword:self.wifiPassword devicePassword:@"123" deviceReceive:^(NSString *deviceId, BOOL isSupport) { // // // NSLog(@"设备%@收到WiFi,isSupport:%d",deviceId,isSupport); // } deviceLinkIn:^(NSDictionary *deviceDict) { // //成功 // }]; //传入设备要连接的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]; } - (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 - (NSString *)currentWifiSSID { NSString *ssid = @"Not Found"; CFArrayRef myArray = CNCopySupportedInterfaces(); if (myArray != nil) { CFDictionaryRef myDict = CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0)); if (myDict != nil) { NSDictionary *dict = (NSDictionary *)CFBridgingRelease(myDict); ssid = [dict valueForKey:@"SSID"]; } } return ssid; } - (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 { BOOL networkOk = NO; AFNetworkReachabilityStatus status = [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus; if (status == AFNetworkReachabilityStatusReachableViaWiFi) { if (![[self currentWifiSSID].lowercaseString hasPrefix:@"ifish"]) { networkOk = YES; } } else if (status == AFNetworkReachabilityStatusReachableViaWWAN) { networkOk = YES; } if (!networkOk) { return; } if (self.isBindingDevice) { return; } if (self.macAddress.length == 0) { return; } self.isBindingDevice = YES; if (self.bindTimer) { [self.bindTimer invalidate]; self.bindTimer = nil; } self.retryTimes = 0; [self bindDeviceWithSsid:self.macAddress]; } - (void)udpHelperMessage:(NSString *)msg { self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES]; self.HUD.mode = MBProgressHUDModeIndeterminate; self.HUD.labelText = msg; } -(void)endProgress{ [self.progressView endProgressWithString:@"连接结束"]; [self.timer invalidate]; self.timer = nil; } #pragma mark - bind -(void)bindDeviceWithSsid:(NSString*)bssid{ NSLog(@"设备bssid_%@",bssid); [self appendTrakContent:@"=================进入绑定函数================="]; NSString *userId = [dataContorl dataControlGetUserIdInfo]; self.HUD.labelText = @"正在绑定设备"; [self appendTrakContent:[NSString stringWithFormat:@"绑定参数 userID:%@", userId]]; [self appendTrakContent:[NSString stringWithFormat:@"绑定参数 macaddress:%@", bssid]]; [AFHttpTool bindDeviceWithUserId:userId macAddress:bssid success:^(id response) { [self.progressView endEditing:YES]; 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.HUD.labelText = @"绑定失败"; self.bakbutton.userInteractionEnabled=YES; }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 < 3) { [self bindDeviceWithSsid:self.macAddress]; 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; } }]; } #pragma mark - Private - (void)appendTrakContent:(NSString *)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