鱼C论坛

 找回密码
 立即注册
查看: 1118|回复: 2

函数的参数为event,之前没见过,想问是什么意思

[复制链接]
发表于 2022-7-3 16:22:20 | 显示全部楼层 |阅读模式
10鱼币
本帖最后由 香喷喷的咸鱼 于 2022-7-3 16:43 编辑

def order_list_timer_cb(event):
        process_order_list()
rospy.Timer(rospy.Duration(1), order_list_timer_cb)

代码如上形式
第三行为每秒调用一次order_list_timer_cb这个函数
第一行中order_list_timer_cb的传入参数为event,找不到它的用法,还是说这是一个默认的形式,想问有见过这样用的人没?


以下是代码

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. #import json         # Used for reading JSON files (loading jobs to JobQueue)
  4. #import os           # Used to get base filename and file and directory handling

  5. import rospy
  6. #import actionlib

  7. #from JobManager.Tasks import TaskStatus, TaskType, RobotMoveBase, AwaitingLoadCompletion
  8. from typing import Union, Any

  9. from JobManager.Job import JobStatus, Job, JobPriority
  10. from JobManager.Location import Location, make_location_dict
  11. from JobManager.JobBuilder import job_builder
  12. from JobManager.JobActivation import job_allocator, job_refiner
  13. from JobManager.MobileExecutor import MExStatus, MobileExecutor
  14. from JobManager.Order import *
  15. from JobManager.JobServiceMethods import call_get_mex_list, call_unassign_job

  16. from rooster_fleet_manager.srv import PlaceOrder, PlaceOrderResponse, GetPendingJobs, GetPendingJobsResponse, \
  17.     GetActiveJobs, GetActiveJobsResponse, GetJobInfo, GetJobInfoResponse, \
  18.     GetMexList, GetMexListResponse, GetMexListRequest, AssignJobToMex, AssignJobToMexRequest
  19. from rooster_fleet_manager.msg import PendingJob, ActiveJob, JobInfo, TaskInfo

  20. NODE_NAME = "[job_manager] "

  21. #region Service callback definitions

  22. # - PlaceOrder service callback -
  23. def order_service_cb(request):
  24.     """
  25.     PlaceOrder service callback function.
  26.     Takes in a PlaceOrderRequest request with a order keyword, priority and arguments.
  27.     Processes these and adds the processed order in list form to the order_list.
  28.     Returns a PlaceOrderResponse response with information on if the call failed and why.
  29.     """
  30.     print(NODE_NAME + "Order service has been called with: " + str(request))
  31.     # print(NODE_NAME + "Arguments: ", request.order_args, "List size: ", len(request.order_args) )
  32.     order_response = PlaceOrderResponse()

  33.     # NOTE RUDIMENTARY ORDER PROCESSING, RIGID IN NATURE.
  34.     if request.keyword == OrderKeyword.TRANSPORT.name: # Keyword: TRANSPORT.
  35.         # Expecting: transport, priority, [from_location, to_location]
  36.         if len(request.order_args) == OrderTypeArgCount.TRANSPORT.value:
  37.             priority = JobPriority[request.priority].value   # Check if it's >= 1 and <= 4.
  38.             from_loc = request.order_args[0]        # Check if it's in the known locations dictionary
  39.             to_loc = request.order_args[1]          # Check if it's in the known locations dictionary
  40.             if (priority >= 1 and priority <= 4) and (from_loc in location_dict) and (to_loc in location_dict):
  41.                 # Succesful check on keyword and arguments, add order to order_list.
  42.                 order_response.error_status = OrderResponseStatus.SUCCES.name
  43.                 order_response.error_report = ""
  44.                 order_list.append([request.keyword, JobPriority(priority), from_loc, to_loc])
  45.             else:
  46.                 # Error occured, set status to ERROR and supply erorr report.
  47.                 order_response.error_status = OrderResponseStatus.ERROR.name
  48.                 order_response.error_report = \
  49.                     "[TRANSPORT] Invalid priority (" + str(not (priority >= 1 and priority <= 4)) + \
  50.                     ") or location argument (" + \
  51.                     str(not ((from_loc in location_dict) and (to_loc in location_dict))) + \
  52.                     ")."
  53.         else:
  54.             # Error occured, set status to ERROR and supply erorr report.
  55.             order_response.error_status = OrderResponseStatus.ERROR.name
  56.             order_response.error_report = "[TRANSPORT] Invalid number of arguments, expected " + \
  57.                 str(OrderTypeArgCount.TRANSPORT.value) + \
  58.                 ", received " + str(len(request.order_args))
  59.         
  60.     elif request.keyword == OrderKeyword.MOVE.name:    # Keyword: MOVE.
  61.         # Expecting: move, priority, [to_location]
  62.         if len(request.order_args) == OrderTypeArgCount.MOVE.value:
  63.             priority = JobPriority[request.priority].value   # Check if it's >= 1 and <= 4.
  64.             to_loc = request.order_args[0]          # Check if it's in the known locations dictionary
  65.             if (priority >= 1 and priority <= 4) and (to_loc in location_dict):
  66.                 # Succesful check on keyword and arguments, add order to order_list.
  67.                 order_response.error_status = OrderResponseStatus.SUCCES.name
  68.                 order_response.error_report = ""
  69.                 order_list.append([request.keyword, JobPriority(priority), to_loc])
  70.             else:
  71.                 # Error occured, set status to ERROR and supply error report.
  72.                 order_response.error_status = OrderResponseStatus.ERROR.name
  73.                 order_response.error_report = "[MOVE] Invalid priority (" + \
  74.                     str(not (priority >= 1 and priority <= 4)) + \
  75.                     ") or location argument (" + \
  76.                     str(not (to_loc in location_dict) ) + ")."
  77.         else:
  78.             # Error occured, set status to ERROR and supply erorr report.
  79.             order_response.error_status = OrderResponseStatus.ERROR.name
  80.             order_response.error_report = "[MOVE] Invalid number of arguments, expected " + \
  81.                 str(OrderTypeArgCount.MOVE.value) + \
  82.                 ", received " + str(len(request.order_args))

  83.     elif request.keyword == OrderKeyword.LOAD.name:     # Keyword: LOAD
  84.         # Expecting: load, priority, []
  85.         if len(request.order_args) == OrderTypeArgCount.LOAD.value:
  86.             priority = JobPriority[request.priority].value  # Check if it's >= 1 and <= 4.
  87.             if (priority >= 1 and priority <= 4):
  88.                 # Succesful check on keyword and arguments, add order to order_list.
  89.                 order_response.error_status = OrderResponseStatus.SUCCES.name
  90.                 order_response.error_report = ""
  91.                 order_list.append([request.keyword, JobPriority(priority)])
  92.             else:
  93.                 # Error occured, set status to ERROR and supply error report.
  94.                 order_response.error_status = OrderResponseStatus.ERROR.name
  95.                 order_response.error_report = "[LOAD] Invalid priority."
  96.         else:
  97.             # Error occured, set status to ERROR and supply error report.
  98.             order_response.error_status = OrderResponseStatus.ERROR.name
  99.             order_response.error_report = "[LOAD] Invalid number of arguments, expected " + \
  100.                 str(OrderTypeArgCount.LOAD.value) + \
  101.                 ", received " + str(len(request.order_args))

  102.     elif request.keyword == OrderKeyword.UNLOAD.name:     # Keyword: UNLOAD
  103.         # Expecting: load, priority, []
  104.         if len(request.order_args) == OrderTypeArgCount.UNLOAD.value:
  105.             priority = JobPriority[request.priority].value  # Check if it's >= 1 and <= 4.
  106.             if (priority >= 1 and priority <= 4):
  107.                 # Succesful check on keyword and arguments, add order to order_list.
  108.                 order_response.error_status = OrderResponseStatus.SUCCES.name
  109.                 order_response.error_report = ""
  110.                 order_list.append([request.keyword, JobPriority(priority)])
  111.             else:
  112.                 # Error occured, set status to ERROR and supply error report.
  113.                 order_response.error_status = OrderResponseStatus.ERROR.name
  114.                 order_response.error_report = "[LOAD] Invalid priority."
  115.         else:
  116.             # Error occured, set status to ERROR and supply error report.
  117.             order_response.error_status = OrderResponseStatus.ERROR.name
  118.             order_response.error_report = "[LOAD] Invalid number of arguments, expected " + \
  119.                 str(OrderTypeArgCount.UNLOAD.value) + \
  120.                 ", received " + str(len(request.order_args))
  121.     else:
  122.         # Error occured, set status to ERROR and supply erorr report.
  123.         order_response.error_status = OrderResponseStatus.ERROR.name
  124.         order_response.error_report = "Invalid keyword."    # Could not interpret order keyword.

  125.     # print(NODE_NAME + "Order service is done, current order_list: " + str(order_list))
  126.     return order_response # the service Response class, in this case PlaceOrderResponse

  127. # - GetPendingJobs service callback -
  128. def get_pending_jobs_service_cb(request):
  129.     """
  130.     GetPendingJobs service callback function.
  131.     Takes in a empty request.
  132.     Returns a response with a list of all Pending Jobs and some basic information.
  133.     """
  134.     # print(NODE_NAME + "A service request for the Pending Jobs List has been received.")
  135.     pending_jobs_response = GetPendingJobsResponse()
  136.     pending_jobs_response.jobs_count = len(pending_job_list)
  137.     for job in pending_job_list:
  138.         pending_job = PendingJob()
  139.         pending_job.priority = job.priority.name
  140.         pending_job.job_id = job.id
  141.         pending_job.task_count = job.task_count
  142.         pending_job.keyword = job.keyword
  143.         pending_jobs_response.jobs.append(pending_job)
  144.     return pending_jobs_response

  145. # - GetActiveJobs service callback -
  146. def get_active_jobs_service_cb(request):
  147.     """
  148.     GetActiveJobs service callback function.
  149.     Takes in a empty request.
  150.     Returns a response with a list of all Active Jobs and all basic information.
  151.     """
  152.     # print(NODE_NAME + "A service request for the Active Jobs List has been received.")
  153.     active_jobs_response = GetActiveJobsResponse()  #数据类型,被激活的任务数量
  154.     active_jobs_response.jobs_count = len(active_job_list)
  155.     for job in active_job_list:   #多个任务的详细信息被存储
  156.         active_job = ActiveJob()
  157.         active_job.job_id = job.id
  158.         active_job.status = job.status.name
  159.         active_job.priority = job.priority.name
  160.         active_job.mex_id = job.mex_id
  161.         active_job.task_count = job.task_count
  162.         active_job.current_task = job.task_current
  163.         active_job.keyword = job.keyword
  164.         active_jobs_response.jobs.append(active_job)
  165.     return active_jobs_response

  166. # - GetJobInfo service callback -
  167. def get_job_info_service_cb(request):
  168.     """
  169.     GetJobInfo service callback function.
  170.     Takes in a request with a Job ID.
  171.     Returns a response with all information on the Job
  172.     matching the call ID, including a list of the Job's Tasks.
  173.     """
  174.     job_id_to_find = request.job_id
  175.     print(NODE_NAME + "A service request for the Get Job Info has been received for " + job_id_to_find + ".")
  176.     job_info_response = GetJobInfoResponse()
  177.     found_job = None
  178.     for job in pending_job_list:
  179.         if job.id == job_id_to_find:
  180.             found_job = job
  181.             break
  182.     else:
  183.         for job in active_job_list:
  184.             if job.id == job_id_to_find:
  185.                 found_job = job
  186.                 break
  187.         else:
  188.             job_info_response.error_status = "ERROR"  # TODO Replace with error messages enum.
  189.             job_info_response.error_report = "Could not find " + job_id_to_find + " in pending or active job lists."
  190.    
  191.     if found_job != None:
  192.         job_information = JobInfo()
  193.         job_information.job_id = found_job.id
  194.         job_information.status = found_job.status.name
  195.         job_information.priority = found_job.priority.name
  196.         job_information.mex_id = found_job.mex_id if not found_job.mex_id == None else ""
  197.         job_information.task_count = found_job.task_count
  198.         job_information.current_task = found_job.task_current if not found_job.task_current == None else 0
  199.         job_information.keyword = found_job.keyword
  200.         for task in found_job.task_list:
  201.             task_info = TaskInfo()
  202.             task_info.status = task.status.name
  203.             task_info.type = task.type.name
  204.             job_information.task_list.append(task_info)
  205.         job_info_response.job_info = job_information
  206.         job_info_response.error_status = "SUCCES"

  207.     return job_info_response
  208. #endregion

  209. #region Timer callback definitons

  210. # - Order list timer callback -
  211. def order_list_timer_cb(event):
  212.     """ Order list timer callback function. Calls process_order_list function. """
  213.     print(NODE_NAME + "Order list timer callback, processing order_list and building rough jobs.")
  214.     process_order_list()

  215. # - Job allocator timer callback -
  216. def job_allocator_timer_cb(event):
  217.     """ Job allocator timer callback function. Calls job allocator function. """
  218.     #删除choose后,根据job类型选择不同种类mex
  219.     #if job_allocator(pending_jobs_list=pending_job_list, active_jobs_list=active_job_list, mexs_list=mex_list,choose="rdg") != 0:
  220.     #1.有job被分配:job_allocator = 0
  221.     #2.无job被分配:job_allocator !=0
  222.     #无论有无job被分配,都执行该函数即可
  223.     if job_allocator(pending_jobs_list=pending_job_list, active_jobs_list=active_job_list, mexs_list=mex_list) != 0:
  224.         # rospy.loginfo("Failed to allocate job.")
  225.         pass

  226. #endregion

  227. #region Job completion callback definition
  228. def job_completion_cb(job_id, mex_id):
  229.     """
  230.     Job completion callback function, gets called when a
  231.     Jobs is finished (succesful, cancel, error or abort).
  232.     It is attached to a Job in the job_builder function.
  233.     """
  234.     print(NODE_NAME + "Job called the job_completion_cb function: " + str(job_id) + ", " + str(mex_id))
  235.     # First send update to MEx Sentinel to unassign job.
  236.     call_unassign_job(mex_id=mex_id)
  237.     # Then call MEx Sentinel to provide latest MEx List.
  238.     mex_list = call_get_mex_list()

  239.     # Remove completed Job from the active_job_list.
  240.     index_to_pop = None
  241.     for index, job in enumerate(active_job_list):
  242.         if job.id == job_id:
  243.             index_to_pop = index
  244.             break
  245.     else:
  246.         # Couldn't find job_id in active_job_list... Handle this?
  247.         pass
  248.     if not index_to_pop == None:
  249.         active_job_list.pop(index_to_pop)
  250. #endregion

  251. def process_order_list():
  252.     """
  253.     Build jobs from all orders in the order_list by calling
  254.     the job_builder function, then clear the order_list.
  255.     """
  256.     global job_index    #设置全局变量,job的索引
  257.     for order in order_list:      #每一个order,即添加一个job
  258.         job_index = job_builder(pending_jobs_list=pending_job_list, order=order, job_index=job_index, location_dict=location_dict, completion_cb=job_completion_cb)  # type: Union[int, Any]
  259.     del order_list[:]

  260. if __name__ == '__main__':
  261.     try:
  262.         # Retrieve robots and set up a list of available MobileExecutor (MEx) instances
  263.         #加载了所有mex,存至mex_list
  264.         mex_list = call_get_mex_list()
  265.         # for robot in robot_namespaces:
  266.         #     mex_list.append(MobileExecutor(robot))
  267.         for mex in mex_list:
  268.             print(NODE_NAME + str( (mex.id, mex.status, mex.job_id) ) )
  269.         
  270.         # Lists for Orders, PendingJobs, ActiveJobs:
  271.         order_list = []
  272.         pending_job_list = []
  273.         active_job_list = []
  274.         job_index = 1

  275.         # Testing the adding of multiple Location class instances, storing them in a dictionary.
  276.         # TODO Replace this with a dynamic(?) dictionary which is constructed from the MEx Sentinel.
  277.         location_dict = make_location_dict()
  278.         
  279.         # Initialize the node.
  280.         rospy.init_node('job_manager')
  281. ####################以上皆是初始化#########################
  282.         # Initialize services.
  283.         order_service = rospy.Service('~place_order', PlaceOrder , order_service_cb)  #服务名:/job_manager/place_order
  284.         get_pending_jobs_service = rospy.Service('~get_pending_jobs', GetPendingJobs, get_pending_jobs_service_cb)
  285.         get_active_jobs_service = rospy.Service('~get_active_jobs', GetActiveJobs, get_active_jobs_service_cb)
  286.         get_job_info_service = rospy.Service('~get_job_info', GetJobInfo, get_job_info_service_cb)

  287.         # Initialize timers for the JobBuilder, and JobAllocator.
  288.         rospy.Timer(rospy.Duration(1), order_list_timer_cb)     # Every second check order list to try build rough jobs.
  289.         rospy.Timer(rospy.Duration(5), job_allocator_timer_cb)  # Call the job_allocator in 5 seconds to try allocating jobs.
  290.         # The above job_allocator timer should be replaced with something more elegant...

  291.         # Keep node running.
  292.         rospy.spin()

  293.     except rospy.ROSInterruptException:
  294.         pass
复制代码

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-7-3 16:28:42 | 显示全部楼层
用代码格式把全部代码发出来,仅从这一小部分我们无法判断。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2022-7-3 16:43:39 | 显示全部楼层
suchocolate 发表于 2022-7-3 16:28
用代码格式把全部代码发出来,仅从这一小部分我们无法判断。

好的
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-3-29 19:18

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表