コード例 #1
0
 def wsClientConnect(self):
     self.serviceObject = 'connecting'
     yield logClient.tornadoInfoLog("trying to connect")
     try:
         self.serviceObject = yield websocket_connect(WS_HOST)
     except Exception as e:
         self.serviceObject = None
         yield self.closeAllClient()
         yield logClient.tornadoInfoLog("connection error")
     else:
         yield logClient.tornadoInfoLog("connected")
         self.ioloop.add_timeout(self.ioloop.time(), self.wsClientLoopRun)
コード例 #2
0
    def handleOnMessage(self, ReceiveMessageObject):
        topic_list = ReceiveMessageObject.topicList
        meeting_room_guid = topic_list[1]
        if topic_list[2] == 'receive':
            # 其他服务主动获取--会议室排程信息[当前会议,下次会议,会议室排程状态]
            if topic_list[6] == 'schedule_info':
                get_from = topic_list[7]
                topic = '/aaiot/{}/send/controlbus/event/schedule/schedule_info/{}'.format(
                    meeting_room_guid, get_from)
                meeting_room_object = self.meetingRoomDict.get(
                    meeting_room_guid)
                if meeting_room_object != None:
                    info = yield meeting_room_object.getSelfScheduleInfo()
                    yield logClient.tornadoInfoLog('会议室:{}.获取排程信息'.format(
                        meeting_room_object.name))
                    if get_from == 0 or get_from == '0':
                        yield self.myPublish(topic,
                                             json_dumps(info),
                                             qos=QOSLOCAL)

                    elif get_from == 1 or get_from == '1':
                        yield self.myPublish(topic, json_dumps(info), qos=QOS)
                else:
                    return
            # 其他服务主动获取--会议室排程剩余时间
            elif topic_list[6] == 'remaining_time':
                topic = '/aaiot/{}/send/controlbus/event/schedule/remaining_time/0'.format(
                    meeting_room_guid)
                meeting_room_object = self.meetingRoomDict.get(
                    meeting_room_guid)
                if meeting_room_object != None:
                    yield logClient.tornadoInfoLog('会议室:{}.获取排程剩余时间信息'.format(
                        meeting_room_object.name))
                    info = yield meeting_room_object.getSelfRemainingTime()
                    yield self.myPublish(topic, json_dumps(info), qos=QOSLOCAL)
            # 取消排程
            elif topic_list[6] == 'cancel':
                meeting_room_object = self.meetingRoomDict.get(
                    meeting_room_guid)
                if meeting_room_object == None:
                    return
                yield meeting_room_object.overNowSchedule()
        # 监控到会议室排程信息发生改变
        elif topic_list[2] == 'send':
            print(ReceiveMessageObject.topic)
            if topic_list[6] == 'add' or topic_list[
                    6] == 'change' or topic_list[6] == 'remove':
                meeting_room_object = self.meetingRoomDict.get(
                    meeting_room_guid)
                if meeting_room_object != None:
                    yield gen.sleep(5)
                    yield meeting_room_object.handleSelfSchedule(
                        update_schedule=1)
コード例 #3
0
 def wsClientConnect(self):
     yield logClient.tornadoInfoLog("trying to connect")
     try:
         self.connectionObject = yield websocket_connect(WEBSOCKET_SERVICE)
     except Exception as e:
         self.connectionObject = None
         self.ioloop.add_timeout(self.ioloop.time() + 1, self.wsClientConnect)
         yield logClient.tornadoInfoLog("connection error")
     else:
         yield logClient.tornadoInfoLog("connected")
         self.ioloop.add_timeout(self.ioloop.time(), self.wsClientLoopRun)
         if self.device_init_flag == True:
             yield self.meetingRoomLogin()
コード例 #4
0
    def updateSelfStatus(self, channel_guid, status):
        self.status = status
        self.update_time = time.time()

        if self.on_name and self.status == 'on':
            string_status = self.on_name
        elif self.off_name and self.status == 'off':
            string_status = self.off_name
        else:
            string_status = self.status

        if self.unit:
            string_status += ' {}'.format(self.unit)
        yield logClient.tornadoInfoLog('会议室:{}的房间状态:{},更新:{}'.format(
            self.meeting_room_object.name, self.name, string_status))
        #同步会议室状态值
        yield self.meeting_room_object.updateMeetingRoomStatus(
            self.guid, self.name, string_status)
        # 状态触发规则
        for callback_info in self.updateCallback:
            function = callback_info.get('function')
            if function == None:
                continue
            selfStatus = yield self.getStatusValue()
            yield function(**callback_info.get('kwargs'),
                           status_value=selfStatus,
                           update_time=self.update_time,
                           auto_callback=0)
