ifish/Ifish/controllers/leftcontrollers/ConnectHotpotViewController.m

338 lines
13 KiB
Objective-C

//
// 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<SystemConfiguration/CaptiveNetwork.h>
#import "IFishHotpotUDPHelper.h"
#import "ESPTouchResult.h"
#import "ESPTouchTask.h"
#import "IfishDataUnity.h"
#import "MBProgressHUD.h"
@interface ConnectHotpotViewController ()<UITextFieldDelegate, IFishHotpotUDPHelperDelegate>
@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 (weak, nonatomic) IBOutlet UITextField *wifiNameTextField;
@property (nonatomic, strong) ESPTouchTask* epTask;
@property (nonatomic, strong) NSMutableString *trackString;
@property (nonatomic, strong) MBProgressHUD *HUD;
/**
设备返回的mac地址
*/
@property (nonatomic, copy) NSString *macAddress;
/**
是否正在绑定设备
*/
@property (nonatomic, assign) BOOL isBindingDevice;
@property (nonatomic, strong) NSTimer *bindTimer;
@property (nonatomic, assign) NSInteger retryTimes;
Copy NSString *wifiName;//当前wifi名称
@end
@implementation ConnectHotpotViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self addTitleViewWithTitle:@"热点连接"];
[[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];
}
UITapGestureRecognizer *fiveTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(test)];
fiveTapGesture.numberOfTapsRequired = 5;
[self.containerView addGestureRecognizer:fiveTapGesture];
// UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
// back.frame = CGRectMake(0,0,48,44);
// [back setImage:[UIImage imageNamed:@"back_btn"] forState:UIControlStateNormal];
// // [_bakbutton setBackgroundImage:[UIImage imageNamed:@"back_btn"] forState:UIControlStateNormal];
// back.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
// [back addTarget: self action: @selector(clickBack) forControlEvents: UIControlEventTouchUpInside];
// [back setContentEdgeInsets:UIEdgeInsetsMake(0, 10, 0, -10)];
// back.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
// UIBarButtonItem * backItem=[[UIBarButtonItem alloc] initWithCustomView:back];
//
// self.navigationItem.leftBarButtonItem=backItem;
NSDictionary *wifiDic = [self fetchSSIDInfo];
NSString *wifiName = [wifiDic objectForKey:@"SSID"];
self.wifiNameTextField.text = wifiName;
}
//获取当前链接WiFi信息
- (id)fetchSSIDInfo
{
NSArray *ifs = (id)CFBridgingRelease(CNCopySupportedInterfaces());
NSLog(@"%s: Supported interfaces: %@", __func__, ifs);
id info = nil;
for (NSString *ifnam in ifs) {
info = (id)CFBridgingRelease(CNCopyCurrentNetworkInfo((CFStringRef)ifnam));
if (info && [info count]) {
break;
}
}
return info ;
}
-(void)clickBack{
[self.navigationController popViewControllerAnimated:YES];
}
- (void)test {
[UIPasteboard generalPasteboard].string = [self.trackString copy];
}
- (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.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;
}
#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.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.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.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"];
}
@end