// // SecondConnectWifiController.m // Ifish // // Created by imac on 16/2/24. // Copyright © 2016年 imac. All rights reserved. // #import "SecondConnectWifiController.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" @interface EspTouchDelegateImpl : NSObject @end @implementation EspTouchDelegateImpl -(void) dismissAlert:(UIAlertView *)alertView { [alertView dismissWithClickedButtonIndex:[alertView cancelButtonIndex] animated:YES]; } -(void) showAlertWithResult: (ESPTouchResult *) result { NSString *title = nil; NSString *message = [NSString stringWithFormat:@"%@ is connected to the wifi" , result.bssid]; NSTimeInterval dismissSeconds = 3.5; UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:title message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:nil]; [alertView show]; [self performSelector:@selector(dismissAlert:) withObject:alertView afterDelay:dismissSeconds]; } -(void) onEsptouchResultAddedWithResult: (ESPTouchResult *) result { NSLog(@"EspTouchDelegateImpl onEsptouchResultAddedWithResult bssid: %@", result.bssid); dispatch_async(dispatch_get_main_queue(), ^{ // [self showAlertWithResult:result]; }); } @end typedef NS_ENUM(NSInteger,lodingViewdissMissStyle) { lodingViewdissMissSuccsess=0,// default is 0 lodingViewdissMissfail, lodingViewdissMissAlreadyBinded }; @interface SecondConnectWifiController () @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,strong)IfishConnectingView *connectingView; Strong CLLocationManager *locationManager;//iOS13,获取WiFi名称必须开启定位权限 @end //extern BOOL formLogIn;//连接页面是否来自登录界面 extern BOOL isfromCameraView; @implementation SecondConnectWifiController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. self.view.backgroundColor=[UIColor whiteColor]; _deviceArry =[[NSMutableArray alloc]init]; [self updateUI]; //输入框在上面新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.shuoMingShuBtn addTarget:self action:@selector(shuoMingShuBtnAction:) forControlEvents:UIControlEventTouchUpInside]; [self creatConnectStateUI]; //获取WiFi名称 [self getSSid]; } - (void)updateUI { CGFloat yOffset = 0; if (is_iPhone_X) { yOffset = 20 + 88; } else { yOffset = 20 + 64; } self.nodImg.frame = CGRectMake(12, yOffset, 10, 10); self.wifiNamelabel.frame = CGRectMake(23, yOffset - 18 + 5, 336, 36); self.attentionLabel.frame=CGRectMake(30, CGRectGetMidY(self.waveProgressView.frame), kScreenWidth-60, 130); [self.view bringSubviewToFront:self.attentionLabel]; [self.view bringSubviewToFront:self.connectTipLbl]; [self.view bringSubviewToFront:self.connectBtn]; } -(void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; } -(void)viewDidDisappear:(BOOL)animated{ [super viewDidDisappear:animated]; } #pragma mark -连接不上? -(void)shuoMingShuBtnAction:(UIButton *)btn{ PushMasssageWebViewController*webVC=[[PushMasssageWebViewController alloc]init]; webVC.pushlink =IFISH_DEVCEITROURL; webVC.pushtitle = NSLocalizedString(@"ifish_deviceuse", nil);; [self.navigationController pushViewController:webVC animated:YES]; } -(void)creatConnectStateUI{ [self connectNormalView]; } -(void)connectNormalView { if (!self.connectingView) { CGFloat yOffset = 0; if (is_iPhone_X) { yOffset = 88; } else { yOffset = 64; } IfishConnectingView *connectingView=[[IfishConnectingView alloc] initWithFrame:CGRectMake(0,yOffset, kScreenSize.width, CGRectGetMaxY(self.wifiTextFiled.frame))]; self.connectingView =connectingView; [self.connectingView.textChangeView animationWithTexts:[NSArray arrayWithObjects:@"正在拼命连接中...",@"请将水族箱放在wifi信号良好的位置",@"连接成功后过几秒才能看到温度哟",@"连接不上,请点击下方说明书",nil]]; //self.connectingView.backgroundColor = [UIColor redColor]; self.connectingView.alpha = 0; [self.view addSubview:connectingView]; self.wifiNamelabel.hidden = NO; self.wifiTextFiled.hidden = NO; self.connectTipLbl.hidden = NO; self.connectBtn.hidden = NO; self.shareButton.hidden = NO; self.nodImg.hidden = NO; self.redTextLable.hidden=NO; }else{ [UIView animateWithDuration:2.0 animations:^{ self.connectingView.alpha = 0; //self.connectingView.hidden = YES; } completion:^(BOOL finished) { [self.connectingView.textChangeView stopAnimation]; self.wifiNamelabel.hidden = NO; self.wifiTextFiled.hidden = NO; self.connectTipLbl.hidden = NO; self.connectBtn.hidden = NO; self.shareButton.hidden = NO; self.nodImg.hidden = NO; self.redTextLable.hidden=NO; }]; } } -(void)connectNotNormalView{ [UIView animateWithDuration:2.0 animations:^{ self.connectingView.alpha = 1; //self.connectingView.hidden = NO; } completion:^(BOOL finished) { [self.connectingView.textChangeView startTextAnimation]; }]; self.wifiNamelabel.hidden = YES; self.wifiTextFiled.hidden = YES; self.connectTipLbl.hidden = YES; self.connectBtn.hidden = YES; self.shareButton.hidden = YES; self.nodImg.hidden = YES; self.redTextLable.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{ dispatch_async(dispatch_get_main_queue(), ^{ self.wifigifImgView.animationImages=[NSArray arrayWithObjects:[UIImage imageNamed:@"fish_png_0"],[UIImage imageNamed:@"fish_png_1"],[UIImage imageNamed:@"fish_png_2"],[UIImage imageNamed:@"fish_png_3"], nil]; self.wifigifImgView.animationDuration=2; self.wifigifImgView.animationRepeatCount=0; [self.wifigifImgView startAnimating]; }); } /* #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 tapConfirmForResults]; // [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{ NSUserDefaults*userDefsult=[NSUserDefaults standardUserDefaults]; NSString*pass=[userDefsult objectForKey:@"wifiPass"]; NSDictionary *netInfo = [self fetchNetInfo]; _ssid = [netInfo objectForKey:@"SSID"]; _bssid = [netInfo objectForKey:@"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]; _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 - (NSDictionary *)fetchNetInfo { NSArray *interfaceNames = CFBridgingRelease(CNCopySupportedInterfaces()); // NSLog(@"%s: Supported interfaces: %@", __func__, interfaceNames); NSDictionary *SSIDInfo; for (NSString *interfaceName in interfaceNames) { SSIDInfo = CFBridgingRelease( CNCopyCurrentNetworkInfo((__bridge CFStringRef)interfaceName)); // NSLog(@"%s: %@ => %@", __func__, interfaceName, SSIDInfo); BOOL isNotEmpty = (SSIDInfo.count > 0); if (isNotEmpty) { break; } } return SSIDInfo; } //保存wifi密码 -(void)savePassw{ NSUserDefaults*userdefult=[NSUserDefaults standardUserDefaults]; [userdefult setObject:self.wifiTextFiled.text forKey:@"wifiPass"]; self.wifiPass=self.wifiTextFiled.text; [userdefult synchronize]; } - (void) tapConfirmForResults{ NSLog(@"ViewController do confirm action..."); dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); 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]) { _deviceBssid=firstResult.bssid; 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]; } } } // else{ // // [self.view makeToast:@"您的设备数量已超过限制"]; // [self mmPogressHUDdismiss]; // [self connectNormalView]; // // } 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 { self.lodviewMissStyle=lodingViewdissMissfail; [self mmPogressHUDdismiss]; [self connectNormalView]; self.bakbutton.userInteractionEnabled=YES; [self.view makeToast:@"未获取到设备mac"]; } } else if(firstResult.isCancelled) { self.lodviewMissStyle=lodingViewdissMissfail; [self mmPogressHUDdismiss]; [self connectNormalView]; self.bakbutton.userInteractionEnabled=YES; [self.view makeToast:@"连接被取消"]; } else if(!esptouchResultArray.count) { self.lodviewMissStyle=lodingViewdissMissfail; [self mmPogressHUDdismiss]; [self connectNormalView]; self.bakbutton.userInteractionEnabled=YES; [self.view makeToast:@"未有设备响应"]; } }); }); } - (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._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); NSString *userId = [dataContorl dataControlGetUserIdInfo]; [AFHttpTool requestWihtMethod:RequestMethodTypePost url:@"" params:@{} success:^(id response) { } failure:^(NSError *err) { }]; 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"]); 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 showTitle:@"" messsage:@"网络异常"]; [self.view makeToast:@"网络异常"]; 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.shareButton convertRect:self.shareButton.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