def control_room_services(authToken, type, enable): serviceInfo = db.query( "select * from SERVICE where authToken='%s' and serviceType='%d'" % (authToken, type)) if len(serviceInfo) < 1: get_room_services(authToken) serviceInfo = db.query( "select * from SERVICE where authToken='%s' and serviceType='%d'" % (authToken, type)) if len(serviceInfo) < 1: print "cant find service info" return 0 service = serviceInfo[0] cmd = { "serviceType": type, "authToken": authToken, "cmd": "requestServiceControl", "ignoreCardStatus": 0, "serviceToken": service['serviceToken'], "enableService": enable } send_rcu_cmd(json.dumps(cmd))
def send_status_mqtt(id, ep): # mqtt发送状态更新 print "dev status changed" gwInfo = db.query( "select * from ROOM r,DEVICE d where r.gw=d.gw and d.id='%s' AND d.ep='%d'" % (id, ep)) if len(gwInfo) < 1: return 0 dev = gwInfo[0] statusJson = { "wxCmd": "devStatus", "devName": dev['devName'], "onLine": dev['ol'], "actionCode": dev['onoff'], "devId": dev['id'] + str(dev['ep']) } mqtt_client.publish_message(config.project_name + dev['roomNo'], json.dumps(statusJson)) statusJson['wsCmd'] = statusJson.pop('wxCmd') statusJson['roomNo'] = dev['roomNo'] websocketServer.send_message_to_all(json.dumps(statusJson)) # 情景模式控制RCUservices if dev['controlType'] in {104, 105, 106} and dev['onoff'] == 1: serviceInfo = db.query( "select * from SERVICE where authToken='%s' and serviceType='%d'" % (dev['authToken'], dev['controlType'])) if len(serviceInfo) > 0: service = serviceInfo[0] haier_proxy.control_service(service, 1) #请稍后104,请勿扰105,两个服务互斥处理,控制另一个面板关闭 # if dev['onoff'] == 1 and dev['controlType'] in {104, 105}: # mutexType = 209 - dev['controlType'] # serviceDev = db.query("select * from DEVICE where gw='%s' and controlType='%d' and onoff='1'" % (dev['gw'], mutexType)) # if len(serviceDev) > 0: # d = serviceDev[0] # sendControlDev(d['id'], d['ep'], {"on" : 0}, d['gw']) #处理双控,判断设备controlType为201,主设备进行取反操作 elif dev['controlType'] == 201 and dev['onoff'] in {1}: devInfo = db.query( "select * from DEVICE where devName='%s' and controlType=1" % (dev['devName'])) if len(devInfo) > 0: masterDev = devInfo[0] actionCode = 1 if masterDev['onoff'] in {0, 1}: actionCode = 1 - masterDev['onoff'] paraDict = {"on": actionCode} sendControlDev(id=masterDev['id'], ep=masterDev['ep'], paraDict=paraDict, gw_mac=masterDev['gw']) # 自己立即关闭不保存开关状态 paraDict = {"on": 0} sendControlDev(id=dev['id'], ep=dev['ep'], paraDict=paraDict, gw_mac=dev['gw'])
def getDevList(roomNo): roomInfo = db.query("select * from ROOM where roomNo='%s'" % (roomNo)) if len(roomInfo) < 1: print "房间不存在" return copy.deepcopy(constant.BAD_REQUEST_RES_JSON) room = roomInfo[0] rcuInfo = db.query("select * from HAIER_DEVICE where authToken='%s'" % (room['authToken'])) gwInfo = db.query("select * from DEVICE where gw='%s' and controlType=1" % (room['gw'])) aliveInfo = db.query("select * from ALIVE_DEVICE where aliveRcuId='%s'" % (room['aliveRcuId'])) # serviceInfo = db.query("select * from SERVICE where authToken='%s'" % (room['authToken'])) devListJson = {"rescode":"200", "devList": []} for item in rcuInfo: if item.get('clearDevType', 'null') not in {'hr_lock', 'hr_airCondition', 'hr_card'}: continue devJson = {'devName': item['devName'], 'onLine': item['onLine'], 'devType': item['clearDevType'], 'devId': item['devId'], 'actionCode': item['devActionCode']} if item['devStatus']: devJson['devStatus'] = json.loads(item['devStatus']) devListJson['devList'].append(devJson) for item in gwInfo: if item.get('clearDevType', 'null') not in {'sz_switch', 'sz_curtain', 'sz_adapter'}: continue devJson = {'devName': item['devName'], 'onLine': item['ol'], 'devType': item['clearDevType'], 'devId': item['id'] + str(item['ep']), 'actionCode': item['onoff']} devListJson['devList'].append(devJson) for item in aliveInfo: if item.get('clearDevType', 'null') not in {'alive_airCondition'}: continue devJson = {'devName': item['devName'], 'onLine': item['onLine'], 'devType': item['clearDevType'], 'devId': item['devId'], 'actionCode': item['devActionCode']} if item['devStatus']: devJson['devStatus'] = json.loads(item['devStatus']) devListJson['devList'].append(devJson) # for item in serviceInfo: # devJson = {'devName': item['devName'], # 'onLine': 1, # 'actionCode': item['serviceStatus']} # devListJson['devList'].append(devJson) return devListJson
def welcomeFunc(room): print "open all light" scene.controlGroup(room['roomNo'], constant.GROUP_ALL_LIGHT, {"on": 1}) time.sleep(1) openWindow(room) time.sleep(1) print "open window" scene.controlGroup(room['roomNo'], constant.GROUP_ALL_LIGHT, {"on": 1}) lightInfo = db.query( "SELECT * FROM DEVICE WHERE gw='%s' and devName LIKE '%%灯%%'" % (room['gw'])) for dev in lightInfo: sendControlDev(id=dev['id'], ep=dev['ep'], paraDict={"on": 1}, gw_mac=room['gw']) time.sleep(3) lightInfo = db.select('DEVICE', where={'devName': '廊灯', 'gw': room['gw']}) for dev in lightInfo: sendControlDev(id=dev['id'], ep=dev['ep'], paraDict={"on": 1}, gw_mac=room['gw']) print "open all light again" scene.controlGroup(room['roomNo'], constant.GROUP_ALL_LIGHT, {"on": 1})
def controlScene(messageJson): sceneName = messageJson.get("sceneName", None) resJson = copy.deepcopy(constant.BAD_REQUEST_RES_JSON) if sceneName is None: resJson['errInfo'] = 'parameter error ,no sceneName' return resJson roomInfo = db.query("select * from ROOM where roomNo='%s'" % (messageJson['roomNo'])) if len(roomInfo) < 1: resJson['errInfo'] = 'no such roomNo' return resJson room = roomInfo[0] print "scnenName:",sceneName if "模式" in sceneName:#普通模式,控制顺舟开关面板 print "4 scene" whereDict = {'gw': room['gw'], 'devName': sceneName} dictJson = copy.deepcopy(messageJson) dev = db.select(constant.TABLE_SHUNZHOU,where=whereDict).first() if dev is None: resJson['errInfo'] = 'can not set this sceneName: %s'%(sceneName) return resJson dictJson['devName'] = sceneName dictJson['devType'] = dev['clearDevType'] dictJson['actionCode'] = 1 dictJson['devId'] = dev['id'] + str(dev['ep']) return controlDevice(dictJson) elif sceneName == "灯光全开" or sceneName == "灯光全关": print "control all_light:",sc return mqtt_client.crontrolScene(messageJson) elif sceneName == '打开窗帘': protocol.openWindow(room) elif sceneName == '关闭窗帘': protocol.closeWindow(room) return copy.deepcopy(constant.OK_RES_JSON)
def getGowildList(messageJson): gowildId = messageJson.get('gowildId', None) if gowildId is None: roomInfo = db.query("select roomNo,gowildId from ROOM") else: roomInfo = db.query("select roomNo,gowildId from ROOM where gowildId='%s'"%(gowildId)) if len(roomInfo) < 1: resJson = copy.deepcopy(constant.BAD_REQUEST_RES_JSON) resJson['errInfo'] = 'no such gowildId' resJson['gowildId'] = gowildId return resJson resJson = copy.deepcopy(constant.OK_RES_JSON) resJson['gowildList'] = [] for r in roomInfo: rJson = {'roomNo':r['roomNo'], 'gowildId':r['gowildId']} resJson['gowildList'].append(rJson) return resJson
def controlDevice(messageJson): resJson = copy.deepcopy(constant.BAD_REQUEST_RES_JSON) devType = messageJson.get('devType', None) roomInfo = db.query("select * from ROOM where roomNo='%s'" % (messageJson['roomNo'])) if devType is None or len(roomInfo) < 1: print "no devType or on such roomNo" resJson['errInfo'] = 'parameter error ,no devType or no such roomNo' return resJson room = roomInfo[0] # 顺舟设备控制,devType以'sz_'开头 if re.match('sz', devType) is not None: whereDict = {'id' : messageJson['devId'][0:-1], 'ep' : messageJson['devId'][-1:], 'gw' : room['gw']} # dev = db.select('DEVICE', where = whereDict).first() # if dev is None: # resJson['errInfo'] = 'no such device' # return resJson paraDict = {'on' : messageJson['actionCode']} if devType == 'sz_curtain': paraDict = {"cts" : messageJson['actionCode']} print "sz cmd:" protocol.sendControlDev(id=whereDict['id'], ep=whereDict['ep'], paraDict=paraDict, gw_mac=room['gw']) elif re.match('hr', devType) is not None: whereDict = {'devId': messageJson['devId'], 'authToken' : room['authToken']} dev = db.select('HAIER_DEVICE', where=whereDict).first() if dev is None: resJson['errInfo'] = 'no such device' return resJson devStatus = messageJson.get('devStatus', None) cmdJson = { "devId": dev['devId'], "devType": dev['devType'], "authToken": dev['authToken'], "ignoreCardStatus": 0, "actionCode": 1, "cmd": "requestDeviceControl", "devSecretKey": dev['devSecretKey'] } if dev['devType'] == 64 and devStatus: print "devstatus:", devStatus cmdJson['mode'] = devStatus['mode'] cmdJson['setTemp'] = devStatus['setTemp'] cmdJson['speed'] = devStatus['speed'] cmdJson['actionCode'] = devStatus['switch'] print "cmdJson:", cmdJson haier_proxy.send_rcu_cmd(json.dumps(cmdJson)) elif re.match('alive', devType) is not None: if devType == 'alive_airCondition': whereDict = {'devId': messageJson['devId'], 'aliveRcuId': room['aliveRcuId']} dev = db.select('ALIVE_DEVICE', where=whereDict).first() alive_protocol.controlAirCondition(room, dev, messageJson.get('devStatus', None)) print "control complette" return copy.deepcopy(constant.OK_RES_JSON)
def getSceneList(roomNo): roomInfo = db.query("select * from ROOM where roomNo='%s'" % (roomNo)) resJson = copy.deepcopy(constant.BAD_REQUEST_RES_JSON) if len(roomInfo) < 1: resJson['errInfo'] = 'no such roomNo' return resJson sceneJson = {"rescode": "200", "sceneList": []} sceneJson['sceneList'].append("灯光全开") sceneJson['sceneList'].append("灯光全关") sceneJson['sceneList'].append("明亮模式") sceneJson['sceneList'].append("睡眠模式") sceneJson['sceneList'].append("起夜模式") sceneJson['sceneList'].append("影音模式") sceneJson['sceneList'].append("打开窗帘") sceneJson['sceneList'].append("关闭窗帘") return sceneJson
def message_received(client, server, message): print("Client %d said: %s"%(client['id'], message)) try: messageJson = json.loads(message) except: resJson = copy.deepcopy(constant.BAD_REQUEST_RES_JSON) resJson['errInfo'] = 'not json data:' + str(message) server.send_message(client, json.dumps(resJson)) return 0 try: roomNo = messageJson.get('roomNo', None) wsCmd = messageJson.get('wsCmd', None) print "roomNo:", roomNo roomInfo = db.query("select * from ROOM where roomNo='%s'" % (roomNo)) resJson = copy.deepcopy(constant.BAD_REQUEST_RES_JSON) # if len(roomInfo) < 1 and wsCmd is None: # resJson['errInfo'] = 'no such roomNo:%s'%(roomNo) if wsCmd == 'getDevList':#获取设备列表 resJson = getDevList(roomNo) elif wsCmd == 'getSceneList':#获取场景列表 resJson = getSceneList(roomNo) elif wsCmd == 'controlScene':#控制场景 resJson = controlScene(messageJson) elif wsCmd == 'controlDevice':#控制设备 resJson = controlDevice(messageJson) elif wsCmd == 'getGowildList':#猎取狗尾草设备和房间对应列表 resJson = getGowildList(messageJson) elif wsCmd == 'heartbeat': # 心跳连接 resJson = copy.deepcopy(constant.OK_RES_JSON) resJson['heartSuccessTime'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') else: resJson['errInfo'] = 'unknow command' resJson['wsCmd'] = wsCmd resJson['cmdMessage'] = messageJson print "websocket server send message %s to client %d:"%(json.dumps(resJson),client['id']) server.send_message(client, json.dumps(resJson)) except Exception as e: print "invalid message",str(e) resJson = copy.deepcopy(constant.BAD_REQUEST_RES_JSON) resJson['errInfo'] = 'invalid message' + str(e) resJson['wsCmd'] = wsCmd resJson['cmdMessage'] = messageJson server.send_message(client, json.dumps(resJson))
def devControl(dictData): devName = dictData.get('devName', None) devType = dictData.get('devType', None) devId = dictData.get('devId', None) roomInfo = db.query("select * from ROOM where roomNo='%s'" % (dictData['roomNo'])) resJson = copy.deepcopy(constant.BAD_REQUEST_RES_JSON) if len(roomInfo) < 1: print "no such roomNo" resJson['errInfo'] = 'parameter error : no such roomNo' return resJson # if devType is None or devId is None: if devName is None: print "no devName or on such roomNo" resJson[ 'errInfo'] = 'parameter error :no clearDevType or devId or devName' return resJson room = roomInfo[0] # if re.match('sz', devType) is not None: # paraDict = {'on': dictData['actionCode']} # if devType == 'sz_curtain': # paraDict = {"cts": dictData['actionCode']} # print "sz cmd:" # protocol.sendControlDev(id=devId[0:-1], ep=devId[-1:], paraDict=paraDict, gw_mac=room['gw']) # elif re.match('hr', devType) is not None: # pass # elif re.match('alive', devType) is not None: # pass rcuInfo = db.query( "select * from HAIER_DEVICE where devName='%s' and authToken='%s'" % (devName, room['authToken'])) gwInfo = db.query("select * from DEVICE where devName='%s'and gw='%s'" % (devName, room['gw'])) serviceInfo = db.query( "select * from SERVICE where devName='%s' and authToken='%s'" % (devName, room['authToken'])) aliveInfo = db.query( "select * from ALIVE_DEVICE where devName='%s' and aliveRcuId='%s'" % (devName, room['aliveRcuId'])) devStatus = dictData.get('devStatus', None) if len(rcuInfo) < 1 and len(gwInfo) < 1 and len(serviceInfo) < 1 and len( aliveInfo) < 1: print "cant find device:", devName resJson['errInfo'] = "cant find device:'%s'" % (devName) return resJson elif len(rcuInfo) > 0: #rcu设备控制 print "rcu control" dev = rcuInfo[0] cmdJson = { "devId": dev['devId'], "devType": dev['devType'], "authToken": dev['authToken'], "ignoreCardStatus": 0, "actionCode": 1, "cmd": "requestDeviceControl", "devSecretKey": dev['devSecretKey'] } if dev['devType'] == 64 and devStatus: print "devstatus:", devStatus cmdJson['mode'] = devStatus['mode'] cmdJson['setTemp'] = devStatus['setTemp'] cmdJson['speed'] = devStatus['speed'] cmdJson['actionCode'] = devStatus['switch'] print "cmdJson:", cmdJson haier_proxy.send_rcu_cmd(json.dumps(cmdJson)) elif len(gwInfo) > 0: #gw设备控制 print "gw control" dev = gwInfo[0] actionCode = dictData.get('actionCode') #先判断 是不是网关电机 if dev['did'] == constant.SZ_CURTAIN_DID: protocol.sendControlDev(id=dev['id'], ep=dev['ep'], paraDict={"cts": actionCode}, gw_mac=room['gw']) return copy.deepcopy(constant.OK_RES_JSON) #开关面板如果actionCode是2,取反操作 if actionCode == 2 and dev['onoff'] in {0, 1}: actionCode = 1 - dev['onoff'] elif actionCode == 2: actionCode = 1 paraDict = {"on": actionCode} protocol.sendControlDev(id=dev['id'], ep=dev['ep'], paraDict=paraDict, gw_mac=room['gw']) elif len(serviceInfo) > 0: #海尔service控制 service = serviceInfo[0] haier_proxy.control_service(service, dictData.get('actionCode')) elif len(aliveInfo) > 0: dev = aliveInfo[0] if dev['clearDevType'] == 'alive_service': alive_protocol.controlService(dev, dictData) elif dev['clearDevType'] == 'alive_airCondition': alive_protocol.controlAirCondition(room, dev, devStatus) return copy.deepcopy(constant.OK_RES_JSON)
def get_dev_list(dictData): roomInfo = db.query("select * from ROOM where roomNo='%s'" % (dictData['roomNo'])) if len(roomInfo) < 1: #房间不存在 print "房间不存在" return 0 room = roomInfo[0] rcuInfo = db.query("select * from HAIER_DEVICE where authToken='%s'" % (room['authToken'])) gwInfo = db.query("select * from DEVICE where gw='%s' and controlType=1" % (room['gw'])) serviceInfo = db.query("select * from SERVICE where authToken='%s'" % (room['authToken'])) aliveInfo = db.query("select * from ALIVE_DEVICE where aliveRcuId='%s'" % (room['aliveRcuId'])) devListJson = {"wxCmd": "devList", "devList": []} for item in rcuInfo: devJson = { 'devName': item['devName'], 'onLine': item['onLine'], 'devType': item['clearDevType'], 'devId': item['devId'], 'actionCode': item['devActionCode'] } if item['devStatus']: devJson['devStatus'] = json.loads(item['devStatus']) devListJson['devList'].append(devJson) for item in gwInfo: devJson = { 'devName': item['devName'], 'onLine': item['ol'], 'devType': item['clearDevType'], 'devId': item['id'] + str(item['ep']), 'actionCode': item['onoff'] } devListJson['devList'].append(devJson) for item in serviceInfo: devJson = { 'devName': item['devName'], 'onLine': 1, 'actionCode': item['serviceStatus'] } devListJson['devList'].append(devJson) for item in aliveInfo: devJson = { 'devName': item['devName'], 'onLine': 1, 'devType': item['clearDevType'], 'devId': item['devId'], 'actionCode': item['devActionCode'] } if item['devStatus']: devJson['devStatus'] = json.loads(item['devStatus']) devListJson['devList'].append(devJson) publish_message(config.project_name + dictData['roomNo'], json.dumps(devListJson))
def dev_status_notify(data): token = data.get('authToken', None) statusJson = data.get('info', None) roomInfo = db.query("select * from ROOM where authToken='%s'" % (token)) devId = statusJson['devId'] if len(roomInfo) < 1 or statusJson is None: raise Exception("room token: %s or status: %s not found" % (token, statusJson)) room = roomInfo[0] res = db.query("select * from HAIER_DEVICE where devId='%s'" % (devId)) devStatus = statusJson.get('devStatus', None) onLine = 0 if statusJson['offLine'] else 1 if len(res) < 1: # 设备不存在,插入 db.insert('HAIER_DEVICE', devId=statusJson['devId'], devName=statusJson['devName'], devType=statusJson['devType'], devSecretKey=statusJson['devSecretKey'], devActionCode=statusJson['devActionCode'], devStatus=json.dumps(devStatus), onLine=onLine, authToken=token) else: #更新rcu设备状态到数据库 db.update('HAIER_DEVICE', where="devId = $ID", vars={'ID': devId}, onLine=onLine, devStatus=json.dumps(devStatus), devActionCode=statusJson['devActionCode']) # mqtt发送状态更新 devInfo = db.query( "select * from ROOM r,HAIER_DEVICE d where r.authToken=d.authToken and d.devId='%s'" % (statusJson['devId'])) if len(devInfo) > 0: dev = devInfo[0] mqttJson = { "wxCmd": "devStatus", "devName": dev['devName'], "onLine": dev['onLine'], "actionCode": dev['devActionCode'] } if devStatus is not None: mqttJson['devStatus'] = devStatus mqtt_client.publish_message(config.project_name + room['roomNo'], json.dumps(mqttJson)) # 将状态变动发给websocket mqttJson['wsCmd'] = mqttJson.pop('wxCmd') mqttJson['roomNo'] = room['roomNo'] websocketServer.send_message_to_all(json.dumps(mqttJson)) #插卡取电 if statusJson['devType'] == 2 and devStatus is not None: if devStatus['cardStatus'] == 1: protocol.openWindow(room) thread.start_new_thread(welcomeStrategy, (room, 1)) get_room_devices(token) get_room_services(token) elif devStatus['cardStatus'] == 0: thread.start_new_thread(goodbyeStrategy, (room, 9)) thread.start_new_thread(goodbyeStrategy, (room, 13))
def makeStrategyJson(self, name): #得到策略 的 信息 sInfo = db.select("STRATEGY_ALL_INDEX", where={"name": name}).first() print sInfo if sInfo is None: print "Strategy is not support ! name: %s" % name raise Exception("Strategy is not support ! name: %s" % name) else: table = sInfo.get("table_name") #得到场景的设备列表 sql = "select name,id,ep,gw,tigger,act,delay from %s s,DEVICE d where d.gw = \"%s\" and s.name=d.devName and s.room_type=\"%s\"" % ( str(table), self.gw_mac, self.room_type) print "json maker sql: ", sql sDevList = db.query(sql) sDevList = list(sDevList) print json.dumps(sDevList) self.rid = sInfo.get("rid") #生成策略Josn sJson = { "code": 1013, "serial": getSerial(), "name": name, "rid": self.rid, "state": 1, "trig": 0, "ct": time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime()), "exp": "function main(a1,b1) if (a1==b1) then return true else return false end end", "cond": [], "act": [] } #TODO: 获取策略列表 生成不重复 的rid 暂时用时间的Timestamp condIdx = 1 actIdx = 1 for dev in sDevList: if dev.get("tigger") == 1: #cond 触发器 obj = { "idx": condIdx, "type": 2, "id": dev["id"], "ep": dev["ep"] } act = json.loads(dev.get("act")) obj.update(act) sJson["cond"].append(obj) condIdx += 1 elif dev.get("tigger") == 0: #act 执行动作 obj = { "idx": actIdx, "delay": dev.get("delay", 0), "type": 1, "id": dev["id"], "ep": dev["ep"] } print "act:", str(dev.get("act")) act = json.loads(dev.get("act")) obj.update(act) sJson["act"].append(obj) actIdx += 1 elif dev.get("tigger") == 2: #分组策略 obj = {"idx": actIdx, "delay": dev.get("delay", 0), "type": 2} print "act:", str(dev.get("act")) act = json.loads(dev.get("act")) obj.update(act) sJson["act"].append(obj) actIdx += 1 print "scene json" print json.dumps(sJson) self.sJson = sJson return sJson