IHLightCommandService.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. //
  2. // IHLightCommandService.swift
  3. // Inhealth
  4. //
  5. // Created by weclouds on 2020/8/27.
  6. // Copyright © 2020 weclouds. All rights reserved.
  7. //
  8. import UIKit
  9. import PKHUD
  10. let KNotifiSetLightBrightAndColor = "KNotifiSetLightBrightAndColor"
  11. let KNotifiDeviceTurnOn = "KNotifiDeviceTurnOn"
  12. class IHLightCommandService: NSObject {
  13. static let share : IHLightCommandService = IHLightCommandService()
  14. private lazy var clientSocket: GCDAsyncUdpSocket? = {
  15. var mainQueue = DispatchQueue.main
  16. var clientSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: mainQueue)
  17. return clientSocket
  18. }()
  19. var light : (address: String, type: String, location: String)?
  20. var bright : String?
  21. var colorT : String?
  22. var isTurnOn : Bool = false
  23. var operationLightState : Bool = false
  24. deinit {
  25. log.debug("IHLightCommandService销毁")
  26. clientSocket = nil
  27. }
  28. //开关灯(485/cw)
  29. func setCWOrOtherLightTurnOn(isTurnOn : Bool, device : (address: String, type: String,location : String), ip : String, port : String) {
  30. operationLightState = isTurnOn
  31. light = device
  32. if device.type == "31" {
  33. //485
  34. //[0x12, 0xa1, 0x52, 0x03,0x01,0x17,0x00,0x20]
  35. // isDelete = false
  36. // isAdd = false
  37. self.isTurnOn = true
  38. // isCwLight = false
  39. let addressArr = hexStringConvertToDecimal(hexString: device.address)
  40. var bytes: [UInt8] = [18, 161, 82, 3,addressArr[0],addressArr[1]]
  41. if isTurnOn == false {
  42. //关
  43. bytes.append(0)
  44. }else{
  45. bytes.append(80)
  46. }
  47. setCommand(bytesArr: bytes, ip: ip, port: port)
  48. }else{
  49. //cw
  50. //[0x12, 0xa1, 0x5A,0x04, 0x01,0x17,0x1e,0x1e,0x65]
  51. // isDelete = false
  52. // isAdd = false
  53. self.isTurnOn = true
  54. // isCwLight = true
  55. let addressArr = hexStringConvertToDecimal(hexString: device.address)
  56. var bytes: [UInt8] = [18, 161, 90, 4,addressArr[0],addressArr[1]]
  57. if isTurnOn == false {
  58. //关
  59. bytes.append(0)
  60. bytes.append(0)
  61. }else{
  62. bytes.append(255)
  63. bytes.append(255)
  64. }
  65. setCommand(bytesArr: bytes, ip: ip, port: port)
  66. }
  67. }
  68. //设置不是485灯的亮度与色温
  69. func setLightCWBrightnessAndColorValue(device : (address: String, type: String, location: String),brightness: String, color: String, ip : String, port : String,isColor : Bool) {
  70. //[0x12, 0xa1, 0x01, 0x00,0xb4] 0001010c
  71. self.light = device
  72. self.bright = brightness
  73. self.colorT = color
  74. if device.type != "31" {
  75. //不是485
  76. let addressArr = hexStringConvertToDecimal(hexString: device.address)
  77. var bytes: [UInt8] = [18, 161, 90, 4,addressArr[0],addressArr[1]]
  78. // let bright = hexStringToInt(from: brightness)
  79. // let color = hexStringToInt(from: color)
  80. let bright = Int(brightness)!
  81. let colorT = Int(color)!
  82. bytes.append(UInt8(bright))
  83. bytes.append(UInt8(colorT))
  84. setCommand(bytesArr: bytes, ip: ip, port: port)
  85. }else{
  86. //485
  87. if isColor == true {
  88. //调色温
  89. //调亮度
  90. let addressArr = hexStringConvertToDecimal(hexString: device.address)
  91. var bytes: [UInt8] = [18, 161, 83, 3,addressArr[0],addressArr[1]]
  92. let colorT = Int(color)!
  93. bytes.append(UInt8(colorT))
  94. setCommand(bytesArr: bytes, ip: ip, port: port)
  95. }else{
  96. //调亮度
  97. let addressArr = hexStringConvertToDecimal(hexString: device.address)
  98. var bytes: [UInt8] = [18, 161, 82, 3,addressArr[0],addressArr[1]]
  99. let bright = Int(brightness)!
  100. bytes.append(UInt8(bright))
  101. setCommand(bytesArr: bytes, ip: ip, port: port)
  102. }
  103. }
  104. // do{
  105. //
  106. // //不连接,直接发命令
  107. // try clientSocket?.enableBroadcast(true)
  108. // try clientSocket?.beginReceiving() // 0117-设备地址
  109. // //[0x12, 0xa1, 0x52, 0x06,0x01,0x17,0x10,0x33]
  110. // //"12a1 01 05 01 0001010c c8"
  111. // //12a10203 011d 0400000000da
  112. //
  113. // let addressArr = hexStringConvertToDecimal(hexString: address)
  114. // var bytes: [UInt8] = [18, 161, 90, 4,addressArr[0],addressArr[1]]
  115. //// let bright = hexStringToInt(from: brightness)
  116. //// let color = hexStringToInt(from: color)
  117. // let bright = Int(brightness)!
  118. // let colorT = Int(color)!
  119. // bytes.append(UInt8(bright))
  120. // bytes.append(UInt8(colorT))
  121. // let totalStr = deciConvertHexStr(deciArr: bytes)
  122. // let sum = checksum(command: totalStr)
  123. // let dec = hexStringToInt(from: sum)
  124. // bytes.append(UInt8(dec))
  125. //
  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. //
  130. // }catch{
  131. // log.debug("绑定失败\(error)")
  132. // }
  133. }
  134. private func setCommand(bytesArr : [UInt8], ip : String,port : String){
  135. do{
  136. //不连接,直接发命令
  137. try clientSocket?.enableBroadcast(true)
  138. try clientSocket?.beginReceiving() // 0117-设备地址
  139. var bytes = bytesArr
  140. let totalStr = deciConvertHexStr(deciArr: bytes)
  141. let sum = checksum(command: totalStr)
  142. let dec = hexStringToInt(from: sum)
  143. bytes.append(UInt8(dec))
  144. let command: Data = Data.init(bytes: bytes, count: bytes.count)
  145. // self.vc?.gateway?.ip! self.vc?.gateway?.port
  146. clientSocket?.send(command, toHost: ip, port:UInt16(port)! , withTimeout: -1, tag: 0)
  147. }catch{
  148. log.debug("绑定失败\(error)")
  149. }
  150. }
  151. //添加设备到网关
  152. // func addDeviceToGateway(deviceUUid : String,ip : String, port : String){
  153. // //[0x12, 0xa1, 0x01, 0x00,0xb4] 0001010c
  154. // let uuidArr = hexStringConvertToDecimal(hexString: deviceUUid)
  155. // let bytes: [UInt8] = [18, 161, 2, 5,1,uuidArr[0],uuidArr[1],uuidArr[2],uuidArr[3]]
  156. // setCommand(bytesArr: bytes, ip: ip, port: port)
  157. //
  158. //
  159. //// do{
  160. ////
  161. //// //不连接,直接发命令
  162. //// try clientSocket?.enableBroadcast(true)
  163. //// try clientSocket?.beginReceiving() // 0117-设备地址
  164. //// //[0x12, 0xa1, 0x52, 0x06,0x01,0x17,0x10,0x33]
  165. //// //"12a1 01 05 01 0001010c c8"
  166. //// //12a10203 011d 0400000000da
  167. //// //[0x12, 0xa1, 0x02, 0x05,0x01,0x00,0x01,0x01,0x69,0x26]
  168. //// let uuidArr = hexStringConvertToDecimal(hexString: deviceUUid)
  169. //// var bytes: [UInt8] = [18, 161, 2, 5,1,uuidArr[0],uuidArr[1],uuidArr[2],uuidArr[3]]
  170. //// let totalStr = deciConvertHexStr(deciArr: bytes)
  171. //// let sum = checksum(command: totalStr)
  172. //// let dec = hexStringToInt(from: sum)
  173. //// bytes.append(UInt8(dec))
  174. ////
  175. //// let command: Data = Data.init(bytes: bytes, count: bytes.count)
  176. //// // self.vc?.gateway?.ip! self.vc?.gateway?.port
  177. //// clientSocket?.send(command, toHost: ip, port:UInt16(port)! , withTimeout: -1, tag: 0)
  178. ////
  179. //// }catch{
  180. //// log.debug("绑定失败\(error)")
  181. //// }
  182. // }
  183. }
  184. extension IHLightCommandService : GCDAsyncUdpSocketDelegate{
  185. func udpSocket(_ sock: GCDAsyncUdpSocket, didNotConnect error: Error?) {
  186. log.debug("didNotConnect")
  187. }
  188. func udpSocket(_ sock: GCDAsyncUdpSocket, didConnectToAddress address: Data) {
  189. log.debug("didConnectToAddress:\(String(data: address, encoding: String.Encoding.utf8))")
  190. }
  191. func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?) {
  192. // HUD.hide()
  193. //12 A1 04 01 00 B8
  194. let hexStr = dataConvertToHexString(data: data)
  195. if isTurnOn == false {
  196. //调节灯的亮度与色温
  197. adjustLampBrightnessAndColor(respondStr: hexStr)
  198. }else{
  199. //灯的开关
  200. turnOffLight(respondStr: hexStr)
  201. }
  202. log.debug("didReceive")
  203. }
  204. func udpSocket(_ sock: GCDAsyncUdpSocket, didSendDataWithTag tag: Int) {
  205. log.debug("didSendDataWithTag")
  206. // DispatchQueue.main.asyncAfter(deadline: .now()+1) {
  207. //
  208. // }
  209. }
  210. func udpSocketDidClose(_ sock: GCDAsyncUdpSocket, withError error: Error?) {
  211. log.debug("withError")
  212. }
  213. func udpSocket(_ sock: GCDAsyncUdpSocket, didNotSendDataWithTag tag: Int, dueToError error: Error?) {
  214. log.debug("didNotSendDataWithTag")
  215. }
  216. }
  217. extension IHLightCommandService{
  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(KNotifiDeviceTurnOn), object: nil, userInfo: ["turnOn" :(oldDevice : light,state : isfail,turnOn : isfail == true ? operationLightState : !operationLightState)])
  239. // NotificationCenter.default.post(name: NSNotification.Name(KNotifiTurnOnLightFalse), object: nil)
  240. }
  241. //调节CW灯的亮度与色温
  242. func adjustLampBrightnessAndColor(respondStr: String){
  243. //"12a1 5a 03 0117 0028"
  244. let str = respondStr as NSString
  245. let componeStr = str.substring(with: NSRange.init(location: 12, length: 2))
  246. if componeStr == "00" {
  247. //成功
  248. log.debug("调节成功")
  249. HUD.flash(.label("成功"), delay: 0.7)
  250. //保存
  251. let defaults = UserDefaults.standard
  252. let arrDevice = defaults.object(forKey: "saveDeviceList") as? [[String : String]]
  253. if let arrDevice = arrDevice {
  254. var newDevice = [[String : String]]()
  255. newDevice = arrDevice
  256. if arrDevice.count > 0 {
  257. for (index,subDic) in arrDevice.enumerated() {
  258. let address = subDic["address"]!
  259. let type = subDic["type"]!
  260. // let bright = subDic["bright"]!
  261. // let color = subDic["color"]
  262. if self.light!.address == address{
  263. //485 address,type,bright,color
  264. newDevice.remove(at: index)
  265. newDevice.append(["address":address,"type" : type, "bright" : self.bright!, "color" : self.colorT!])
  266. break
  267. }
  268. }
  269. }
  270. defaults.set(newDevice, forKey: "saveDeviceList")
  271. defaults.synchronize()
  272. }
  273. }else{
  274. //失败
  275. log.debug("调节失败")
  276. HUD.flash(.label("失败"), delay: 0.7)
  277. }
  278. NotificationCenter.default.post(name: NSNotification.Name(KNotifiSetLightBrightAndColor), object: nil)
  279. }
  280. }