Пример #1
0
    def _Check_Connection(self):
        #TCP是否关闭或正在关闭,则重连
        isReConnect = False
        #if(self.usrConn.is_closed or self.usrConn.is_closing):
        if (self.usrConn.is_closed):
            self.Init()
            isReConnect = True

        #重建频道
        if (isReConnect or self.usrChannel.is_closed):
            usrType = myData.iif(self.isSender, "生产者", "消费者")
            myDebug.Print("消息队列MQ::",
                          usrType + ">> " + self.nameQueue + "已经掉线!")

            #在连接上创建一个频道
            #self.usrChannel = self.usrConn.channel()

            #声明一个队列,生产者和消费者都要声明一个相同的队列,用来防止万一某一方挂了,另一方能正常运行
            #self.usrChannel.queue_declare(queue=self.nameQueue)

            try:
                self.Init_Queue(self.nameQueue, self.isDurable, self.isAutoAck)
                time.sleep(2)
                myDebug.Print("消息队列MQ::",
                              usrType + ">> " + self.nameQueue + "已重连!")
            except Exception as ex:
                myDebug.Print("消息队列MQ::",
                              usrType + ">> " + self.nameQueue + "重连失败!")
                myError.Error(ex)
                pass
        self.isInited = self.usrConn.is_open  #标识是否在线
Пример #2
0
    def callback_Consumer(self, ch, method, properties, body):
        #回调,通知处理消息
        if (self.callback_RecvMsg != None):
            try:
                strMsg = body.decode('utf-8')
                if (strMsg == self.strHeartbeat):
                    ch.basic_ack(delivery_tag=method.delivery_tag
                                 )  #接收到消息后会给rabbitmq发送一个确认
                    #myDebug.Print("消息队列MQ::", self.nameQueue + ">> ", "接受心跳::" + strMsg)
                    return

                #消息回调
                self.callback_RecvMsg(strMsg)
                ch.basic_ack(
                    delivery_tag=method.delivery_tag)  #接收到消息后会给rabbitmq发送一个确认
            except Exception as ex:
                usrType = myData.iif(self.isSender, "生产者", "消费者")
                myDebug.Print("消息队列MQ::",
                              usrType + ">> " + self.nameQueue + "连接中断!")
                myError.Error(ex)
            finally:
                #if(self.isAutoAck == False):
                #    #不论当前消息是否成功,都表示消息确实处理完了 手动确认 否则没有ack不再发送新消息 保证确实被处理了再确认
                #    ch.basic_ack(delivery_tag = method.delivery_tag)  #接收到消息后会给rabbitmq发送一个确认
                pass
Пример #3
0
 def active_reply(self):
     # 提取消息类型对应的装饰函数
     if (self.funActive != None):
         try:
             r = self.funActive()
         except Exception as ex:
             myError.Error(ex)
             pass
Пример #4
0
    def callback_RecvMsg(self, body):
        if (self.isRunning):
            try:
                msg = ast.literal_eval(body)
                myDebug.Debug("接收队列消息robot::", msg['msg'])

                #调用消息处理(并推送消息管理器)
                self.Done_ByMsg(msg, True)
                return True
            except Exception as ex:
                myError.Error(ex)
                return True
        return False
