| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431 |
- //
- // IHLoginView.swift
- // Inhealth
- //
- // Created by weclouds on 2019/12/10.
- // Copyright © 2019 weclouds. All rights reserved.
- //
- import UIKit
- import PKHUD
- import SwiftyJSON
- //清楚password
- let kNotificationIHLoginViewClearPassword = "kNotificationIHLoginViewClearPassword"
- //改变角色
- let kNotifactionIHLoginViewChangeRole = "kNotifactionIHLoginViewChangeRole"
- @objc protocol IHLoginViewDelegate : NSObjectProtocol{
- @objc optional func signIn(with account:String?,password:String?)
- @objc optional func signUp()
-
- //role ;0表示客人 账户 1 表示管理员账户
- @objc optional func changeAuthority(_ role:Int)
- @objc optional func goPrivacyPolicy()
-
- @objc optional func jumpToClassgatewayCtr(gatewayList list : [Any])
- }
- class IHLoginView: UIView {
-
- weak var loginDelegate : IHLoginViewDelegate?
-
- var role :String? = "0"{
- didSet{
- //管理员
- if let role = self.role {
- authoritySelected(role)
- }
- }
-
- }
-
- lazy var clientSocket: GCDAsyncUdpSocket? = {
- var mainQueue = DispatchQueue.main
- var clientSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: mainQueue)
- return clientSocket
- }()
- var modelList = [gatewayInfor]()
-
- //提示框
- @IBOutlet weak var tipsLabel: UILabel! // 提示语
-
- @IBOutlet weak var accountTextField: UITextField!
-
- @IBOutlet weak var passwordTextField: UITextField!
- //权限选择按钮
- @IBOutlet weak var authorityBtn: UIButton!
-
- @IBOutlet weak var signInBtn: UIButton!
- //注册按钮
- @IBOutlet weak var signUpBtn: UIButton!
-
- @IBOutlet weak var privacyBtn: UIButton!
- var isSearchGateway : Bool = false
- var isOnce : Bool = false
- func hexStringToInt(from:String) -> Int {
- let str = from.uppercased()
- var sum = 0
- for i in str.utf8 {
- sum = sum * 16 + Int(i) - 48 // 0-9 从48开始
- if i >= 65 { // A-Z 从65开始,但有初始值10,所以应该是减去55
- sum -= 7
- }
- }
- return sum
- }
-
- override func awakeFromNib() {
- super.awakeFromNib()
-
- // let str = "12a102050100010169" as NSString
- // let count = str.length / 2
- // var arr = [Int]()
- // for i in 0..<count {
- // let subStr = str.substring(with: NSRange.init(location: i * 2, length: 2))
- //
- // let hex = hexStringToInt(from: subStr)
- // arr.append(hex)
- // }
-
-
- // let str = "12a102050100010169" as NSString
- // let count = str.length / 2
- // var sum = 0x0
- // for i in 0..<count {
- // let subStr = str.substring(with: NSRange.init(location: i * 2, length: 2))
- // sum = sum + hexStringToInt(from: subStr)
- // }
- // //10进制转换成16进制
- // let hexStr = String(sum,radix:16) as NSString
- // let kk = hexStr.substring(with: NSRange.init(location: hexStr.length - 2, length: 2))
- // log.debug("kkdkk:\(kk)")
-
- //从沙盒中取出
- let username = IHHotelStorage.shareInstance.getStorageUsername()
- let password = IHHotelStorage.shareInstance.getStoragePassword()
- let _role = IHHotelStorage.shareInstance.getStorageRole()
- if username != nil && password != nil{
- accountTextField.text = username
- passwordTextField.text = password
- }
- if role != nil {
- self.role = _role
- }
- //添加通知
- NotificationCenter.default.addObserver(self, selector: #selector(notifyClearPassword), name: NSNotification.Name(kNotificationIHLoginViewClearPassword), object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(notifyChangeRole(notif:)), name:NSNotification.Name(kNotifactionIHLoginViewChangeRole), object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(notifyRegisterSuccess(_:)), name: NSNotification.Name(kNotifactionRegisterSuccess), object: nil)
-
- // 设置UI
- signUpBtn.set(image: UIImage(named: "箭头"), title: "注 册", titlePosition: .left, additionalSpacing: 10, state: .normal)
-
- self.authorityBtn.setTitle("I Am Hotel Guests", for: .selected)
- self.authorityBtn.setTitle("我是管理员", for: .normal)
- let privacyStr = "阅读并同意《用户隐私协议》"
- let text = NSMutableAttributedString(string: privacyStr)
- //#657085
- let attrs = [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue,NSAttributedString.Key.foregroundColor : UIColor(hexString: "#657085") as Any] as [NSAttributedString.Key : Any]
- //#657085
- let attrs2 = [NSAttributedString.Key.foregroundColor: UIColor(hexString: "#657085")]
- text.addAttributes(attrs, range: NSRange(location: 13, length: text.length - 13))
- text.addAttributes(attrs2 as [NSAttributedString.Key : Any], range: NSRange(location: 0, length: text.length))
- privacyBtn.setAttributedTitle(text, for: .normal)
-
- accountTextField.delegate = self
- passwordTextField.delegate = self
-
- // sendCommandGetGateway()
- //getCommandGetGateway()
- }
-
- func getCommandGetGateway() {
- let udp = IHUdpRequest.init()
- udp.sendCommandGetGateway()
- udp.complete = { gatewayInfors in
- self.modelList = gatewayInfors
- }
- }
-
- func sendCommandGetGateway(){
- do{
- //不连接,直接发命令
- // let connected = clientSocket?.isConnected()
- // if connected == false {
- // }
- try clientSocket?.enableBroadcast(true)
- let wifiIp = getLocalIPAddressForCurrentWiFi()
- //第二次就不用了,直接使用这个
- if isOnce == false{
- try clientSocket?.bind(toPort: 37030)
- try clientSocket?.joinMulticastGroup("239.255.255.250")
- }
-
- //第一次要绑定interface,后面就不用了
- // try clientSocket?.bind(toPort: 37030, interface: wifiIp)
- try clientSocket?.beginReceiving()
- // try clientSocket?.joinMulticastGroup("239.255.255.250")
- // try clientSocket?.connect(toHost: "255.255.255.255", onPort: 37030)
- let command = "scanning".data(using: .utf8)
- //let command = "12a10100b4".data(using: .utf8)
- // 0x01 0xb4 0x04 0xb7
-
- //"ip\":\"10.0.0.9\",\n\t\"port\":\"37032\
- //239.255.255.250 37030
- clientSocket?.send(command!, toHost: "239.255.255.250", port: 37030, withTimeout: -1, tag: 0)
- isOnce = true
-
- }catch{
- HUD.flash(.label("绑定失败"), delay: 0.6)
- log.debug("绑定失败\(error)")
- }
- }
-
-
- // 获取当前wifi的IP地址
- func getLocalIPAddressForCurrentWiFi() -> String? {
- var address: String?
-
- // get list of all interfaces on the local machine
- var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil
- guard getifaddrs(&ifaddr) == 0 else {
- return nil
- }
- guard let firstAddr = ifaddr else {
- return nil
- }
- for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
-
- let interface = ifptr.pointee
-
- // Check for IPV4 or IPV6 interface
- let addrFamily = interface.ifa_addr.pointee.sa_family
- if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
- // Check interface name
- let name = String(cString: interface.ifa_name)
- if name == "en0" {
-
- // Convert interface address to a human readable string
- var addr = interface.ifa_addr.pointee
- var hostName = [CChar](repeating: 0, count: Int(NI_MAXHOST))
- getnameinfo(&addr, socklen_t(interface.ifa_addr.pointee.sa_len), &hostName, socklen_t(hostName.count), nil, socklen_t(0), NI_NUMERICHOST)
- address = String(cString: hostName)
- }
- }
- }
- freeifaddrs(ifaddr)
- return address
- }
-
- deinit {
- NotificationCenter.default.removeObserver(self)
- }
-
- @objc func notifyRegisterSuccess(_ notifaction : Notification){
- let username = notifaction.object as! String
- self.accountTextField.text = username
- self.passwordTextField.text = ""
- }
- @objc func notifyClearPassword() {
- self.passwordTextField.text = ""
- }
-
- @objc func notifyChangeRole(notif:Notification){
- let role = notif.object as? String
-
- if role == "1" {
- self.tipsLabel.text = "Login as an administrator !"
- // self.signUpBtn.isHidden = true
- self.authorityBtn.isSelected = true
-
- }else{
- self.tipsLabel.text = "The best service for you !"
- //self.signUpBtn.isHidden = false
- self.authorityBtn.isSelected = false
- }
- }
- override func layoutSubviews() {
- super.layoutSubviews()
- //xib的frame需要在layoutsubViews中设置 不然有问题
- frame = CGRect(x: 0, y: 0, width: KSCREENWIDTH, height: KSCREENHEIGHT)
- }
-
- @IBAction func installBtn(_ sender: UIButton) {
- //发送命令
- sendCommandGetGateway()
- HUD.flash(.progress)
-
-
-
-
- // self.loginDelegate?.jumpToClassgatewayCtr?(gatewayList: modelList)
-
- // if isSearchGateway == true && modelList.count > 0{
- // HUD.hide()
- // self.loginDelegate?.jumpToClassgatewayCtr?(gatewayList: modelList)
- // }else{
- // HUD.flash(.label("未发现网关"), delay: 0.5)
- // }
-
- }
-
- @IBAction func signInAction(_ sender: Any) {
-
- if let delegate = loginDelegate {
- delegate.signIn?(with: self.accountTextField.text, password: self.passwordTextField.text)
- }
- }
- //325 850 850
- @IBAction func privacyPolicyAction(_ sender: Any) {
- if let delegate = loginDelegate {
- delegate.goPrivacyPolicy?()
- }
-
- }
-
- @IBAction func signUpAction(_ sender: Any) {
- if let delegate = loginDelegate {
- delegate.signUp?()
- }
- }
-
- @IBAction func authoritySelected(_ sender: UIButton) {
- sender.isSelected = !sender.isSelected
- if sender.isSelected == true {
- self.tipsLabel.text = "Login as an administrator !"
- // self.signUpBtn.isHidden = true
- if let delegate = loginDelegate {
- delegate.changeAuthority?(1)
- }
- }else{
- self.tipsLabel.text = "The best service for you !"
- // self.signUpBtn.isHidden = false
- if let delegate = loginDelegate {
- delegate.changeAuthority?(0)
- }
- }
- }
- //这里已废弃
- func authoritySelected(_ role: String) {
- if role == "1" {
- self.tipsLabel.text = "Login as an administrator !"
- // self.signUpBtn.isHidden = true
- }else{
- self.tipsLabel.text = "The best service for you !"
- // self.signUpBtn.isHidden = false
- }
- }
- @IBAction func privacySelected(_ sender: UIButton) {
- sender.isSelected = !sender.isSelected
- if sender.isSelected == true {
- signInBtn.isEnabled = true
- signInBtn.backgroundColor = UIColor(hexString: "#573F95")
- }else{
- signInBtn.isEnabled = false
- signInBtn.backgroundColor = UIColor.lightGray
- }
- }
-
-
-
- }
- extension IHLoginView:GCDAsyncUdpSocketDelegate{
-
- func udpSocket(_ sock: GCDAsyncUdpSocket, didNotConnect error: Error?) {
- log.debug("didNotConnect")
- }
-
- func udpSocket(_ sock: GCDAsyncUdpSocket, didConnectToAddress address: Data) {
- log.debug("didConnectToAddress:\(String(data: address, encoding: String.Encoding.utf8))")
-
- }
- func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?) {
-
- let result = data.string(encoding: .utf8)
- // isSearchGateway = true
- if let result = result{
- // for i in 0..<15 {
- // var model = gatewayInfor()
- // model.SN = "EE20200807000\(i)"
- // model.SW = "1.0.2.30"
- // model.HW = "0003AA01"
- // model.ip = "10.0.0.9"
- // model.port = "37032"
- // modelList.append(model)
- // }
-
-
- if result != "scanning" {
- modelList.removeAll()
-
- log.debug("网关返回的信息:\(result)")
- do {
- modelList.removeAll()
- let json = try JSON(data: data)
- var model = gatewayInfor()
- //"{\n\t\"SN\":\"EE202008070001\",\n\t\"SW\":\"1.0.2.30\",\n\t\"HW\":\"0003AA01\",\n\t\"ip\":\"10.0.0.9\",\n\t\"port\":\"37032\"\n\t}")
- model.SN = json["SN"].stringValue
- model.SW = json["SW"].stringValue
- model.HW = json["HW"].stringValue
- model.ip = json["ip"].stringValue
- model.port = json["port"].string
- modelList.append(model)
-
-
- } catch {
-
- }
- }
- }
-
-
-
- HUD.hide()
- if modelList.count > 0 {
- self.loginDelegate?.jumpToClassgatewayCtr?(gatewayList: modelList)
-
- }else{
- HUD.flash(.label("未发现网关"), delay: 0.5)
- }
- log.debug("didReceive:\(result)")
- }
- func udpSocket(_ sock: GCDAsyncUdpSocket, didSendDataWithTag tag: Int) {
- log.debug("didSendDataWithTag")
-
- // DispatchQueue.main.asyncAfter(deadline: .now()+1) {
- //
- // }
- }
- func udpSocketDidClose(_ sock: GCDAsyncUdpSocket, withError error: Error?) {
- log.debug("withError")
- }
- func udpSocket(_ sock: GCDAsyncUdpSocket, didNotSendDataWithTag tag: Int, dueToError error: Error?) {
- log.debug("didNotSendDataWithTag")
- }
-
- }
- extension IHLoginView:UITextFieldDelegate{
- // func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
- // let currentText = accountTextField.text ?? ""
- // let newText = (currentText as NSString).replacingCharacters(in: range, with: string)
- // if newText == "" {
- // self.passwordTextField.text = ""
- // }
- // return true
- // }
- }
|