JLChen
2021-05-18 a869383e163a18cdedcf587383c1eca043129754
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
//
//  Copyright © 2018年 Zhejiang Dahua Technology Co.,Ltd. All rights reserved.
//    WIFI配置:设备连接WIFI
 
import UIKit
import MediaPlayer
 
class DHWifiConnectViewController: DHAddBaseViewController, DHCycleTimerViewDelegate, DHWifiConnectFailureVCProtocol {
    
    public static func storyboardInstance() -> DHWifiConnectViewController {
        let storyboard = UIStoryboard(name: "AddDevice", bundle: Bundle.dh_addDeviceBundle())
        guard let controller = storyboard.instantiateViewController(withIdentifier: "DHWifiConnectViewController") as? DHWifiConnectViewController else {
            return DHWifiConnectViewController()
        }
        return controller
    }
    
    var showPlayAudio: Bool = true
    var descriptionContent: String = "add_device_adjust_phone_volume_to_hear_bugu".lc_T
    let tipContent: String = "add_device_listen_wifi_pwd_error_tip".lc_T
    
    lazy var wifiPassWordBtn: UIButton = {
        let btn: UIButton = UIButton(frame: CGRect(x: 0, y: 20, width: 50, height: 22))
        btn.backgroundColor = UIColor.clear
        btn.titleLabel?.font = UIFont.dhFont_t3()
        if dh_screenHeight < 667 {
            btn.titleLabel?.font = UIFont.dhFont_t5()
        }
        
        btn.setTitle(tipContent, for: .normal)
        btn.setTitleColor(UIColor.dhcolor_c0(), for: .normal)
        btn.addTarget(self, action: #selector(jumpWifiPassword), for: .touchUpInside)
        return btn
    }()
    
    @IBOutlet weak var wifiStrengthView: UIImageView!
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var cycleTimerView: DHCycleTimerView!
    @IBOutlet weak var contentLabel: UILabel!
    @IBOutlet weak var detailLabel: UILabel!
    
    private var audioPlayer: AVAudioPlayer?
    private var isDeviceFound: Bool = false
    private var failureVc: DHWifiConnectFailureViewController?
    
    /// 开启音频前手机的音量
    private var defaultVolume: Float = 0.5
    
    deinit {
        NotificationCenter.default.removeObserver(self)
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.dhcolor_c43()
        
        // Do any additional setup after loading the view.
        imageView.image = UIImage(named: "adddevice_netsetting_connectrouter")
        setupCustumContents()
        configCycleTimerView()
        configWifiStrengthView()
        registerNotification()
        startSmartConfig()
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
        //恢复默认的音频类型
        try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
        stopSmartConfig()
        stopAudio()
 
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        //设置音频类型
        try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
    
        if cycleTimerView.currentTime > 0, cycleTimerView.currentTime < cycleTimerView.maxTime {
            self.startSmartConfig()
        }
    }
    
    private func setupCustumContents() {
        contentLabel.textColor = UIColor.dhcolor_c2()
        detailLabel.textColor = UIColor.dhcolor_c5()
        let content = "add_device_connect_router_please_wait".lc_T
        contentLabel.dh_setAttributedText(text: content, font: UIFont.dhFont_t1())
        
        let detail = descriptionContent
        detailLabel.dh_setAttributedText(text: detail, font: UIFont.dhFont_t3())
        
        if dh_screenHeight < 667 {
            contentLabel.dh_setAttributedText(text: content, font: UIFont.dhFont_t2())
            detailLabel.dh_setAttributedText(text: detail, font: UIFont.dhFont_t5())
        }
        
        ///国内乐橙配对路由器等待页面下方增加提示语,并能跳转到输入WIFI密码页面
        if DHModuleConfig.shareInstance().isLeChange {
            self.view.addSubview(wifiPassWordBtn)
            wifiPassWordBtn.snp.makeConstraints({ (make) in
                make.centerX.equalTo(self.view)
                make.bottom.equalTo(self.view).offset(-dh_bottomSafeMargin)
            })
        }
    }
    
    @objc private func jumpWifiPassword() {
        for controller in baseStackControllers() {
            DHUserManager.shareInstance().removeSSID(DHAddDeviceManager.sharedInstance.wifiSSID)
            if controller is DHWifiPasswordViewController {
                self.navigationController?.popToViewController(controller, animated: true)
                break
            }
        }
    }
    
    private func configCycleTimerView() {
        cycleTimerView.maxTime = DHAddConfigTimeout.wifiConnect
        cycleTimerView.delegate = self
        weak var weakSelf = self
        cycleTimerView.timeout = {
            weakSelf?.stopSmartConfig()
            weakSelf?.stopAudio()
        }
    }
    
    private func configWifiStrengthView() {
        let imageNames = ["adddevice_netsetting_connectrouter_1",
                          "adddevice_netsetting_connectrouter_2",
                          "adddevice_netsetting_connectrouter_3",
                          "adddevice_netsetting_connectrouter_4"]
        
        var images = [UIImage]()
        for name in imageNames {
            if let image = UIImage(named: name) {
                images.append(image)
            }
        }
        
        wifiStrengthView.animationImages = images
        wifiStrengthView.animationDuration = 1.5
        wifiStrengthView.animationRepeatCount = 0
    }
    
    private func registerNotification() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(self.handleInterruption(_:)), name: NSNotification.Name.AVAudioSessionInterruption, object: nil)
        
    }
    
    // MARK: - handleInterruption
    
    @objc func handleInterruption(_ notification: Notification) {
        guard let interruptionType = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt else {
            return
        }
        if interruptionType == AVAudioSessionInterruptionType.began.rawValue {
            // started
            //self.audioPlayer?.pause()
        } else if interruptionType == AVAudioSessionInterruptionType.ended.rawValue {
            //self.audioPlayer?.play()
        }
        
    }
    
    // MARK: - SmartConfig
    private func startSmartConfig() {
        
        if cycleTimerView.currentTime > 0, cycleTimerView.currentTime < cycleTimerView.maxTime {
            cycleTimerView.resumeTimer()
        } else {
            cycleTimerView.startTimer()
        }
        
        wifiStrengthView.startAnimating()
        smartConfig(openAudio: showPlayAudio)
    }
    
    private func stopSmartConfig() {
        LCSmartConfig.shareInstance().stop()
        cycleTimerView.stopTimer()
        wifiStrengthView.stopAnimating()
    }
    
    // MARK: - Audio
    private func smartConfig(openAudio: Bool) {
        let manager = DHAddDeviceManager.sharedInstance
        let fskMode: DHFSKMode = manager.ncType == .soundWaveV2 ? .new : .old
        LCSmartConfig.shareInstance().start(withDevice: manager.deviceId,
                                                ssid: manager.wifiSSID,
                                            password: manager.wifiPassword,
                                            security: "",
                                            fskMode: fskMode)
        //不需要开启音频,直接return
//        if openAudio == false {
//            return
//        }
//
//        if self.audioPlayer == nil {
//            if let path = wavePath, path.count > 0 {
//                let fileUrl = URL(fileURLWithPath: path)
//                self.audioPlayer = try? AVAudioPlayer(contentsOf: fileUrl)
//                self.audioPlayer?.numberOfLoops = -1
//                self.audioPlayer?.prepareToPlay()
//            }
//        }
//
//        self.audioPlayer?.play()
    }
    
    private func stopAudio() {
//        self.audioPlayer?.stop()
//        self.audioPlayer = nil
    }
    
    
    // MARK: - Find Device Process
    private func findDevice() {
        print("🍎🍎🍎 \(NSStringFromClass(self.classForCoder))::Device found...")
        isDeviceFound = true
        stopSmartConfig()
        stopAudio()
        uploadWifiPairInfo()
        DHAddDeviceManager.sharedInstance.stopGetDeviceStatus()
        
        //【*】在线或者支持sc码的,配网后,直接跳转连接云平台即可
        //【*】其他需要跳转旧的初始化流程
        if DHAddDeviceManager.sharedInstance.isSupportSC {
            basePushToConnectCloudVC()
        } else {
            basePushToInitializeSearchVC()
        }
    }
    
    //上报WIFI配对信息
    private func uploadWifiPairInfo() {
        
        /* SMB 不上报 */
    }
    
    // MARK: - DHAddBaseVCProtocol
    override func leftActionType() -> DHAddBaseLeftAction {
        return .quit
    }
    
    override func isLeftActionShowAlert() -> Bool {
        return true
    }
    
    override func isRightActionHidden() -> Bool {
        return false
    }
    
    override func rightActionType() -> [DHAddBaseRightAction] {
        if failureVc != nil {
            var actions: [DHAddBaseRightAction] = [.restart]
            if DHAddDeviceManager.sharedInstance.supportConfigModes.contains(.wired) &&
                DHAddDeviceManager.sharedInstance.supportConfigModes.contains(.wifi) {
                if DHAddDeviceManager.sharedInstance.netConfigMode == .wifi {
                    actions.append(.switchToWired)
                } else if DHAddDeviceManager.sharedInstance.netConfigMode == .wired {
                    actions.append(.switchToWireless)
                }
            }
            
            return actions
        } else {
            return [.restart]
        }
    }
}
 