Пример #5
0
    def Done_Swap_MsgOut(self, msg, isGroup=False):
        if (msg or len(msg) > 1):
            myDebug.Debug("消息接收::", msg['Text'])
            if (str(msg['Text']) == '[]'): return
            if (msg.get('Type', "") == 'System'): return

            #特殊消息处理
            try:
                destPath = ""
                dtTime = myData_Trans.Tran_ToTime_byInt(
                    myData_Trans.To_Int(str(msg.get('CreateTime', 0))))
                msgType = msg['MsgType']
                if (msgType == 3):  # 图片
                    destPath = self.dirPic + "Temps/" + msg.fileName
                    msg.download(destPath)
                    time.sleep(1)
                elif (msgType == 49):  # 文件
                    destPath = self.dirFile + "Temps/" + msg.fileName
                    msg.download(destPath)
                    time.sleep(1)

                #组装消息内容
                wxMsg = self.pMMsg.OnCreatMsg()
                wxMsg['usrID'] = msg['User']['UserName']
                wxMsg['usrName'] = msg['User']['NickName']
                wxMsg['usrNameNick'] = msg['User']['RemarkName']
                wxMsg['groupID'] = myData.iif(isGroup, msg['User']['UserName'],
                                              "")
                if (wxMsg['groupID'] != ""):
                    wxMsg['usrNameNick'] = msg['ActualNickName']
                    if (wxMsg['usrNameNick'] == ""):
                        if (msg['FromUserName'] == self.usrName):
                            wxMsg['usrNameNick'] = self.usrName_Alias
                wxMsg['msgID'] = msg['MsgId']
                wxMsg['msgType'] = msg['Type'].upper()
                wxMsg['msg'] = msg['Text']
                wxMsg['msgContent'] = msg.get('Content', '')
                wxMsg['usrPlat'] = "wx"
                wxMsg['msgTime'] = myData_Trans.Tran_ToTime_str(dtTime)
                if (destPath != ""):
                    wxMsg['msg'] = destPath

                #保存
                if (msgType == 1 or msgType == 10002):
                    if (wxMsg['msg'] != ""):
                        self.swapOut.SwapData_Out(wxMsg)
            except Exception as ex:
                myError.Error(ex)
        return
Пример #6
0
    def checkMsg(self, strMsg):
        try:
            myDebug.Debug("\r\n接收队列消息window::", strMsg)
            msgR = ast.literal_eval(strMsg)

            #时间校检, 十分钟内缓存数据有效(过早时间数据忽略)
            if (self.checkTimeOut(msgR)):
                myDebug.Debug("--队列消息已超时window::", strMsg)
                return True

            #消息处理
            return self.handelMsg(msgR)
        except Exception as ex:
            myError.Error(ex)
            return True
Пример #7
0
    def _Monitor_Consumer(self):
        while True:
            try:
                self._Check_Connection()
                time.sleep(self.nHeartbeat)

                #主动发送内容,模拟心跳
                if (self.isSender):
                    self.Send_Msg(self.nameQueue, self.strHeartbeat)
                    #myDebug.Print("消息队列MQ::", self.nameQueue + ">> ", "发送心跳::" + self.strHeartbeat)
            except Exception as ex:
                usrType = myData.iif(self.isSender, "生产者", "消费者")
                myDebug.Print("消息队列MQ::",
                              usrType + ">> " + self.nameQueue + "连接中断!")
                myError.Error(ex)
                pass
Пример #8
0
    def Done(self, usrID, usrName, usrNameNick, strText, msgID = "", msgType = "TEXT", msgTime = 0, idGroup = "", nameGroup = '', nameSelf = '', noteMsg = None, srcMsg = None):
        #组装请求参数字典
        # {'msg': '@@Repeater', 'usrName': '墨紫_0', 'usrNameNick': '墨紫', 'groupID': '', 'usrPlat': 'wx', 'msgType': 'TEXT', 'usrID': 'zxc_0', 'msgID': ''}
        msg = self.usrMMsg.OnCreatMsg()
        msg["usrID"] = usrID
        msg["usrName"] = usrName
        msg["usrNameNick"] = usrNameNick
        msg['usrNameSelf'] = nameSelf       #自己发自己标识 
        msg["groupID"] = idGroup
        msg["groupName"] = nameGroup

        msg["msg"] = strText
        msg["msgID"] = msgID
        msg["msgType"] = msgType
        if(msgTime > 0): msg['time'] = msgTime 
        msg["usrPlat"] = "wx"
        if(noteMsg != None): 
            msg['noteInfo'] = noteMsg       #加入通知信息 noteMsg  
            msg["msg"] = str(noteMsg)       #调整消息内容为noteMsg
        print("请求消息:: ", msg)

        #请求robotAPI
        robotPath = self.routeReply + str(msg) 
        strReturn = ""
        try:
            if(self.useMQ):
                self.usrMMsg.OnHandleMsg(msg, 'robot')     #消息处理--推送至消息处理器
                return None
            else:
                strReturn = self.robotAPI.Do_API_get(robotPath, "zxcAPI-py") 

                #处理返回结果 
                if(strReturn == "null" or strReturn == ""): return None
                if(strReturn != None):
                    msgRe = ast.literal_eval(strReturn) 
                    return msgRe
        except Exception as ex:
            myError.Error(ex)
            pass
        return None