コード例 #5
0
 def autoLogin(self, autoFlag=None):
     yield self.login()
     if autoFlag != None:
         yield logClient.tornadoInfoLog('重新获取新的token')
         self.timerTask = self.ioloop.add_timeout(self.ioloop.time() +
                                                  86400,
                                                  self.autoLogin,
                                                  autoFlag=1)
     else:
         if self.timerTask != None:
             yield logClient.tornadoInfoLog('中途被认为token失效')
             self.ioloop.remove_timeout(self.timerTask)
         self.timerTask = self.ioloop.add_timeout(self.ioloop.time() +
                                                  86400,
                                                  self.autoLogin,
                                                  autoFlag=1)
コード例 #6
0
 def tokenChangeHandle(self):
     remove_list = []
     for client in self.callback_address_set:
         try:
             clientInfo = json.loads(client)
         except:
             remove_list.append(client)
             continue
         callback = clientInfo.get('callback')
         method = clientInfo.get('method')
         if method not in ['post', 'get', 'POST', 'GET'
                           ] or callback == None:
             remove_list.append(client)
             continue
         data = {'token': self.token}
         if method == 'get' or method == 'GET':
             result = yield asyncTornadoRequest(callback,
                                                method='GET',
                                                params=data)
         else:
             result = yield asyncTornadoRequest(callback,
                                                method='POST',
                                                body=data)
         if result.get('ret') == 0:
             yield logClient.tornadoInfoLog('token反推成功,{}'.format(callback))
             continue
         else:
             yield logClient.tornadoWarningLog(
                 'token反推失败,{}'.format(callback))
             remove_list.append(client)
     for client in remove_list:
         self.callback_address_set.discard(client)
コード例 #7
0
 def on_close(self):
     #从server的websocket对象集合中移除自己
     self.server.clientObjectSet.discard(self)
     yield logClient.tornadoInfoLog('用户 {} 退出登录,当前连接数量:{}'.format(
         self.user_name, len(self.server.clientObjectSet)))
     msg = {'type': 'logout', 'connection_token': self.connection_token}
     self.server.sendToService(json_dumps(msg))
     self = None
コード例 #8
0
 def updataSelfStatus(self,status):
     if self.type == 'button' or self.type == 'channel':
         if status == 'on' or status == 'off':
             self.channel_value = status
     elif self.type == 'level':
         try:
             self.level_value = float(status)
         except:
             pass
     elif self.type == 'string':
         self.string_value = status
     elif self.type == 'macro':
         if status == 'on' or status == 'off':
             self.channel_value = status
         else:
             yield logClient.tornadoInfoLog('聚集通道狀態反饋錯誤:{}'.format(status))
     elif self.type == 'matrix':
         if isinstance(status,dict):
             self.matrix_value = status.get('channel_guid')
             yield logClient.tornadoDebugLog('矩阵通道:{}更新状态为:{}'.format(self.name, self.matrix_value))
         else:
             try:
                 status = json.loads(status)
                 self.matrix_value = status.get('channel_guid')
                 yield logClient.tornadoDebugLog('矩阵通道:{}更新状态为:{}'.format(self.name,self.matrix_value))
             except:
                 yield logClient.tornadoErrorLog(status)
     elif self.type == 'none':
         if self.feedback == 'button' or self.feedback == 'channel':
             if status == 'on' or status == 'off':
                 self.channel_value = status
         elif self.feedback == 'level':
             try:
                 self.level_value = float(status)
             except:
                 pass
         elif self.feedback == 'string':
             self.string_value = status
         elif self.feedback == 'matrix':
             if isinstance(status, dict):
                 self.matrix_value = status.get('channel_guid')
                 yield logClient.tornadoDebugLog('矩阵通道:{}更新状态为:{}'.format(self.name, self.matrix_value))
             else:
                 try:
                     status = json.loads(status)
                     self.matrix_value = status.get('channel_guid')
                     yield logClient.tornadoDebugLog('矩阵通道:{}更新状态为:{}'.format(self.name, self.matrix_value))
                 except:
                     yield logClient.tornadoErrorLog(status)
         else:
             yield logClient.tornadoErrorLog('未知通道:{}'.format(self.guid))
             return
     else:
         yield logClient.tornadoErrorLog('未知通道:{}'.format(self.guid))
         return
     for callback in self.updateCallback:
         yield callback(self.guid,self.getSelfStatus())
