123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321 |
- //
- // IHLightCommandService.swift
- // Inhealth
- //
- // Created by weclouds on 2020/8/27.
- // Copyright © 2020 weclouds. All rights reserved.
- //
- import UIKit
- import PKHUD
- let KNotifiSetLightBrightAndColor = "KNotifiSetLightBrightAndColor"
- let KNotifiDeviceTurnOn = "KNotifiDeviceTurnOn"
- class IHLightCommandService: NSObject {
- static let share : IHLightCommandService = IHLightCommandService()
-
- private lazy var clientSocket: GCDAsyncUdpSocket? = {
- var mainQueue = DispatchQueue.main
- var clientSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: mainQueue)
- return clientSocket
- }()
- var light : (address: String, type: String, location: String)?
- var bright : String?
- var colorT : String?
- var isTurnOn : Bool = false
- var operationLightState : Bool = false
-
- deinit {
- log.debug("IHLightCommandService销毁")
- clientSocket = nil
- }
- //开关灯(485/cw)
- func setCWOrOtherLightTurnOn(isTurnOn : Bool, device : (address: String, type: String,location : String), ip : String, port : String) {
- operationLightState = isTurnOn
- light = device
- if device.type == "31" {
- //485
- //[0x12, 0xa1, 0x52, 0x03,0x01,0x17,0x00,0x20]
- // isDelete = false
- // isAdd = false
- self.isTurnOn = true
- // isCwLight = false
- let addressArr = hexStringConvertToDecimal(hexString: device.address)
- var bytes: [UInt8] = [18, 161, 82, 3,addressArr[0],addressArr[1]]
- if isTurnOn == false {
- //关
- bytes.append(0)
- }else{
- bytes.append(80)
- }
-
- setCommand(bytesArr: bytes, ip: ip, port: port)
-
-
- }else{
- //cw
- //[0x12, 0xa1, 0x5A,0x04, 0x01,0x17,0x1e,0x1e,0x65]
- // isDelete = false
- // isAdd = false
- self.isTurnOn = true
- // isCwLight = true
- let addressArr = hexStringConvertToDecimal(hexString: device.address)
- var bytes: [UInt8] = [18, 161, 90, 4,addressArr[0],addressArr[1]]
- if isTurnOn == false {
- //关
- bytes.append(0)
- bytes.append(0)
- }else{
- bytes.append(255)
- bytes.append(255)
- }
- setCommand(bytesArr: bytes, ip: ip, port: port)
- }
- }
- //设置不是485灯的亮度与色温
- func setLightCWBrightnessAndColorValue(device : (address: String, type: String, location: String),brightness: String, color: String, ip : String, port : String,isColor : Bool) {
- //[0x12, 0xa1, 0x01, 0x00,0xb4] 0001010c
- self.light = device
- self.bright = brightness
- self.colorT = color
- if device.type != "31" {
- //不是485
- let addressArr = hexStringConvertToDecimal(hexString: device.address)
- var bytes: [UInt8] = [18, 161, 90, 4,addressArr[0],addressArr[1]]
- // let bright = hexStringToInt(from: brightness)
- // let color = hexStringToInt(from: color)
- let bright = Int(brightness)!
- let colorT = Int(color)!
- bytes.append(UInt8(bright))
- bytes.append(UInt8(colorT))
- setCommand(bytesArr: bytes, ip: ip, port: port)
- }else{
- //485
- if isColor == true {
- //调色温
- //调亮度
- let addressArr = hexStringConvertToDecimal(hexString: device.address)
- var bytes: [UInt8] = [18, 161, 83, 3,addressArr[0],addressArr[1]]
- let colorT = Int(color)!
- bytes.append(UInt8(colorT))
- setCommand(bytesArr: bytes, ip: ip, port: port)
-
-
- }else{
- //调亮度
- let addressArr = hexStringConvertToDecimal(hexString: device.address)
- var bytes: [UInt8] = [18, 161, 82, 3,addressArr[0],addressArr[1]]
- let bright = Int(brightness)!
- bytes.append(UInt8(bright))
- setCommand(bytesArr: bytes, ip: ip, port: port)
-
- }
-
- }
-
-
-
- // do{
- //
- // //不连接,直接发命令
- // try clientSocket?.enableBroadcast(true)
- // try clientSocket?.beginReceiving() // 0117-设备地址
- // //[0x12, 0xa1, 0x52, 0x06,0x01,0x17,0x10,0x33]
- // //"12a1 01 05 01 0001010c c8"
- // //12a10203 011d 0400000000da
- //
- // let addressArr = hexStringConvertToDecimal(hexString: address)
- // var bytes: [UInt8] = [18, 161, 90, 4,addressArr[0],addressArr[1]]
- //// let bright = hexStringToInt(from: brightness)
- //// let color = hexStringToInt(from: color)
- // let bright = Int(brightness)!
- // let colorT = Int(color)!
- // bytes.append(UInt8(bright))
- // bytes.append(UInt8(colorT))
- // let totalStr = deciConvertHexStr(deciArr: bytes)
- // let sum = checksum(command: totalStr)
- // let dec = hexStringToInt(from: sum)
- // bytes.append(UInt8(dec))
- //
- // let command: Data = Data.init(bytes: bytes, count: bytes.count)
- // // self.vc?.gateway?.ip! self.vc?.gateway?.port
- // clientSocket?.send(command, toHost: ip, port:UInt16(port)! , withTimeout: -1, tag: 0)
- //
- // }catch{
- // log.debug("绑定失败\(error)")
- // }
- }
-
- private func setCommand(bytesArr : [UInt8], ip : String,port : String){
- do{
-
- //不连接,直接发命令
- try clientSocket?.enableBroadcast(true)
- try clientSocket?.beginReceiving() // 0117-设备地址
- var bytes = bytesArr
- let totalStr = deciConvertHexStr(deciArr: bytes)
- let sum = checksum(command: totalStr)
- let dec = hexStringToInt(from: sum)
- bytes.append(UInt8(dec))
-
- let command: Data = Data.init(bytes: bytes, count: bytes.count)
- // self.vc?.gateway?.ip! self.vc?.gateway?.port
- clientSocket?.send(command, toHost: ip, port:UInt16(port)! , withTimeout: -1, tag: 0)
-
- }catch{
- log.debug("绑定失败\(error)")
- }
- }
- //添加设备到网关
- // func addDeviceToGateway(deviceUUid : String,ip : String, port : String){
- // //[0x12, 0xa1, 0x01, 0x00,0xb4] 0001010c
- // let uuidArr = hexStringConvertToDecimal(hexString: deviceUUid)
- // let bytes: [UInt8] = [18, 161, 2, 5,1,uuidArr[0],uuidArr[1],uuidArr[2],uuidArr[3]]
- // setCommand(bytesArr: bytes, ip: ip, port: port)
- //
- //
- //// do{
- ////
- //// //不连接,直接发命令
- //// try clientSocket?.enableBroadcast(true)
- //// try clientSocket?.beginReceiving() // 0117-设备地址
- //// //[0x12, 0xa1, 0x52, 0x06,0x01,0x17,0x10,0x33]
- //// //"12a1 01 05 01 0001010c c8"
- //// //12a10203 011d 0400000000da
- //// //[0x12, 0xa1, 0x02, 0x05,0x01,0x00,0x01,0x01,0x69,0x26]
- //// let uuidArr = hexStringConvertToDecimal(hexString: deviceUUid)
- //// var bytes: [UInt8] = [18, 161, 2, 5,1,uuidArr[0],uuidArr[1],uuidArr[2],uuidArr[3]]
- //// let totalStr = deciConvertHexStr(deciArr: bytes)
- //// let sum = checksum(command: totalStr)
- //// let dec = hexStringToInt(from: sum)
- //// bytes.append(UInt8(dec))
- ////
- //// let command: Data = Data.init(bytes: bytes, count: bytes.count)
- //// // self.vc?.gateway?.ip! self.vc?.gateway?.port
- //// clientSocket?.send(command, toHost: ip, port:UInt16(port)! , withTimeout: -1, tag: 0)
- ////
- //// }catch{
- //// log.debug("绑定失败\(error)")
- //// }
- // }
- }
- extension IHLightCommandService : 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?) {
-
- // HUD.hide()
- //12 A1 04 01 00 B8
- let hexStr = dataConvertToHexString(data: data)
- if isTurnOn == false {
- //调节灯的亮度与色温
- adjustLampBrightnessAndColor(respondStr: hexStr)
- }else{
- //灯的开关
- turnOffLight(respondStr: hexStr)
- }
-
-
- log.debug("didReceive")
- }
- 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 IHLightCommandService{
-
- //开关灯
- fileprivate func turnOffLight(respondStr : String){
- log.debug()
- //"12a15203011f0028"
- isTurnOn = false
- // isCwLight = false
- let respone = respondStr as NSString
- let subStr = respone.substring(with: NSRange.init(location: 12, length: 2))
- var isfail = false
- if subStr == "00"{
- isfail = true
- DispatchQueue.main.async {
- HUD.flash(.label("成功"), delay: 0.6)
- }
- }else{
- isfail = false
- DispatchQueue.main.async {
- HUD.flash(.label("失败"), delay: 0.6)
-
- }
- }
-
- NotificationCenter.default.post(name: NSNotification.Name(KNotifiDeviceTurnOn), object: nil, userInfo: ["turnOn" :(oldDevice : light,state : isfail,turnOn : isfail == true ? operationLightState : !operationLightState)])
-
-
- // NotificationCenter.default.post(name: NSNotification.Name(KNotifiTurnOnLightFalse), object: nil)
- }
-
- //调节CW灯的亮度与色温
- func adjustLampBrightnessAndColor(respondStr: String){
- //"12a1 5a 03 0117 0028"
- let str = respondStr as NSString
- let componeStr = str.substring(with: NSRange.init(location: 12, length: 2))
- if componeStr == "00" {
- //成功
- log.debug("调节成功")
- HUD.flash(.label("成功"), delay: 0.7)
- //保存
- let defaults = UserDefaults.standard
- let arrDevice = defaults.object(forKey: "saveDeviceList") as? [[String : String]]
- if let arrDevice = arrDevice {
- var newDevice = [[String : String]]()
- newDevice = arrDevice
- if arrDevice.count > 0 {
- for (index,subDic) in arrDevice.enumerated() {
- let address = subDic["address"]!
- let type = subDic["type"]!
- // let bright = subDic["bright"]!
- // let color = subDic["color"]
- if self.light!.address == address{
- //485 address,type,bright,color
- newDevice.remove(at: index)
- newDevice.append(["address":address,"type" : type, "bright" : self.bright!, "color" : self.colorT!])
- break
- }
-
- }
- }
- defaults.set(newDevice, forKey: "saveDeviceList")
- defaults.synchronize()
- }
-
- }else{
- //失败
- log.debug("调节失败")
- HUD.flash(.label("失败"), delay: 0.7)
- }
-
- NotificationCenter.default.post(name: NSNotification.Name(KNotifiSetLightBrightAndColor), object: nil)
- }
- }
|