// // ConnectHotpotViewController.m // Ifish // // Created by Minghao Xue on 2018/7/16. // Copyright © 2018年 lianlian. All rights reserved. // #import "ConnectHotpotViewController.h" #import "ConnectHotspotTipViewController.h" #import "dataContorl.h" #import #import "IFishHotpotUDPHelper.h" #import "ESPTouchResult.h" #import "ESPTouchTask.h" @interface ConnectHotpotViewController () @property (weak, nonatomic) IBOutlet UIScrollView *scrollView; @property (weak, nonatomic) IBOutlet UITextField *nameLbl; @property (strong, nonatomic) IBOutletCollection(UIImageView) NSArray *dashView; @property (weak, nonatomic) IBOutlet UITextField *pwdTf; @property (weak, nonatomic) IBOutlet UIView *containerView; @property (nonatomic, strong) ESPTouchTask* epTask; @end @implementation ConnectHotpotViewController - (void)viewDidLoad { [super viewDidLoad]; self.title = @"热点连接"; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keybordframeChanged:) name:UIKeyboardDidChangeFrameNotification object:nil]; for (UIImageView *view in self.dashView) { view.backgroundColor = [UIColor clearColor]; view.image = [self imageWithLineWithSize:view.frame.size]; } } - (UIImage *)imageWithLineWithSize:(CGSize)size{ CGFloat width = size.width; UIGraphicsBeginImageContext(size); CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound); CGFloat lengths[] = {2,2}; CGContextRef line = UIGraphicsGetCurrentContext(); CGContextSetStrokeColorWithColor(line, [UIColor colorWithRed:133/255.0 green:133/255.0 blue:133/255.0 alpha:1.0].CGColor); CGContextSetLineDash(line, 0, lengths, 1); CGContextMoveToPoint(line, 0, 1); CGContextAddLineToPoint(line, width-10, 1); CGContextStrokePath(line); return UIGraphicsGetImageFromCurrentImageContext(); } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } - (void)keybordframeChanged:(NSNotification *)no { NSDictionary *userInfo = no.userInfo; // 动画的持续时间 double duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; // 键盘的frame CGRect keyboardF = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; keyboardF = [self.view convertRect:keyboardF fromView:[UIApplication sharedApplication].keyWindow]; CGRect containerViewF = [self.view convertRect:self.containerView.frame fromView:self.scrollView]; CGFloat miniSpacing = 4; CGFloat offset = CGRectGetMaxY(containerViewF) + miniSpacing - CGRectGetMinY(keyboardF); if (offset <= 0) { offset = 0; } [UIView animateWithDuration:duration animations:^{ self.scrollView.contentInset = UIEdgeInsetsMake(-offset, 0, 0, 0); }]; } - (IBAction)clickHereBtnClicked:(id)sender { ConnectHotspotTipViewController *vc = [[ConnectHotspotTipViewController alloc] initWithNibName:@"ConnectHotspotTipViewController" bundle:nil]; [self.navigationController pushViewController:vc animated:YES]; } #pragma mark - UITextFieldDelegate - (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return YES; } - (IBAction)setLinkBtnClicked:(id)sender { if (self.nameLbl.text.length == 0) { [self.view makeToast:@"请输入正确的路由器名称"]; return; } BOOL isRight =[dataContorl isIncludeSpecialCharact:self.pwdTf.text]; if (!isRight) { [self.view makeToast:@"路由器密码不能包含特殊字符,只能为数字字母下划线"]; return; } if (![[self currentWifiSSID].lowercaseString hasPrefix:@"ifish"]) { [self.view makeToast:@"请先将手机连接到wifi:ifish-xxxx"]; return; } NSString *ssidName = self.nameLbl.text; NSString *ssidPwd = self.pwdTf.text; [self sendToDeviceWithSSIDName:ssidName andSSIDPWD:ssidPwd]; } - (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; } #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.view makeToast:[NSString stringWithFormat:@"连接设置成功,mac 地址:%@",backModel.senderMacAddress]]; [self tapConfirmForResults]; } - (void)udpHelperMessage:(NSString *)msg { [self.view makeToast:msg]; } #pragma mark - bind - (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 = 5; if ([firstResult isSuc]) { NSString * _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.bakbutton.userInteractionEnabled=YES; //[self.navigationController popViewControllerAnimated:YES]; [self.view makeToast:@"该设备已存在"]; }else{ [self bindDeviceWithSsid:_deviceBssid]; } }else{ [self.view makeToast:@"您的设备数量已超过限制"]; } 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.bakbutton.userInteractionEnabled=YES; [self.view makeToast:@"未获取到设备mac"]; } } }); }); } - (NSArray *) executeForResults { NSString *apSsid = self.ssid; NSString *apPwd = self.pwdTf.text; NSString *apBssid = self.bssid; BOOL isSsidHidden = YES; int taskCount=1; self.epTask = [[ESPTouchTask alloc]initWithApSsid:apSsid andApBssid:apBssid andApPwd:apPwd andIsSsidHiden:isSsidHidden]; NSArray * esptouchResults = [self.epTask executeForResults:taskCount]; NSLog(@"ViewController executeForResult() result is: %@",esptouchResults); return esptouchResults; } -(void)bindDeviceWithSsid:(NSString*)bssid{ NSLog(@"设备bssid_%@",bssid); NSString *userId = [dataContorl dataControlGetUserIdInfo]; [AFHttpTool bindDeviceWithUserId:userId macAddress:bssid 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.view makeToast:@"用户绑定设备成功,但设备初次入网失败请重新登陆"]; }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 showTitle:@"" messsage:@"设备不在服务器"]; }else{ //绑定成功 加 经验值 [[IfishUserObsever sharedInstance] xinZengJingYanZhi:IFISHADDEXP_BIDDEVICE addType:IFISHADDEXPTYPE1]; } } }else if ([resultDic[@"result"] isEqualToString:@"101"]){ [self.view makeToast:@"绑定失败"]; self.bakbutton.userInteractionEnabled=YES; }else if ([resultDic[@"result"] isEqualToString:@"301"]){ [self.view makeToast:@"请求验证失败,请重新登录"]; self.bakbutton.userInteractionEnabled=YES; }else if ([resultDic[@"result"] isEqualToString:@"302"]){ // 请求被舍弃未执行 self.bakbutton.userInteractionEnabled=YES; } } failure:^(NSError *err) { [self.view makeToast:@"网络异常"]; self.bakbutton.userInteractionEnabled=YES; }]; } @end