コード例 #9
0
    def on_message(self, data):
        '''
        1>接受前端的信息,2>发送给websocketService,3>接受websocketService的消息,4>分发给前端
        '''
        try:
            msg = json.loads(data)
        except JSONDecodeError as e:
            try:
                msg = eval(data)
            except:
                return

        if not isinstance(msg, dict):
            return
        yield logClient.tornadoDebugLog('1---中控客户端信息:{}'.format(msg))
        msg_type = msg.get('type')
        if msg_type == 'login':
            self.meeting_room_list = msg.get('meeting_room_list')
            if self.login == None:
                self.login = True
                data = {'type': 'update_device', 'meeting_room_guid': None}
                self.sendToClientService(json_dumps(data))
        if not self.login:
            return

        if msg_type == 'heartbeat':
            # self.lastHeartbeat = time.time()
            self.lastHeartbeat = msg.get('time')

        if msg_type == 'channel_status':
            #收到中控的通道反馈信息,通过网关同步回去
            topic = msg.get('topic')
            data = msg.get('data')
            topic_list = self.TopicToList(topic)
            self.mosquittoClient.handleChannelSync(topic, topic_list, data)
        elif msg_type == 'update_device':
            yield logClient.tornadoInfoLog('从中控中获取设备更新信息')
            self.mosquittoClient.updateMeetingRoomDevice(
                msg.get('meeting_room_device_list'))
        elif msg_type == 'sync_device':
            yield logClient.tornadoInfoLog('从中控中获取设备同步信息')
            self.mosquittoClient.syncMeetingRoomDevice(
                msg.get('meeting_room_device_list'))
コード例 #10
0
    def handle_on_connect(self):
        topic = '/aaiot/mqttService/receive/controlbus/system/heartbeat'
        qos_type = QOSLOCAL
        self.connectObject.subscribe(topic, qos=qos_type)
        yield logClient.tornadoInfoLog('添加订阅主题为:{},订阅等级为:{}'.format(
            topic, qos_type))

        # 订阅排程信息
        topic = '/aaiot/+/send/controlbus/event/schedule/schedule_info/0'
        qos_type = QOSLOCAL
        self.connectObject.subscribe(topic, qos=qos_type)
        yield logClient.tornadoInfoLog('添加订阅主题为:{},订阅等级为:{}'.format(
            topic, qos_type))
        # 订阅时间事件信息
        topic = '/aaiot/0/send/controlbus/event/time/#'
        qos_type = QOSLOCAL
        self.connectObject.subscribe(topic, qos=qos_type)
        yield logClient.tornadoInfoLog('添加订阅主题为:{},订阅等级为:{}'.format(
            topic, qos_type))
コード例 #11
0
    def updateLabelInfo(self,name,company_db,delayFlag=None,callback=None):
        now_time = time.time()
        brush_info = yield self.getSelfInfo()
        if callback == None:
            if brush_info == self.lastBrushInfo:
                yield logClient.tornadoInfoLog('会议室:{},两次推送内容相同,取消推送'.format(name))
                return
        if now_time - self.lastBrushTime < 60:
            yield logClient.tornadoInfoLog('会议室:{},两次推送间隔太短,启动延时推送'.format(name))
            if self.waitBrushTask != None:
                #有任务
                yield logClient.tornadoDebugLog('会议室:{},存在相同任务,删除任务'.format(name))
                self.ioloop.remove_timeout(self.waitBrushTask)
            else:
                yield logClient.tornadoDebugLog('会议室:{},无相同任务,添加任务'.format(name))
            if callback == None:
                self.waitBrushTask = self.ioloop.add_timeout(self.ioloop.time() + 60-int((now_time - self.lastBrushTime)), self.updateLabelInfo, name,company_db, delayFlag)
            else:
                self.waitBrushTask = self.ioloop.add_timeout(self.ioloop.time() + 60-int((now_time - self.lastBrushTime)), self.updateLabelInfo, name,company_db, delayFlag, callback)
            return None

        self.lastBrushTime = now_time
        self.waitBrushTask = None
        yield self.checkSelfLabelTemplate(name)
        fault_count = 0
        while True:
            result = yield self.brushSelfInfo(brush_info)
            if result == True:
                yield logClient.tornadoInfoLog('会议室:{},{}推送商品成功'.format(name,'延时' if delayFlag else ''))
                yield self.keepNowBrushInfo(brush_info)
                yield self.storageSelf(company_db)
                yield self.printNowBrushInfo(brush_info)
                break
            elif result == 501:
                yield logClient.tornadoErrorLog('会议室:{},推送商品token失效'.format(name))
                yield self.eslCloudClient.tokenError()
            else:
                yield logClient.tornadoErrorLog('会议室:{},{}推送商品失败'.format(name,'延时' if delayFlag else ''))
            yield gen.sleep(10)
            fault_count += 1
            if fault_count >= 10:
                break
