ifish/Ifish/controllers/leftcontrollers/ConfigWifiViewController.m

1633 lines
57 KiB
Objective-C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// SecondConnectWifiController.m
// Ifish
//
// Created by imac on 16/2/24.
// Copyright © 2016年 imac. All rights reserved.
//
#import "SPAlertController.h"
#import "ConfigWifiViewController.h"
#import <SystemConfiguration/CaptiveNetwork.h>
#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 <CoreLocation/CoreLocation.h>
#import "ConnectHotpotViewController.h"
#import "ConAquarNowWiFiPwdVC.h"
#import "InfoByImageViewController.h"
#import "YooseeNextConnectViewController.h"
#import "HKPieChartView.h"
#import "dataContorl.h"
#import<SystemConfiguration/CaptiveNetwork.h>
#import "IFishHotpotUDPHelper.h"
#import "ESPTouchResult.h"
#import "ESPTouchTask.h"
#import "IfishDataUnity.h"
#import "MyMD5.h"
#import <GWP2P/GWP2P.h>
#import "UIView+Toast.h"
#import "ContactDAO.h"
#import "AppDelegate.h"
#import "UDManager.h"
#import "LoginResult.h"
#import "Utils.h"
#import "RightViewController.h"
#import "LeftViewController.h"
#import "IfishCameraModel.h"
#import "FListManager.h"
#define GIWEI_INITPASS @"123"
#import "IfishP2PMonitorController.h"
#import "LXWaveProgressView.h"
#import "IfishConnectingView.h"
#import "PushMasssageWebViewController.h"
#import "IfishUserObsever.h"
#import <GWP2P/GWP2P.h>
#import "MyMD5.h"
#import "IfishUserDataUnity.h"
#import "DeviceCameraModel.h"
#import "ConAquarChooseWiFiVC.h"
#import "InfoByImageViewController.h"
typedef NS_ENUM(NSInteger,lodingViewdissMissStyle) {
lodingViewdissMissSuccsess=0,// default is 0
lodingViewdissMissfail,
lodingViewdissMissAlreadyBinded
};
@interface ConfigWifiViewController ()<IFishHotpotUDPHelperDelegate,UITextFieldDelegate,GWPP2PDeviceLinkerProtocol>
@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;
//摄像头变量
@property (strong, nonatomic) NSString *lastSetPassword;
@property (strong,nonatomic) NSMutableDictionary *addresses;
@property (strong,nonatomic) NSMutableDictionary *linkDict;
@property (copy, nonatomic) NSString *deviceID;//摄像头设备id
@property (assign, nonatomic) BOOL isDeviceLinkIn;//是否已经连接智能设备
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 addTitleViewWithTitle:self.titleString];
self.view.backgroundColor=[UIColor whiteColor];
if(self.deviceType == DEVICECAMERA)
{
self.connectType = ConnectTypeSmartConfig;
self.connectTypeTitle.text=@"智能配网";
}
else
{
self.connectType = ConnectTypeAirKiss;
}
//摄像头
self.isDeviceLinkIn = NO;
[GWP2PDeviceLinker shareInstance].delegate=self;
self.deviceID=nil;
self.addresses = [[NSMutableDictionary alloc] initWithCapacity:1];
self.linkDict = [[NSMutableDictionary alloc] initWithCapacity:1];
_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;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewWillEnterForeground:) name:Noti_WillEnterForeground object:nil];
[self creatConnectStateUI];
//获取WiFi名称
[self getSSid];
}
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
}
-(void)viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:animated];
}
-(void)goBackAction{
if(self.connectingView.hidden==NO)
{
[self connectNormalView];
}
else
{
[self.navigationController popViewControllerAnimated:YES];
}
}
#pragma mark -连接不上?
-(void)connectTypeClick:(UIButton *)btn
{
if(self.indicator.isAnimating)
{
[self.view makeToast:@"绑定中..."];
return;
}
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 connectNormalView];
weakSelf.connectType = ConnectTypeAirKiss;
weakSelf.connectTypeTitle.text = airkisTitle;
weakSelf.connectTipLbl.text = airkisTips;
[weakSelf.connectBtn setTitle:@"确定" forState:UIControlStateNormal];
}];
SPAlertAction*smart =[SPAlertAction actionWithTitle:smartTitle style:SPAlertActionStyleDefault handler:^(SPAlertAction * _Nonnull action) {
[weakSelf connectNormalView];
weakSelf.connectType = ConnectTypeSmartConfig;
weakSelf.connectTypeTitle.text = smartTitle;
weakSelf.connectTipLbl.text = smartTips;
[weakSelf.connectBtn setTitle:@"确定" forState:UIControlStateNormal];
}];
SPAlertAction*ap =[SPAlertAction actionWithTitle:apTitle style:SPAlertActionStyleDefault handler:^(SPAlertAction * _Nonnull action) {
[weakSelf connectNormalView];
weakSelf.connectType = ConnectTypeAP;
weakSelf.connectTypeTitle.text = apTitle;
weakSelf.connectTipLbl.text = apTips;
[weakSelf.connectBtn setTitle:@"下一步" forState:UIControlStateNormal];
}];
SPAlertAction*cancel =[SPAlertAction actionWithTitle:@"取消" style:SPAlertActionStyleCancel handler:^(SPAlertAction * _Nonnull action) {
}];
if(self.deviceType!=DEVICECAMERA)
{
[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模式
-(IBAction)goSettingClick:(UIButton*)button
{
if(self.connectType == ConnectTypeAP)
{
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.reasonBtn.hidden = YES;
self.resultLabel.hidden = YES;
self.line.hidden = YES;
[self.indicator stopAnimating];
}
-(void)connectNotNormalView
{
self.connectingView.hidden=NO;
[self.indicator startAnimating];
self.reasonBtn.hidden = YES;
self.resultLabel.hidden = YES;
self.line.hidden = YES;
self.connectBtn.hidden = YES;
}
-(void)showFailResultViewWithMsg:(NSString*)msg
{
self.connectingView.hidden=NO;
[self.indicator stopAnimating];
self.connectBtn.hidden = YES;
self.reasonBtn.hidden = NO;
self.resultLabel.hidden = NO;
self.line.hidden = NO;
self.resultLabel.text = msg?:@"连接失败";
}
-(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";
}
[self showFailResultViewWithMsg:_maclabel.text];
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;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self.view makeToast:_maclabel.text];
});
}
- (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];
}
[self showFailResultViewWithMsg: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==ConnectTypeSmartConfig)
{
if(self.deviceType == DEVICECAMERA)
{
UIAlertView *alert= [[UIAlertView alloc] initWithTitle:@"提示" message:@"即将使用声波连接,请调大手机音量,并靠近设备,确认设备已经重置(按复位小孔,听到“等待连接“或者“滴”)后再点击确认" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
alert.tag = ALERT_TAG_B_SURE;
[alert show];
}
else
{
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)
{
[self goSettingClick:nil];
}
}
#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];
self.isGoChangeWiFi = NO;
});
}
}
-(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;
if (self.connectType==ConnectTypeAP&&self.ssid.length&&self.wifiPass.length&&self.deviceType==DEVICECAMERA)
{
[self connectNotNormalView];
[self apLinkConnect];
}
else
{
[self sendToDeviceWithSSIDName:self.ssid andSSIDPWD:self.wifiPass];
}
}];
}
- (void)sendToDeviceWithSSIDName:(NSString *)name andSSIDPWD:(NSString *)pwd {
[self connectNotNormalView];
[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.deviceBssid = 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.deviceBssid.length == 0) {
return;
}
self.retryTimes = 0;
if (self.deviceType==DEVICEPETS)
{
[self showStoreNameView];
}
else
{
[self bindDeviceWithSsid:self.deviceBssid];
}
}
}];
}
- (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];
[self connectNormalView];
}
-(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];
[weakSelf connectNormalView];
};
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)resetPassWord{
NSString *newPassword = GIWEI_INITPASS;
self.lastSetPassword = [Utils GetTreatedPassword:newPassword];
}
#pragma mark - 搜索到设备,弹出添加设备提示 暂不用
/**
局域网里面有设备联网成功后都会回调此方法。UDP使用
@param deviceDict 设备信息
*/
- (void)p2pDeviceLinker:(GWP2PDeviceLinker *)linker deviceLinkSuccess:(NSDictionary *)deviceDict
{
NSLog(@"扫描到设备");
[self deviceLinkin:deviceDict linkType:self.connectType == ConnectTypeAP?conectType_ap:conectType_Intelligent ];
}
-(void)deviceLinkin:(NSDictionary*)deviceDict linkType:(NSInteger)type
{
NSLog(@"声波配网成功,返回数据:%@",deviceDict);
NSString *deviceID = [deviceDict[@"deviceID"] stringValue];
NSString *deviceIP = deviceDict[@"deviceIP"];
if ([self.linkDict[deviceID] boolValue]) {
return;
}
//AP配网时有值 smart没有值
if ([self.deviceID isEqualToString:deviceID]||self.deviceID==nil)
{
if (type==conectType_Intelligent)
{
[self.view makeToast:@"声波配网成功"];
[[GWP2PDeviceLinker shareInstance] p2pStopSmartLink];
}
else
{
[self.view makeToast:@"AP配网成功"];
[[GWP2PDeviceLinker shareInstance] p2pStopAPLink];
}
// NSString *devicePassword = deviceDict[@"devicePassword"];
self.deviceID = deviceID;
self.linkDict[deviceID]=@(YES);
[self resetPassWord];//初始化密码
if (![deviceDict[@"isInitPassword"] boolValue]){ //设备没有初始化密码,设置密码
[[GWP2PClient sharedClient] setDeviceInitialPassword:self.lastSetPassword withDeviceID:deviceIP completionBlock:^(GWP2PClient *client, BOOL success, NSDictionary<NSString *,id> *dataDictionary) {
NSLog(@"success:%i %@",success,dataDictionary);
[self resetPassWord];//初始化密码
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self bindCameraDevice];
});
}];
}else{//如果已经设置过初始密码,则直接使用
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self bindCameraDevice];
});
}
}
}
-(void)deviceLinkinTimeout:(NSInteger)type
{
//
if (self.deviceID.length&&![self.linkDict[self.deviceID] boolValue]) {//90秒之后还未连接上连接超时
[CommonUtils getNetworkTypeComplete:^(NSString *netconnType, NSString *BSSID, NSString *SSID) {
[[GWP2PDeviceLinker shareInstance] p2pStopSmartLink];
[[GWP2PDeviceLinker shareInstance] p2pStopAPLink];
if ([SSID isEqualToString:self.ssid])
{
[self.view makeToast:@"请确保Wifi密码正确,重置设备后再试!"];
}
else
{
[self.view makeToast:[NSString stringWithFormat:@"WiFi连接失败请确保手机连接到%@",self.ssid]];
}
[self showFailResultViewWithMsg:@"连接超时"];
}];
}
else if(!self.deviceID.length)
{
[self.view makeToast:@"获取设备ID失败"];
[[GWP2PDeviceLinker shareInstance] p2pStopSmartLink];
[[GWP2PDeviceLinker shareInstance] p2pStopAPLink];
[self connectNormalView];
}
}
-(void)apLinkConnect
{
WEAK_SELF;
[[GWP2PDeviceLinker shareInstance] p2pStopAPLink];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(90 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self deviceLinkinTimeout:self.connectType == ConnectTypeAP?conectType_ap:conectType_Intelligent];
});
[self resetPassWord];//初始化密码
[[GWP2PDeviceLinker shareInstance] p2pAPLinkDeviceWithWiFiSSID:weakSelf.ssid wifiPassword:weakSelf.wifiPass devicePassword:weakSelf.lastSetPassword deviceReceive:^(NSString *deviceId, BOOL isSupport) {
if (isSupport)
{
weakSelf.deviceID=deviceId;
[weakSelf.view makeToast:[NSString stringWithFormat:@"设备即将连接网络,请将手机自动重新连接到%@",weakSelf.ssid]];
}
else
{
[weakSelf.view makeToast:@"该设备不支持AP配网"];
}
} deviceLinkIn:^(NSDictionary *deviceDict) {
[weakSelf deviceLinkin:deviceDict linkType:weakSelf.connectType == ConnectTypeAP?conectType_ap:conectType_Intelligent];
}];
}
//智能联机
-(void)smartLinkConnect{
//拿到AVAudioSession的单例对象
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
//设置为听筒模式
//[audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:nil];
//设置为公放模式
[audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
//让我的App占用听筒或扬声器
[audioSession setActive:YES error:nil];
WEAK_SELF;
[[GWP2PDeviceLinker shareInstance] p2pStopSmartLink];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(100 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[[GWP2PDeviceLinker shareInstance] p2pStopSmartLink];
[self deviceLinkinTimeout:self.connectType == ConnectTypeAP?conectType_ap:conectType_Intelligent];
});
[[GWP2PDeviceLinker shareInstance] p2pSmartLinkDeviceWithWiFiSSID:weakSelf.ssid password:weakSelf.wifiPass useSimpleConfig:YES deviceLinkIn:^(NSDictionary *deviceDict) {
[weakSelf deviceLinkin:deviceDict linkType:weakSelf.connectType == ConnectTypeAP?conectType_ap:conectType_Intelligent];
}];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (alertView.tag==ALERT_TAG_B_SURE){
if (buttonIndex ==1) {
//显示连接中效果
[self connectNotNormalView];
//声波智能联机
if (self.connectType==ConnectTypeSmartConfig)
{
[self smartLinkConnect];
}
else
{
[self apLinkConnect];
}
}
}//重试wifi
}
//初始化设备密码回调
-(void)bindCameraDevice{
NSString * contactName = [NSString stringWithFormat:@"Cam%@", self.deviceID];
ContactDAO *contactDAO = [[ContactDAO alloc] init];
Contact *contact = [contactDAO isContact:self.deviceID];
if(contact!=nil){
contact.contactName = contactName;
contact.contactPassword = self.lastSetPassword;//updatepwd
[[FListManager sharedFList] updatee:contact];
[self ifishUserBindcameraIdBy:self.deviceID];
}else{
Contact *contact = [[Contact alloc] init];
contact.contactId = self.deviceID;
contact.contactName = contactName;
contact.contactPassword = self.lastSetPassword;
contact.contactType = CONTACT_TYPE_UNKNOWN;
[[FListManager sharedFList] insert:contact];
//设置密码成功后爱鱼奇用户绑定摄像头
[self ifishUserBindcameraIdBy:self.deviceID];
}
}
-(void)dealloc{
[[GWP2PDeviceLinker shareInstance] p2pStopSmartLink];
[[GWP2PDeviceLinker shareInstance] p2pStopAPLink];
[[NSNotificationCenter defaultCenter] removeObserver:self name:Noti_WillEnterForeground object:nil];
}
#pragma mark - 绑定摄像头
//让爱鱼奇用户 与摄像头建立关系
-(void)ifishUserBindcameraIdBy:(NSString *)cameraId
{
NSLog(@"cameraId = %@",cameraId);
NSMutableArray *oldCameraArr= [[DataCenter defaultDtacenter]valueForKey:@"cameraArr"];
if (!oldCameraArr) {
//无设备
oldCameraArr = [[NSMutableArray alloc] init];
}
IfishCameraModel *camer=[[IfishCameraModel alloc] init];
NSMutableArray *idArr=[[NSMutableArray alloc] init];
for (IfishCameraModel *model in oldCameraArr ) {
[idArr addObject:model.cameraId];
if (model.cameraId == cameraId) {
camer = model;
[self connectNormalView];
[self.view makeToast:@"已经绑定过了"];
return;
}
}
UserModel*model=[[DataCenter defaultDtacenter]valueForKey:@"UserLogIn"];
[AFNOHeaderHttpTool bindCameraWith:cameraId userId:model.userId success:^(id response) {
NSDictionary*resultDic=[NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",resultDic[@"result"]);
if ([resultDic[@"result"] isEqualToString:@"100"]) {
self.lodviewMissStyle =lodingViewdissMissSuccsess;
//绑定成功之后,直接跳转详情页面
/**
存储摄像头设备信息
*/
NSMutableArray *newCamerArr = [[NSMutableArray alloc] initWithArray:oldCameraArr];
NSDictionary * cameraDic=resultDic[@"data"];
NSString *newPassword = GIWEI_INITPASS;
NSString *cameraPass = [Utils GetTreatedPassword:newPassword];
IfishCameraModel *camera=[[IfishCameraModel alloc] init];
camera.cameraId = cameraDic[@"cameraId"];
camera.isMaster = cameraDic[@"isMaster"];
camera.showName = cameraDic[@"showName"];
camera.cameraPass = cameraPass;
camera.isActive = cameraDic[@"isActive"];
camera.isLook = cameraDic[@"isLook"];
camera.isLive = cameraDic[@"isLive"];
[newCamerArr insertObject:camera atIndex:0];
//存储摄像头数组
[[DataCenter defaultDtacenter]setValue: newCamerArr forKey:@"cameraArr"];
NSUserDefaults*userdefult=[NSUserDefaults standardUserDefaults];
NSInteger index=0;
[userdefult setObject:nil forKey:@"lastIndex"];
[userdefult setInteger:index forKey:@"cameralastIndex"];
[userdefult synchronize];
[self setWindowRootWith:camera];
}else{
//lodingViewdissMissSuccsess 只做移除loding效果
self.lodviewMissStyle =lodingViewdissMissSuccsess;
[self showFailResultViewWithMsg:@"绑定失败错误码101"];
[self.view makeToast:@"绑定失败错误码101"];
}
} failure:^(NSError *err) {
[self showFailResultViewWithMsg:err.description];
[self.view makeToast:@"绑定失败未知错误"];
}];
}
//绑定成功之后,重新获取用户信息
-(void)setWindowRootWith:(IfishCameraModel *)cameraMdel{
[self.view makeToast:@"添加成功"];
[self getMoreUserData:cameraMdel];
}
//获取个人信息
-(void)getMoreUserData:(IfishCameraModel *)cameraMdel{
NSString *userId = [dataContorl dataControlGetUserIdInfo];
[AFHttpTool getMoreUserDataWith:userId success:^(id response) {
NSDictionary *reDic=[NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:nil];
NSString *result=reDic[@"result"];
if ([result isEqualToString:@"100"]) {
NSDictionary *dataDic = reDic[@"data"];
//设备信息
NSArray*deviceArray=dataDic[@"device"];
NSArray*cameraA=dataDic[@"camera"];
NSMutableArray *deviceArr = [[NSMutableArray alloc] init];
if ([deviceArray count]!=0) {
for (NSDictionary*deviceDic in deviceArray) {
DeviceModel*devicemodel=[[DeviceModel alloc] initWithDict:deviceDic];
[deviceArr insertObject:devicemodel atIndex:0];
}
}
[[DataCenter defaultDtacenter]setValue:deviceArr forKey:@"deviceInfo"];
//存储摄像头设备信息
NSMutableArray *camras = [[NSMutableArray alloc] init];
if (cameraA .count !=0) {
if ([cameraA count]!=0) {
for (NSDictionary * cameraDic in cameraA) {
IfishCameraModel *camera=[[IfishCameraModel alloc] initWithDict:cameraDic];
[camras insertObject:camera atIndex:0];
}
}
}
//存储摄像头数组
[[DataCenter defaultDtacenter]setValue:camras forKey:@"cameraArr"];
/**
* 设备摄像头关系数组
*/
NSArray*deviceCamera=dataDic[@"deviceCamera"];
NSMutableArray *devicamerArr=[[NSMutableArray alloc] init];
if (deviceCamera) {
for (NSDictionary * deviceCameraDic in deviceCamera) {
DeviceCameraModel *dcmodel=[[DeviceCameraModel alloc] init];
dcmodel.deviceId = deviceCameraDic[@"deviceId"];
dcmodel.cameraId = deviceCameraDic[@"cameraId"];
[devicamerArr addObject:dcmodel];
}
}
//存储摄像头设备关系数组
[[DataCenter defaultDtacenter]setValue:devicamerArr forKey:@"devicamerArr"];
//添加设备之后先断开device连接之后进入摄像头页面再重新添加链接
[[GWP2PClient sharedClient] disconnect];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
IfishP2PMonitorController *monitorVC=[[IfishP2PMonitorController alloc] init];
monitorVC.contact = cameraMdel;
UINavigationController *nav=[[UINavigationController alloc] initWithRootViewController:monitorVC];
UIApplication*app=[UIApplication sharedApplication];
AppDelegate*app1=(AppDelegate*)app.delegate;
app1.window.rootViewController=nav;
//绑定成功 加 经验值
[[IfishUserObsever sharedInstance] xinZengJingYanZhi:IFISHADDEXP_BIDCAMERA addType:IFISHADDEXPTYPE1];
});
}
} failure:^(NSError *err) {
}];
}
#pragma mark 绑定设备
-(void)bindDeviceWithSsid:(NSString*)bssid{
NSLog(@"设备bssid_%@",bssid);
NSLog(@"设备bssid_%@",bssid);
if (self.isBindingDevice) {
return;
}
else
{
self.isBindingDevice = YES;
[self connectNotNormalView];
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.deviceBssid = 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.deviceBssid];
self.retryTimes += 1;
});
} else {
self.tap.enabled=YES;
self.isBindingDevice = NO;
self.HUD.labelText = err.localizedDescription;
[self.HUD hide:YES afterDelay:2];
[self initMacIdString:err.description];
[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<UITouch *> *)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