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 getDevInfo(id, ep): dev = db.select("DEVICE", where={"id": id, "ep": ep}).first() if dev is None: print "Dev not found id: %s ep: %s" % (str(id), str(ep)) return None else: return dev
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 statusNotify(msg): statusType = msg[16:18] print "statusType:",statusType if statusType == '01':#温湿度 curTemp = int(msg[22:24],16) print "curTemp:",curTemp ret = db.select("ALIVE_DEVICE", where={"aliveRcuId": msg[4:10],"clearDevType": 'alive_airCondition'}).first() if ret is not None: st = ret.get("devStatus", None) if st is not None: stJson = json.loads(ret['devStatus']) stJson['currentTemp'] = curTemp else: stJson = {'currentTemp' : curTemp} print "stJson:", stJson devInfo = {'devStatus': json.dumps(stJson)} db.update("ALIVE_DEVICE", where={"aliveRcuId": msg[4:10],"clearDevType": 'alive_airCondition'}, **devInfo) elif statusType == '02':#服务状态 pass elif statusType == '03':#空调状态 pass elif statusType == '04':#主机ID查询 rcuInfo = {'aliveRcuId': msg[4:10], 'last_timestamp': time.time()} db_replace("ROOM", {"aliveRcuId": msg[4:10]}, rcuInfo) send_cmd(msg[4:10])
def makeJson(self, name): # 得到分组 的 信息 gInfo = self.getInfo(name) self.gid = gInfo.get("gid") gJson = { "code": 1005, "name": name, "gid": self.gid, "serial": getSerial(), "device": [] } #得到设备列表信息 devList = gInfo.get("dev_list") devList = str2List(devList) for devName in devList: devInfo = db.select("DEVICE", where={ "devName": devName, "gw": self.gw_mac }).first() if devInfo is not None: gJson["device"].append({ "id": devInfo["id"], "ep": devInfo["ep"] }) print json.dumps(gJson) self.gjson = gJson
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 welcomeStrategy(room, interval): print "welcomeStrategy:", room['roomNo'] protocol.openWindow(room) time.sleep(2) cardInfo = db.select('ALIVE_DEVICE', where={'clearDevType': constant.ALIVE_CLEARTYPE_CARD, 'aliveRcuId': room['aliveRcuId']}).first() if cardInfo is not None and cardInfo['devActionCode'] == 0: protocol.welcomeFunc(room) thread.exit()
def __init__(self, roomNo): rInfo = db.select("ROOM", where={"roomNo": roomNo}).first() if rInfo is None: print "roomNo is not exist: %s" % str(roomNo) raise Exception("roomNo is not exist: %s" % str(roomNo)) self.room_type = rInfo["room_type"] self.gw_mac = rInfo["gw"] pass
def goodbyeStrategy(room, interval): print "goodbyeStrategy:", room['roomNo'] time.sleep(interval) print "goodbyeStrategy thread" cardInfo = db.select('ALIVE_DEVICE', where={'clearDevType': constant.ALIVE_CLEARTYPE_CARD, 'aliveRcuId': room['aliveRcuId']}).first() if cardInfo is not None and cardInfo['devActionCode'] == 1: protocol.closeWindow(room) thread.exit()
def service_status_notify(data): authToken = data.get('authToken', None) serviceToken = data.get('serviceToken', None) if authToken is None or serviceToken is None: print "wrong service status nofify message:", str(data) return 0 serviceDict = { 'authToken': data['authToken'], 'serviceToken': data['serviceToken'], 'serviceStatus': data['serviceStatus'], 'serviceType': data['serviceType'], 'devName': constant.HAIER_SERVICE_DEVNAME_DICT[data['serviceType']] } db_replace('SERVICE', { 'authToken': authToken, 'serviceToken': serviceToken }, serviceDict) # 请稍后104,请勿扰105,两个服务互斥处理,控制另一个服务关闭 if data['serviceStatus'] == 1 and data['serviceType'] in {104, 105}: mutexType = 209 - data['serviceType'] mutexInfo = db.select("SERVICE", where={ 'serviceType': mutexType, 'serviceStatus': 1 }) for s in mutexInfo: control_service(s, 0) roomInfo = db.select('ROOM', where={'authToken': authToken}) if len(roomInfo) < 1: print "no such room:", authToken return 0 room = roomInfo[0] #mqtt反馈状态更新 statusDict = { 'devName': serviceDict['devName'], 'onLine': 1, 'actionCode': serviceDict['serviceStatus'], 'roomNo': room['roomNo'] } mqtt_client.publish_dev_status(statusDict)
def getGwList(): gwList = db.select("ROOM") gwList = list(gwList) cTime = time.time() for gw in gwList: lastTime = gw.get("last_timestamp") if cTime - lastTime < 60: gw.update({"ol": 1}) else: gw.update({"ol": 0}) return gwList
def getGwInfo(gw_mac): gInfo = db.select("ROOM", where={"gw": gw_mac}).first() if gInfo is None: return None cTime = time.time() lastTime = gInfo.get("last_timestamp") if cTime - lastTime < 60: gInfo.update({"ol": 1}) else: gInfo.update({"ol": 0}) return gInfo
def closeWindow(room): curtainInfo = db.select('DEVICE', where={ 'did': constant.SZ_CURTAIN_DID, 'gw': room['gw'] }) for dev in curtainInfo: sendControlDev(id=dev['id'], ep=dev['ep'], paraDict={"cts": 0}, gw_mac=room['gw'])
def goodbyeStrategy(room, interval): print "goodbyeStrategy:", room['roomNo'] time.sleep(interval) print "goodbyeStrategy thread" cardInfo = db.select('HAIER_DEVICE', where={ 'devType': constant.HAIER_CARD_TYPE, 'authToken': room['authToken'] }) for card in cardInfo: cStatus = json.loads(card['devStatus']) print "cardStatus:", cStatus if cStatus['cardStatus'] == 0: protocol.closeWindow(room) thread.exit_thread()
def welcomeStrategy(room, interval): print "welcomeStrategy:", room['roomNo'] time.sleep(2) cardInfo = db.select('HAIER_DEVICE', where={ 'devType': constant.HAIER_CARD_TYPE, 'authToken': room['authToken'] }) for card in cardInfo: cStatus = json.loads(card['devStatus']) print "cardStatus:", cStatus if cStatus['cardStatus'] == 0: thread.exit() protocol.welcomeFunc(room) thread.exit_thread()
def sendControlDev(id, ep, paraDict, gw_mac=None): if gw_mac is None: devInfo = db.select("DEVICE", where={"id": id, "ep": ep}).first() if devInfo is None: raise Exception("ID %s, ep %s not found" % (str(id), str(ep))) gw_mac = devInfo["gw"] global serial serial += 1 controlJson = { "code": 1002, "id": id, "ep": ep, "serial": serial, "control": paraDict } sendMessage(gw_mac, controlJson)
def update_room_devices(data): authToken = data.get('authToken', None) devInfo = data.get('devInfos', None) if authToken is None or len(devInfo) < 1: print "no devices found" return 0 for d in devInfo: d['onLine'] = 1 - d['offLine'] d['authToken'] = authToken d.pop('offLine') if d.get('devStatus', None) is not None: d['devStatus'] = json.dumps(d.get('devStatus')) ret = db.select('HAIER_DEVICE', where={'devId': d['devId']}).first() if ret is None: db.insert('HAIER_DEVICE', **d) else: d.pop('devName') db.update('HAIER_DEVICE', where={'devId': d['devId']}, **d)
def revDevInfo(device, gw_mac=None): devInfo = { "id": device.get("id"), "ol": device.get("ol"), "ep": device.get("ep"), "pid": device.get("pid", None), "did": device.get("did", None), "st": json.dumps(device.get("st", {})), "onoff": device.get("st", {}).get("on", None), "time_last": time.time() } if gw_mac is not None: devInfo.update({"gw": gw_mac}) if device.get("did") == constant.SZ_CURTAIN_DID: devInfo['onoff'] = device.get("st", {}).get("pt", None) elif device.get("did") == constant.SZ_MENCI_DID: zsta = device.get("st", {}).get("zsta", None) if zsta is None: #光感照明 return 0 devInfo['onoff'] = zsta - 4 ret = db.select("DEVICE", where={ "id": devInfo["id"], "ep": devInfo["ep"] }).first() if ret is None: db.insert("DEVICE", **devInfo) else: st = ret.get("st", None) if st is not None: stJson = json.loads(ret['st']) for k, v in device.get("st", {}).items(): stJson[k] = v print "stJson:", stJson devInfo['st'] = json.dumps(stJson) db.update("DEVICE", where={ "id": devInfo["id"], "ep": devInfo["ep"] }, **devInfo)
def getInfo(self, name): gInfo = db.select("GROUP_INFO", where={"group_name": name}).first() if gInfo is None: print "group is not found ! name: %s" % name raise Exception("group is not found ! name: %s" % name) return gInfo
def getSupportStrategyList(self): sList = db.select("STRATEGY_ALL_INDEX", what="id,name") return list(sList)
def serviceUploadPacket(clinet_msg, msg): msgInfo = {'aliveRcuId':msg[4:10], 'onLine':1} devId = msg[4:10] + msg[14:20] msgInfo['devId'] = devId room = db.select("ROOM", where={"aliveRcuId": msg[4:10]}).first() if room is None: return 0 if msg[18:20] == '01': #插卡取电 msgInfo['devActionCode'] = int(msg[22:24], 16) db_replace("ALIVE_DEVICE", {"aliveRcuId": msg[4:10], "devId": devId}, msgInfo) if msgInfo['devActionCode'] == 0:#插卡 thread.start_new_thread(welcomeStrategy, (room, 1)) else:#拔卡 thread.start_new_thread(goodbyeStrategy, (room, 2)) thread.start_new_thread(goodbyeStrategy, (room, 4)) elif msg[18:20] == '02':#服务状态 for id in range(1, int(msg[20:22], 16), 2): step = id * 2 msgInfo['devId'] = msg[4:10] + msg[14:20] + msg[20+step:22+step] msgInfo['devActionCode'] = int(msg[22+step:24+step], 16) print "service id:", msg[20+step:22+step] if msg[20+step:22+step] not in {'1a', '1b', '1c'}:#除了service继电器,其它继电器不用记录 continue db_replace("ALIVE_DEVICE", {"aliveRcuId": msg[4:10], "devId": msgInfo['devId']}, msgInfo) mqttJson = { "wxCmd": "devStatus", "devName": constant.ALIVE_SERVICE[msg[20+step:22+step]], "onLine": 1, "actionCode": msgInfo['devActionCode'] } mqtt_client.publish_message(config.project_name + room['roomNo'], json.dumps(mqttJson)) elif msg[18:20] == '03':#空调状态 stringValue = msg[24:52] statusJson = {'stringValue': stringValue, 'mode':constant.ALVIE_2API_MODE_TUP[int(stringValue[0:2], 16)], 'setTemp': int(stringValue[2:4], 16) + 16, 'speed': constant.ALVIE_2API_SPEED_TUP[int(stringValue[4:6], 16)], 'switch': 2 - int(stringValue[20:22], 16)%2} ret = db.select("ALIVE_DEVICE", where={"aliveRcuId": msg[4:10], "clearDevType": 'alive_airCondition'}).first() if ret is not None: stJson = json.loads(ret['devStatus']) statusJson['currentTemp'] = stJson['currentTemp'] else: statusJson['currentTemp'] = 20 send_cmd(msg[4:10]) msgInfo['devActionCode'] = int(msg[44:46],16) msgInfo['devStatus'] = json.dumps(statusJson) db_replace("ALIVE_DEVICE", {"aliveRcuId": msg[4:10],"devId":devId}, msgInfo) mqttJson = { "wxCmd": "devStatus", "devName": '空调', "onLine": 1, "actionCode": msgInfo['devActionCode'], 'devStatus':statusJson } mqtt_client.publish_message(config.project_name + room['roomNo'], json.dumps(mqttJson)) elif msg[18:20] == '04':#当前温度上传 curTemp = int(msg[22:24], 16) print "curTemp:", curTemp ret = db.select("ALIVE_DEVICE", where={"aliveRcuId": msg[4:10],"clearDevType": 'alive_airCondition'}).first() if ret is not None: st = ret.get("devStatus", None) if st is not None: stJson = json.loads(ret['devStatus']) print "stjson:",stJson stJson['currentTemp'] = curTemp else: stJson = {'currentTemp': curTemp} print "stJson:", stJson devInfo = {'devStatus': json.dumps(stJson)} db.update("ALIVE_DEVICE", where={"aliveRcuId": msg[4:10], "clearDevType": 'alive_airCondition'},**devInfo)
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
def getDevList(gw_mac): devList = db.select("DEVICE", where={"gw": gw_mac}) return list(devList)
def getSupportGroupList(self): sList = db.select("GROUP_INFO", where={'room_type': self.room_type}, what="gid,group_name") return list(sList)