コード例 #12
0
 def updateSelfScheduleStatus(self, new_schedule_status):
     if self.scheduleStatus != new_schedule_status:
         last_status = self.scheduleStatus
         self.scheduleStatus = new_schedule_status
         yield self.storgeSelfScheduleStatus(new_schedule_status)
         if last_status == 2 and new_schedule_status == 0:
             topic = '/aaiot/{}/send/controlbus/event/schedule/remaining_time/{}'.format(
                 self.guid, 0)
             yield self.updateSelfScheduleRemainingTime(0, None)
             yield self.myPublish(topic, '', qos=QOSLOCAL)
             yield logClient.tornadoInfoLog('会议室:({})进行中排除时间变更为:{}'.format(
                 self.name, 0))
コード例 #13
0
 def brushLed(self,mac:str,color:int,total:int=1500,period:int=500,interval:int=1000,brigthness:int=5):
     if color == 0:
         real_color = 2
     elif color == 1:
         real_color = 1
     elif color == 2:
         real_color = 3
     else:
         real_color = 2
     STATUS_TO_NAME = {
         0: '空闲中',
         1: '准备中',
         2: '进行中',
     }
     yield logClient.tornadoInfoLog('{}:状态切换为{}'.format(self.name, STATUS_TO_NAME[color]),company=self.company_name)
     headers = {
         'content-type': 'application/json',
         'Authorization': 'Bearer ' + self.eslCloudClient.token
     }
     data = {
         'storeUuid': self.eslCloudClient.storeCode,
         'mac': mac,
         'color': real_color,
         'total': total,
         'period': period,
         'interval': interval,
         'brigthness': brigthness,
     }
     url = self.eslCloudClient.controlLedUrl
     result = yield asyncTornadoRequest(url, method='PUT', headers=headers, params=data, body=data)
     yield logClient.tornadoInfoLog('会议室:{},led控制推送结果:{}'.format(self.name,result),company=self.company_name)
     status = result.get('status')
     if status == 200:
         self.schedule_status = color
         return True
     else:
         yield logClient.tornadoErrorLog('{}的led推送失败'.format(self.name),company=self.company_name)
         yield self.eslCloudClient.tokenError()
         self.ioloop.add_timeout(self.ioloop.time() + 60, self.brushLed, mac, color)
         return False
コード例 #14
0
 def updateSelfScheduleRemainingTime(self, remaining_time, schedule_guid):
     try:
         remaining_time = int(remaining_time)
     except:
         return
     if self.remainingTime != remaining_time:
         self.remainingTime = remaining_time
         msg = {'schedule_guid': schedule_guid}
         topic = '/aaiot/{}/send/controlbus/event/schedule/remaining_time/{}'.format(
             self.guid, remaining_time)
         yield self.myPublish(topic, msg, qos=QOSLOCAL)
         yield logClient.tornadoInfoLog('会议室:({})进行中排除时间变更为:{}'.format(
             self.name, remaining_time))
コード例 #15
0
 def updateSelfSwitchOffStatus(self, channel_guid, status, no_channel=None):
     if channel_guid == self.off_info.get('channel_guid'):
         #判断是否关机
         if self.switch_status != 0:
             if no_channel:
                 if status == 'off':
                     self.switch_status = 0
                     yield self.meeting_room_object.updateDeviceSwitchStatus(
                         self)
                     yield logClient.tornadoInfoLog(
                         '会议室:({}),设备({}),状态更新为关机'.format(
                             self.meeting_room_name, self.name))
                     yield self.storageDeviceClose()
             else:
                 if status == self.off_info.get('realize_status'):
                     self.switch_status = 0
                     yield self.meeting_room_object.updateDeviceSwitchStatus(
                         self)
                     yield logClient.tornadoInfoLog(
                         '会议室:({}),设备({}),状态更新为关机'.format(
                             self.meeting_room_name, self.name))
                     yield self.storageDeviceClose()
