ifish/Ifish/controllers/IfishYooseeFile/IfishYooseeControlller/YooseeNextConnectViewContro...

1217 lines
42 KiB
Plaintext
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.

//
// YooseeNextConnectViewController.m
// IfihYooeeDemo
//
// Created by imac on 16/5/31.
// Copyright © 2016年 xiang. All rights reserved.
//
#import "YooseeNextConnectViewController.h"
#import "elian.h"
#import "WaitingPageView.h"
#define WAITING_CONTENT_VIEW_HEIGHT 300
#define NAVIGATION_BAR_HEIGHT ([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0 ? (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ? 44:44):(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ? 64:64))
#import "AppDelegate.h"
#include <arpa/inet.h>
#include <ifaddrs.h>
#import <SystemConfiguration/CaptiveNetwork.h>
#import "Toast+UIView.h"
#import "ContactDAO.h"
#import "Contact.h"
#import "AppDelegate.h"
#import "Constants.h"
#import "P2PClient.h"
#import "FListManager.h"
#import "Toast+UIView.h"
#import "MBProgressHUD.h"
#import "UDManager.h"
#import "LoginResult.h"
#import "Utils.h"
#import "MD5Manager.h"
#import "RightViewController.h"
#import "LeftViewController.h"
#import "ICSDrawerController.h"
#import "UDPManager.h"
#import "YooseeCenterViewController.h"
#import "Socketsingleton.h"
#import "IfishCameraModel.h"
#import "FListManager.h"
#define GIWEI_INITPASS @"123"
#import "IfishP2PMonitorController.h"
#import "LSemTMFSet.h"
#import "LXWaveProgressView.h"
#import "IfishConnectingView.h"
#import "PushMasssageWebViewController.h"
#import "IfishUserObsever.h"
typedef NS_ENUM(NSInteger,lodingViewdissMissStyle) {
lodingViewdissMissSuccsess=0,// default is 0
lodingViewdissMissfail,
lodingViewdissMissAlreadyBinded
};
@interface YooseeNextConnectViewController ()<UITextFieldDelegate,P2PClientDelegate,LSemTMFSetDelegate,UIAlertViewDelegate>
{
void *_context;
BOOL _bQuit;
BOOL _bInitWif;
BOOL _initPwSuc;//初始化密码是否成功
int _soundInitCode;
}
@property (strong,nonatomic) NSMutableDictionary *addresses;
//技威服务器 socket返回contactID 即cameraId
@property (nonatomic,copy) NSString *contactID;
@property (nonatomic,assign) NSInteger flag;
@property (nonatomic,assign) NSInteger type;
@property (nonatomic,copy) NSString *address;
@property (nonatomic,copy) NSString *wifiName;
@property (nonatomic,strong) UIButton *sBtn;
@property(nonatomic)BOOL autodismiss;
@property(nonatomic,assign)lodingViewdissMissStyle lodviewMissStyle;
@property(nonatomic,retain) NSTimer* getInfTimer ;
@property(nonatomic,strong) UILabel *wifilabel;
@property(nonatomic,strong) UIImageView *nodImg;
@property(nonatomic,strong) LXWaveProgressView *waveProgressView;;
@property(nonatomic,strong) IfishConnectingView *connectingView;
@end
@implementation YooseeNextConnectViewController
- (void)viewDidLoad {
[super viewDidLoad];
//[self getWifiLoop];
// Do any additional setup after loading the view from its nib.
//智能联机
_initPwSuc = NO;
// [[P2PClient sharedClient] setDelegate:self];
self.conectType = conectType_Intelligent;
self.addresses = [[NSMutableDictionary alloc] initWithCapacity:1];
self.view.backgroundColor = [UIColor whiteColor];
[self addTitleViewWithTitle:@"连接摄像头"];
[self initComponent];
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
self.navigationItem.backBarButtonItem = item;
//
[self soundInit];
_canDissMissController = YES;
[self redTipLable];
}
-(UILabel *)redTipLable{
if (_redTipLable==nil) {
CGFloat y = CGRectGetMaxY(self.wifiSecFiled.frame) + 5;
_redTipLable=[[UILabel alloc]initWithFrame:CGRectMake(19, y, 100, 10)];
_redTipLable.text=@"(暂不支持5G网络请使用2.4G网络)";
_redTipLable.font=[UIFont systemFontOfSize:13];
_redTipLable.textColor=[UIColor redColor];
[_redTipLable sizeToFit];
// _redTipLable.backgroundColor=[UIColor blackColor];
[self.view addSubview:_redTipLable];
[self.view bringSubviewToFront:_redTipLable];
}
return _redTipLable;
}
#pragma mark - 声波SDK初始化
-(void)soundInit{
[[LSemTMFSet sharedInstance] setDelegate:self];
int soundCode=[[LSemTMFSet sharedInstance]initSDK:@"gwelltimes"
client:@"gwelltimes"
productModel:@"gm8135s-8136"
license:@"11625ae8060111e6b5123e1d05defe78"];
NSLog(@"声波初始化的结果码:%d",soundCode);
_soundInitCode = soundCode;
if (soundCode!=1) {//如果不能正常使用SDK,就不让发送SDK
//
[self.view makeToast:@"声波初始化失败"];
}
}
- (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)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:self.wifiSecFiled];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:RECEIVE_REMOTE_MESSAGE object:nil];
_bQuit = YES;
if (_context){
elianStop(_context);
elianDestroy(_context);
_context = NULL;
}
self.isWaiting = NO;//isWaiting is NO
self.isFinish = YES;
self.isRun = NO;
if(self.socket){
[self.socket close];
self.socket=nil;
}
[self soundExit];
}
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
_bQuit = NO;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveRemoteMessage:) name:RECEIVE_REMOTE_MESSAGE object:nil];
//[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wifiviewkeyboradWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
[self setSoket];
}
- (void)receiveRemoteMessage:(NSNotification *)notification{
_initPwSuc = YES;
NSDictionary *parameter = [notification userInfo];
int key = [[parameter valueForKey:@"key"] intValue];
NSString * contactName = [NSString stringWithFormat:@"Cam%@", self.contactID];
switch(key){
case RET_SET_INIT_PASSWORD:
{
int result = [[parameter valueForKey:@"result"] intValue];
if(result==0){
ContactDAO *contactDAO = [[ContactDAO alloc] init];
Contact *contact = [contactDAO isContact:self.contactID];
if(contact!=nil){
contact.contactName = contactName;
contact.contactPassword = self.lastSetPassword;//updatepwd
[[FListManager sharedFList] updatee:contact];
dispatch_async(dispatch_get_main_queue(), ^{
// [self.view makeToast:NSLocalizedString(@"operator_success", nil)];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
usleep(800000);
dispatch_async(dispatch_get_main_queue(), ^{
//不同
//设置密码成功后爱鱼奇用户绑定摄像头
//
[self ifishUserBindcameraIdBy:self.contactID];
});
});
});
}else{
Contact *contact = [[Contact alloc] init];
contact.contactId = self.contactID;
contact.contactName = contactName;
contact.contactPassword = self.lastSetPassword;
contact.contactType = CONTACT_TYPE_UNKNOWN;
[[FListManager sharedFList] insert:contact];
[[P2PClient sharedClient] getContactsStates:[NSArray arrayWithObject:contact.contactId]];
[[P2PClient sharedClient] getDefenceState:contact.contactId password:contact.contactPassword];
//contact 原始数据暂不动 现在摄像头数据 模型用IfishCameraModel
dispatch_async(dispatch_get_main_queue(), ^{
// [self.view makeToast:NSLocalizedString(@"operator_success", nil)];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
usleep(800000);
dispatch_async(dispatch_get_main_queue(), ^{
//设置密码成功后爱鱼奇用户绑定摄像头
[self ifishUserBindcameraIdBy:self.contactID];
});
});
});
}
}else if(result==43){
dispatch_async(dispatch_get_main_queue(), ^{
self.lodviewMissStyle =lodingViewdissMissSuccsess;
[self mmPogressHUDdismiss];
[self connectNormalView];
_canDissMissController = YES;
[self.view makeToast:NSLocalizedString(@"device_already_exist_password", nil)];
});
}else{
dispatch_async(dispatch_get_main_queue(), ^{
//只为做 dissPogress处理并非成功
self.lodviewMissStyle =lodingViewdissMissSuccsess;
[self mmPogressHUDdismiss];
[self connectNormalView];
_canDissMissController = YES;
[self.view makeToast:NSLocalizedString(@"operator_failure", nil)];
});
}
}
break;
case RET_SET_DEVICE_PASSWORD:
{
NSInteger result = [[parameter valueForKey:@"result"] intValue];
if(result==0){
dispatch_async(dispatch_get_main_queue(), ^{
//[self.view makeToast:NSLocalizedString(@"operator_success", nil)];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
usleep(800000);
dispatch_async(dispatch_get_main_queue(), ^{
[self ifishUserBindcameraIdBy:self.contactID];
});
});
});
}else{
dispatch_async(dispatch_get_main_queue(), ^{
self.lodviewMissStyle =lodingViewdissMissSuccsess;
[self mmPogressHUDdismiss];
[self connectNormalView];
_canDissMissController = YES;
[self.view makeToast:NSLocalizedString(@"operator_failure", nil)];
});
}
}
break;
}
}
-(void)setWindowRootWith:(IfishCameraModel *)cameraMdel{
Socketsingleton *soket=[Socketsingleton sharedInstance];
if (soket.clientSocket.isConnected) {
[soket cutOffSocket];
}
// LeftViewController *left=[[LeftViewController alloc] init];
// RightViewController *right= [[RightViewController alloc] init];
// YooseeCenterViewController *center= [[YooseeCenterViewController alloc] init];
// center.cameraModel = cameraMdel;
// ICSDrawerController *ics = [[ICSDrawerController alloc] initWithLeftViewController:left centerViewController: center rightViewController:right];
// UIApplication*app=[UIApplication sharedApplication];
// AppDelegate*app1=app.delegate;
// UINavigationController*nav=[[UINavigationController alloc]initWithRootViewController:ics];
// [nav.navigationBar setBackgroundImage:[UIImage imageNamed:@"blackbar.png"] forBarMetrics:UIBarMetricsDefault];
// app1.window.rootViewController=nav;
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];
}
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
}
-(void)setSoket{
self.isRun = YES;
self.isPrepared = NO;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
while(self.isRun){//不断广播获取设置好WIFI的设备
if(!self.isPrepared){
[self prepareSocket];
}
usleep(1000000);
}
});
}
-(BOOL)prepareSocket{
GCDAsyncUdpSocket *socket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
NSError *error = nil;
if (![socket bindToPort:9988 error:&error])
{
//NSLog(@"Error binding: %@", [error localizedDescription]);
return NO;
}
if (![socket beginReceiving:&error])
{
NSLog(@"Error receiving: %@", [error localizedDescription]);
return NO;
}
if (![socket enableBroadcast:YES error:&error])
{
NSLog(@"Error enableBroadcast: %@", [error localizedDescription]);
return NO;
}
self.socket = socket;
self.isPrepared = YES;
return YES;
}
#pragma mark - 空中发包给设备设置wifi
- (void)startSetWifiLoop
{
//ssid
const char *ssid = [self.wifiName cStringUsingEncoding:NSUTF8StringEncoding];
//authmode
int authmode = 9;//delete
//pwd
const char *password = [self.wifiSecFiled.text cStringUsingEncoding:NSUTF8StringEncoding];//NSASCIIStringEncoding
//target
unsigned char target[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
_context = elianNew(NULL, 0, target, ELIAN_SEND_V1 | ELIAN_SEND_V4);
elianPut(_context, TYPE_ID_AM, (char *)&authmode, 1);//delete
elianPut(_context, TYPE_ID_SSID, (char *)ssid, strlen(ssid));
elianPut(_context, TYPE_ID_PWD, (char *)password, strlen(password));
elianStart(_context);
}
#pragma mark - 使用90秒来进行空中发包给设备设置wifi
-(void)setWifiAniminte{
self.isWaiting = YES;
__weak typeof(self) weakself= self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
int index = 0;
while(weakself.isWaiting){
NSLog(@"%i",index);
index++;
if (weakself.conectType == conectType_Intelligent){
//startSetWifiLoop
if (index >= 21 && index <= 30)
{
if (index == 21)
{
elianStop(_context);
}
}
else if (index >= 51 && index <= 60)
{
if (index == 51)
{
elianStop(_context);
}
}
else if (index >= 81)
{
if (index == 81)
{
elianStop(_context);
}
}
else
{
if (index==31 || index==61)
{
elianStart(_context);
}
}
if(index>=90)
{//90
[weakself soundSendStop];
NSLog(@"声波发送时间达上限,停止发送");
break;
}
}
else
{
if(index>=60)
{//60
break;
}
}
sleep(1.0);
}
if(!weakself.isFinish){
if (weakself.conectType == conectType_Intelligent){//startSetWifiLoop
if (_context){
elianStop(_context);
elianDestroy(_context);
_context = NULL;
//dispatch_async(, <#^(void)block#>)
[weakself connectNormalView];
_canDissMissController = YES;
weakself.lodviewMissStyle =lodingViewdissMissfail;
[weakself mmPogressHUDdismiss];
NSLog(@"设置WIFI失败停止");
}//设置WIFI失败停止
}
}
});
}
#pragma mark - 声波开始发送
-(void)soundSendStart{
NSLog(@"开始发送声波");
NSString* strWiFiName=self.wifiName;
NSString* strWiFiPwd=self.wifiSecFiled.text;
NSLog(@"要发送的WiFi是:%@,其密码是:%@",self.wifiName,self.wifiSecFiled.text);
[[LSemTMFSet sharedInstance] sendWiFiSet:strWiFiName password:strWiFiPwd];
}
#pragma mark - 声波停止发送
-(void)soundSendStop{
NSLog(@"停止发送声波");
[[LSemTMFSet sharedInstance] stopSend];
[[LSemTMFSet sharedInstance] cancleConnectTimer];
}
#pragma mark - 声波SDK退出和释放
-(void)soundExit{
NSLog(@"退出声波SDK");
[self soundSendStop];
[[LSemTMFSet sharedInstance] exitEMTMFSDK];
}
#pragma mark - 声波的几个协议
- (void)didSetWifiResultErrcode:(EMTMFErrcodeType*)errcode content:(NSString*)content{
if (errcode==(EMTMFErrcodeType*)EMTMFErrcodeType_SUCESS){
NSLog(@"声波配对成功");
NSLog(@"content%@",content);
[self soundSendStop];
}else{
NSLog(@"声波配对失败content%@,重新发送",content);
[self soundSendStart];
}
}
- (void)didFSKSendingComplete{
[[LSemTMFSet sharedInstance] startConnectTimeOutListener:1];//暂停1秒,然后继续发送声波
}
-(void)didSDKErrcode:(int) errCode errMsg:(NSString*)errMsg{
NSLog(@"声波初始化结果码:%d,结果码解释:%@",errCode,errMsg);
}
-(void)dealloc{
[self soundExit];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)initComponent{
//967/1018/ 0.95
CGFloat percentHbiW = 0.117 ;//5s 35/300
CGFloat y = 20;
self.nodImg= [[UIImageView alloc] initWithFrame:CGRectMake(5, y,12, 12)];
self.nodImg.image = [UIImage imageNamed:@"linkingdevice_point"];
[self.view addSubview:self.nodImg];
self.wifilabel=[[UILabel alloc] init];
NSDictionary *ifs = [self fetchSSIDInfo];
self.wifiName = [ifs objectForKey:@"SSID"];
self.wifilabel.text = [NSString stringWithFormat:@"请输入当前WiFi:%@密码",self.wifiName];
self.wifilabel.textAlignment = NSTextAlignmentLeft;
self.wifilabel.textColor = [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1];
NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:self.wifilabel.text];
NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:8];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [self.wifilabel.text length])];
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:0 green:170.0/255.0 blue:218.0/255.0 alpha:1] range:NSMakeRange(10,self.wifiName.length)];
[self.wifilabel setAttributedText:attributedString];
[self.wifilabel sizeToFit];
CGFloat labelSizeW = [self widthForString:self.wifilabel.text fontSize:18 andHeight:10];
CGFloat labelH= [self heightForString:self.wifilabel.text fontSize:18 andWidth:labelSizeW];
self.wifilabel.frame = CGRectMake(CGRectGetMaxX(self.nodImg.frame), y, labelSizeW, labelH);
[self.view addSubview:self.wifilabel];
//wifi 输入框
CGFloat wifiFileW=kScreenSize.width - 2*10;
CGFloat wifiFileH=wifiFileW*percentHbiW;
self.wifiSecFiled=[[UITextField alloc] initWithFrame:CGRectMake(10,CGRectGetMaxY(self.wifilabel.frame) + 10, wifiFileW, wifiFileH)];
//[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wifiviewkeyboradWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
self.wifiSecFiled.placeholder = @"请输入WiFi密码";
self.wifiSecFiled.delegate=self;
self.wifiSecFiled.layer.masksToBounds=YES;
self.wifiSecFiled.layer.cornerRadius=5;
[self.wifiSecFiled setValue:[UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1] forKeyPath:@"_placeholderLabel.textColor"];
self.wifiSecFiled.borderStyle = UITextBorderStyleNone;
self.wifiSecFiled.backgroundColor = [UIColor colorWithRed:244.0/255.0 green:244.0/255.0 blue:244.0/255.0 alpha:1];
NSUserDefaults*userDefsult=[NSUserDefaults standardUserDefaults];
NSString*pass=[userDefsult objectForKey:@"wifiPass"];
if (pass) {
self.wifiSecFiled.text = pass;
}
self.wifiSecFiled.textAlignment = NSTextAlignmentLeft;
[self.view addSubview:self.wifiSecFiled];
//占位view 让输入框文字 偏移 也有别的方法 contentoffset
UIView*phoneView=[[UIView alloc]initWithFrame:CGRectMake(0,0, 9, 10)];
self.wifiSecFiled.leftView=phoneView;
self.wifiSecFiled.leftViewMode=UITextFieldViewModeAlways;
CGFloat btnW=100;
//输入框内白色2像素view
UIView *whiteView=[[UIView alloc] initWithFrame:CGRectMake(wifiFileW - btnW -2, 0, 2, wifiFileH)];
whiteView.backgroundColor = [UIColor whiteColor];
[self.wifiSecFiled addSubview:whiteView];
self.sBtn=[UIButton buttonWithType:UIButtonTypeCustom];
[self.sBtn setTitle:@"确定" forState:UIControlStateNormal];
self.sBtn.frame = CGRectMake(wifiFileW - btnW,0, btnW,wifiFileH);
[self.sBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[self.sBtn addTarget:self action:@selector(sBtn:) forControlEvents:UIControlEventTouchUpInside];
//self.sBtn.backgroundColor = COLOR_LABEL_TITLE;
[self.sBtn setBackgroundImage:[UIImage imageNamed:@"linkingdevice_botton"] forState:UIControlStateNormal];
[self.wifiSecFiled addSubview:self.sBtn];
//底部背景
UIImageView *backImg=[[UIImageView alloc] initWithFrame:CGRectMake(0,kScreenSize.height - kScreenSize.width * 1.1,kScreenSize.width,kScreenSize.width * 1.1)];
backImg.image = [UIImage imageNamed:@"linkingdevice_setting"];
backImg.userInteractionEnabled = YES;
[self.view addSubview:backImg];
//波纹
self.waveProgressView = [[LXWaveProgressView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.wifiSecFiled.frame) +10, kScreenSize.width,CGRectGetMinY(backImg.frame) - CGRectGetMaxY(self.wifiSecFiled.frame))];
[self.view addSubview:self.waveProgressView];
[self.view bringSubviewToFront:self.waveProgressView];
//说明书
UIButton *shuimingshuBtn=[UIButton buttonWithType:UIButtonTypeCustom];
shuimingshuBtn.frame = CGRectMake(0,kScreenSize.height - 44 - 200, kScreenSize.width*1/3, 200);
[shuimingshuBtn addTarget:self action:@selector(ChaKanShuimingShu) forControlEvents:UIControlEventTouchUpInside];
//[shuimingshuBtn setBackgroundColor:[UIColor redColor]];
[self.view addSubview:shuimingshuBtn];
//设置输入状态UI
[self connectNormalView];
}
#pragma mark - ChaKanShuimingShu
-(void)ChaKanShuimingShu{
if (!_canDissMissController ) {
[self.view makeToast:@"正在连接中请稍后操作"];
return;
}
PushMasssageWebViewController*webVC=[[PushMasssageWebViewController alloc]init];
webVC.pushlink =IFISH_DEVCEITROURL;
webVC.pushtitle = NSLocalizedString(@"ifish_deviceuse", nil);;
[self.navigationController pushViewController:webVC animated:YES];
}
#pragma mark- 点击确定
-(void)sBtn:(UIButton*)btn{
UIAlertView *alert= [[UIAlertView alloc] initWithTitle:@"提示" message:@"即将使用声波连接,请调大手机音量,并靠近设备,在听到“等待连接“后再点击确认" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
alert.tag = ALERT_TAG_B_SURE;
[alert show];
}
-(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:@""];
//[self.view makeToast:NSLocalizedString(@"connect_success", nil)];
}
break;
case lodingViewdissMissfail:
{
//[MMProgressHUD dismissWithError:@""];
[self.view makeToast:@"再试一下!"];
}
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];
}
//保存wifi密码
-(void)savePassw{
NSUserDefaults*userdefult=[NSUserDefaults standardUserDefaults];
[userdefult setObject:self.wifiSecFiled.text forKey:@"wifiPass"];
[userdefult synchronize];
}
#pragma -mark -functions
//获取字符串的宽度
-(float) widthForString:(NSString *)value fontSize:(float)fontSize andHeight:(float)height
{
CGSize sizeToFit = [value sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:CGSizeMake(CGFLOAT_MAX, height) lineBreakMode:NSLineBreakByWordWrapping];//此处的换行类型lineBreakMode可根据自己的实际情况进行设置
return sizeToFit.width;
}
//获得字符串的高度
-(float) heightForString:(NSString *)value fontSize:(float)fontSize andWidth:(float)width
{
CGSize sizeToFit = [value sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:CGSizeMake(width, CGFLOAT_MAX) lineBreakMode:NSLineBreakByCharWrapping];//此处的换行类型lineBreakMode可根据自己的实际情况进行设置
return sizeToFit.height;
}
#pragma mark - GCDAsyncUdpSocket
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag
{
NSLog(@"did send");
}
- (void)udpSocketDidClose:(GCDAsyncUdpSocket *)sock withError:(NSError *)error
{
NSLog(@"error %@", error);
}
#pragma mark 搜索设备
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
fromAddress:(NSData *)address
withFilterContext:(id)filterContext
{
NSLog(@"data%@",data);
//A buffer into which to copy the receiver's data. The buffer must be at least length bytes.
if (data) {
Byte receiveBuffer[1024];
//Copies a range of bytes from the receivers data into a given buffer.
[data getBytes:receiveBuffer length:1024];
if(receiveBuffer[0]==1){
NSString *host = nil;
uint16_t port = 0;
[GCDAsyncUdpSocket getHost:&host port:&port fromAddress:address];
int contactId = *(int*)(&receiveBuffer[16]);
int type = *(int*)(&receiveBuffer[20]);
int flag = *(int*)(&receiveBuffer[24]);
self.contactID = [NSString stringWithFormat:@"%d",contactId];
self.type = type;
self.flag = flag;
[self.addresses setObject:host forKey:[NSString stringWithFormat:@"%i",contactId]];
if(self.isWaiting){
self.isWaiting = NO;//isWaiting is NO
dispatch_async(dispatch_get_main_queue(), ^{
self.isFinish = YES;
if (self.conectType == conectType_Intelligent){//startSetWifiLoop
if (_context){
elianStop(_context);
elianDestroy(_context);
_context = NULL;
//设置WIFI成功
}
}
if (self.flag == 0){
//没有初始化过密码
[self initPaw];
}else if (self.flag == 1){
//设备默认已经初始化密码 有设备复位后会如此
[self modifyPassW];
}
//声波停止发送 声波SDK退出和释放
[self soundExit];
});
}
}
}
}
//初始化设备密码
-(void)initPaw{
NSString *newPassword = @"123";
self.lastSetPassword = [Utils GetTreatedPassword:newPassword];
//很容易设置失败?? 定时重发
[[P2PClient sharedClient] setInitPasswordWithId:self.contactID initPassword:self.lastSetPassword];
}
//已初始化密码修改密码
-(void)modifyPassW{
NSString *newPassword = @"123";
self.lastSetPassword = [Utils GetTreatedPassword:newPassword];
//NSString *oldPass= [Utils GetTreatedPassword:@"123"];
[[P2PClient sharedClient] setDevicePasswordWithId:self.contactID password:GIWEI_INITPASS newPassword:self.lastSetPassword];
}
#pragma mark - 搜索到设备,弹出添加设备提示 暂不用
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (alertView.tag==ALERT_TAG_SET_FAILED) {
if(buttonIndex==0){
}
}else if(alertView.tag==ALERT_TAG_SET_SUCCESS){
if(buttonIndex==0){
if (self.flag == 0) {//设备未初始化过密码
NSString *newPassword = GIWEI_INITPASS;
self.lastSetPassword = [Utils GetTreatedPassword:newPassword];;
[[P2PClient sharedClient] setInitPasswordWithId:self.contactID initPassword:self.lastSetPassword];
}else{
}
}
}else if (alertView.tag==ALERT_TAG_B_SURE){
if (buttonIndex ==1) {
[self.wifiSecFiled resignFirstResponder];
//NSString *pwdString = self.wifiSecFiled.text;
// if (!pwdString) {//ios<7.0
// pwdString = @"";
// }
if (self.wifiSecFiled.text.length<=0||[self.wifiName isEqualToString:@"无Wi-Fi"]) {
//[self.view makeToast:NSLocalizedString(@"link_wifi", nil)];
[self.view makeToast:@"请保证手机已连接wifi且wifi密码不能为空"];
return;
}
// BOOL isRight =[dataContorl isIncludeSpecialCharact:self.wifiSecFiled.text];
//
// if (!isRight) {
// [self.view makeToast:@"Wifi密码不能包含特殊字符只能为数字字母下划线"];
//
// return;
// }
if (!self.wifiName) {
[self.view makeToast:@"未检测到wifi"];
return;
}
NSString *ssidName = [self.wifiName substringWithRange:NSMakeRange(self.wifiName.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;
}
//旧连接效果已去
//[self initMMProgressHUD];
//最新连接效果
[self connectNotNormalView];
_canDissMissController = NO;
//空中抓包方式
self.conectType = conectType_Intelligent;
[self savePassw];
[self startSetWifiLoop];//给设备设置wifi
[self setWifiAniminte];//直接调用,不用点击“听到了”按钮
self.isFinish = NO;
//声波配置方式
[self soundSendStart];
}
}
}
#pragma mark - UI正常状态
-(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.wifiSecFiled.frame))];
self.connectingView =connectingView;
[self.connectingView.textChangeView animationWithTexts:[NSArray arrayWithObjects:@"正在拼命连接中...",@"请将摄像头放在wifi信号良好的位置",@"连接时,请开大手机音量",@"连接过程会持续40s左右请耐心等待",@"连接不上,请点击下方说明书",nil]];
//self.connectingView.backgroundColor = [UIColor redColor];
[self.view addSubview:self.connectingView];
self.wifilabel.hidden = NO;
self.wifiSecFiled.hidden = NO;
self.sBtn.hidden = NO;
self.nodImg.hidden = NO;
self.redTipLable.hidden=NO;
self.connectingView.alpha = 0;
}else{
[UIView animateWithDuration:2.0 animations:^{
self.connectingView.alpha = 0;
} completion:^(BOOL finished) {
[self.connectingView.textChangeView stopAnimation];
self.wifilabel.hidden = NO;
self.wifiSecFiled.hidden = NO;
self.sBtn.hidden = NO;
self.nodImg.hidden = NO;
self.redTipLable.hidden=NO;
}];
}
}
#pragma mark - UI连接状态
-(void)connectNotNormalView{
[UIView animateWithDuration:2.0 animations:^{
self.connectingView.alpha = 1;
self.connectingView.lineView.alpha = 1;
self.connectingView.fishImageView.alpha = 1;
} completion:^(BOOL finished) {
[self.connectingView.textChangeView startTextAnimation];
}];
self.wifilabel.hidden = YES;
self.wifiSecFiled.hidden = YES;
self.sBtn.hidden = YES;
self.nodImg.hidden = YES;
self.redTipLable.hidden=YES;
}
-(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.sBtn convertRect:self.sBtn.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{
[self.wifiSecFiled resignFirstResponder];
}
#pragma mark - 绑定摄像头
//让爱鱼奇用户 与摄像头建立关系
-(void)ifishUserBindcameraIdBy:(NSString *)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;
_canDissMissController = YES;
[self mmPogressHUDdismiss];
[self connectNormalView];
//绑定成功
/**
* 存储摄像头设备信息
*/
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 mmPogressHUDdismiss];
[self connectNormalView];
_canDissMissController = YES;
[self.view makeToast:@"绑定失败错误码101"];
}
} failure:^(NSError *err) {
[self.view makeToast:@"绑定失败未知错误"];
}];
}
@end