extension DHWifiConnectViewController {
    
    // MARK: - DHCycleTimerViewDelegate
    func cycleTimerView(cycleView: DHCycleTimerView, tick: Int) {
        let deviceId = DHAddDeviceManager.sharedInstance.deviceId
        let device = DHNetSDKSearchManager.sharedInstance().getNetInfo(byID: deviceId)
        guard isDeviceFound == false else {
            return
        }
        
        //【*】判断局域网是否搜索到
        if device != nil, deviceId == DHAddDeviceManager.sharedInstance.deviceId {
            findDevice()
        }
        
        //【*】每隔5秒进行一次轮循设备在线状态,支持sc码的才查询
        guard tick % 5 == 0, DHAddDeviceManager.sharedInstance.isSupportSC else {
            return
        }
        
        DHAddDeviceManager.sharedInstance.getDeviceStatus(success: { (bindInfo) in
            
            print("🍎🍎🍎 \(NSStringFromClass(self.classForCoder)):: Time:\(cycleView.currentTime), deviceType:\(bindInfo.dh_accessType().rawValue), existed:\(bindInfo.dh_isExisted()), onlineStatus:\(bindInfo.dh_isOnline())")
            
            //【*】保证设备已注册成功
            guard bindInfo.dh_isExisted() else {
                return
            }
            
            //【*】防止页面已跳转,接口仍在处理
            guard self.isDeviceFound == false else {
                return
            }
            
            if bindInfo.dh_isOnline() {
                print("🍎🍎🍎 \(NSStringFromClass(self.classForCoder)):: DMS is online, start to connect cloud...")
                self.findDevice()
            }
            
        }) { (error) in
            
        }
    }
    
