// // 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 } } }