コード例 #16
0
    def handle_on_connect(self):
        topic = '/aaiot/mqttService/receive/controlbus/system/heartbeat'
        qos_type = QOSLOCAL
        self.connectObject.subscribe(topic, qos=qos_type)
        yield logClient.tornadoInfoLog('添加订阅主题为:{},订阅等级为:{}'.format(
            topic, qos_type))

        topic = '/aaiot/+/receive/controlbus/event/schedule/schedule_info/0'
        qos_type = QOSLOCAL
        self.connectObject.subscribe(topic, qos=qos_type)
        yield logClient.tornadoInfoLog('添加订阅主题为:{},订阅等级为:{}'.format(
            topic, qos_type))

        topic = '/aaiot/+/receive/controlbus/event/schedule/remaining_time/0'
        qos_type = QOSLOCAL
        self.connectObject.subscribe(topic, qos=qos_type)
        yield logClient.tornadoInfoLog('添加订阅主题为:{},订阅等级为:{}'.format(
            topic, qos_type))

        topic = '/aaiot/+/receive/controlbus/event/schedule/cancel/0'
        qos_type = QOSLOCAL
        self.connectObject.subscribe(topic, qos=qos_type)
        yield logClient.tornadoInfoLog('添加订阅主题为:{},订阅等级为:{}'.format(
            topic, qos_type))

        topic = '/aaiot/+/send/controlbus/event/schedule/add'
        qos_type = QOSLOCAL
        self.connectObject.subscribe(topic, qos=qos_type)
        yield logClient.tornadoInfoLog('添加订阅主题为:{},订阅等级为:{}'.format(
            topic, qos_type))

        topic = '/aaiot/+/send/controlbus/event/schedule/remove'
        qos_type = QOSLOCAL
        self.connectObject.subscribe(topic, qos=qos_type)
        yield logClient.tornadoInfoLog('添加订阅主题为:{},订阅等级为:{}'.format(
            topic, qos_type))

        topic = '/aaiot/+/send/controlbus/event/schedule/change'
        qos_type = QOSLOCAL
        self.connectObject.subscribe(topic, qos=qos_type)
        yield logClient.tornadoInfoLog('添加订阅主题为:{},订阅等级为:{}'.format(
            topic, qos_type))

        topic = '/aaiot/+/receive/controlbus/event/schedule/schedule_info/1'
        qos_type = QOS
        self.connectObject.subscribe(topic, qos=qos_type)
        yield logClient.tornadoInfoLog('添加订阅主题为:{},订阅等级为:{}'.format(
            topic, qos_type))
コード例 #17
0
 def login(self):
     url = TOKEN_SERVICE_ADDRESS
     data = {'callback': TOKEN_CHANGE_ADDRESS, 'method': 'POST'}
     while True:
         result = yield asyncTornadoRequest(url, method='GET', params=data)
         if result.get('ret') == 0:
             self.token = result.get('token')
             if self.token != None:
                 yield logClient.tornadoInfoLog('登录成功,token:{}'.format(
                     self.token))
                 break
         yield logClient.tornadoWarningLog('登录失败')
         yield gen.sleep(5)
     yield self.updateCallback()
コード例 #18
0
 def wsClientLoopRun(self):
     '''接收websocket服务器的信息'''
     try:
         msg = yield self.serviceObject.read_message()
     except:
         msg = None
         # return
     if msg is None:
         yield logClient.tornadoInfoLog("connection closed")
         yield self.closeAllClient()
     else:
         msg = json.loads(msg)
         yield logClient.tornadoDebugLog('2---服务端信息:({})'.format(msg))
         yield self.forwardInformation(json_dumps(msg))
         self.ioloop.add_timeout(self.ioloop.time(), self.wsClientLoopRun)
コード例 #19
0
 def get(self, *args, **kwargs):
     callback = self.get_argument('callback', None)
     method = self.get_argument('method', None)
     token_error = self.get_argument('token_error', None)
     if token_error != None:
         yield logClient.tornadoInfoLog('收到反馈,token失效')
         yield self.server.login()
         content = {'ret': 0, 'token': self.server.token}
     elif callback != None and method != None:
         info = {'callback': callback, 'method': method}
         self.server.callback_address_set.add(json_dumps(info))
         content = {'ret': 0, 'token': self.server.token}
     else:
         content = {
             'ret': 1,
         }
     self.write(json_dumps(content))
コード例 #20
0
 def login(self):
     body = {'username': self.username, 'password': self.password}
     url = self.loginUrl
     while True:
         result = yield asyncTornadoRequest(url, method='POST', body=body)
         if result.get('errcode') == 200:
             result_body = result.get('body')
             if result_body == None:
                 yield gen.sleep(10)
                 continue
             self.token = result_body.get('token')
             if self.token == None:
                 yield gen.sleep(10)
                 continue
             yield logClient.tornadoInfoLog('登录成功')
             break
         else:
             yield logClient.tornadoWarningLog('登录失败')
     yield self.tokenChangeHandle()
コード例 #21
0
 def updateAllMeetingRoom(self):
     '''获取所有的会议室'''
     #todo:首先获取所有的商品
     yield self.updateGoods()
     #todo:然后获取取所有的会议室
     for DATABASE in DATABASES:
         db = DATABASE['name']
         data = {
             'database':
             db,
             'fields': [
                 'd_meeting_room.guid', 'd_meeting_room.room_name',
                 'd_meeting_room.sin_minute',
                 'd_meeting_room.status_group_guid_id as schedule_status',
                 'd_company.name as company_name'
             ],
             'eq': {
                 'd_meeting_room.is_delete': False,
                 'd_company.is_delete': False,
                 'd_meeting_room.company_guid_id': {
                     'key': 'd_company.guid'
                 }
             },
         }
         msg = yield mysqlClient.tornadoSelectAll(
             'd_meeting_room,d_company', data)
         if msg['ret'] != '0':
             yield logClient.tornadoErrorLog('获取数据库:会议室信息失败')
             break
         meeting_rooms = msg['msg']
         for meeting_room in meeting_rooms:
             # 把每一个会议室转换为会议室对象
             meeting_room_ = MeetingRoom(company_db=db,
                                         ioloop=self.ioloop,
                                         mqttClient=self.connectObject,
                                         eslCloudClient=self.eslCloudClient,
                                         goods_dict=self.goods_dict,
                                         **meeting_room)
             self.meeting_room_list.append(meeting_room_)
             # 添加会议室guid和mqtt_name的转换对象
             self.GuidToMeetingRoom[meeting_room_.guid] = meeting_room_
         else:
             yield logClient.tornadoInfoLog('公司:{}会议室初始化完成'.format(db))
