def add_journey_request(): data = flask.request.json data['trip_id'] = uuid4().hex data['status'] = 'WAIT' data['from_location'] = Location(data['start']['latitude'], data['start']['longitude']) data['to_location'] = Location(data['end']['latitude'], data['end']['longitude']) data['distance_area'] = uniform(0, 2) data['position'] = data['from_location'] Thread(target=add_agent_to_oef, args=(data,)).start() return to_json({"trip_id": data['trip_id']})
def on_message(self, msg_id: int, dialogue_id: int, origin: str, content: bytes): data = json.loads(content.decode('utf-8')) if 'type' in data and data['type'] == 'location': new_loop = asyncio.new_event_loop() print('Transport: get msg from origin {}'.format(origin)) Thread(target=self.update_transport_location, args=(origin, Location(data['from_location_latitude'], data['from_location_longitude']), Location(data['to_location_latitude'], data['to_location_longitude']), new_loop)).start()
def test_serialization(self, location: Location): """Test that serialization and deserialization of Location objects work correctly.""" actual_location = location actual_location_pb = actual_location.to_pb() expected_location = Location.from_pb(actual_location_pb) assert actual_location == expected_location
def from_pb(cls, relation: query_pb2.Query.Relation): """ From the Relation Protobuf object to the associated instance of a subclass of Relation. :param relation: the Protobuf object that represents the relation constraint. :return: an instance of one of the subclasses of Relation. """ relations_from_pb = { query_pb2.Query.Relation.GTEQ: GtEq, query_pb2.Query.Relation.GT: Gt, query_pb2.Query.Relation.LTEQ: LtEq, query_pb2.Query.Relation.LT: Lt, query_pb2.Query.Relation.NOTEQ: NotEq, query_pb2.Query.Relation.EQ: Eq } relation_class = relations_from_pb[relation.op] value_case = relation.val.WhichOneof("value") if value_case == "s": return relation_class(relation.val.s) elif value_case == "b": return relation_class(relation.val.b) elif value_case == "i": return relation_class(relation.val.i) elif value_case == "d": return relation_class(relation.val.d) elif value_case == "l": return relation_class(Location.from_pb(relation.val.l))
def from_pb(cls, range_pb: query_pb2.Query.Range): """ From the Range Protobuf object to the associated instance of ``Range``. :param range_pb: the Protobuf object that represents the range. :return: an instance of ``Range`` equivalent to the Protobuf object provided as input. """ range_case = range_pb.WhichOneof("pair") if range_case == "s": return cls((range_pb.s.first, range_pb.s.second)) elif range_case == "i": return cls((range_pb.i.first, range_pb.i.second)) elif range_case == "d": return cls((range_pb.d.first, range_pb.d.second)) elif range_case == "l": return cls((Location.from_pb(range_pb.l.first), Location.from_pb(range_pb.l.second)))
def from_pb(cls, distance_pb: query_pb2.Query.Distance): """ From the ``Distance`` Protobuf object to the associated instance of :class:`~oef.query.Distance`. :param distance_pb: the Protobuf object that represents the ``~oef.query.Distance`` constraint. :return: an instance of ``~oef.query.Distance``. """ center = Location.from_pb(distance_pb.center) distance = distance_pb.distance return cls(center, distance)
def add_transport_agent_to_oef(): print('Attempt to add transport agent') data = { 'id': uuid4().hex, 'location': Location(uniform(59.932097364508536, 59.93209736450854), uniform(30.312159061431885, 30.31215906143189)), 'price_per_km': uniform(1, 3), 'status': 'WAIT' } loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) print('Appear transport agent: ' + str(data)) add_transport_agent(data)
def drive_to_point(self, origin, target_point: Location, transp_status): cur_loc = Location(self.data['location_latitude'], self.data['location_longitude']) x_diff = target_point.latitude - cur_loc.latitude y_diff = target_point.longitude - cur_loc.longitude diff_ratio = abs(y_diff / x_diff) x_velocity = self.velocity / (1 + diff_ratio) y_velocity = x_velocity * diff_ratio x_diff_sign = -1 if x_diff < 0 else 1 y_diff_sign = -1 if y_diff < 0 else 1 time.sleep(1) while abs(cur_loc.latitude - target_point.latitude) >= abs(x_velocity) and \ abs(cur_loc.longitude - target_point.longitude) >= abs(y_velocity): cur_loc = Location(cur_loc.latitude + x_velocity * x_diff_sign, cur_loc.longitude + y_velocity * y_diff_sign) # print('Update location of transport to {} {}'.format(cur_loc.latitude, cur_loc.longitude)) self.send_transp_loc(origin, cur_loc, transp_status) time.sleep(1) cur_loc = target_point self.send_transp_loc(origin, cur_loc, transp_status) self.data['location_latitude'] = cur_loc.latitude self.data['location_longitude'] = cur_loc.longitude if transp_status == 'Getting to trip': print("[{0}]: Transport: {1}.".format(self.public_key, 'Picked up account')) else: print("[{0}]: Transport: {1}.".format(self.public_key, 'Trip finished')) self.send_message(randint(1, 1e9), randint(1, 1e9), origin, json.dumps({ 'type': 'finished' }).encode('utf-8')) self.data['state'] = 'WAIT' self.search_drivers()
def __init__(self, data, *args, **kwargs): super(TripAgent, self).__init__(*args, **kwargs) self._entity = Entity() self._address = Address(self._entity) self.data = { "account_id": data['account_id'], "can_be_driver": data['can_be_driver'], "trip_id": data['trip_id'], "from_location_latitude": float(data['from_location'].latitude), "from_location_longitude": float(data['from_location'].longitude), "to_location_latitude": float(data['to_location'].latitude), "to_location_longitude": float(data['to_location'].longitude), "distance_area": data['distance_area'], } self.trip_description = Description(self.data, TRIP_DATAMODEL()) self.data['state'] = 'free' self.data['position'] = Location(self.data['from_location_latitude'], self.data['from_location_longitude']) self.data['transp_location'] = None self.possible_trips = []
def from_pb(cls, set_pb: query_pb2.Query.Set): """ From the Set Protobuf object to the associated instance of a subclass of :class:`~oef.query.Set`. :param set_pb: the Protobuf object that represents the set constraint. :return: the object of one of the subclasses of :class:`~oef.query.Set`. """ op_from_pb = { query_pb2.Query.Set.IN: In, query_pb2.Query.Set.NOTIN: NotIn } set_class = op_from_pb[set_pb.op] value_case = set_pb.vals.WhichOneof("values") if value_case == "s": return set_class(set_pb.vals.s.vals) elif value_case == "b": return set_class(set_pb.vals.b.vals) elif value_case == "i": return set_class(set_pb.vals.i.vals) elif value_case == "d": return set_class(set_pb.vals.d.vals) elif value_case == "l": locations = [Location.from_pb(loc) for loc in set_pb.vals.l.vals] return set_class(locations)
def test_not_equal_when_compared_with_different_type(self): a_distance = Distance(Location(45.0, 45.0), 1.0) not_a_distance = tuple() assert a_distance != not_a_distance
def locations(draw): latitude = draw(floats(min_value=-90.0, max_value=90.0)) longitude = draw(floats(min_value=-180.0, max_value=180.0)) return Location(latitude, longitude)
class ChargerAgent(OEFAgent): """Class that implements the behaviour of the charger agent.""" print("\n".join(sys.argv)) price_kwh = int(sys.argv[1]) #55 location = Location(float(sys.argv[2]), float(sys.argv[3])) #52.2057092, 0.1183431) bonus = int(sys.argv[6]) charger_description = Description( { "price_kilowatt_hour": price_kwh, "charger_location": location, "charger_available": True, "charger_bonus": bonus, }, CHARGING_MODEL) def __init__(self, *args, **kwargs): super(ChargerAgent, self).__init__(*args, **kwargs) self._entity = Entity.from_hex(sys.argv[5]) self._address = Address(self._entity) #print(self._address) #h = self._address.to_hex() #print(h) #print(Address(binascii.unhexlify(h))) # with open("./full_contract.etch", "r") as fb: # self._source = fb.read() # self.prepare_contract() def prepare_contract(self): # Setting API up self._api = LedgerApi('ledger', 8000) # Need funds to deploy contract self._api.sync(self._api.tokens.wealth(self._entity, 5000000)) # Create contract self._contract = SmartContract(self._source) # Deploy contract self._api.sync( self._api.contracts.create(self._entity, self._contract, 2456766)) def on_cfp(self, msg_id: int, dialogue_id: int, origin: str, target: int, query: CFP_TYPES): """Send a simple Propose to the sender of the CFP.""" print("[{0}]: Received CFP from {1}".format(self.public_key, origin)) # prepare the proposal with a given price. proposal = Description({ "price_kilowatt_hour": self.price_kwh, "charger_location": self.location, 'charger_bonus': self.bonus }) print("[{}]: Sending propose at price: {} location {},{}".format( self.public_key, self.price_kwh, self.location.latitude, self.location.longitude)) self.send_propose(msg_id + 1, dialogue_id, origin, target + 1, [proposal]) def on_accept(self, msg_id: int, dialogue_id: int, origin: str, target: int): """Once we received an Accept, send the requested data.""" print("[{0}]: Received accept from {1}.".format( self.public_key, origin)) # Preparing contract # PLACE HOLDER TO PREPARE AND SIGN TRANSACTION contract = { "address": self._address.to_hex(), "value": self.price_kwh, "bonus": self.bonus } # Sending contract encoded_data = json.dumps(contract).encode("utf-8") print("[{0}]: Sending contract to {1}".format(self.public_key, origin)) self.send_message(0, dialogue_id, origin, encoded_data) def on_decline(self, msg_id: int, dialogue_id: int, origin: str, target: int): """Once we received an Decline, send the requested data.""" print("[{0}]: Received decline from {1}.".format( self.public_key, origin))
def on_message(self, msg_id: int, dialogue_id: int, origin: str, content: bytes): """Extract and print data from incoming (simple) messages.""" # PLACE HOLDER TO SIGN AND SUBMIT TRANSACTION msg = json.loads(content.decode("utf-8")) if 'type' not in msg: print('unkown type') return if msg['type'] == 'contract': print('Receivied contract from transport') return # api = LedgerApi('185.91.52.11', 10002) # Need funds to deploy contract # api.sync(api.tokens.wealth(Address(self), 59000000)) # msg.action(api, 'endJourney', 2456766, [Address(origin), Address(self)], Address(origin), Address(self), self.data['account_id'], # self.data['can_be_driver']) if msg['type'] == 'request': print('Trip received request from transport') self.send_message( msg_id, dialogue_id, origin, json.dumps({ 'type': 'location', 'from_location_latitude': self.data['from_location_latitude'], 'from_location_longitude': self.data['from_location_longitude'], 'to_location_latitude': self.data['to_location_latitude'], 'to_location_longitude': self.data['to_location_longitude'] }).encode('utf-8')) return if msg['type'] == 'location': if msg['status'] == 'Trip started': self.data['position'] = Location(msg['location_latitude'], msg['location_longitude']) self.data['transp_location'] = { 'latitude': msg['location_latitude'], 'longitude': msg['location_longitude'] } print('Agent change location', msg) print('Account upd location to {} {}'.format( self.data['position'].latitude, self.data['position'].longitude)) else: print('Transport change location', msg) self.data['transp_location'] = { 'latitude': msg['location_latitude'], 'longitude': msg['location_longitude'] } return if msg['type'] == 'finish': print('Trip agent unregister') self.unregister_agent(randint(1, 1e9)) self.stop()