def from_dict(request_dict): id = request_dict.get('id', generate_uuid()) request = TaskRequest(id=id) request.load_type = request_dict["loadType"] request.load_id = request_dict["loadId"] request.user_id = request_dict["userId"] request.earliest_pickup_time = TimeStamp.from_str( request_dict["earliestPickupTime"]) request.latest_pickup_time = TimeStamp.from_str( request_dict["latestPickupTime"]) pickup_area_dict = request_dict.get('pickup_pose', None) if pickup_area_dict: request.pickup_pose = Area.from_dict(pickup_area_dict) else: # when the provided dict is from json schema request.pickup_pose = Area() request.pickup_pose.name = request_dict.get("pickupLocation", '') request.pickup_pose.floor_number = request_dict.get( "pickupLocationLevel", 0) delivery_area_dict = request_dict.get('delivery_pose', None) if delivery_area_dict: request.delivery_pose = Area.from_dict(delivery_area_dict) else: # when the provided dict is from json schema request.delivery_pose = Area() request.delivery_pose.name = request_dict.get( "deliveryLocation", '') request.delivery_pose.floor_number = request_dict.get( "deliveryLocationLevel", 0) request.priority = request_dict["priority"] return request
def __init__(self, robot_id, uuid=None, **kwargs): self.robot_id = robot_id if uuid is None: self.uuid = generate_uuid() else: self.uuid = uuid self.last_update = dict() self.position = kwargs.get('position', None) self.availability = kwargs.get('availability', None) self.component_status = kwargs.get('component_status', None) self.schedule = kwargs.get('schedule', None) self.current_task = kwargs.get('current_task', None) self.nickname = kwargs.get('nickname', None) self.version = kwargs.get( 'version', { 'hardware': Hardware.full_version(), 'software': Software.full_version(), 'black_box': BlackBox.full_version() }) for attr in attributes: val = self.__dict__.get('attr', None) if val is not None: self.last_update[attr] = val
def full_version(uuid=None): if uuid is None: uuid = generate_uuid() return { 'uuid': uuid, 'logger': Software.ropod_sw(), 'fault_detection': Software.ropod_sw() }
def get_header(message_type, meta_model='msg', recipients=[]): if recipients is not None and not isinstance(recipients, list): raise Exception("Recipients must be a list of strings") return {"header": {'type': message_type, 'metamodel': 'ropod-%s-schema.json' % meta_model, 'msgId': generate_uuid(), 'timestamp': TimeStamp().to_str(), 'receiverIds': recipients}}
def send_message(self, msg_type, payload_dict=None): query_msg = MessageFactory.get_header(msg_type, recipients=[]) query_msg['payload'] = {} query_msg['payload']['senderId'] = generate_uuid() if payload_dict is not None: for key in payload_dict.keys(): query_msg['payload'][key] = payload_dict[key] print(json.dumps(query_msg, indent=2, default=str)) self.shout(query_msg)
def update_msg_id(message, id=None): header = message.get('header') if header: if id: header.update(msgId=id) else: header.update(msgId=generate_uuid()) else: header = MessageFactoryBase.get_header(None) message.update(header)
class DatasetPerformance(MongoModel): """ Stores dataset performance information: dataset_id (UUID): uniquely identifies the dataset completion_time (float): Difference between the start navigation of the first task and the finish time of the last allocated task makespan (float): Finish time of the last allocated task fleet_work_time (float): % of time taken to perform all allocated tasks. fleet_travel_time (float): % of time taken to travel to task locations fleet_idle_time (float): % of time robots are idle (waiting) to start their next allocated task robot_usage (float): % of robots used out of all the available robots usage_most_loaded_robot (float): % of tasks allocated to the robot with most allocations """ dataset_id = fields.UUIDField(primary_key=True, default=generate_uuid()) completion_time = fields.FloatField() makespan = fields.FloatField() fleet_work_time = fields.FloatField() fleet_travel_time = fields.FloatField() fleet_idle_time = fields.FloatField() robot_usage = fields.FloatField() usage_most_loaded_robot = fields.FloatField() tasks = fields.ListField(fields.ReferenceField(TaskPerformance)) class Meta: archive_collection = 'dataset_performance_archive' ignore_unknown_fields = True def save(self): try: super().save(cascade=True) except ServerSelectionTimeoutError: logging.warning('Could not save models to MongoDB') def archive(self): with switch_collection(DatasetPerformance, DatasetPerformance.Meta.archive_collection): super().save() self.delete() @classmethod def create(cls, dataset_id, task_ids): performance = cls(dataset_id=dataset_id, tasks=task_ids) performance.save() return performance
def __new__(cls, message_type, meta_model=None, **kwargs): recipients = kwargs.get('recipients', list()) if recipients is not None and not isinstance(recipients, list): raise Exception("Recipients must be a list of strings") return { 'type': message_type, 'metamodel': meta_model, 'msgId': str(generate_uuid()), 'timestamp': TimeStamp().to_str(), 'receiverIds': recipients }
def __init__(self, id=''): if not id: self.id = generate_uuid() else: self.id = id self.pickup_pose = Area() self.delivery_pose = Area() self.earliest_pickup_time = TimeStamp() self.latest_pickup_time = TimeStamp() self.user_id = '' self.load_type = '' self.load_id = '' self.priority = -1
def trigger(self): print("Test triggered") test_msg = dict() test_msg['header'] = dict() test_msg['payload'] = dict() test_msg['header']['type'] = 'START-TEST' test_msg['header']['metamodel'] = 'ropod-msg-schema.json' test_msg['header']['msgId'] = generate_uuid() test_msg['header']['timestamp'] = TimeStamp().to_str() test_msg['payload']['metamodel'] = 'ropod-bid_round-schema.json' self.shout(test_msg)
def __init__(self, **kwargs): self.logger = logging.getLogger('mrs.auctioneer.round') self.tasks_to_allocate = kwargs.get('tasks_to_allocate', dict()) self.round_time = kwargs.get('round_time', 0) self.n_robots = kwargs.get('n_robots', 0) self.alternative_timeslots = kwargs.get('alternative_timeslots', False) self.closure_time = 0 self.id = generate_uuid() self.finished = True self.opened = False self.received_bids = dict() self.received_no_bids = dict()
def _send_request(self, msg_type, payload_dict=None): request_msg = dict() request_msg['header'] = dict() request_msg['header']['metamodel'] = 'ropod-msg-schema.json' request_msg['header']['type'] = msg_type request_msg['header']['msgId'] = str(uuid.uuid4()) request_msg['header']['timestamp'] = time.time() request_msg['payload'] = dict() request_msg['payload']['senderId'] = generate_uuid() if payload_dict is not None: for key in payload_dict.keys(): request_msg['payload'][key] = payload_dict[key] # print(json.dumps(request_msg, indent=2, default=str)) self.shout(request_msg)
def __init__(self, tasks_lots, round_id, zero_timepoint): """ Constructor for the TaskAnnouncement object Args: tasks_lots (list): List of TaskLot objects to be announced round_id (str): A string of the format UUID that identifies the round zero_timepoint (TimeStamp): Zero Time Point. Origin time to which task temporal information must be referenced to """ self.tasks_lots = tasks_lots if not round_id: self.round_id = generate_uuid() else: self.round_id = round_id self.zero_timepoint = zero_timepoint
def __init__(self, tasks, round_id, ztp, earliest_admissible_time): """ Constructor for the TaskAnnouncement object Args: tasks (list): List of Task objects to be announced round_id (str): A string of the format UUID that identifies the round ztp (TimeStamp): Zero Time Point. Origin time to which task temporal information must be referenced to """ self.tasks = tasks if not round_id: self.round_id = generate_uuid() else: self.round_id = round_id self.earliest_admissible_time = earliest_admissible_time self.ztp = ztp
def load_tasks_to_db(dataset_module, dataset_name, **kwargs): dataset_dict = load_yaml_file_from_module(dataset_module, dataset_name + '.yaml') initial_time = kwargs.get('initial_time', datetime.now()) tasks_dict = dataset_dict.get('tasks') ordered_tasks = collections.OrderedDict(sorted(tasks_dict.items())) tasks = list() for task_id, task_info in ordered_tasks.items(): earliest_pickup_time, latest_pickup_time = reference_to_initial_time( task_info.get("earliest_pickup_time"), task_info.get("latest_pickup_time"), initial_time) request = TransportationRequest( request_id=generate_uuid(), pickup_location=task_info.get('pickup_location'), delivery_location=task_info.get('delivery_location'), earliest_pickup_time=earliest_pickup_time, latest_pickup_time=latest_pickup_time, hard_constraints=task_info.get('hard_constraints')) request.save() duration = InterTimepointConstraint() pickup = TimepointConstraint( earliest_time=request.earliest_pickup_time, latest_time=request.latest_pickup_time) temporal = TransportationTemporalConstraints(pickup=pickup, duration=duration) constraints = TransportationTaskConstraints( hard=request.hard_constraints, temporal=temporal) task = TransportationTask.create_new(task_id=task_id, request=request.request_id, constraints=constraints) tasks.append(task) return tasks
def main(): logging.getLogger('pyre').setLevel(logging.WARNING) logging.getLogger("requests").setLevel(logging.WARNING) logging.basicConfig( format="%(asctime)s [%(name)-12.12s] [%(levelname)-5.5s] %(message)s", level=logging.DEBUG) node1 = RopodPyre('node1', ["TEST-GROUP"], ["TEST_MSG"], True, acknowledge=True) node1.start() msg_id = generate_uuid() msg = { 'header': { 'type': 'TEST_MSG', 'msgId': msg_id, 'receiverIds': ['node2', 'node3'] }, 'payload': { 'msg': 'test' } } node1.shout(msg) time.sleep(6) node2 = RopodPyre('node2', ["TEST-GROUP"], ["TEST_MSG"], False, acknowledge=True) node3 = RopodPyre('node3', ["TEST-GROUP"], ["TEST_MSG"], False, acknowledge=True) node2.start() node3.start() time.sleep(6) node1.shutdown() node2.shutdown() node3.shutdown()
def test(self): print(self.name()) print(self.groups()) print(self.peers()) time.sleep(ZYRE_SLEEP_TIME) msg = { 'header': { 'type': 'TEST_MSG', 'msgId': generate_uuid() }, 'payload': { 'msg': 'test' } } for group in self.own_groups(): self.shout(msg, group) time.sleep(1) self.shout('hello') self.whisper(msg, "chat_tester") self.whisper(msg, ["chat_tester", "chat_tester"])
def send_request(self, msg_type, payload_dict=None): time.sleep(1) request_msg = dict() request_msg['header'] = dict() request_msg['header'][ 'metamodel'] = 'ropod-black-box-logging-cmd-schema.json' request_msg['header']['type'] = msg_type request_msg['header']['msgId'] = str(uuid.uuid4()) request_msg['header']['timestamp'] = time.time() request_msg['header']['blackBoxId'] = self.black_box_id request_msg['payload'] = dict() request_msg['payload']['senderId'] = generate_uuid() if payload_dict is not None: for key in payload_dict.keys(): request_msg['payload'][key] = payload_dict[key] request_msg = json.dumps(request_msg, indent=2, default=str) # print(request_msg) self.shout(request_msg)
def __init__(self, robot_ids, tasks_to_allocate, **kwargs): simulator = kwargs.get('simulator') super().__init__(simulator) self.logger = logging.getLogger('mrs.auctioneer.round') self.robot_ids = robot_ids self.tasks_to_allocate = tasks_to_allocate self.n_tasks = kwargs.get('n_tasks') self.closure_time = kwargs.get('closure_time') self.alternative_timeslots = kwargs.get('alternative_timeslots', False) self.id = generate_uuid() self.finished = True self.opened = False self.received_bids = dict() self.received_no_bids = dict() self.bidding_robots = { robot_id: BiddingRobot(robot_id) for robot_id in self.robot_ids } self.start_time = time.time() self.time_to_allocate = None
def load_yaml_dataset(dataset_path): dataset_dict = load_yaml(dataset_path) dataset_id = dataset_dict.get('dataset_id') tasks_performance = list() tasks_dict = dataset_dict.get('tasks') ordered_tasks = collections.OrderedDict(sorted(tasks_dict.items())) for task_id, task_info in ordered_tasks.items(): start_location = task_info.get("start_location") finish_location = task_info.get("finish_location") earliest_start_time, latest_start_time = reference_to_current_time( task_info.get("earliest_start_time"), task_info.get("latest_start_time")) hard_constraints = task_info.get("hard_constraints") request = TransportationRequest( request_id=generate_uuid(), pickup_location=start_location, delivery_location=finish_location, earliest_pickup_time=earliest_start_time, latest_pickup_time=latest_start_time, hard_constraints=hard_constraints) task = Task.create_new(task_id=task_id, request=request) # TaskLot.create(task_id, start_location, finish_location, earliest_start_time, # latest_start_time, hard_constraints) task_performance = TaskPerformance.create(task) tasks_performance.append(task_performance) DatasetPerformance.create(dataset_id, tasks_performance) return tasks_performance
def __init__(self, id=None, robot_actions=dict(), team_robot_ids=list(), earliest_start_time=-1, latest_start_time=-1, estimated_duration=-1, pickup_pose=Area(), delivery_pose=Area(), **kwargs): """Constructor for the Task object Args: id (str): A string of the format UUID robot_actions (dict): A dictionary with robot IDs as keys, and the list of actions to execute as values loadType (str): Valid values are "MobiDik", "Sickbed". Defaults to MobiDik loadId (str): A string of the format UUID team_robot_ids (list): A list of strings containing the UUIDs of the robots in the task earliest_start_time (TimeStamp): The earliest a task can start latest_start_time (TimeStamp): The latest a task can start estimated_duration (timedelta): A timedelta object specifying the duration pickup_pose (Area): The location where the robot should collect the load delivery_pose (Area): The location where the robot must drop off its load priority (constant): The task priority as defined by the constants EMERGENCY, HIGH, NORMAL, LOW hard_constraints (bool): False if the task can be scheduled ASAP, True if the task is not flexible. Defaults to True """ if not id: self.id = generate_uuid() else: self.id = id self.robot_actions = robot_actions self.loadType = kwargs.get('loadType', 'MobiDik') self.loadId = kwargs.get('loadId', generate_uuid()) self.team_robot_ids = team_robot_ids self.earliest_start_time = earliest_start_time self.latest_start_time = latest_start_time self.estimated_duration = estimated_duration self.earliest_finish_time = earliest_start_time + estimated_duration self.latest_finish_time = latest_start_time + estimated_duration self.start_time = kwargs.get('start_time', None) self.finish_time = kwargs.get('finish_time', None) self.hard_constraints = kwargs.get('hard_constraints', True) if isinstance(pickup_pose, Area): self.pickup_pose = pickup_pose else: raise Exception('pickup_pose must be an object of type Area') if isinstance(delivery_pose, Area): self.delivery_pose = delivery_pose else: raise Exception('delivery_pose must be an object of type Area') self.status = TaskStatus(self.id) priority = kwargs.get('priority', self.NORMAL) if priority in (self.EMERGENCY, self.NORMAL, self.HIGH, self.LOW): self.priority = priority else: raise Exception("Priority must have one of the following values:\n" "0) Urgent\n" "1) High\n" "2) Normal\n" "3) Low")
def refresh(self): """Update the header with new values """ self['header']['timestamp'] = TimeStamp().to_str() self['header']['msgId'] = str(generate_uuid())