IHLoginView.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. //
  2. // IHLoginView.swift
  3. // Inhealth
  4. //
  5. // Created by weclouds on 2019/12/10.
  6. // Copyright © 2019 weclouds. All rights reserved.
  7. //
  8. import UIKit
  9. import PKHUD
  10. import SwiftyJSON
  11. //清楚password
  12. let kNotificationIHLoginViewClearPassword = "kNotificationIHLoginViewClearPassword"
  13. //改变角色
  14. let kNotifactionIHLoginViewChangeRole = "kNotifactionIHLoginViewChangeRole"
  15. @objc protocol IHLoginViewDelegate : NSObjectProtocol{
  16. @objc optional func signIn(with account:String?,password:String?)
  17. @objc optional func signUp()
  18. //role ;0表示客人 账户 1 表示管理员账户
  19. @objc optional func changeAuthority(_ role:Int)
  20. @objc optional func goPrivacyPolicy()
  21. @objc optional func jumpToClassgatewayCtr(gatewayList list : [Any])
  22. }
  23. class IHLoginView: UIView {
  24. weak var loginDelegate : IHLoginViewDelegate?
  25. var role :String? = "0"{
  26. didSet{
  27. //管理员
  28. if let role = self.role {
  29. authoritySelected(role)
  30. }
  31. }
  32. }
  33. lazy var clientSocket: GCDAsyncUdpSocket? = {
  34. var mainQueue = DispatchQueue.main
  35. var clientSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: mainQueue)
  36. return clientSocket
  37. }()
  38. var modelList = [gatewayInfor]()
  39. //提示框
  40. @IBOutlet weak var tipsLabel: UILabel! // 提示语
  41. @IBOutlet weak var accountTextField: UITextField!
  42. @IBOutlet weak var passwordTextField: UITextField!
  43. //权限选择按钮
  44. @IBOutlet weak var authorityBtn: UIButton!
  45. @IBOutlet weak var signInBtn: UIButton!
  46. //注册按钮
  47. @IBOutlet weak var signUpBtn: UIButton!
  48. @IBOutlet weak var privacyBtn: UIButton!
  49. var isSearchGateway : Bool = false
  50. var isOnce : Bool = false
  51. func hexStringToInt(from:String) -> Int {
  52. let str = from.uppercased()
  53. var sum = 0
  54. for i in str.utf8 {
  55. sum = sum * 16 + Int(i) - 48 // 0-9 从48开始
  56. if i >= 65 { // A-Z 从65开始,但有初始值10,所以应该是减去55
  57. sum -= 7
  58. }
  59. }
  60. return sum
  61. }
  62. override func awakeFromNib() {
  63. super.awakeFromNib()
  64. // let str = "12a102050100010169" as NSString
  65. // let count = str.length / 2
  66. // var arr = [Int]()
  67. // for i in 0..<count {
  68. // let subStr = str.substring(with: NSRange.init(location: i * 2, length: 2))
  69. //
  70. // let hex = hexStringToInt(from: subStr)
  71. // arr.append(hex)
  72. // }
  73. // let str = "12a102050100010169" as NSString
  74. // let count = str.length / 2
  75. // var sum = 0x0
  76. // for i in 0..<count {
  77. // let subStr = str.substring(with: NSRange.init(location: i * 2, length: 2))
  78. // sum = sum + hexStringToInt(from: subStr)
  79. // }
  80. // //10进制转换成16进制
  81. // let hexStr = String(sum,radix:16) as NSString
  82. // let kk = hexStr.substring(with: NSRange.init(location: hexStr.length - 2, length: 2))
  83. // log.debug("kkdkk:\(kk)")
  84. //从沙盒中取出
  85. let username = IHHotelStorage.shareInstance.getStorageUsername()
  86. let password = IHHotelStorage.shareInstance.getStoragePassword()
  87. let _role = IHHotelStorage.shareInstance.getStorageRole()
  88. if username != nil && password != nil{
  89. accountTextField.text = username
  90. passwordTextField.text = password
  91. }
  92. if role != nil {
  93. self.role = _role
  94. }
  95. //添加通知
  96. NotificationCenter.default.addObserver(self, selector: #selector(notifyClearPassword), name: NSNotification.Name(kNotificationIHLoginViewClearPassword), object: nil)
  97. NotificationCenter.default.addObserver(self, selector: #selector(notifyChangeRole(notif:)), name:NSNotification.Name(kNotifactionIHLoginViewChangeRole), object: nil)
  98. NotificationCenter.default.addObserver(self, selector: #selector(notifyRegisterSuccess(_:)), name: NSNotification.Name(kNotifactionRegisterSuccess), object: nil)
  99. // 设置UI
  100. signUpBtn.set(image: UIImage(named: "箭头"), title: "注 册", titlePosition: .left, additionalSpacing: 10, state: .normal)
  101. self.authorityBtn.setTitle("I Am Hotel Guests", for: .selected)
  102. self.authorityBtn.setTitle("我是管理员", for: .normal)
  103. let privacyStr = "阅读并同意《用户隐私协议》"
  104. let text = NSMutableAttributedString(string: privacyStr)
  105. //#657085
  106. let attrs = [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue,NSAttributedString.Key.foregroundColor : UIColor(hexString: "#657085") as Any] as [NSAttributedString.Key : Any]
  107. //#657085
  108. let attrs2 = [NSAttributedString.Key.foregroundColor: UIColor(hexString: "#657085")]
  109. text.addAttributes(attrs, range: NSRange(location: 13, length: text.length - 13))
  110. text.addAttributes(attrs2 as [NSAttributedString.Key : Any], range: NSRange(location: 0, length: text.length))
  111. privacyBtn.setAttributedTitle(text, for: .normal)
  112. accountTextField.delegate = self
  113. passwordTextField.delegate = self
  114. // sendCommandGetGateway()
  115. //getCommandGetGateway()
  116. }
  117. func getCommandGetGateway() {
  118. let udp = IHUdpRequest.init()
  119. udp.sendCommandGetGateway()
  120. udp.complete = { gatewayInfors in
  121. self.modelList = gatewayInfors
  122. }
  123. }
  124. func sendCommandGetGateway(){
  125. do{
  126. //不连接,直接发命令
  127. // let connected = clientSocket?.isConnected()
  128. // if connected == false {
  129. // }
  130. try clientSocket?.enableBroadcast(true)
  131. let wifiIp = getLocalIPAddressForCurrentWiFi()
  132. //第二次就不用了,直接使用这个
  133. if isOnce == false{
  134. try clientSocket?.bind(toPort: 37030)
  135. try clientSocket?.joinMulticastGroup("239.255.255.250")
  136. }
  137. //第一次要绑定interface,后面就不用了
  138. // try clientSocket?.bind(toPort: 37030, interface: wifiIp)
  139. try clientSocket?.beginReceiving()
  140. // try clientSocket?.joinMulticastGroup("239.255.255.250")
  141. // try clientSocket?.connect(toHost: "255.255.255.255", onPort: 37030)
  142. let command = "scanning".data(using: .utf8)
  143. //let command = "12a10100b4".data(using: .utf8)
  144. // 0x01 0xb4 0x04 0xb7
  145. //"ip\":\"10.0.0.9\",\n\t\"port\":\"37032\
  146. //239.255.255.250 37030
  147. clientSocket?.send(command!, toHost: "239.255.255.250", port: 37030, withTimeout: -1, tag: 0)
  148. isOnce = true
  149. }catch{
  150. HUD.flash(.label("绑定失败"), delay: 0.6)
  151. log.debug("绑定失败\(error)")
  152. }
  153. }
  154. // 获取当前wifi的IP地址
  155. func getLocalIPAddressForCurrentWiFi() -> String? {
  156. var address: String?
  157. // get list of all interfaces on the local machine
  158. var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil
  159. guard getifaddrs(&ifaddr) == 0 else {
  160. return nil
  161. }
  162. guard let firstAddr = ifaddr else {
  163. return nil
  164. }
  165. for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
  166. let interface = ifptr.pointee
  167. // Check for IPV4 or IPV6 interface
  168. let addrFamily = interface.ifa_addr.pointee.sa_family
  169. if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
  170. // Check interface name
  171. let name = String(cString: interface.ifa_name)
  172. if name == "en0" {
  173. // Convert interface address to a human readable string
  174. var addr = interface.ifa_addr.pointee
  175. var hostName = [CChar](repeating: 0, count: Int(NI_MAXHOST))
  176. getnameinfo(&addr, socklen_t(interface.ifa_addr.pointee.sa_len), &hostName, socklen_t(hostName.count), nil, socklen_t(0), NI_NUMERICHOST)
  177. address = String(cString: hostName)
  178. }
  179. }
  180. }
  181. freeifaddrs(ifaddr)
  182. return address
  183. }
  184. deinit {
  185. NotificationCenter.default.removeObserver(self)
  186. }
  187. @objc func notifyRegisterSuccess(_ notifaction : Notification){
  188. let username = notifaction.object as! String
  189. self.accountTextField.text = username
  190. self.passwordTextField.text = ""
  191. }
  192. @objc func notifyClearPassword() {
  193. self.passwordTextField.text = ""
  194. }
  195. @objc func notifyChangeRole(notif:Notification){
  196. let role = notif.object as? String
  197. if role == "1" {
  198. self.tipsLabel.text = "Login as an administrator !"
  199. // self.signUpBtn.isHidden = true
  200. self.authorityBtn.isSelected = true
  201. }else{
  202. self.tipsLabel.text = "The best service for you !"
  203. //self.signUpBtn.isHidden = false
  204. self.authorityBtn.isSelected = false
  205. }
  206. }
  207. override func layoutSubviews() {
  208. super.layoutSubviews()
  209. //xib的frame需要在layoutsubViews中设置 不然有问题
  210. frame = CGRect(x: 0, y: 0, width: KSCREENWIDTH, height: KSCREENHEIGHT)
  211. }
  212. @IBAction func installBtn(_ sender: UIButton) {
  213. //发送命令
  214. sendCommandGetGateway()
  215. HUD.flash(.progress)
  216. // self.loginDelegate?.jumpToClassgatewayCtr?(gatewayList: modelList)
  217. // if isSearchGateway == true && modelList.count > 0{
  218. // HUD.hide()
  219. // self.loginDelegate?.jumpToClassgatewayCtr?(gatewayList: modelList)
  220. // }else{
  221. // HUD.flash(.label("未发现网关"), delay: 0.5)
  222. // }
  223. }
  224. @IBAction func signInAction(_ sender: Any) {
  225. if let delegate = loginDelegate {
  226. delegate.signIn?(with: self.accountTextField.text, password: self.passwordTextField.text)
  227. }
  228. }
  229. //325 850 850
  230. @IBAction func privacyPolicyAction(_ sender: Any) {
  231. if let delegate = loginDelegate {
  232. delegate.goPrivacyPolicy?()
  233. }
  234. }
  235. @IBAction func signUpAction(_ sender: Any) {
  236. if let delegate = loginDelegate {
  237. delegate.signUp?()
  238. }
  239. }
  240. @IBAction func authoritySelected(_ sender: UIButton) {
  241. sender.isSelected = !sender.isSelected
  242. if sender.isSelected == true {
  243. self.tipsLabel.text = "Login as an administrator !"
  244. // self.signUpBtn.isHidden = true
  245. if let delegate = loginDelegate {
  246. delegate.changeAuthority?(1)
  247. }
  248. }else{
  249. self.tipsLabel.text = "The best service for you !"
  250. // self.signUpBtn.isHidden = false
  251. if let delegate = loginDelegate {
  252. delegate.changeAuthority?(0)
  253. }
  254. }
  255. }
  256. //这里已废弃
  257. func authoritySelected(_ role: String) {
  258. if role == "1" {
  259. self.tipsLabel.text = "Login as an administrator !"
  260. // self.signUpBtn.isHidden = true
  261. }else{
  262. self.tipsLabel.text = "The best service for you !"
  263. // self.signUpBtn.isHidden = false
  264. }
  265. }
  266. @IBAction func privacySelected(_ sender: UIButton) {
  267. sender.isSelected = !sender.isSelected
  268. if sender.isSelected == true {
  269. signInBtn.isEnabled = true
  270. signInBtn.backgroundColor = UIColor(hexString: "#573F95")
  271. }else{
  272. signInBtn.isEnabled = false
  273. signInBtn.backgroundColor = UIColor.lightGray
  274. }
  275. }
  276. }
  277. extension IHLoginView:GCDAsyncUdpSocketDelegate{
  278. func udpSocket(_ sock: GCDAsyncUdpSocket, didNotConnect error: Error?) {
  279. log.debug("didNotConnect")
  280. }
  281. func udpSocket(_ sock: GCDAsyncUdpSocket, didConnectToAddress address: Data) {
  282. log.debug("didConnectToAddress:\(String(data: address, encoding: String.Encoding.utf8))")
  283. }
  284. func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?) {
  285. let result = data.string(encoding: .utf8)
  286. // isSearchGateway = true
  287. if let result = result{
  288. // for i in 0..<15 {
  289. // var model = gatewayInfor()
  290. // model.SN = "EE20200807000\(i)"
  291. // model.SW = "1.0.2.30"
  292. // model.HW = "0003AA01"
  293. // model.ip = "10.0.0.9"
  294. // model.port = "37032"
  295. // modelList.append(model)
  296. // }
  297. if result != "scanning" {
  298. modelList.removeAll()
  299. log.debug("网关返回的信息:\(result)")
  300. do {
  301. modelList.removeAll()
  302. let json = try JSON(data: data)
  303. var model = gatewayInfor()
  304. //"{\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}")
  305. model.SN = json["SN"].stringValue
  306. model.SW = json["SW"].stringValue
  307. model.HW = json["HW"].stringValue
  308. model.ip = json["ip"].stringValue
  309. model.port = json["port"].string
  310. modelList.append(model)
  311. } catch {
  312. }
  313. }
  314. }
  315. HUD.hide()
  316. if modelList.count > 0 {
  317. self.loginDelegate?.jumpToClassgatewayCtr?(gatewayList: modelList)
  318. }else{
  319. HUD.flash(.label("未发现网关"), delay: 0.5)
  320. }
  321. log.debug("didReceive:\(result)")
  322. }
  323. func udpSocket(_ sock: GCDAsyncUdpSocket, didSendDataWithTag tag: Int) {
  324. log.debug("didSendDataWithTag")
  325. // DispatchQueue.main.asyncAfter(deadline: .now()+1) {
  326. //
  327. // }
  328. }
  329. func udpSocketDidClose(_ sock: GCDAsyncUdpSocket, withError error: Error?) {
  330. log.debug("withError")
  331. }
  332. func udpSocket(_ sock: GCDAsyncUdpSocket, didNotSendDataWithTag tag: Int, dueToError error: Error?) {
  333. log.debug("didNotSendDataWithTag")
  334. }
  335. }
  336. extension IHLoginView:UITextFieldDelegate{
  337. // func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
  338. // let currentText = accountTextField.text ?? ""
  339. // let newText = (currentText as NSString).replacingCharacters(in: range, with: string)
  340. // if newText == "" {
  341. // self.passwordTextField.text = ""
  342. // }
  343. // return true
  344. // }
  345. }