コード例 #22
0
 def updateCallback(self):
     url = self.updateCallbackUrl
     body = {'pushUrl': CALLBACK_ADDRESS}
     self.headers = {
         'content-type': 'application/json',
         'Authorization': 'Bearer ' + self.token
     }
     while True:
         result = yield asyncTornadoRequest(url,
                                            method='POST',
                                            headers=self.headers,
                                            params=body,
                                            allow_nonstandard_methods=True)
         if result.get('status') == '200' or result.get('status') == 200:
             yield logClient.tornadoInfoLog('设定回调地址成功')
             return
         else:
             yield logClient.tornadoErrorLog('设定回调地址失败')
             yield self.tokenError()
             yield gen.sleep(10)
コード例 #23
0
 def wsClientLoopRun(self):
     '''接收websocket服务器的信息'''
     try:
         msg = yield self.connectionObject.read_message()
     except:
         msg = None
         # return
     if msg is None:
         yield logClient.tornadoInfoLog("connection closed")
         self.connectionObject = None
         self.ioloop.add_timeout(self.ioloop.time()+1, self.wsClientConnect)
     else:
         self.ioloop.add_timeout(self.ioloop.time(), self.wsClientLoopRun)
         try:
             msg = json.loads(msg)
         except:
             return
         yield logClient.tornadoDebugLog('2---收到服务端信息:({})'.format(msg))
         type = msg.get('type')
         if type == 'control':
             topic = msg.get('topic')
             topic_list = msg.get('topic_list')
             control_event = msg.get('control_event')
             meeting_room_guid = topic_list[1]
             try:
                 port = topic_list[6]
                 port = int(port)
             except:
                 return
             meeting_room_object = self.meeting_room_dict.get(meeting_room_guid)
             if meeting_room_object == None:
                 return
             for device_guid, device_object in meeting_room_object.items():
                 if port == device_object.port or port == str(device_object.port):
                     yield device_object.controlSelf(msg)
         elif type == 'update_device' or type == 'sync_device':
             meeting_room_guid = msg.get('meeting_room_guid')
             yield self.reportSelfDevice(type_info = type,meeting_room_guid=meeting_room_guid)
コード例 #24
0
 def infoHandler(self, msg_type, msg):
     connection_token = msg.get('connection_token')
     login_info = yield self.checkLoginState(msg_type,connection_token)
     if login_info == False:
         return
     user_type = login_info.get('user_type')
     user_name = login_info.get('user_name')
     yield logClient.tornadoInfoLog('用户 {} 获取权限内会议室所有控制通道'.format(user_name))
     control_info = msg.get('control_info')
     if control_info == '' or control_info == None:
         control_info = 0
     if user_type == 'ipad':
         # use_room_list类型判断
         use_room_list = msg.get('use_room_list')
         if not isinstance(use_room_list, list):
             yield self.baseErrorReturn(msg_type,'use_room_list Type error',connection_token)
             return
         # use_room_list权限判断
         for room_guid in use_room_list:
             if room_guid not in self.login_info[connection_token]['room_list']:
                 yield self.baseErrorReturn(msg_type, 'The whole school without meeting rooms {}'.format(room_guid), connection_token)
                 return
         use_room_list = list(set(use_room_list))
     elif user_type == 'back-end':
         use_room_list = login_info.get('room_list')
     else:
         yield self.baseErrorReturn(msg_type, 'Unable to get info', connection_token)
         return
     self.login_info[connection_token]['use_room_list'] = use_room_list
     topic = '/aaiot/0/receive/controlbus/event/websocket/0/info'
     msg = {
         'ret': 0,
         'type': msg_type,
         'control_info': control_info,
         'use_room_list': use_room_list,
         'connection_token': connection_token,
     }
     self.mosquittoClient.myPublish(topic, json_dumps(msg), QOS_LOCAL)