    func cycleTimerViewTimeout(cycleView: DHCycleTimerView) {
        if failureVc == nil {
            failureVc = DHWifiConnectFailureViewController()
            failureVc?.delegate = self
        }
        
        //【*】默认使用旧的错误类型
        //【*】SoftAp流程,如果配置了,使用新的
        let parser = DHAddDeviceManager.sharedInstance.getIntroductionParser()
        var type: DHNetConnectFailureType? = parser?.errorType
        if DHAddDeviceManager.sharedInstance.netConfigMode == .softAp, let softApErrorType = parser?.softApErrorType {
            type = softApErrorType
        }
        
        if type != nil, type != .ipcGeneral {
            failureVc?.failureType = type!
        } else {
            failureVc?.failureType = DHAddDeviceManager.sharedInstance.supportConfigModes.contains(.wired) ? .commonWithWired : .commonWithoutWired
        }
        
        //【!测试】
        if DHAddDeviceTest.openTest {
            failureVc?.failureType = testFailureType()
        }
        
        self.failureVc?.showOnParent(controller: self)
        
    }
}
 
// MARK: - DHWifiConnectFailureVCProtocol
extension DHWifiConnectViewController {
    func reconnectWifiAction(controller: DHWifiConnectFailureViewController) {
        self.startSmartConfig()
        smartConfig(openAudio: showPlayAudio)
        
    }
}
 
 
// MARK: - Test
extension DHWifiConnectViewController {
    
    private func testFailureType() -> DHNetConnectFailureType {
        var type: DHNetConnectFailureType = .commonWithoutWired
        let allTypes: [DHNetConnectFailureType] = [.tp1, .tp1s, .g1, .door, .overseasA, .overseasC,
                                                   .overseasDoorbell, .commonWithWired, .commonWithoutWired,
                                                   .accessory, .cloudTimeout]
        DHAddDeviceTest.failureIndex = (DHAddDeviceTest.failureIndex % (allTypes.count - 1)) + 1
        type = allTypes[DHAddDeviceTest.failureIndex ]
        
        return type
    }
}