Пример #9
0
    def Run_Monitor_Cmd_ByMQ(self, strMsg):
        try:
            myDebug.Debug("接收队列消息wx::", strMsg)
            msgR = ast.literal_eval(strMsg)

            #时间校检, 十分钟内缓存数据有效(过早时间数据忽略)
            if (self.wxReply.Check_TimeOut(msgR)):
                myDebug.Debug("--队列消息已超时wx::", strMsg)
                return True

            #消息发送
            if (msgR.get('groupID', '') != ''
                    or msgR.get('groupName', '') != ''):  #区分群、个人
                self.Send_Msg(msgR['groupID'], msgR['groupName'], msgR['msg'],
                              msgR['msgType'], 1)
            else:
                self.Send_Msg(msgR['usrID'], msgR['usrName'], msgR['msg'],
                              msgR['msgType'])
            return True
        except Exception as ex:
            myError.Error(ex)
            return True
Пример #10
0
    def _GetParam(self, argv=None):
        if argv is None:
            self.baseArgv = sys.argv
        elif (type(argv) == str):
            self.baseArgv = self.clone_Argv_sys()
            self.baseArgv.append(argv)
        elif (type(argv) == list):
            self.baseArgv = self.clone_Argv_sys()
            for x in argv:
                if (type(x == str)):
                    self.baseArgv.append(x)
        #print("Usparam Test:")
        #Usage("Err")

        try:
            try:
                #处理命令行参数
                self.basePath = self.baseArgv[0]
                opts, args = getopt.getopt(self.baseArgv[1:], self.baseOptions,
                                           self.baseLong_Options)

                #循环提取命令行参数
                for opt, arg in opts:
                    #提取参数名
                    nCount = opt.count("-")
                    bLong = False
                    strName = opt[1:]
                    if (nCount == 2):
                        strName = opt[2:]
                        bLong = True

                    #转换为类属性
                    if (bLong):
                        #判断是否有=好,无的为布尔类型
                        nIndex = self.baseLong_Options_N.index(strName)
                        if (self.baseLong_Options[nIndex] == strName):
                            #名称相同为无=参数
                            self.__dict__[strName] = True
                        else:
                            self.__dict__[strName] = arg
                    else:
                        self.__dict__[strName] = arg

                    if (self.basePrintDict):
                        print(strName)
                        print(self.__dict__[strName])

                if (self.basePrintDict):
                    print("Done: Param Loaded.")

            except (getopt.error):
                strLong = ""
                for opt in self.baseLong_Options:
                    strLong += "--" + opt + " "
                print("Err: Param Error \n  you can use param like:")
                print("    ***.py " + self.baseOptions + " or " + strLong)
                print("  for help you can use --help")
                raise Usage("Err")

        except Exception as e:
            myError.Error(e)
            #print(sys.stderr, "for help use --help")
            return 2
Пример #11
0
        return pValues

    #克隆系统项目
    def clone_Argv_sys(self, bClear=True):
        pArgv = sys.argv.copy()
        if (bClear):
            while (len(pArgv) > 1):
                pArgv.pop()
        return pArgv


def main(*args):
    #pArgv = Usargv("",["help","output="])
    pArgv = Usargv("", ["prj=", "prj2=", "prj3="], *args)
    print(pArgv._GetParamValue("prj"))
    print(pArgv._GetParamValue("prj2"))
    print(pArgv._GetParamValue("prj3"))
    print(pArgv.basePath)


if __name__ == '__main__':
    sys.argv.append("--prj=GModel_Base")
    main("--prj2=GModel_Base2")
    print("")
    main(["--prj2=GModel_Base22", "--prj3=GModel_Base33"])

    try:
        a = 1 / 0
    except Exception as e:
        myError.Error(e)