IHConfigGatewayDetailService.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. //
  2. // IHConfigGatewayDetailService.swift
  3. // Inhealth
  4. //
  5. // Created by weclouds on 2020/8/26.
  6. // Copyright © 2020 weclouds. All rights reserved.
  7. //
  8. import UIKit
  9. import PKHUD
  10. let KNotifiAddDeviceToGateway = "KNotifiAddDeviceToGateway"
  11. let KNotifiDeleteDeviceFromGateway = "KNotifiDeleteDeviceFromGateway"
  12. let KNotifiTurnOnLightFalse = "KNotifiTurnOnLightFalse"
  13. class IHConfigGatewayDetailService: NSObject {
  14. static let share : IHConfigGatewayDetailService = IHConfigGatewayDetailService()
  15. private lazy var clientSocket: GCDAsyncUdpSocket? = {
  16. var mainQueue = DispatchQueue.main
  17. var clientSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: DispatchQueue.global())
  18. return clientSocket
  19. }()
  20. var isDelete : Bool = false //删除设备
  21. var isAdd : Bool = false //添加设备
  22. var deleteAddress : String?
  23. var isTurnOn : Bool = false //开关灯
  24. var isCwLight : Bool = false //是什么类型的灯
  25. var operationLightState : Bool = false //关/开灯
  26. var light : (address: String, type: String)?
  27. var isModel : Bool = false
  28. deinit {
  29. log.debug("IHConfigGatewayDetailService销毁")
  30. }
  31. //485灯的传感器工作模式
  32. func setLightWorkModel(device : (address: String, type: String),dodgeEnable: String, bodyEnable: String, ip : String, port : String) {
  33. isModel = true
  34. light = device
  35. let addressArr = hexStringConvertToDecimal(hexString: device.address)
  36. var bytes: [UInt8] = [18, 161, 85, 4,addressArr[0],addressArr[1]]
  37. bytes.append(UInt8(dodgeEnable)!)
  38. bytes.append(UInt8(bodyEnable)!)
  39. setCommand( device: device, byteArr: bytes, ip: ip, port: port)
  40. }
  41. //开关灯(485/cw)
  42. func setCWOrOtherLightTurnOn(isTurnOn : Bool, device : (address: String, type: String), ip : String, port : String) {
  43. operationLightState = isTurnOn
  44. light = device
  45. if device.type == "31" {
  46. //485
  47. //[0x12, 0xa1, 0x52, 0x03,0x01,0x17,0x00,0x20]
  48. isDelete = false
  49. isAdd = false
  50. self.isTurnOn = true
  51. isCwLight = false
  52. let addressArr = hexStringConvertToDecimal(hexString: device.address)
  53. var bytes: [UInt8] = [18, 161, 82, 3,addressArr[0],addressArr[1]]
  54. if isTurnOn == false {
  55. //关
  56. bytes.append(0)
  57. }else{
  58. bytes.append(80)
  59. }
  60. setCommand( device: device, byteArr: bytes, ip: ip, port: port)
  61. }else{
  62. //cw
  63. //[0x12, 0xa1, 0x5A,0x04, 0x01,0x17,0x1e,0x1e,0x65]
  64. isDelete = false
  65. isAdd = false
  66. self.isTurnOn = true
  67. isCwLight = true
  68. let addressArr = hexStringConvertToDecimal(hexString: device.address)
  69. var bytes: [UInt8] = [18, 161, 90, 4,addressArr[0],addressArr[1]]
  70. if isTurnOn == false {
  71. //关
  72. bytes.append(0)
  73. bytes.append(0)
  74. }else{
  75. bytes.append(255)
  76. bytes.append(255)
  77. }
  78. setCommand( device: device, byteArr: bytes, ip: ip, port: port)
  79. }
  80. }
  81. private func setCommand( device : (address: String, type: String),byteArr : [UInt8], ip : String, port : String){
  82. do{
  83. //不连接,直接发命令
  84. try clientSocket?.enableBroadcast(true)
  85. try clientSocket?.beginReceiving() // 0117-设备地址
  86. // let addressArr = hexStringConvertToDecimal(hexString: device.address)
  87. // var bytes: [UInt8] = [18, 161, 82, 3,addressArr[0],addressArr[1]]
  88. // if isTurnOn == false {
  89. // //关
  90. // bytes.append(0)
  91. // }else{
  92. // bytes.append(80)
  93. // }
  94. var bytes = [UInt8]()
  95. bytes = byteArr
  96. let totalStr = deciConvertHexStr(deciArr: bytes)
  97. let sum = checksum(command: totalStr)
  98. let dec = hexStringToInt(from: sum)
  99. bytes.append(UInt8(dec))
  100. let command: Data = Data.init(bytes: bytes, count: bytes.count)
  101. // self.vc?.gateway?.ip! self.vc?.gateway?.port
  102. clientSocket?.send(command, toHost: ip, port:UInt16(port)! , withTimeout: -1, tag: 0)
  103. }catch{
  104. log.debug("绑定失败\(error)")
  105. }
  106. }
  107. //删除设备
  108. func deleteDeviceFromGateway(deviceAddress : String, ip : String, port : String) {
  109. //[0x12, 0xa1, 0x01, 0x00,0xb4] 0001010c
  110. do{
  111. isDelete = true
  112. isAdd = false
  113. deleteAddress = deviceAddress
  114. //不连接,直接发命令
  115. try clientSocket?.enableBroadcast(true)
  116. try clientSocket?.beginReceiving() // 0117-设备地址
  117. //[0x12, 0xa1, 0x52, 0x06,0x01,0x17,0x10,0x33]
  118. //"12a1 01 05 01 0001010c c8"
  119. //12a10203 011d 0400000000da
  120. let addressArr = hexStringConvertToDecimal(hexString: deviceAddress)
  121. var bytes: [UInt8] = [18, 161, 3, 2,addressArr[0],addressArr[1]]
  122. let totalStr = deciConvertHexStr(deciArr: bytes)
  123. let sum = checksum(command: totalStr)
  124. let dec = hexStringToInt(from: sum)
  125. bytes.append(UInt8(dec))
  126. let command: Data = Data.init(bytes: bytes, count: bytes.count)
  127. // self.vc?.gateway?.ip! self.vc?.gateway?.port
  128. clientSocket?.send(command, toHost: ip, port:UInt16(port)! , withTimeout: -1, tag: 0)
  129. }catch{
  130. log.debug("绑定失败\(error)")
  131. }
  132. }
  133. //添加设备到网关
  134. func addDeviceToGateway(deviceUUid : String,ip : String, port : String){
  135. //[0x12, 0xa1, 0x01, 0x00,0xb4] 0001010c
  136. do{
  137. isDelete = false
  138. isAdd = true
  139. //不连接,直接发命令
  140. try clientSocket?.enableBroadcast(true)
  141. try clientSocket?.beginReceiving() // 0117-设备地址
  142. //[0x12, 0xa1, 0x52, 0x06,0x01,0x17,0x10,0x33]
  143. //"12a1 01 05 01 0001010c c8"
  144. //12a10203 011d 0400000000da
  145. //[0x12, 0xa1, 0x02, 0x05,0x01,0x00,0x01,0x01,0x69,0x26]
  146. let uuidArr = hexStringConvertToDecimal(hexString: deviceUUid)
  147. var bytes: [UInt8] = [18, 161, 2, 5,1,uuidArr[0],uuidArr[1],uuidArr[2],uuidArr[3]]
  148. let totalStr = deciConvertHexStr(deciArr: bytes)
  149. let sum = checksum(command: totalStr)
  150. let dec = hexStringToInt(from: sum)
  151. bytes.append(UInt8(dec))
  152. let command: Data = Data.init(bytes: bytes, count: bytes.count)
  153. // self.vc?.gateway?.ip! self.vc?.gateway?.port
  154. clientSocket?.send(command, toHost: ip, port:UInt16(port)! , withTimeout: -1, tag: 0)
  155. }catch{
  156. log.debug("绑定失败\(error)")
  157. }
  158. }
  159. }
  160. extension IHConfigGatewayDetailService : GCDAsyncUdpSocketDelegate{
  161. func udpSocket(_ sock: GCDAsyncUdpSocket, didNotConnect error: Error?) {
  162. log.debug("didNotConnect")
  163. }
  164. func udpSocket(_ sock: GCDAsyncUdpSocket, didConnectToAddress address: Data) {
  165. log.debug("didConnectToAddress:\(String(data: address, encoding: String.Encoding.utf8))")
  166. }
  167. func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?) {
  168. //12 A1 04 01 00 B8
  169. let hexStr = dataConvertToHexString(data: data)
  170. if isAdd == true {
  171. //添加设备到网关
  172. addDeviceToGateway(respondStr: hexStr)
  173. }
  174. if isDelete == true {
  175. //删除设备
  176. deleteDevieFromGateway(respondStr : hexStr)
  177. }
  178. if self.isTurnOn == true{
  179. //开关灯
  180. turnOffLight(respondStr : hexStr)
  181. }
  182. if self.isModel == true {
  183. //485灯的传感器工作模式
  184. lightWorkModel(respondStr : hexStr)
  185. }
  186. log.debug("didReceive:\(hexStr)")
  187. }
  188. func udpSocket(_ sock: GCDAsyncUdpSocket, didSendDataWithTag tag: Int) {
  189. log.debug("didSendDataWithTag")
  190. }
  191. func udpSocketDidClose(_ sock: GCDAsyncUdpSocket, withError error: Error?) {
  192. log.debug("withError")
  193. }
  194. func udpSocket(_ sock: GCDAsyncUdpSocket, didNotSendDataWithTag tag: Int, dueToError error: Error?) {
  195. log.debug("didNotSendDataWithTag")
  196. }
  197. }
  198. extension IHConfigGatewayDetailService{
  199. //485灯传感器工作模式
  200. fileprivate func lightWorkModel(respondStr : String){
  201. isModel = false
  202. let respone = respondStr as NSString
  203. let subStr = respone.substring(with: NSRange.init(location: 12, length: 2))
  204. if subStr == "00"{
  205. //保存此灯 deviceWorkModel
  206. let defaults = UserDefaults.standard
  207. let deviceArr = defaults.object(forKey: "deviceWorkModel") as? [[String : String]]
  208. if deviceArr == nil {
  209. defaults.set([["address" : light!.address,"type" : light!.type]], forKey: "deviceWorkModel")
  210. }else{
  211. var newDeviceArr = [[String : String]]()
  212. newDeviceArr = deviceArr!
  213. newDeviceArr.append(["address" : light!.address,"type" : light!.type])
  214. }
  215. defaults.synchronize()
  216. }
  217. }
  218. //开关灯
  219. fileprivate func turnOffLight(respondStr : String){
  220. log.debug()
  221. //"12a15203011f0028"
  222. isTurnOn = false
  223. isCwLight = false
  224. let respone = respondStr as NSString
  225. let subStr = respone.substring(with: NSRange.init(location: 12, length: 2))
  226. var isfail = false
  227. if subStr == "00"{
  228. isfail = true
  229. DispatchQueue.main.async {
  230. HUD.flash(.label("成功"), delay: 0.6)
  231. }
  232. }else{
  233. isfail = false
  234. DispatchQueue.main.async {
  235. HUD.flash(.label("失败"), delay: 0.6)
  236. }
  237. }
  238. NotificationCenter.default.post(name: NSNotification.Name(KNotifiTurnOnLightFalse), object: nil, userInfo: ["turnOn" : (address : self.light?.address,type : self.light?.type,turnOn : isfail == true ? operationLightState : !operationLightState)])
  239. // NotificationCenter.default.post(name: NSNotification.Name(KNotifiTurnOnLightFalse), object: nil)
  240. }
  241. //添加设备到网关
  242. fileprivate func addDeviceToGateway(respondStr: String){
  243. // a.Byte 0-1: sequence number, when replying back, module will have to repeat the same SEQ number.
  244. // b.Byte 2: 0x02.
  245. // c.Byte 3: 2
  246. // d.Byte 4-5: Device Address.
  247. // e.Byte 6: Device Type
  248. // f.Byte 7-8: System Version.
  249. // g.Byte 9-10: Hardware Version.
  250. // h.Byte 11: CheckSum
  251. if respondStr.count == 24 {
  252. // DispatchQueue.main.async {
  253. // HUD.flash(.label("成功"), delay: 0.6)
  254. // }
  255. DispatchQueue.main.async {
  256. NotificationCenter.default.post(name: NSNotification.Name(KNotifiAddDeviceToGateway), object: nil)
  257. }
  258. }else{
  259. DispatchQueue.main.async {
  260. HUD.flash(.label("绑定失败"), delay: 0.6)
  261. }
  262. }
  263. }
  264. //删除设备
  265. fileprivate func deleteDevieFromGateway(respondStr : String){
  266. // deleteAddress
  267. let respone = respondStr as NSString
  268. let subStr = respone.substring(with: NSRange.init(location: 8, length: 4))
  269. if let deleteAddress = deleteAddress{
  270. if subStr == deleteAddress {
  271. NotificationCenter.default.post(name: NSNotification.Name(KNotifiDeleteDeviceFromGateway), object: nil)
  272. }
  273. }
  274. }
  275. }