Blame view

Twear/Setting(设置)/SettingViewController.swift 18.1 KB
75d24c15   yangbin   123
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
  //
  //  SettingViewController.swift
  //  Twear
  //
  //  Created by yangbin on 2021/11/16.
  //
  
  import UIKit
  import MBProgressHUD
  
  class SettingViewController: UIViewController {
  
      @IBOutlet weak var connectView: UIView!
      @IBOutlet weak var addDeviceView: UIView!
      @IBOutlet weak var collectionView: UICollectionView!
      @IBOutlet weak var collectionViewFlowLayout: UICollectionViewFlowLayout!
      
      @IBOutlet weak var deviceNameLabel: UILabel!
      @IBOutlet weak var batteryBtn: UIButton!
      @IBOutlet weak var connectLabel: UILabel!
      @IBOutlet weak var connectImageView: UIImageView!
      @IBOutlet weak var deleteBtn: UIButton!
      @IBOutlet weak var idLabel: UILabel!
      
      @IBOutlet weak var dailImageView2: UIImageView!
      @IBOutlet weak var dailImageView1: UIImageView!
      @IBOutlet weak var dailImageView3: UIImageView!
      @IBOutlet weak var collectionViewHeight: NSLayoutConstraint!
      
      @IBOutlet weak var totalDistanceLabel: UILabel!
      @IBOutlet weak var totalCalorieLabel: UILabel!
      
      var scanView: ScanView? = nil
      
      private let settingDic: [String: String] = ["遥控拍照": "remote_camera", "查找手环": "set_find", "提醒功能": "set_reminder", "语言设置": "set_language", "其他设置": "set_other", "抬腕亮屏": "lift_wrist", "勿扰模式": "no_disturb", "目标设置": "set_goals", "微信运动": "wechat_sport", "手环说明": "device_desc", "固件升级": "firmware_update", "联系人": "set_contacts", "名片": "set_card", "NFC": "set_nfc"]
      
      
      private let setting_all = ["遥控拍照", "查找手环", "提醒功能", "语言设置", "其他设置", "抬腕亮屏", "勿扰模式", "目标设置", "微信运动", "固件升级", "联系人"]
      
      private let setting_818 = ["遥控拍照", "查找手环", "提醒功能", "语言设置", "其他设置", "抬腕亮屏", "勿扰模式", "目标设置", "微信运动", "固件升级"]
      
      private let setting_816 = ["遥控拍照", "查找手环", "目标设置", "其他设置"]
      
      
      
      
      private var settingArray: [String] = [] {
          didSet {
              collectionViewHeight.constant = CGFloat(82*(settingArray.count/4 + (settingArray.count%4 == 0 ? 0 : 1)) + 12)
          }
      }
      override func viewWillAppear(_ animated: Bool) {
          super.viewWillAppear(animated)
          self.navigationController?.setNavigationBarHidden(false, animated: true)
          if DeviceIsConnected {
              if CurDevice.platform == ._816 {
                  BluetoothManager.shared.queryBattery()
              } else {
                  updateBattery(Battery)
              }
          }
          
      }
      
      
      override func viewDidLoad() {
          super.viewDidLoad()
          setupUI()
          
          BluetoothManager.shared.registerDelegate(self)
          BluetoothManager.shared.registerSyncDelegate(self)
          // Do any additional setup after loading the view.
      }
      
      
      func setupUI() {
          let bindButton = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 28))
          bindButton.setImage(UIImage(named: "device_add"), for: .normal)
          bindButton.addTarget(self, action: #selector(didClickRightBar), for: .touchUpInside)
          navigationItem.rightBarButtonItem =  UIBarButtonItem(customView: bindButton)
          
          let setButton = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 28))
          setButton.setTitle(LocString("设备"), for: .normal)
          setButton.titleLabel?.font = BoldFont(18)
          setButton.setTitleColor(.black, for: .normal)
          setButton.addTarget(self, action: #selector(clickSetButton), for: .touchUpInside)
          navigationItem.leftBarButtonItem =  UIBarButtonItem(customView: setButton)
          
          let addTap = UITapGestureRecognizer(target: self, action:#selector(bindDevice))
          addDeviceView.addGestureRecognizer(addTap)
          
  
          collectionViewFlowLayout.minimumLineSpacing = 5
          collectionViewFlowLayout.minimumInteritemSpacing = 5
          collectionViewFlowLayout.sectionInset = UIEdgeInsets(top: 12, left: 5, bottom: 10, right: 5)
          collectionViewFlowLayout.itemSize = CGSize(width: (SCREEN_WIDTH-80)/4.0, height: 72)
          collectionView.bounces = false
          collectionView.showsHorizontalScrollIndicator = false
      
          idLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(reconnect)))
          updateConnectView(DeviceIsConnected)
          updateTotalDataView()
      }
      @objc func reconnect() {
  //        print("重连")
          if idLabel.text == LocString("重新连接") {
              BluetoothManager.shared.reConnect()
          }
          
      }
      
      private func updateConnectView(_ isConnected: Bool) {
          let curDevice = CurDevice
          if curDevice.uuid.count == 0 {
              addDeviceView.isHidden = false
              connectView.isHidden = true
              dailImageView1.image = UIImage(named: "dail_default_1")
              dailImageView2.image = UIImage(named: "dail_default_2")
              dailImageView3.image = UIImage(named: "dail_default_3")
              settingArray = setting_all
              return
          }
         
  //        if curDevice.platform == .other {
  //            dailImageView1.image = UIImage(named: "dail_default_1")
  //            dailImageView2.image = UIImage(named: "dail_default_2")
  //            dailImageView3.image = UIImage(named: "dail_default_3")
  //
  //        } else
  //        UIImage(contentsOfFile:  "\(Bundle.main.resourcePath!)/dial/dialrtkpreview/\(indexPath.row)/preview@2x")
          
          if curDevice.platform == ._816 {
              settingArray = setting_816
              dailImageView1.image = UIImage(contentsOfFile:  "\(Bundle.main.resourcePath!)/dial/dialpreview280/0/preview_00@2x")
              dailImageView2.image = UIImage(contentsOfFile:  "\(Bundle.main.resourcePath!)/dial/dialpreview280/1/preview_01@2x")
              dailImageView3.image = UIImage(contentsOfFile:  "\(Bundle.main.resourcePath!)/dial/dialpreview280/2/preview_02@2x")
          } else if curDevice.platform == ._818 {
              settingArray = setting_818
              dailImageView1.image = UIImage(contentsOfFile:  "\(Bundle.main.resourcePath!)/dial/dialrtkpreview/0/preview@2x")
              dailImageView2.image = UIImage(contentsOfFile:  "\(Bundle.main.resourcePath!)/dial/dialrtkpreview/1/preview@2x")
              dailImageView3.image = UIImage(contentsOfFile:  "\(Bundle.main.resourcePath!)/dial/dialrtkpreview/2/preview@2x")
          } else if curDevice.platform == ._818_hq7 {
              settingArray = setting_818
              dailImageView1.image = UIImage(contentsOfFile:  "\(Bundle.main.resourcePath!)/dial/dialrtkpreviewHQ7/0/preview")
              dailImageView2.image = UIImage(contentsOfFile:  "\(Bundle.main.resourcePath!)/dial/dialrtkpreviewHQ7/1/preview")
              dailImageView3.image = UIImage(contentsOfFile:  "\(Bundle.main.resourcePath!)/dial/dialrtkpreviewHQ7/2/preview")
          }
          addDeviceView.isHidden = true
          connectView.isHidden = false
          deviceNameLabel.text = CurDevice.name
          deleteBtn.isHidden = isConnected
          batteryBtn.isHidden = !isConnected
          connectLabel.text = isConnected ? LocString("已连接") : LocString("正在连接...")
          connectImageView.image = UIImage(named: isConnected ? "bluetooth_connected" : "bluetooth_disconnected")
          idLabel.textColor = isConnected ? .black : UIColor.rgbColorFromHex(0xFF0000)
          idLabel.text = isConnected ? CurDevice.mac : LocString("重新连接")
      }
      
      private func updateTotalDataView() {
          let stepArray = StepModel.getStepsByYear(Date())
          totalDistanceLabel.text = "\(String(format:"%.2f", stepArray.sum(\.distance)))\(LocString("公里"))"
          totalCalorieLabel.text = "\(String(format:"%.2f", stepArray.sum(\.calorie)))\(LocString("千卡"))"
      }
      
      
      @IBAction func deleteDevice(_ sender: Any) {
          unbindDevice()
      }
      
      @objc func didClickRightBar() {
          if CurDevice.uuid.count > 0 {
              unbindDevice()
  
          } else {
              bindDevice()
          }
          
      }
      func unbindDevice() {
          let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "UnbindViewController") as! UnbindViewController
          vc.unbindClosure = {[weak self] in
              self?.updateConnectView(false)
          }
          navigationController?.pushViewController(vc, animated: true)
      }
  
      
      @objc func bindDevice() {
          scanView = ScanView()
          scanView?.show()
          startScan()
          
          scanView?.clickClosure = {[weak self] index, device in
              if index == 2 {
                  self?.scanView = nil
                  BluetoothManager.shared.stopScanning()
              } else if index == 3 { //配对失败 重试
                  self?.startScan()
              } else if index == 4 { //重新搜索
                  self?.startScan()
              }
              
              if let per = device as? CBPeripheral {
                  BluetoothManager.shared.stopScanning()
                  BluetoothManager.shared.connect(peripheral: per)
                  self?.scanView?.updateUI(.Pairing)
                  if GCDTimer.shared.isExistTimer(WithTimerName: "StartScan") {
                      GCDTimer.shared.cancleTimer(WithTimerName: "StartScan")
                  }
                  if GCDTimer.shared.isExistTimer(WithTimerName: "DevicePairing") {
                      GCDTimer.shared.cancleTimer(WithTimerName: "DevicePairing")
                  }
                  GCDTimer.shared.scheduledDispatchTimerNotNow(WithTimerName: "DevicePairing", timeInterval: 12, queue: .main, repeats: false) {
                      self?.pairingFail()
                  }
              }
              
          }
      }
      
      private func pairingFail() {
          if !DeviceIsConnected {
              BluetoothManager.shared.forgetPeripheral()
              scanView?.updateUI(.PairFail)
          }
      }
      
      private func startScan() {
          BluetoothManager.shared.startScanning()
          GCDTimer.shared.scheduledDispatchTimerNotNow(WithTimerName: "StartScan", timeInterval: 10, queue: .main, repeats: false) {
              BluetoothManager.shared.stopScanning()
              self.scanView?.updateUI(.ScanComplete)
          }
      }
      
      
      @objc func clickSetButton() {
          
          
      }
      
      private func showALert() -> Bool {
          if !IsBindDevice {
              MBProgressHUD.showh(LocString("请先绑定设备"))
              return true
          }
          if !DeviceIsConnected {
              MBProgressHUD.showh(LocString("设备未连接"))
              return true
          } else {
              if isFirstSync {
                  MBProgressHUD.showh(LocString("正在同步中..."))
                  return true
              }
          }
          return false
      }
      
      @IBAction func gotoDailVC(_ sender: Any) {
          if showALert() {
              return
          }
  //        if CurDevice.uuid == "" {
  //            return
  //        }
          let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "DailSyncViewController")
          navigationController?.pushViewController(vc, animated: true)
      }
  
      func updateBattery(_ value: Int) {
          var imageName = ""
          switch value {
          case 98...100:
              imageName = "battery_100"
          case 90...97:
              imageName = "battery_90"
          case 80...89:
              imageName = "battery_80"
          case 70...79:
              imageName = "battery_70"
          case 60...69:
              imageName = "battery_60"
          case 50...59:
              imageName = "battery_50"
          case 40...49:
              imageName = "battery_40"
          case 30...39:
              imageName = "battery_30"
          case 20...29:
              imageName = "battery_20"
          case 10...19:
              imageName = "battery_10"
          case 0...9:
              imageName = "battery_5"
          default:
              imageName = "battery_5"
          }
          batteryBtn.setImage(UIImage(named: imageName), for: .normal)
          batteryBtn.setTitle(" \(value)%", for: .normal)
      }
      
      deinit {
          BluetoothManager.shared.unRegisterSyncDelegate(self)
          BluetoothManager.shared.unRegisterDelegate(self)
          print("deinit\(NSStringFromClass(type(of: self)))!!!!!!!")
      }
  
  }
  
  extension SettingViewController: BluetoothSyncDelegate {
      func didReceiveBattery(value: Int) {
          
       updateBattery(value)
      }
      
  }
  extension SettingViewController: BluetoothManagerDelegate {
      func centralManagerDidUpdateState(_ state: Int) {
          switch state {
   
          case 4:
              print("poweredOff22")
              updateConnectView(false)
              connectLabel.text = LocString("已断开")
  //            connectImageView.image = UIImage(named: "bluetooth_disconnected")
  //            idLabel.text = "重新连接"
  //            idLabel.textColor = UIColor.rgbColorFromHex(0xFF0000)
  //            deleteBtn.isHidden = false
  //            batteryBtn.isHidden = true
              
          case 5:
              connectLabel.text = LocString("正在连接...")
          default:
              print(" ")
          }
          
      }
      
      func didConnect(_ peripheral: CBPeripheral) {
          print("已经连接")
          switch CurDevice.platform {
          case ._816:
              settingArray = setting_816
          case ._818, ._818_hq7:
              settingArray = setting_818
          default:
              settingArray = setting_all
          }
          if GCDTimer.shared.isExistTimer(WithTimerName: "StartScan") {
              GCDTimer.shared.cancleTimer(WithTimerName: "StartScan")
          }
          if GCDTimer.shared.isExistTimer(WithTimerName: "DevicePairing") {
              GCDTimer.shared.cancleTimer(WithTimerName: "DevicePairing")
          }
          
          collectionView.reloadData()
          scanView?.updateUI(.PairSuccess)
  //        addDeviceView.isHidden = true
  //        connectView.isHidden = false
          
          updateConnectView(true)
   
  
      }
      
      func didDisconnected() {
          updateConnectView(false)
          DeviceIsConnected = false
          connectLabel.text = LocString("已断开")
      }
       
      
      func didDiscover(devices: [ScanDevice]) {
          if scanView != nil {
              scanView?.deviceArray = devices
          }
      }
  }
  
  
  extension SettingViewController: UICollectionViewDelegate, UICollectionViewDataSource {
      func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
          return settingArray.count
      }
      
      func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
          let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SettingCell", for: indexPath) as! SettingCell
          cell.imageView.image = UIImage(named: settingDic[settingArray[indexPath.row]]!)
          cell.label.text = LocString(settingArray[indexPath.row])
          return cell
      }
      
      func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  //        BluetoothManager.shared.clearDelegate()
  //        if AppSettings.shared.language != .Chinese {
  //            AppSettings.shared.setLanguage(language: .Chinese)
  //        } else {
  //            AppSettings.shared.setLanguage(language: .English)
  //        }
  //        return
  
          if showALert() {
              return
          }
          MBProgressHUD.hide()
          switch settingArray[indexPath.row] {
          case "目标设置":
              let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "SetGoalsViewController")
              navigationController?.pushViewController(vc, animated: true)
          case "语言设置":
              let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "LanguageSettingVC")
              navigationController?.pushViewController(vc, animated: true)
          case "查找手环":
              let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "FindBraceletVC")
              navigationController?.pushViewController(vc, animated: true)
          case "遥控拍照":
              SystemAuth.authCamera  {[weak self] isAuth in
                  if isAuth {
                      let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "CameraViewController")
                      vc.modalPresentationStyle = .fullScreen
                      self?.present(vc, animated: true, completion: nil)
                      
                      IsCameraOpen = true
                  } else {
                      self?.showAlert(title: LocString("提示"), message: LocString("请在“设置-隐私-相机”选项中,允许'HDF wear'访问你的相机"), cancelText: nil, confirm: nil)
                  }
              }
          case "其他设置":
              let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "OtherSettingVC")
              navigationController?.pushViewController(vc, animated: true)
          case "抬腕亮屏":
              let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "WristViewController")
              navigationController?.pushViewController(vc, animated: true)
          case "勿扰模式":
              let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "NotDisturbViewController")
              navigationController?.pushViewController(vc, animated: true)
          case "提醒功能":
              let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "RemindViewController")
              navigationController?.pushViewController(vc, animated: true)
          case "固件升级":
              let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "FirmwareUpdateVC")
              navigationController?.pushViewController(vc, animated: true)
          case "微信运动":
              let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "WeChatSportVC")
              navigationController?.pushViewController(vc, animated: true)
          case "联系人":
              let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "ContactsViewController")
              navigationController?.pushViewController(vc, animated: true)
          default:
              break
          }
      }
      
      
  }