# 下面是主程序入口 # ################################################################################################ if __name__ == '__main__': s_g_iTaskMang_Listen_Port_PromptTask = 3 # 任务管理中心,对任务提交者的监听端口 s_g_iTaskMang_Listen_Port_PluginStatusResult = 4 # 任务管理中心,插件报告状态,和传回结果。收到后,发送参数块过去 # bot = FBot(name='TaskRegCenter', listen_mode=True, listen_operate_id=) #获取配置文件路径及文件名,文件夹不存在则创建 config_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), u"config") config_file = os.path.join(config_dir, u"config.ini") if not os.path.exists(config_dir): os.makedirs(config_dir) if not os.path.isfile(config_file): CTYLB_Log.ShowLog(0, u'Main', u'[%s] config file missing...Quit!' % g_strProgName) #配置文件不存在,直接退出 os._exit(-1) db_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), u"db") db_file = os.path.join(db_dir, u"data.db") if not os.path.exists(db_dir): os.makedirs(db_dir) # 创建机器人框架 g_LessTYLB_Bot_TRC_Srv_FrameThread = CLessTYBotFrameThread( config_file, db_file) # 设置默认环境处理 g_LessTYLB_Bot_TRC_Srv_FrameThread.SetDefaultConsoleCompatible(CtrlCHandle) # 注册用到的数据单元,当HLSession单元收到后,里面用到的单元数据 g_LessTYLB_Bot_TRC_Srv_FrameThread.RegisterNewCTUnit(
eachCTUnit.s_strParam1, eachCTUnit.s_strParam2) # ################################################################################################ # 主程序入口 实现 # ################################################################################################ if __name__ == '__main__': #获取配置文件路径及文件名,文件夹不存在则创建 config_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), u"config") config_file = os.path.join(config_dir, u"config.ini") if not os.path.exists(config_dir): os.makedirs(config_dir) if not os.path.isfile(config_file): CTYLB_Log.ShowLog(0, u'Main', u'[%s] config file missing...Quit!' % g_strProgName) #配置文件不存在,直接退出 os._exit(-1) db_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), u"db") db_file = os.path.join(db_dir, u"data.db") if not os.path.exists(db_dir): os.makedirs(db_dir) # 创建机器人框架 g_LessTYLB_Bot_FrameThread = CLessTYBotFrameThread(config_file, db_file) # 设置默认环境处理 g_LessTYLB_Bot_FrameThread.SetDefaultConsoleCompatible(CtrlCHandle) # 准备运行 g_LessTYLB_Bot_FrameThread.Prepare_Start()
def CtrlCHandle(signum, frame): global g_bSysRunning CTYLB_Log.ShowLog(1, 'CTRL_C', "Ctrl+C Input, exiting") g_bSysRunning = False
hlSockMang.PassiveSend_To_AcceptSock(iEachAcceptSock, retDataArray) pass # ################################################################################################ # 主程序入口 实现 # ################################################################################################ if __name__ == '__main__': #获取配置文件路径及文件名,文件夹不存在则创建 config_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), u"config") config_file = os.path.join(config_dir, u"config.ini") if not os.path.exists(config_dir): os.makedirs(config_dir) if not os.path.isfile(config_file): CTYLB_Log.ShowLog(0, u'Main', u'[%s] config file missing...Quit!' % g_strProgName) #配置文件不存在,直接退出 os._exit(-1) db_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), u"db") db_file = os.path.join(db_dir, u"data.db") if not os.path.exists(db_dir): os.makedirs(db_dir) # 链接主数据库 g_mainOperateWeiXinDB.ReConnect(u"172.16.56.130", 3306, u"testzhuangshiqi", u"abc888+222@@@", g_ustr_WeiXinBot_DBName) # 创建机器人框架 g_LessTYLB_Bot_FrameThread = CLessTYBotFrameThread(config_file, db_file) # 设置默认环境处理
newCTUnit2.SetStrData(strContent) retCTArray = [newCTUnit, newCTUnit1, newCTUnit2] return retCTArray # 主程序入口 if __name__ == '__main__': #获取配置文件路径及文件名,文件夹不存在则创建 config_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "config") config_file = os.path.join(config_dir, "config.ini") if not os.path.exists(config_dir): os.makedirs(config_dir) if not os.path.isfile(config_file): CTYLB_Log.ShowLog(0, 'Main', '[%s] config file missing...Quit!' % g_strProgName) #配置文件不存在,直接退出 os._exit(-1) db_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "db") db_file = os.path.join(db_dir, "data.db") if not os.path.exists(db_dir): os.makedirs(db_dir) # 创建机器人框架 g_LessTYLB_Bot_FrameThread = CLessTYBotFrameThread(config_file, db_file) # 设置默认环境处理 g_LessTYLB_Bot_FrameThread.SetDefaultConsoleCompatible(CtrlCHandle) # 准备运行 g_LessTYLB_Bot_FrameThread.Prepare_Start() g_strSelfID = g_LessTYLB_Bot_FrameThread.GetMyName()
def __init__(self, connect_to_socks=None, loop_event_callbacks=None, listen_socks=None, listen_accpet_callback=None, config_file="config/config.yaml", report_status=False, report_interval=60, comment=""): ''' 功能Bot初始化对象 :param connect_to_socks: 需要连接的套管对象集合,字典格式{"连接端的惟一ID":创建连接对应的指令值} :param loop_event_callbacks: 需要在每次主轮询时执行的函数回调集合,一般用于数据库检测操作,List集合 :param listen_socks: 需要监听的套管对象ID集合,List格式[ID] :param config_file: 配置文件路径,默认为"./config/config.ini" :param report_status: 是否向节点状态监测节点发送节点状态信息:True-发送当前节点状态信息,False-不发送当前节点状态信息,默认为False :param report_interval: 状态汇报时间间隔,单位秒,默认60秒 :param comment: 节点描述/备注,用于描述节点功能说明,默认为"" ''' # 功能Bot的名字,一般与配置文件中一致 self.__bot_name = get_config_value(config_file, 'client.myid') self.__connect_to_socks = connect_to_socks if connect_to_socks else {} self.__listen_socks = listen_socks if listen_socks else [] self.__listen_accept_callback = listen_accpet_callback self.__config_file = config_file self.__report_status = report_status self.__report_interval = report_interval self.__last_report_time = time.time() self.__node_comments = comment self.__connect_to_callbacks = {} self.__listen_callbacks = {} self.__loop_event_callbacks = loop_event_callbacks if loop_event_callbacks else [] self.__node_status = NodeStatus(name=self.__bot_name, comment=self.__node_comments) # 增加节点当前状态汇报 if self.__report_status: self.__add_report_status_sock_callbacks() assert (isinstance(self.__connect_to_socks, dict)) if len(self.__listen_socks) < 1 and len( self.__connect_to_socks.keys()) < 1: CTYLB_Log.ShowLog( 2, "Error Sock Pipes", "Connect to socks and Listen socks could not be zero at the same time." ) exit(-1) # 需要发送到服务端的数据队列数组,可能连接到多个服务端,因此以字典形式存储每个对应的发送队列数组 self.__connect_wait_to_send_arrays = {} # 监听模式下,只有一个监听行为 # 监听模式下需要发送的数据队列数组 self.__listen_wait_to_send_arrays = [] # 初始化客户端发送队列数组 for key in self.__connect_to_socks.keys(): for port in self.__connect_to_socks[key]: if key not in self.__connect_wait_to_send_arrays.keys(): self.__connect_wait_to_send_arrays[key] = {} self.__connect_wait_to_send_arrays[key][port] = [] if self.__report_status: sockInfo = SockInfo(name=key, operateId=self.__connect_to_socks[key]) obj = sockInfo.dump_obj() key = CTYLB_MainSys_MiscFunc.SafeGetUnicode(key) self.__node_status.SocksInfo['Socks'][key] = obj
def run(self): global IS_SYS_RUNNING IS_SYS_RUNNING = True # 获取配置文件路径及文件名,文件夹不存在则创建 config_file = os.path.abspath(self.__config_file) if not os.path.isfile(config_file): CTYLB_Log.ShowLog( 0, 'Main', '[%s] config file missing...Quit!' % self.__bot_name) # 配置文件不存在,直接退出 os._exit(-1) db_dir = os.path.join(os.path.abspath("."), u"db") db_file = os.path.join(db_dir, "{0}.db".format(self.__bot_name)) if not os.path.exists(db_dir): os.makedirs(db_dir) # 创建机器人框架 botFrameThread = CLessTYBotFrameThread(config_file, db_file) # 设置默认对环境全局事件处理 botFrameThread.SetDefaultConsoleCompatible( FBotV4.environment_event_handle) # 准备运行 botFrameThread.Prepare_Start() # 获得通讯管套管理对象 sockManager = botFrameThread.s_HLSockMang connectToSocks = {} # 获得通讯管套管理对象、操作结果以及操作参数块 for key in self.__connect_to_socks.keys(): connectToSocks[key] = {} for port in self.__connect_to_socks[key]: # 若为状态汇报,则间隔时间由用户指定 if key == TYFBOT_STATUS_MANAGER_IDENTIFY_NAME: sock = CTYFBot_OpSession_ConnectSock( hlSockMang=sockManager, strDestSrvName=key, iDestPort=port, iDefaultIdleTick=self.__report_interval) else: sock = CTYFBot_OpSession_ConnectSock( hlSockMang=sockManager, strDestSrvName=key, iDestPort=port, iDefaultIdleTick=1) connectToSocks[key][port] = sock CTYLB_Log.ShowLog( 0, 'exec', 'Start HLSock connect remote [{0}:{1}] --{2}'.format( key, port, self.__bot_name)) listenSocks = [] acceptSocks = [] for sockID in self.__listen_socks: listenSock = sockManager.CreateListenSock(sockID) listenSocks.append(listenSock) iFreeCount = 0 while IS_SYS_RUNNING: isTaskBusy = False for key in connectToSocks.keys(): for port in connectToSocks[key].keys(): sock = connectToSocks[key][port] if (sock.ExecNextCheck()): isTaskBusy = True if (sock.CanExecSendData()): for port in self.__connect_to_callbacks[key].keys(): execSendCTArray = self.__connect_send_package_handle( key, port) sock.ExecSendData(execSendCTArray) isTaskBusy = True if self.__report_status: if key in self.__node_status.SocksInfo[ 'Socks'].keys(): self.__node_status.SocksInfo['Socks'][key][ 'Status'] = "Up" self.__node_status.SocksInfo['Socks'][key][ 'TotalSend'] += len(execSendCTArray) self.__node_status.SocksInfo['Socks'][key][ 'LastSendTime'] = NodeStatus.get_now_timestamp( ) self.__node_status.SocksInfo[ 'TotalSend'] += len(execSendCTArray) recvCTArray = sock.PopRetriveRecvCTArray() if (not recvCTArray): bSockExist, recvCTArray = sockManager.PassiveRecv_From_ConnectSock( sock.s_iExecConnectSockIndex) if (not bSockExist): CTYLB_Log.ShowLog( 0, 'exec', 'sock close by remote. restarting.') sock.Close() if (recvCTArray): isTaskBusy = True strPeerName, iPeerPort = sockManager.GetSockPeerAddr( sock.s_iExecConnectSockIndex) if isinstance(strPeerName, bytes): strPeerName = strPeerName.decode() isNonePackageReply = True arrayLen = len(recvCTArray) if self.__report_status: if key in self.__node_status.SocksInfo[ 'Socks'].keys(): self.__node_status.SocksInfo['Socks'][key][ 'Status'] = "Up" self.__node_status.SocksInfo['Socks'][key][ 'TotalRecv'] += arrayLen self.__node_status.SocksInfo['Socks'][key][ 'LastRecvTime'] = NodeStatus.get_now_timestamp( ) self.__node_status.SocksInfo[ 'TotalRecv'] += arrayLen packageCount = 0 for eachUnit in recvCTArray: packageCount += 1 eachRetCommCTUnitArray = self.__connect_to_basic_handle( key, port, eachUnit, packageCount == arrayLen) if eachRetCommCTUnitArray: isNonePackageReply = False self.__connect_wait_to_send_arrays[key][ port].extend(eachRetCommCTUnitArray) if isNonePackageReply: defaultPackage = CTYBot_CTUnit_CommonData() self.__connect_wait_to_send_arrays[key][ port].append(defaultPackage) # 若存在监听服务 for listenSock in listenSocks: # 监听服务通信检查,检查新接受的连接 newClientSockIndex = sockManager.ExAcceptNewListenArriveSock( listenSock) if newClientSockIndex: strPeerName, iPeerPort = sockManager.GetSockPeerAddr( newClientSockIndex) if isinstance(strPeerName, bytes): strPeerName = strPeerName.decode() if self.__listen_accept_callback: self.__listen_accept_callback( listen_sock_id=listenSock, peer_name=strPeerName, peer_port=iPeerPort, client_index=newClientSockIndex) CTYLB_Log.ShowLog( 0, u'New Client Accept', u'From [%s:%d] new HLConnect %d accept.' % (strPeerName, iPeerPort, newClientSockIndex)) bTaskBusy = True acceptSocks.append(newClientSockIndex) if self.__report_status: # 添加Listen端SockInfo sockInfo = SockInfo(name=strPeerName, operateId=key, sockType='Listen') self.__node_status.SocksInfo['Socks'][ strPeerName] = sockInfo.dump_obj() self.__node_status.SocksInfo['Socks'][strPeerName][ 'Status'] = "Up" pass for iEachAcceptSock in acceptSocks: # 检查有否新数据包到达 strPeerName, iPeerPort = sockManager.GetSockPeerAddr( iEachAcceptSock) if isinstance(strPeerName, bytes): strPeerName = strPeerName.decode() bSockExist, ctUnitArray = sockManager.ActiveRecv_From_AcceptSock( iEachAcceptSock) if (not bSockExist): # 检查是否管套已经关闭 if self.__report_status: if strPeerName in self.__node_status.SocksInfo[ 'Socks'].keys(): self.__node_status.SocksInfo['Socks'][ strPeerName]['Status'] = "Down" CTYLB_Log.ShowLog( 0, u'Accept Client Closed', u'Accept sock %d closed' % (iEachAcceptSock)) acceptSocks.remove(iEachAcceptSock) break else: if (ctUnitArray): bTaskBusy = True self.__listen_basic_handle(sockManager, iEachAcceptSock, ctUnitArray) if self.__report_status: if strPeerName in self.__node_status.SocksInfo[ 'Socks'].keys(): self.__node_status.SocksInfo['Socks'][ strPeerName]['Status'] = "Up" self.__node_status.SocksInfo['Socks'][ strPeerName]['TotalRecv'] += len( ctUnitArray) self.__node_status.SocksInfo['Socks'][ strPeerName][ 'LastRecvTime'] = NodeStatus.get_now_timestamp( ) self.__node_status.SocksInfo[ 'TotalRecv'] += len(ctUnitArray) # 循环需要调用的回调处理,比如定时从数据库读取任务发送等 for loop_event_callback in self.__loop_event_callbacks: loop_event_callback() if (not isTaskBusy): iFreeCount += 1 if (iFreeCount > 50): time.sleep(0.01) else: iFreeCount = 0 for key in connectToSocks.keys(): for port in connectToSocks[key]: connectToSocks[key][port].Close() connectToSocks = {} listenSocks = [] botFrameThread.SafeStop() CTYLB_Log.ShowLog(0, "System Exited", "Bye Bye!")
def __HandleRecvParamUnExecCount(self, iUnHandleCount, iTotalCount): CTYLB_Log.ShowLog(0, 'recv-param-count', '%s total:[%d], not run:[%d]' % (self.s_bstrObjParamName, iTotalCount, iUnHandleCount))
def Vilu_TimerCheck(self): bRetValue = False # 对每个扫描任务进行检查调度 for eachPromptTask in self.s_RunnDTaskArray: if( eachPromptTask.Vilu_ExecTimerCheck()): bRetValue = True if( self.s_x_TaskRegCenter_Sock.ExecNextCheck()): bRetValue = True if( self.s_x_TaskRegCenter_Sock.CanExecSendData()): bRetValue = True # 对每个任务的准备函数进行调用 needPromptParamArray = [] for eachDTask in self.s_RunnDTaskArray: curParamArray = eachDTask.Sys_Schedule_RequestParamBlock() needPromptParamArray.extend(curParamArray) # 请求插件ID的空余数量 newCommDataCTUnit = CTYBot_CTUnit_CommonData() newCommDataCTUnit.SetIntData(CTYBot_CTUnit_CommonData.s_g_iIntValue_Query_PluginID_Run_ParamBlock_Count) newCommDataCTUnit.SetParam(str(eachDTask.s_iRunPluginID).encode(), b'') needPromptParamArray.append(newCommDataCTUnit) # 提交发送 if( not needPromptParamArray): newCommDataCTUnit = CTYBot_CTUnit_CommonData() needPromptParamArray.append( newCommDataCTUnit) self.s_x_TaskRegCenter_Sock.ExecSendData( needPromptParamArray) pass recvCTArray = self.s_x_TaskRegCenter_Sock.PopRetriveRecvCTArray() if( recvCTArray): bRetValue = True bstrPeerName, iPeerPort = self.s_hlSockMang.GetSockPeerAddr(self.s_x_TaskRegCenter_Sock.s_iExecConnectSockIndex) for eachUnit in recvCTArray: # CTYLB_Log.ShowLog(0, 'data-receive', 'from [%s:%d] recv [%d]' % (strPeerName, iPeerPort, eachUnit.s_iMyDataType)) msgObject = { "monitor_type": "status", "level": "info", "target": "", "plugin_id": -1, "block_id": "", "block_size": 0, "free_size": 0, "wait_size": 0, "success_size": 0, "result_code": 0, "msg": "PLC received <%d> bytes from <%s:%d>" % (eachUnit.s_iMyDataType, bstrPeerName, iPeerPort) } CTYLB_Log.ShowMonitor(msgType="PLC", msgObject=msgObject) if (eachUnit.s_iMyDataType == CTYLB_Bot_BaseDef.s_g_iDataType_CommonTask): self.HandleRecv_CommonData(bstrPeerName, eachUnit) elif (eachUnit.s_iMyDataType == CTYLB_Bot_BaseDef.s_g_iDataType_TaskRegCenter_sk_v1): if (eachUnit.s_iBotCmd_Main == CTYLB_Bot_BaseDef.s_g_iMainCmd_TaskRegCenter_ReportResult_V2): self.HandleRecv_Result_V2(bstrPeerName, eachUnit) self.s_x_TaskRegCenter_Sock.SetNextTempSendWaitTick(0) # 有结果到达,可能还有结果数据,这时候不等待,立即再发送获取 elif (eachUnit.s_iBotCmd_Main == CTYLB_Bot_BaseDef.s_g_iMainCmd_TaskRegCenter_ReportResult): self.HandleRecv_Result(bstrPeerName, eachUnit) self.s_x_TaskRegCenter_Sock.SetNextTempSendWaitTick(0) # 有结果到达,可能还有结果数据,这时候不等待,立即再发送获取 else: CTYLB_Log.ShowLog(1, 'data-receive', 'Unknown packet:%d-%d-%d' % (eachUnit.s_iMyDataType, eachUnit.s_iBotCmd_Main, eachUnit.s_iBotCmd_Sub)) msgObject = { "monitor_type": "status", "level": "warning", "target": "", "plugin_id": -1, "block_id": "", "block_size": 0, "free_size": 0, "wait_size": 0, "success_size": 0, "result_code": 0, "msg": "PLC unknown package received <Type:%d,MainCMD:%d,SubCMD:%d>" % (eachUnit.s_iMyDataType, eachUnit.s_iBotCmd_Main, eachUnit.s_iBotCmd_Sub) } CTYLB_Log.ShowMonitor(msgType="PLC", msgObject=msgObject) pass return bRetValue
def CtrlCHandle( signum, frame): global g_bSysRunning CTYLB_Log.ShowLog(1, u'CTRL_C', u"Ctrl+C Input, exiting %s" % (g_ustrProgName)) g_bSysRunning = False
def SubHandle_Act_Reply_RequestExec( strOrigParamRunParam, strRunType, strTaskRecID): iExRetCode = g_i_Code_Finish_Need_Run strSendUserContent = '' strNeedRunUpdateParam = '' strRunResult = '' try: iRunType = int(strRunType) iTaskRecID = int(strTaskRecID) except: iRunType = 0 iTaskRecID = 0 if( iRunType == g_i_ExecTypeID_LifeSupport_AlarmRing): # 提取json参数内容 paramCollect = json.loads(strOrigParamRunParam) strOrigExecParam = paramCollect[g_str_TotalParam_OrigParam] strRunTimeParam = paramCollect[g_str_TotalParam_RunTimeParam] # 提取原始参数 try: paramCollect = json.loads( strOrigExecParam) strOrigNotifyTime = paramCollect[g_str_Alarm_origParam_Time] strOrigAlarmContent = paramCollect[g_str_Alarm_origParam_AlarmContent] origNotifyTime = datetime.strptime(strOrigNotifyTime, g_ustr_TYLB_TimeFormat) except: origNotifyTime = datetime.now() strOrigAlarmContent = '' # 提取运行参数 try: paramCollect = json.loads( strRunTimeParam) iAlarmCount = paramCollect[g_ustr_runParam_AlarmCount] strLastAlarmTime = paramCollect[g_ustr_runParam_LastAlarmTime] # 修正参数值 lastAlarmTime = datetime.strptime( strLastAlarmTime, g_ustr_TYLB_TimeFormat) except: # 开始时,参数为空。初始化参数 iAlarmCount = 0 lastAlarmTime = datetime(2017,1,1) # 判断当前时间符合 nowTime = datetime.now() if( nowTime > origNotifyTime): # 判断有否有效的时间间隔 timeDiff = nowTime - lastAlarmTime if( timeDiff.seconds >= g_i_Min_Notify_TimeDiff): # 判断有否超过最大次数 iAlarmCount += 1 if( iAlarmCount <= g_i_Max_Notify_Count): iExRetCode = g_i_Code_Finish_Need_Run_Update_RunParam strIsLast = u' [最后一次]' if(iAlarmCount == g_i_Max_Notify_Count) else '' strSendUserContent = u'第%d次事件提醒:[%s]%s' % (iAlarmCount, strOrigAlarmContent, strIsLast) CTYLB_Log.ShowLog(0, 'Exec-Alarm', u'send msg:%s' % strSendUserContent) # 输出更新参数 strExLastAlarmTime = nowTime.strftime( g_ustr_TYLB_TimeFormat) outParamCollect = {g_ustr_runParam_AlarmCount : iAlarmCount, g_ustr_runParam_LastAlarmTime : strExLastAlarmTime} strNeedRunUpdateParam = json.dumps(outParamCollect) else: iExRetCode = g_i_Code_Finish_Stop_Task strSendUserContent = '' pass valueCollect = { g_str_Alarm_Reply_V_ResultCode : iExRetCode, g_str_Alarm_Reply_V_RunResult : strRunResult, g_str_Alarm_Reply_V_NeedUpdateRunParam : strNeedRunUpdateParam, g_str_Alarm_Reply_V_SendUserContent : strSendUserContent } strRetValue = json.dumps(valueCollect) param1Collect = { g_str_Alarm_Reply_P1_RunTypeID : g_i_ExecTypeID_LifeSupport_AlarmRing, g_str_Alarm_Reply_P1_TaskRecID : iTaskRecID } strRetParam1 = json.dumps(param1Collect) retCommCTUnit = CTYBot_CTUnit_CommonData() retCommCTUnit.SetIntData( g_i_OpAction_SubCmd_ReplyExecResult) retCommCTUnit.SetStrData( strRetValue) retCommCTUnit.SetParam( strRetParam1, '') global g_wait_ToBeSend_CTUnitArray g_wait_ToBeSend_CTUnitArray.append( retCommCTUnit)
hlSockMang.PassiveSend_To_AcceptSock(iEachAcceptSock, retDataArray) pass # ################################################################################################ # 主程序入口 实现 # ################################################################################################ if __name__ == '__main__': #获取配置文件路径及文件名,文件夹不存在则创建 config_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), u"config") config_file = os.path.join(config_dir, u"config.ini") if not os.path.exists(config_dir): os.makedirs(config_dir) if not os.path.isfile(config_file): CTYLB_Log.ShowLog(0, u'Main', u'[%s] config file missing...Quit!' % g_strProgName) #配置文件不存在,直接退出 os._exit(-1) db_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), u"db") db_file = os.path.join(db_dir, u"data.db") if not os.path.exists(db_dir): os.makedirs(db_dir) # 链接主数据库 g_mainOperate_RealActionDB.ReConnect(u"127.0.0.1", 3306, u"lessnet", u",,,,,...../////", g_str_TY2FuncBot_MiscCollect_DBName) # 创建机器人框架 g_LessTYLB_Bot_FrameThread = CLessTYBotFrameThread(config_file, db_file)
def ShowLog(iWarnLevel, strMsg): CTYLB_Log.ShowLog(iWarnLevel, u'Connect Thread', strMsg)
def run(self): self.s_MyQueue.get() lastSendResultTime = datetime.now() # 上次发送时间 iSendWaitDiffTime = 30 # 每30秒发送一次 while (self.s_bThreadRunning): iCurStatus = self.Safe_GetStatus() if (iCurStatus == CTYLB_HostExec_V2_Thread.s_g_iPrepareRun): # 调度参数进行运行 self.Safe_SetStatus(CTYLB_HostExec_V2_Thread.s_g_iRunning) # 发送开始运行的消息 bstrOrigParamUniqSign = self.s_runParamUnit.s_assignTaskParam.s_bstrUniqueSign replyCommUnit = CTYBot_CTUnit_CommonData() replyCommUnit.SetIntData( CTYBot_CTUnit_CommonData.s_g_iIntValue_Task_Start_Run) replyCommUnit.SetParam(bstrOrigParamUniqSign, self.s_bstrSelfIDName) self.Safe_AddMiddleResultData( self.s_runParamUnit.s_bstrFromName, replyCommUnit) # 设置参数标识 reportResultV2 = CTYBot_CTUnit_TaskRegCenter_ReportResult_V2() reportResultV2.s_bstrOrigTaskUniqueSign = bstrOrigParamUniqSign # 发送每个运行结果 paramCTUnit = self.s_runParamUnit.s_assignTaskParam if (paramCTUnit.s_iMyDataType == CTYLB_Bot_BaseDef.s_g_iDataType_TaskRegCenter_sk_v1): if (paramCTUnit.s_iBotCmd_Main == CTYLB_Bot_BaseDef. s_g_iMainCmd_TaskRegCenter_Assign_WebNameBlock): if (paramCTUnit.s_iBotCmd_Sub == CTYLB_Bot_BaseDef. s_g_iSubCmd_TaskRegCenter_Assign_WebNameBlock): iRunPluginID = paramCTUnit.s_iRunPluginID bstrRunHostNameArray = paramCTUnit.s_bstrDomainNameArray for bstrEachHost in bstrRunHostNameArray: ustrEachHost = CTYLB_MainSys_MiscFunc.SafeGetUnicode( bstrEachHost) iReplyPluginID, bstrRunContent = 0, b'' if (self.s_pluginExecWebCallBackFunc): try: iReplyPluginID, ustrRunContent = self.s_pluginExecWebCallBackFunc( iRunPluginID, ustrEachHost) bstrRunContent = CTYLB_MainSys_MiscFunc.SafeGetUTF8( ustrRunContent) except Exception as e: ustrMsg = u'Run Plugin [%s] Error.[%s]' % ( ustrEachHost, str(e)) CTYLB_Log.ShowLog( 1, u'Running Plugin %d' % (iRunPluginID), ustrMsg) pass # 加入到队列,进行输出 bstrFixRunContent = CTYLB_P2P_ContentUnit_Base_bytes.SafeConvertStrToUTF8_Base64( bstrRunContent) reportResultV2.AddSubResultUnit( iReplyPluginID, bstrEachHost, bstrFixRunContent) curTime = datetime.now() timeDiff = curTime - lastSendResultTime if (timeDiff.seconds >= iSendWaitDiffTime): lastSendResultTime = curTime self.Safe_AddMiddleResultData( self.s_runParamUnit.s_bstrFromName, reportResultV2) # 输出后,重新申请一个新的单元 reportResultV2 = CTYBot_CTUnit_TaskRegCenter_ReportResult_V2( ) reportResultV2.s_bstrOrigTaskUniqueSign = bstrOrigParamUniqSign time.sleep(0.1) pass # 有有效内容?输出 if (len(reportResultV2.s_subResultUnitArray) > 0): self.Safe_AddMiddleResultData( self.s_runParamUnit.s_bstrFromName, reportResultV2) # 发送运行完成的消息 replyCommUnit = CTYBot_CTUnit_CommonData() replyCommUnit.SetIntData( CTYBot_CTUnit_CommonData.s_g_iIntValue_Task_Finish) replyCommUnit.SetParam( self.s_runParamUnit.s_assignTaskParam.s_bstrUniqueSign, b'') self.Safe_AddMiddleResultData( self.s_runParamUnit.s_bstrFromName, replyCommUnit) # 任务自由,可以重新接收参数运行 self.Safe_SetStatus(CTYLB_HostExec_V2_Thread.s_g_iFree) pass bTaskBusy = False if (not bTaskBusy): time.sleep(0.1) self.s_MyQueue.task_done() # finish queue unit pass
def CtrlCHandle(signum, frame): global g_bSysRunning CTYLB_Log.ShowLog(1, u'CTRL_C', u"Ctrl+C Input, exiting") g_bSysRunning = False # 主程序入口 if __name__ == '__main__': #获取配置文件路径及文件名,文件夹不存在则创建 config_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), u"config") config_file = os.path.join(config_dir, u"config.ini") if not os.path.exists(config_dir): os.makedirs(config_dir) if not os.path.isfile(config_file): CTYLB_Log.ShowLog(0, u'Main', u'[%s] config file missing...Quit!' % g_strProgName) #配置文件不存在,直接退出 os._exit(-1) db_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), u"db") db_file = os.path.join(db_dir, u"data.db") if not os.path.exists(db_dir): os.makedirs(db_dir) s_g_iTaskMang_Listen_Port_PluginStatusResult = 4 # 任务管理中心,插件报告状态,和传回结果。收到后,发送参数块过去 # 创建机器人框架 g_LessTYLB_Bot_ExecPlugin_FrameThread = CLessTYBotFrameThread( config_file, db_file) # 设置默认环境处理 g_LessTYLB_Bot_ExecPlugin_FrameThread.SetDefaultConsoleCompatible( CtrlCHandle)
"block_size":0, "free_size":0, "wait_size":0, "success_size":0, "result_code":0, "msg":"PLC loading config..." } CTYLB_Log.ShowMonitor(msgType="PLC",msgObject=msgObject) #获取配置文件路径及文件名,文件夹不存在则创建 config_dir=os.path.join(os.path.dirname(os.path.realpath(__file__)),"config") config_file= os.path.join(config_dir,"config.ini") if not os.path.exists(config_dir): os.makedirs(config_dir) if not os.path.isfile(config_file): CTYLB_Log.ShowLog(0, 'Main', '[%s] config file missing...Quit!' % g_strProgName) msgObject={ "monitor_type":"status", "level":"error", "target":"", "plugin_id":-1, "block_id":"", "block_size":0, "free_size":0, "wait_size":0, "success_size":0, "result_code":0, "msg":"Config file not found, PLC exiting..." } CTYLB_Log.ShowMonitor(msgType="PLC",msgObject=msgObject) #配置文件不存在,直接退出