コード例 #25
0
 def checkSelfLabelTemplate(self,name):
     for mac,mac_template_info in self.bindingDict.items():
         new_template_id = mac_template_info.get('new_template_id')
         now_template_id = mac_template_info.get('now_template_id')
         fault_count = 0
         if new_template_id != now_template_id:
             while True:
                 result = yield self.updateLabelTemplate(mac, new_template_id)
                 if result == True:
                     self.bindingDict[mac]['now_template_id'] = new_template_id
                     yield logClient.tornadoInfoLog('会议室:{},标签:{},更新模板:{},成功'.format(name, mac, new_template_id))
                     break
                 elif result == 501:
                     yield self.eslCloudClient.tokenError()
                     yield logClient.tornadoErrorLog('会议室:{},更新模板:token失效'.format(name))
                 else:
                     yield logClient.tornadoErrorLog('会议室:{},标签:{},更新模板:{},失败'.format(name, mac, new_template_id))
                 yield gen.sleep(10)
                 fault_count += 1
                 if fault_count >= 10:
                     break
     else:
         yield gen.sleep(30)
コード例 #26
0
    def getSelfWeather(self):
        result = yield self.getWeather(self.city_id,self.name)
        # print(result)
        status = result.get('status')
        if status == 1:
            yield logClient.tornadoErrorLog(result.get('errmsg'))
            return
        city_id = result.get('cityid')          #当前城市ID
        if city_id != self.city_id:
            yield logClient.tornadoErrorLog('{}:获取的天气信息城市不一至:{},{}'.format(self.name,self.city_id,city_id))
            return
        date = result.get('date')               #日期
        # week = result.get('week')               #星期
        update_time = result.get('update_time') #气象台更新时间
        # city = result.get('city')               #天气情况
        # cityEn = result.get('cityEn')           #
        # country = result.get('country')         #
        # countryEn = result.get('countryEn')
        self.wea = result.get('wea')                 #天气情况
        self.wea_img = result.get('wea_img')         #天气对应图标(xue, lei, shachen, wu, bingbao, yun, yu, yin, qing)
        self.tem = result.get('tem')                 #当前温度
        self.tem1 = result.get('tem1')            #最小温度
        self.tem2 = result.get('tem2')            #最大温度
        self.win = result.get('win')                 #风向
        self.win_speed = result.get('win_speed')     #风速等级
        self.win_meter = result.get('win_meter')     #风速 如: 12km/h
        self.humidity = result.get('humidity')       #湿度
        self.visibility = result.get('visibility')   #能见度
        self.pressure = result.get('pressure')       #气压hPa
        self.air = result.get('air')                 #空气质量
        self.air_pm25 = result.get('air_pm25')       #PM2.5
        self.air_level = result.get('air_level')     #空气质量等级
        # air_tips = result.get('air_tips')       #空气质量描述
        # alarm = result.get('alarm')
        now_time = datetime.datetime.now()
        updateTime = datetime.datetime.strptime(date +' '+update_time,'%Y-%m-%d %H:%M')
        last_update_time = updateTime + datetime.timedelta(seconds=self.updateInvertal)
        invertal = (last_update_time - now_time).seconds+30

        yield self.publishSelfInfo()
        self.ioloop.add_timeout(self.ioloop.time()+invertal, self.getSelfWeather)
        yield logClient.tornadoInfoLog('城市:{},天气情况:{}'.format(self.name,self.wea))
        yield logClient.tornadoInfoLog('城市:{},天气对应图标:{}'.format(self.name,self.wea_img))
        yield logClient.tornadoInfoLog('城市:{},当前温度:{}'.format(self.name,self.tem))
        yield logClient.tornadoInfoLog('城市:{},最大温度:{}'.format(self.name, self.tem1))
        yield logClient.tornadoInfoLog('城市:{},最小温度:{}'.format(self.name, self.tem2))
        yield logClient.tornadoInfoLog('城市:{},风向:{}'.format(self.name,self.win))
        yield logClient.tornadoInfoLog('城市:{},风速等级:{}'.format(self.name,self.win_speed))
        yield logClient.tornadoInfoLog('城市:{},风速:{}'.format(self.name,self.win_meter))
        yield logClient.tornadoInfoLog('城市:{},湿度:{}'.format(self.name,self.humidity))
        yield logClient.tornadoInfoLog('城市:{},能见度:{}'.format(self.name,self.visibility))
        yield logClient.tornadoInfoLog('城市:{},气压hPa:{}'.format(self.name,self.pressure))
        yield logClient.tornadoInfoLog('城市:{},空气质量:{}'.format(self.name,self.air))
        yield logClient.tornadoInfoLog('城市:{},PM2.5:{}'.format(self.name,self.air_pm25))
        yield logClient.tornadoInfoLog('城市:{},空气质量等级:{}'.format(self.name,self.air_level))
