// // SecondConnectWifiController.m // Ifish // // Created by imac on 16/2/24. // Copyright © 2016年 imac. All rights reserved. // #import "SPAlertController.h" #import "ConfigWifiViewController.h" #import #import "DeviceModel.h" #import "SaySomethingViewController.h" #import "ConnectErrorViewController.h" #import "AppDelegate.h" #import "ESP_NetUtil.h" #import "ESPTouchTask.h" #import "ESPTouchResult.h" #import "ESPTouchDelegate.h" #import "MyMD5.h" #import "ChatroomModel.h" #import "MMProgressHUD.h" #import "MMProgressHUDOverlayView.h" #define ALERTVIEW_TAG 11001 #define WIFI_KEYBOARD 30 #import "IfishDataUnity.h" #import "Utils.h" #import "IfishConnectingView.h" #import "PushMasssageWebViewController.h" #import "IfishUserObsever.h" #import #import "ConnectHotpotViewController.h" #import "ConAquarNowWiFiPwdVC.h" #import "InfoByImageViewController.h" #import "YooseeNextConnectViewController.h" #import "HKPieChartView.h" #import "dataContorl.h" #import #import "IFishHotpotUDPHelper.h" #import "ESPTouchResult.h" #import "ESPTouchTask.h" #import "IfishDataUnity.h" #import "MyMD5.h" #import typedef NS_ENUM(NSInteger,lodingViewdissMissStyle) { lodingViewdissMissSuccsess=0,// default is 0 lodingViewdissMissfail, lodingViewdissMissAlreadyBinded }; @interface ConfigWifiViewController () @property (nonatomic, strong) NSCondition *_condition; @property (atomic, strong) ESPTouchTask *_esptouchTask; @property (nonatomic, strong) EspTouchDelegateImpl *_esptouchDelegate; @property(nonatomic,strong)NSMutableArray*deviceArry; @property(nonatomic,strong)ICSDrawerController*ics; @property(nonatomic)BOOL autodismiss; @property(nonatomic,assign)lodingViewdissMissStyle lodviewMissStyle; @property(nonatomic,retain) NSTimer* getInfTimer ; @property(nonatomic,copy)NSString*deviceId; @property(nonatomic,strong) UILabel *maclabel; @property (nonatomic, assign) BOOL isGoChangeWiFi; @property (nonatomic, strong) JMAirKissConnection *airKissConnection; ; Strong CLLocationManager *locationManager;//iOS13,获取WiFi名称必须开启定位权限 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; @end //extern BOOL formLogIn;//连接页面是否来自登录界面 extern BOOL isfromCameraView; @implementation ConfigWifiViewController -(JMAirKissConnection *)airKissConnection { if(!_airKissConnection) { _airKissConnection= [[JMAirKissConnection alloc]init]; } return _airKissConnection; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. self.view.backgroundColor=[UIColor whiteColor]; self.connectType = ConnectTypeAirKiss; _deviceArry =[[NSMutableArray alloc]init]; //输入框在上面新UI 可去 _wifiTextFiled.delegate=self; _wifiTextFiled.layer.masksToBounds=YES; _wifiTextFiled.layer.cornerRadius=5; // if (@available(iOS 13.0, *)){//iOS13之后,设置颜色的方便变更 // // }else{ // [_wifiTextFiled setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"]; // } // UIView*phoneView=[[UIView alloc]initWithFrame:CGRectMake(0,0, 9, 10)]; // self.wifiTextFiled.leftView=phoneView; // self.wifiTextFiled.textColor = RGB_51; self.wifiTextFiled.leftViewMode=UITextFieldViewModeAlways; [self addTitleViewWithTitle:self.vcTitle]; self.rightButton = [UIButton buttonWithType:UIButtonTypeCustom]; self.rightButton.frame = CGRectMake(0, 0, 50, 44); [self.rightButton setBackgroundImage:[UIImage imageNamed:@"qr"] forState:UIControlStateNormal]; [self.rightButton addTarget:self action:@selector(rightButtonClickItem:) forControlEvents:UIControlEventTouchUpInside]; self.rightItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton]; // self.navigationItem.rightBarButtonItem = self.rightItem; UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil]; self.navigationItem.backBarButtonItem = item; [self creatConnectStateUI]; //获取WiFi名称 [self getSSid]; } -(void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; } -(void)viewDidDisappear:(BOOL)animated{ [super viewDidDisappear:animated]; } #pragma mark -连接不上? -(void)connectTypeClick:(UIButton *)btn { WEAK_SELF; NSString*airkisTitle = @"一键联网"; NSString*smartTitle = @"快捷联网"; NSString*apTitle = @"AP联网"; NSString*airkisTips = @"1、插座仅支持2.4G的WiFi网络,不支持5G 及 双频合一的网络(需在路由器设置中分开)\n2、先长按插座复位键3秒,松手后红灯绿灯同时 闪烁,再点确定按钮。\n3、如多次尝试一键联网都不成功,可切换其他 联网方式,每次重新连接时插座需断一次电然后重新复位连接。"; NSString*smartTips = airkisTips; NSString*apTips = @"1、插座仅支持2.4G的WiFi网络,不支持5G 及 双频合一的网络(需在路由器设置中分开)\n2、先长按插座复位键13秒左右,松手后红灯绿灯同时熄灭,只有绿灯偶尔闪烁,再点下一步。"; SPAlertController*alert =[SPAlertController alertControllerWithTitle:nil message:nil preferredStyle:SPAlertControllerStyleActionSheet animationType:SPAlertAnimationTypeDefault]; SPAlertAction*airkiss =[SPAlertAction actionWithTitle:airkisTitle style:SPAlertActionStyleDefault handler:^(SPAlertAction * _Nonnull action) { weakSelf.connectType = ConnectTypeAirKiss; weakSelf.connectTypeTitle.text = airkisTitle; weakSelf.connectTipLbl.text = airkisTips; }]; SPAlertAction*smart =[SPAlertAction actionWithTitle:smartTitle style:SPAlertActionStyleDefault handler:^(SPAlertAction * _Nonnull action) { weakSelf.connectType = ConnectTypeSmartESPTouch; weakSelf.connectTypeTitle.text = smartTitle; weakSelf.connectTipLbl.text = smartTips; }]; SPAlertAction*ap =[SPAlertAction actionWithTitle:apTitle style:SPAlertActionStyleDefault handler:^(SPAlertAction * _Nonnull action) { weakSelf.connectType = ConnectTypeSmartESPTouch; weakSelf.connectTypeTitle.text = apTitle; weakSelf.connectTipLbl.text = apTips; }]; SPAlertAction*cancel =[SPAlertAction actionWithTitle:@"取消" style:SPAlertActionStyleCancel handler:^(SPAlertAction * _Nonnull action) { }]; [alert addAction:airkiss]; [alert addAction:smart]; [alert addAction:ap]; [alert addAction:cancel]; [self presentViewController:alert animated:YES completion:nil]; } -(IBAction)shuoMingShuBtnAction:(UIButton *)btn{ // PushMasssageWebViewController*webVC=[[PushMasssageWebViewController alloc]init]; // webVC.pushlink =IFISH_DEVCEITROURL; // webVC.pushtitle = NSLocalizedString(@"ifish_deviceuse", nil);; // // [self.navigationController pushViewController:webVC animated:YES]; InfoByImageViewController*info=[[InfoByImageViewController alloc]init]; info.title=NSLocalizedString(@"ifish_deviceuse", nil);;; info.type=@"instruction"; info.image=[UIImage imageNamed:@"instruction"]; [self.navigationController pushViewController:info animated:YES]; } //ap模式 -(void)goSettingClick:(UIButton*)button { NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString]; if([[UIApplication sharedApplication] canOpenURL:url]) { if (@available(iOS 10.0, *)) { [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil]; }else { [[UIApplication sharedApplication] openURL:url]; } self.isGoChangeWiFi = YES; } } -(void)creatConnectStateUI{ [self connectNormalView]; } -(void)connectNormalView { self.connectingView.hidden=YES; self.connectBtn.hidden = NO; [self.indicator stopAnimating]; } -(void)connectNotNormalView { self.connectingView.hidden=NO; [self.indicator startAnimating]; self.connectBtn.hidden = YES; } -(void)initMacIdString:(NSString *)ssid{ if (!_maclabel) { _maclabel=[[UILabel alloc] init]; } _maclabel.text =ssid; if (ssid) { _maclabel.text =[NSString stringWithFormat:@"设备mac:%@",ssid]; }else{ _maclabel.text = @"无设备mac"; } NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:_maclabel.text]; NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init]; [paragraphStyle setLineSpacing:8]; [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [_maclabel.text length])]; [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0,[_maclabel.text length])]; [_maclabel setAttributedText:attributedString]; [_maclabel setTextColor:[UIColor colorWithRed:153.0/256.0 green:153.0/256.0 blue:153.0/256.0 alpha:1] ]; [_maclabel sizeToFit]; CGFloat LabelTitleW =200; CGFloat LabelTitleH = 20; _maclabel.frame = CGRectMake(kScreenSize.width/2-LabelTitleW/2,CGRectGetMaxY(self.wifiTextFiled.frame)+20, LabelTitleW, LabelTitleH); // [self.view addSubview:_maclabel]; // [self.view bringSubviewToFront:_maclabel]; self.bakbutton.userInteractionEnabled=YES; [self connectNormalView]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [self.view makeToast:@"设备类型不匹配,请重新选择入口绑定"]; }); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(void)initMMProgressHUD{ NSMutableArray *images = [[NSMutableArray alloc] init]; for (int i = 1; i <= 63; i ++) { if (i < 10) { [images addObject:[UIImage imageNamed:[NSString stringWithFormat:@"neves000%d",i]]]; }else{ [images addObject:[UIImage imageNamed:[NSString stringWithFormat:@"neves00%d",i]]]; } } _autodismiss = YES;//MMProgressHUDWindowOverlayModeLinear [MMProgressHUD setPresentationStyle:MMProgressHUDPresentationStyleNone]; /** * status: Custom Animated Image */ [MMProgressHUD showWithTitle:@"" status:@"" images:images]; } -(void)mmPogressHUDdismiss{ // if (_autodismiss == YES) { // double delayInSeconds = 2.0; // dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); // dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ [self setMMProgressHUDMissStayle:self.lodviewMissStyle]; // }); // } } -(void)setMMProgressHUDMissStayle:(lodingViewdissMissStyle)missStyle{ switch (missStyle) { case lodingViewdissMissSuccsess: { [MMProgressHUD dismissWithSuccess:@""]; } break; case lodingViewdissMissfail: { [MMProgressHUD dismissWithError:@""]; [self.view makeToast:@"再试一下!"]; [self initMacIdString:_deviceBssid]; } break; case lodingViewdissMissAlreadyBinded: { [MMProgressHUD dismissWithSuccess:@""]; [self.view makeToast:@"已经绑定过了!"]; } default: break; } } -(void)showTitle:(NSString*)title messsage:(NSString*)message{ UIAlertView *alert=[[UIAlertView alloc]initWithTitle:title message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil]; NSTimeInterval dismissSeconds=1.0; [alert show]; [self performSelector:@selector(dismissAlert:) withObject:alert afterDelay:dismissSeconds]; } -(void)dismissAlert:(UIAlertView*)alertView{ [alertView dismissWithClickedButtonIndex:[alertView cancelButtonIndex] animated:YES]; } -(void)initWifiImage{ } /* #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. } */ - (IBAction)cancleButton:(id)sender { [_wifiTextFiled resignFirstResponder]; [self.navigationController popViewControllerAnimated:YES]; } #pragma mark 连接设备 - (IBAction)makeSureButton:(id)sender { if (!_ssid.length) { [self.view makeToast:@"未能获取到WiFi名称,请确认地理位置权限是否打开"]; return; } if (!_wifiTextFiled.text.length) { [self.view makeToast:@"请输入WiFi密码!"]; return; } [_wifiTextFiled resignFirstResponder]; NSString *ssidName = @""; if (_ssid.length>2) { ssidName= [_ssid substringWithRange:NSMakeRange(_ssid.length-2, 2)]; } if ([ssidName.uppercaseString isEqualToString:@"5G"]) { UIAlertView *alert= [[UIAlertView alloc] initWithTitle:@"" message:@"仅支持2.4G WI-Fi网络,请重新选择" delegate:nil cancelButtonTitle:@"去更改" otherButtonTitles:nil, nil]; [alert show]; return; } BOOL isRight =[dataContorl isIncludeSpecialCharact:_wifiTextFiled.text]; if (!isRight) { [self.view makeToast:@"您输入的密码带特殊符号,请更改路由器密码。"]; return; } [self savePassw]; [self configWifiForDevice]; // [self initMMProgressHUD]; [self connectNotNormalView]; if (_maclabel) { [_maclabel removeFromSuperview]; } } - (IBAction)lickHereBtnClicked:(id)sender { // ConnectHotpotViewController *vc = [[ConnectHotpotViewController alloc] init]; ConAquarNowWiFiPwdVC *vc = [[ConAquarNowWiFiPwdVC alloc]init]; vc.ssid = self.ssid; vc.bssid = self.bssid; vc.deviceType=self.deviceType; [self.navigationController pushViewController:vc animated:YES]; } - (IBAction)commandbackBtn:(id)sender { SaySomethingViewController*say=[[SaySomethingViewController alloc]init]; [self.navigationController pushViewController:say animated:YES]; self.navigationController.navigationBarHidden=NO; } //问题自查 - (IBAction)discoverQuestionBtn:(id)sender { ConnectErrorViewController*error=[[ConnectErrorViewController alloc]init]; [self.navigationController pushViewController:error animated:YES]; self.navigationController.navigationBarHidden=NO; } -(void)getSSid{ Reachability *currReach = [Reachability reachabilityForLocalWiFi]; NetworkStatus status = [currReach currentReachabilityStatus]; NSLog(@"%ld", (long)status); if (status==AFNetworkReachabilityStatusReachableViaWiFi) { [self connectMyWIFI]; }else{ [self showTitle:@"" messsage:@"请切换到WiFi环境下绑定"]; } } -(void)connectMyWIFI{ [CommonUtils getNetworkTypeComplete:^(NSString *netconnType, NSString *BSSID, NSString *SSID) { NSUserDefaults*userDefsult=[NSUserDefaults standardUserDefaults]; NSString*pass=[userDefsult objectForKey:@"wifiPass"]; _ssid = SSID; _bssid = BSSID; NSString *msg = [NSString stringWithFormat:@"请输入当前WiFi:%@的密码",_ssid]; NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:msg]; NSMutableParagraphStyle *paraghStyle =[[NSMutableParagraphStyle alloc] init]; [paraghStyle setLineSpacing:4]; [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:0 green:170.0/255.0 blue:218.0/255.0 alpha:1] range:NSMakeRange(msg.length - 3 -_ssid.length,_ssid.length)]; [attributedString addAttribute:NSParagraphStyleAttributeName value:paraghStyle range:NSMakeRange(0, msg.length)]; // [_wifiNamelabel setAttributedText:attributedString]; _wifiNamelabel.text=_ssid; _wifiTextFiled.secureTextEntry=NO; _wifiTextFiled.text=pass; _wifiTextFiled.clearButtonMode=UITextFieldViewModeAlways; //[self bindDeviceWithSsid:@"5ccf7f003a93"]; // 5CCF7F00669C // 5CCF7F006668 // 5CCF7F0065CA }]; } -(void)checkLocation{ NSString* phoneVersion = [[UIDevice currentDevice] systemVersion]; CGFloat version = [phoneVersion floatValue]; // 如果是iOS13 未开启地理位置权限 需要提示一下 if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined && version >= 13) { self.locationManager = [[CLLocationManager alloc] init]; [self.locationManager requestWhenInUseAuthorization]; } } // refer to http://stackoverflow.com/questions/5198716/iphone-get-ssid-without-private-library //保存wifi密码 -(void)savePassw{ NSUserDefaults*userdefult=[NSUserDefaults standardUserDefaults]; [userdefult setObject:self.wifiTextFiled.text forKey:@"wifiPass"]; self.wifiPass=self.wifiTextFiled.text; [userdefult synchronize]; } - (void)configWifiForDevice{ NSLog(@"ViewController do confirm action..."); void(^success)(NSString*deviceBssid)=^(NSString*deviceBssid) { _deviceBssid=deviceBssid; NSArray*arry=[[DataCenter defaultDtacenter]valueForKey:@"deviceInfo"]; DeviceModel*model=[[DeviceModel alloc]init]; //if (arry.count<5) { NSMutableArray*macdressArr=[[NSMutableArray alloc]init]; for (model in arry) { [macdressArr addObject:model.macAddress]; } BOOL exst=[macdressArr containsObject:_deviceBssid]; if (exst) { self.lodviewMissStyle=lodingViewdissMissAlreadyBinded; [self mmPogressHUDdismiss]; [self connectNormalView]; self.bakbutton.userInteractionEnabled=YES; //[self.navigationController popViewControllerAnimated:YES]; [self.view makeToast:@"该设备已存在"]; }else{ if (self.deviceType==DEVICEPETS) { [self showStoreNameView]; } else { [self bindDeviceWithSsid:_deviceBssid]; } } } }; void(^failure)(NSError*error,NSString*msg)=^(NSError*error,NSString*msg) { self.lodviewMissStyle=lodingViewdissMissfail; [self mmPogressHUDdismiss]; [self connectNormalView]; self.bakbutton.userInteractionEnabled=YES; if(msg.length) { [self.view makeToast:msg]; } }; ConnectType type = self.connectType; dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); if(type == ConnectTypeAirKiss) { self.airKissConnection.connectionSuccess = success; self.airKissConnection.connectionFailure = ^{ failure(nil,nil); }; NSString *apSsid = self.ssid; NSString *apPwd = self.wifiTextFiled.text; [self.airKissConnection connectAirKissWithSSID:apSsid password:apPwd]; } else if(type==ConnectTypeSmartESPTouch) { dispatch_async(queue, ^{ NSLog(@"ViewController do the execute work..."); // execute the task NSArray *esptouchResultArray = [self executeForResults]; // show the result to the user in UI Main Thread dispatch_async(dispatch_get_main_queue(), ^{ // [self._spinner stopAnimating]; // [self enableConfirmBtn]; ESPTouchResult *firstResult = [esptouchResultArray objectAtIndex:0]; // check whether the task is cancelled and no results received if (!firstResult.isCancelled) { NSMutableString *mutableStr = [[NSMutableString alloc]init]; NSUInteger count = 0; // max results to be displayed, if it is more than maxDisplayCount, // just show the count of redundant ones const int maxDisplayCount = 100000; if ([firstResult isSuc]) { success(firstResult.bssid); for (int i = 0; i < [esptouchResultArray count]; ++i) { ESPTouchResult *resultInArray = [esptouchResultArray objectAtIndex:i]; [mutableStr appendString:[resultInArray description]]; [mutableStr appendString:@"\n"]; count++; if (count >= maxDisplayCount) { break; } } if (count < [esptouchResultArray count]) { [mutableStr appendString:[NSString stringWithFormat:@"\nthere's %lu more result(s) without showing\n",(unsigned long)([esptouchResultArray count] - count)]]; } } else { failure(nil,@"未获取到设备mac"); } } else if(firstResult.isCancelled) { failure(nil,@"连接被取消"); } else if(!esptouchResultArray.count) { failure(nil,@"未有设备响应"); [self.view makeToast:@"未有设备响应"]; } }); }); } else if (type == ConnectTypeAP) { } } #pragma mark ap开始 -(void)viewWillEnterForeground:(NSNotification *)noti{ if (self.isGoChangeWiFi) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [self checkWiFi]; }); } } -(void)checkWiFi{ [CommonUtils getNetworkTypeComplete:^(NSString *netconnType, NSString *BSSID, NSString *SSID) { NSString *wifiName = SSID; //先判断之前的wifi名称是否和热点的wifi名称重复,如果冲突,则提示wifi名称错误 if ([wifiName isEqualToString:self.wifiNamelabel.text]) { [self.view makeToast:@"请先连接设备热点"]; return; } [self.timer invalidate]; self.timer = nil; [self sendToDeviceWithSSIDName:self.ssid andSSIDPWD:self.wifiPass]; // // 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)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]; if (self.retryTimes<10) { self.retryTimes++; WEAK_SELF; [[IFishHotpotUDPHelper sharedInstance] closeComplete:^{ [weakSelf sendToDeviceWithSSIDName:weakSelf.ssid andSSIDPWD:weakSelf.wifiPass]; }]; } else { ; } } } - (void)appendTrakContent:(NSString *)msg { } #pragma mark Ap结束 - (NSArray *) executeForResults { [self._condition lock]; NSString *apSsid = self.ssid; NSString *apPwd = self.wifiTextFiled.text; NSString *apBssid = self.bssid; BOOL isSsidHidden = YES; // int taskCount = [self._taskResultCountTextView.text intValue]; int taskCount=1; self._esptouchTask = [[ESPTouchTask alloc]initWithApSsid:apSsid andApBssid:apBssid andApPwd:apPwd andIsSsidHiden:isSsidHidden]; // set delegate // [self._esptouchTask setEsptouchDelegate:self._esptouchDelegate]; [self._esptouchTask setPackageBroadcast:YES]; [self._condition unlock]; NSArray * esptouchResults = [self._esptouchTask executeForResults:taskCount]; NSLog(@"ViewController executeForResult() result is: %@",esptouchResults); return esptouchResults; } -(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]; } -(void)showStoreNameView { [self.storeNameView removeFromSuperview]; StoreNameView*store=[[[NSBundle mainBundle] loadNibNamed:@"StoreNameView" owner:self options:nil] lastObject]; store.frame=CGRectMake((SCREEN_WIDTH-280)/2.0, 100, 280, 280); self.storeNameView.center=self.mask.center; self.storeNameView=store; WEAK_SELF; store.cancelBlock=^(){ [weakSelf.mask removeFromSuperview]; [weakSelf.storeNameView removeFromSuperview]; }; store.sureBlock=^(NSString*name) { if (!name.length) { [weakSelf.view makeToast:@"请设置或者选择名称!"]; return ; } [weakSelf.mask removeFromSuperview]; [weakSelf.storeNameView removeFromSuperview]; weakSelf.storeName=name; [weakSelf bindDeviceWithSsid:_deviceBssid]; }; [self.view addSubview:self.mask]; [self.view addSubview:self.storeNameView]; } #pragma mark 绑定设备 -(void)bindDeviceWithSsid:(NSString*)bssid{ NSLog(@"设备bssid_%@",bssid); NSLog(@"设备bssid_%@",bssid); if (self.isBindingDevice) { return; } else { self.isBindingDevice = YES; if (self.bindTimer) { [self.bindTimer invalidate]; self.bindTimer = nil; } } self.HUD.labelText = @"正在绑定设备"; NSString *userId = [dataContorl dataControlGetUserIdInfo]; 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) { NSDictionary*resultDic=[NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:nil]; NSLog(@"data:%@",resultDic[@"data"]); self.isBindingDevice = NO; self.macAddress = nil; if ([resultDic[@"result"] isEqualToString:@"100"]) { // 保存设备信息 NSDictionary*dataDic=resultDic[@"data"]; DeviceModel*devicemodel=[[DeviceModel alloc] initWithDict:dataDic]; if (!devicemodel.type){ self.lodviewMissStyle=lodingViewdissMissSuccsess; [self mmPogressHUDdismiss]; [self connectNormalView]; [self.view makeToast:@"用户绑定设备成功,但设备初次入网失败请重新登陆"]; [self initMacIdString:bssid]; }else{ self.lodviewMissStyle=lodingViewdissMissSuccsess; [self mmPogressHUDdismiss]; [self connectNormalView]; if (_maclabel) { [_maclabel removeFromSuperview]; } _deviceArry=[[DataCenter defaultDtacenter]valueForKey:@"deviceInfo"]; [_deviceArry insertObject:devicemodel atIndex:0]; [[DataCenter defaultDtacenter]setValue:_deviceArry forKey:@"deviceInfo"]; if ([devicemodel.type isEqual:[NSNull null]]){ //进入此循环 可能因为设备所在服务器 不在 本程序所在 服务器 [self mmPogressHUDdismiss]; [self connectNormalView]; [self showTitle:@"" messsage:@"设备不在服务器"]; }else{ if (isfromCameraView) { self.lodviewMissStyle=lodingViewdissMissSuccsess; [self mmPogressHUDdismiss]; [self connectNormalView]; //此入口设备 是已授权 且非黑名单 [self setWindowRoot]; }else{ [[IfishDataUnity shareDataInstance] initAppCenterVcWith:devicemodel addWithdissMisVc:nil]; //绑定成功 加 经验值 [[IfishUserObsever sharedInstance] xinZengJingYanZhi:IFISHADDEXP_BIDDEVICE addType:IFISHADDEXPTYPE1]; } } } }else if ([resultDic[@"result"] isEqualToString:@"101"]){ NSString*msg= resultDic[@"data"]; if ([msg isKindOfClass:[NSString class]]&&msg.length&&![msg isEqualToString:@"null"]) { } else { msg=@"绑定失败"; } [self.view makeToast:msg]; self.bakbutton.userInteractionEnabled=YES; NSString *str =[NSString stringWithFormat:@"mac%@错误吗101",bssid]; [self initMacIdString:str]; }else if ([resultDic[@"result"] isEqualToString:@"301"]){ [self.view makeToast:@"请求验证失败,请重新登录"]; self.bakbutton.userInteractionEnabled=YES; NSString *str =[NSString stringWithFormat:@"mac%@错误吗301",bssid]; [self initMacIdString:str]; }else if ([resultDic[@"result"] isEqualToString:@"302"]){ // 请求被舍弃未执行 self.bakbutton.userInteractionEnabled=YES; NSString *str =[NSString stringWithFormat:@"mac%@错误吗302",bssid]; [self initMacIdString:str]; } } 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.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; } }]; } -(void)bindDeviceSus{ } -(void)setRootViewBindFromCameraView{ } -(void)wifiviewkeyboardWillHide:(NSNotification *)notify{ // 键盘动画时间 double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]; //视图下沉恢复原状 [UIView animateWithDuration:duration animations:^{ self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height); }]; } -(BOOL)textFieldShouldBeginEditing:(UITextField *)textField { return YES; } -(void)wifiviewkeyboradWillShow:(NSNotification*)notification{ CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; CGRect buttonRect = [self.connectBtn convertRect:self.connectBtn.bounds toView:self.view]; CGFloat buttonMargin =(buttonRect.origin.y + buttonRect.size.height + 10); CGFloat transformY = keyboardFrame.origin.y - buttonMargin; // 取得键盘的动画时间,这样可以在视图上移的时候更连贯 double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]; [UIView animateWithDuration:duration animations:^{ if (keyboardFrame.origin.y < self.view.frame.size.height) { self.view.transform = CGAffineTransformMakeTranslation(0,transformY); }else{ self.view.transform = CGAffineTransformMakeTranslation(0, 0); } }]; } -(BOOL)textFieldShouldReturn:(UITextField *)textField{ [textField resignFirstResponder]; return YES; } -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ [self hiddenKeybord]; } -(void)hiddenKeybord{ // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wifiviewkeyboardWillHide:) name:UIKeyboardWillChangeFrameNotification object:nil]; [self.wifiTextFiled resignFirstResponder]; } -(void)setWindowRoot{ Socketsingleton *soket=[Socketsingleton sharedInstance]; if (soket.clientSocket.isConnected) { [soket cutOffSocket]; } [self setAppTabRoot]; } -(void)setAppTabRoot{ IfishMianTabViewController *mianVC=[[IfishMianTabViewController alloc] init]; UIApplication*app=[UIApplication sharedApplication]; AppDelegate*app1=(AppDelegate*)app.delegate; app1.window.rootViewController=mianVC; [[UIApplication sharedApplication].keyWindow.rootViewController.view makeToast:@"绑定成功"]; //绑定成功 加 经验值 [[IfishUserObsever sharedInstance] xinZengJingYanZhi:IFISHADDEXP_BIDDEVICE addType:IFISHADDEXPTYPE1]; } -(void)rightButtonClickItem:(UIBarButtonItem *)sender{ ConnectErrorViewController*error=[[ConnectErrorViewController alloc]init]; [self.navigationController pushViewController:error animated:YES]; self.navigationController.navigationBarHidden=NO; } @end