コード例 #27
0
 def printNowBrushInfo(self,brush_info):
     yield logClient.tornadoInfoLog('')
     yield logClient.tornadoInfoLog('***********************************************')
     yield logClient.tornadoInfoLog('{}'.format(datetime.datetime.now()))
     yield logClient.tornadoInfoLog('会议室名称:{}'.format(brush_info['label3']))
     yield logClient.tornadoInfoLog('日期:{}'.format(brush_info['label4']))
     yield logClient.tornadoInfoLog('排程一 > 时间:{},主题:{},发起人:{}'.format(brush_info['label5'],brush_info['label6'],brush_info['label7']))
     yield logClient.tornadoInfoLog('排程二 > 时间:{},主题:{},发起人:{}'.format(brush_info['label8'],brush_info['label9'],brush_info['label10']))
     yield logClient.tornadoInfoLog('排程三 > 时间:{},主题:{},发起人:{}'.format(brush_info['label11'],brush_info['label12'],brush_info['label13']))
     yield logClient.tornadoInfoLog('排程四 > 时间:{},主题:{},发起人:{}'.format(brush_info['label14'],brush_info['label15'],brush_info['label16']))
     yield logClient.tornadoInfoLog('公司名称:{}'.format(brush_info['label17']))
     yield logClient.tornadoInfoLog('***********************************************')
     yield logClient.tornadoInfoLog('')
コード例 #28
0
    def initDevie(self):
        self.device_init_flag = False
        path = BASE_DIR + '/protocol_files'
        try:
            file_list = os.listdir(path)
        except FileNotFoundError as e:
            yield logClient.tornadoErrorLog(str(e))
            return
        for file_name in file_list:
            with open(os.path.join(path, file_name), 'r') as file:
                # with open(path + '/' + file_name, 'r') as file:
                msg = file.read()
                if not msg:
                    yield logClient.tornadoErrorLog('{} file is empty'.format(file_name))
                    continue
                else:
                    try:
                        protocol_info = json.loads(msg)
                    except JSONDecodeError as e:
                        yield logClient.tornadoErrorLog(str(e))
                        continue
            setup = protocol_info.get('setup')
            options = protocol_info.get('options')
            systemOnline = protocol_info.get('systemOnline')
            devices_list = protocol_info.get('devices_list')
            if not isinstance(devices_list, list):
                continue
            if isinstance(setup, dict):
                yield logClient.tornadoInfoLog('*****************setup info*****************')
                for key, value in setup.items():
                    yield logClient.tornadoInfoLog(str(key) + ':' + str(value))

            if isinstance(options, dict):
                yield logClient.tornadoInfoLog('*****************options info*****************')
                for key, value in options.items():
                    yield logClient.tornadoInfoLog(str(key) + ':' + str(value))

            if isinstance(systemOnline, dict):
                yield logClient.tornadoInfoLog('*****************systemOnline info*****************')
                for key, value in systemOnline.items():
                    yield logClient.tornadoInfoLog(str(key) + ':' + str(value))

            for device_info in devices_list:
                device_guid = device_info.get('device_guid')
                # device_name = device_info.get('device_name')
                port = device_info.get('port')
                room_id = device_info.get('room_id')
                # gateway_id = device_info.get('gateway_id')
                device_type = device_info.get('device_type')
                # function_list = device_info.get('function_list')
                self.meeting_room_port_set.add((room_id, port))
                if device_type == None:
                    device_ = GroupDevice(ioloop=self.ioloop, aioloop=self.aioloop, websocketClient=self, **device_info)
                    if room_id not in self.meeting_room_dict.keys():
                        self.meeting_room_dict[room_id] = {}
                    self.meeting_room_dict[room_id][device_guid] = device_
                else:
                    del device_info['device_type']
                    device_ = CurtainDevice(ioloop=self.ioloop, aioloop=self.aioloop, websocketClient=self,
                                            **device_info)
                    if room_id not in self.meeting_room_dict.keys():
                        self.meeting_room_dict[room_id] = {}
                    self.meeting_room_dict[room_id][device_guid] = device_
                '''
                self.meeting_room_dict结构
                {
                    'meeting_room_guid':{
                        'device_guid':device_object
                    }
                }
                '''
        yield self.meetingRoomLogin()
        self.device_init_flag = True
コード例 #29
0
 def logoutHandle(self, msg_type, msg):
     connection_token = msg.get('connection_token')
     if connection_token in self.login_info.keys():
         del self.login_info[connection_token]
         yield logClient.tornadoInfoLog('用户{},推出登录'.format(connection_token))
     return
コード例 #30
0
 def on_close(self):
     #从server的websocket对象集合中移除自己
     self.server.clientObjectSet.discard(self)
     yield logClient.tornadoInfoLog('用户退出登录,当前连接数量:{}'.format(
         len(self.server.clientObjectSet)))
     self = None