Beispiel #1
0
    def on_propose(self, msg_id: int, dialogue_id: int, origin: str, target: int, proposals: PROPOSE_TYPES):
        for i,p in enumerate(proposals):
            self.received_proposals.append({"agent" : origin,
                                            "proposal":p.values})
            newPrice = self.received_proposals[0]['proposal']['price']
            newOffer = newPrice + self.interval
            self.prevPrice = newOffer
            if self.Auction == False:
                if self.received_proposals[0]['proposal']['auction']:
                    print('[{0}] Accepting Auction with maxPrice: {1}, at interval: {2}'.format(self.public_key, self.maxPrice, self.interval))
                    self.send_accept(msg_id, dialogue_id, self.received_proposals[0]['agent'], msg_id+1)
                    self.received_proposals.clear()
                    self.Auction = True
            else:
                if self.received_proposals[0]['proposal']['auction'] == False:
                    if newPrice <= self.maxPrice:
                        print('Accepting Offer of Price: {}'.format(newPrice))
                        self.send_accept(msg_id, dialogue_id, self.received_proposals[0]['agent'], msg_id+1)
                        self.api.sync(self.api.tokens.transfer(self.account, Address(origin) , self.prevPrice - self.interval, 20))
                        print('Final Balance:', self.api.tokens.balance(self.account))
                    else:
                        print('Cannot Afford')
                        self.send_decline(msg_id,dialogue_id,self.received_proposals['agent'],msg_id + 1)

                if newOffer <= self.maxPrice:
                    print('{} : Sending proposal of: {}'.format(self.public_key,newOffer))
                    proposal = Description({"price" : newOffer})
                    self.send_propose(msg_id+1, dialogue_id, origin, target+1, [proposal])
                    self.received_proposals.clear()
                else:
                    print('{} : Sending proposal of: {}'.format(self.public_key,self.maxPrice))
                    proposal = Description({"price" : self.maxPrice})
                    self.send_propose(msg_id+1, dialogue_id, origin, target+1, [proposal])
                    self.received_proposals.clear()
Beispiel #2
0
    def test_on_search_result_agents(self, local):
        """
        Test that an agent can do a search for agents.
        """

        with setup_test_agents(3, local, prefix="search_agents") as agents:

            for a in agents:
                a.connect()

            agent_0, agent_1, agent_2 = agents

            foo_attr = AttributeSchema("foo", int, False, "A foo attribute.")
            bar_attr = AttributeSchema("bar", str, False, "A bar attribute.")

            dummy_datamodel = DataModel("dummy_datamodel",
                                        [foo_attr, bar_attr])
            agent_1.register_agent(
                0, Description({
                    "foo": 15,
                    "bar": "BAR"
                }, dummy_datamodel))
            agent_2.register_agent(
                0, Description({
                    "foo": 5,
                    "bar": "ABC"
                }, dummy_datamodel))

            agent_0.search_agents(
                0, Query([Constraint("foo", Eq(0))], dummy_datamodel))
            agent_0.search_agents(
                0,
                Query([
                    Constraint("foo", Gt(10)),
                    Constraint("bar", Gt("B")),
                ], dummy_datamodel))
            agent_0.search_agents(
                0, Query([
                    Constraint("bar", Gt("A")),
                ], dummy_datamodel))

            asyncio.ensure_future(agent_0.async_run())
            asyncio.get_event_loop().run_until_complete(
                asyncio.sleep(_ASYNCIO_DELAY))
            agent_1.unregister_agent(0)
            agent_2.unregister_agent(0)

        expected_message_01 = (0, [])
        expected_message_02 = (0, [agent_1.public_key])
        expected_message_03 = (0, [agent_1.public_key, agent_2.public_key])

        assert 3 == len(agent_0.received_msg)
        assert expected_message_01 == agent_0.received_msg[0]
        assert expected_message_02 == agent_0.received_msg[1]
        assert expected_message_03 == agent_0.received_msg[2]
Beispiel #3
0
    def on_propose(self, msg_id: int, dialogue_id: int, origin: str, target: int, proposals: PROPOSE_TYPES):
        """When we receive a Propose message, check if we can afford the data. If so we accept, else we decline the proposal."""
        print("[{0}]: Received propose from agent {1}".format(self.public_key, origin))

        for i,p in enumerate(proposals):
            self.received_proposals.append({"agent" : origin,
                                            "proposal":p.values})


        received_cfp = len(self.received_proposals) + self.received_declines
        global currentPrice

        self.received_proposals.sort(key = lambda i: (i['proposal']['id']), reverse = True)

        # once everyone has responded, let's accept them.
        print("I am here")
        if len( self.received_proposals) >= 1 :
            proposed = str(self.received_proposals[0]['proposal'])
            price = int(self.received_proposals[0]['proposal']['price'])
            offer = int(self.received_proposals[0]['proposal']['offer'])
            previous = int(self.received_proposals[0]['proposal']['previous'])
            proposalID = self.received_proposals[0]['proposal']['id']
            print('----->PRICE:', price)
            print('----->OFFER:', offer)
            print('----->PREVIOUS:', previous)
            print('----->ID:', proposalID)
            if price <= highest_price:
                print('Accept the offer!')
                #check if we can afford the data.
                if api.tokens.balance(client_agentID) > price :
                    #if we can, transfer tokens from the client account to the proposal address.
                    api.sync(api.tokens.transfer(client_agentID, Address(self.received_proposals[0]['agent']) , price, 20))
                    self.send_accept(msg_id,dialogue_id,self.received_proposals[0]['agent'],msg_id + 1)
                    print ("Accept")
                else :
                    print("Not enough tokens!")
                    #cannot afford! Decline the proposal.
                    self.send_decline(msg_id,dialogue_id,self.received_proposals[0]['agent'],msg_id + 1)

                    self.stop()
            elif price == previous:
                print('They are sticking with offer, better offer higher...')
                proposal = Description({"price" : highest_price, "previous": price, "offer": offer, "id": proposalID+1})
                print("[{0}]: Sending propose at price: {1}".format(self.public_key, highest_price))
                self.send_propose(msg_id + 1, dialogue_id, origin, target + 1, [proposal])
            else:
                print('Too Expensive, want lower!')
                self.reduceOffer(price)
                proposal = Description({"price" : currentPrice, "previous": price, "offer": offer, "id": proposalID+1})
                print("[{0}]: Sending propose at price: {1}".format(self.public_key, currentPrice))
                self.send_propose(msg_id + 1, dialogue_id, origin, target + 1, [proposal])
        else :
            print("They don't have data")
            self.stop()
    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))

        #data = self.get_latest(0)
        if self.preferences["currentCapacity"] < self.preferences['maxAllowed']:
            proposal = Description({
                "data": True,
                "driverVect": json.dumps(self.preferences)
            })
        else:
            proposal = Description({"data": False})
        self.send_propose(msg_id + 1, dialogue_id, origin, target + 1,
                          [proposal])
Beispiel #5
0
    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))
        data = json.loads(query.decode("UTF-8"))
        print("GOT DATA: ", data)

        # prepare the proposal with a given price.
        price = 50
        proposal = Description({"price": price})
        print("[{}]: Sending propose at price: {}".format(
            self.public_key, price))
        print("********", proposal.to_pb())
        self.send_propose(msg_id + 1, dialogue_id, origin, target + 1,
                          [proposal])
    def test_group_dialogue_one_client_n_servers(self):
        with NetworkOEFNode():
            client_proxy = OEFNetworkProxy("client",
                                           oef_addr="127.0.0.1",
                                           port=3333)
            client = ClientAgentGroupDialogueTest(client_proxy)
            client.connect()

            N = 10
            server_proxies = [
                OEFNetworkProxy("server_{:02d}".format(i),
                                oef_addr="127.0.0.1",
                                port=3333) for i in range(N)
            ]
            server_data_model = DataModel("server",
                                          [AttributeSchema("foo", bool, True)])

            servers = [
                ServerAgentTest(server_proxy, price=random.randint(10, 100))
                for server_proxy in server_proxies
            ]
            for server in servers:
                server.connect()
                server.register_service(
                    0, Description({"foo": True}, server_data_model))

            best_server = ServerAgentTest(OEFNetworkProxy("best_server",
                                                          oef_addr="127.0.0.1",
                                                          port=3333),
                                          price=5)
            best_server.connect()
            best_server.register_service(
                0, Description({"foo": True}, server_data_model))
            servers.append(best_server)

            asyncio.get_event_loop().run_until_complete(
                asyncio.sleep(_ASYNCIO_DELAY))

            query = Query([Constraint("foo", Eq(True))], server_data_model)

            client.search_services(0, query)

            asyncio.get_event_loop().run_until_complete(
                asyncio.gather(client.async_run(),
                               *[server.async_run() for server in servers]))

            assert "best_server" == client.group.best_agent
            assert 5 == client.group.best_price
Beispiel #7
0
    def on_propose(self, msg_id: int, dialogue_id: int, origin: str, target: int, proposals: PROPOSE_TYPES):
        """When we receive a Propose message, check if we can afford the data. If so we accept, else we decline the proposal."""
        print("[{0}]: Received propose from agent {1}".format(self.public_key, origin))

        for i,p in enumerate(proposals):
            self.received_proposals.append({"agent" : origin,
                                            "proposal":p.values})

        received_cfp = len(self.received_proposals) + self.received_declines
        self.proposalsTot = self.proposalsTot + 1

        print('prevOffer:', self.prevOffer)

        print("I am here")
        if len( self.received_proposals) >= 1 :
            proposed = str(self.received_proposals[self.proposalsTot-1]['proposal'])
            price = int(self.received_proposals[self.proposalsTot-1]['proposal']['price'])
            print('----->PRICE:', price)
            if price >= self.lowest_price:
                print('Good offer! Return offer and wait for accept...')
                proposal = Description({"price" : price})
                print("[{0}]: Sending propose at price: {1}".format(self.public_key, price))
                self.send_propose(msg_id + 1, dialogue_id, origin, target + 1, [proposal])
            elif price == self.prevOffer:
                print('Not going high enough. Ending dialogue')
                self.prevPrice = self.wanted_price
                self.prevOffer = 0
                self.send_decline(msg_id,dialogue_id,self.received_proposals[self.proposalsTot-1]['agent'],msg_id + 1)
                return
            else:
                print('Too Low!')
                self.prevOffer = price
                price = ((price + self.prevPrice)/2)
                if price >= self.lowest_price:
                    print('Ok, meet in the middle')
                    self.prevPrice = price
                    proposal = Description({"price" : price})
                    print("[{0}]: Sending propose at price: {1}".format(self.public_key, price))
                    self.send_propose(msg_id + 1, dialogue_id, origin, target + 1, [proposal])
                else:
                    print('Not Budging!')
                    price = self.prevPrice
                    proposal = Description({"price" : price})
                    print("[{0}]: Sending propose at price: {1}".format(self.public_key, price))
                    self.send_propose(msg_id + 1, dialogue_id, origin, target + 1, [proposal])
        else:
            print("They don't have data")
            self.stop()
Beispiel #8
0
    def test_unregister_service(self, local):
        """
        Test that the unregistration of services works correctly.
        """

        with setup_test_agents(2, local,
                               prefix="unregister_service") as agents:

            for a in agents:
                a.connect()

            agent_0, agent_1 = agents

            dummy_datamodel = DataModel("dummy_datamodel",
                                        [AttributeSchema("foo", int, False)])
            dummy_service_description = Description({}, dummy_datamodel)
            agent_1.register_service(0, dummy_service_description)
            agent_1.unregister_service(0, dummy_service_description)

            agent_0.search_services(
                0, Query([Constraint("foo", Eq(0))], dummy_datamodel))
            asyncio.ensure_future(agent_0.async_run())
            asyncio.get_event_loop().run_until_complete(
                asyncio.sleep(_ASYNCIO_DELAY))

        assert 1 == len(agent_0.received_msg)
        assert (0, []) == agent_0.received_msg[0]
    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))

        price = self.price

        timeArr = []
        for key in self.scheduler.keys():
            timeArr.append(self.scheduler[key])

        # prepare the proposal with a given price.
        proposal = Description({
            "price_per_energy_percent":
            price,
            "digest":
            str(self._contract),
            "longitude":
            self.longitude,
            "latitude":
            self.latitude,
            "scheduler":
            json.dumps(timeArr),
            "rate":
            self.rate,
            "max_count":
            self.max_count,
            "charger_address":
            str(Address(self.chargers[0]))
        })
        print("[{}]: Sending propose at price: {}".format(
            self.public_key, price))
        self.send_propose(msg_id + 1, dialogue_id, origin, target + 1,
                          [proposal])
 def test_serialization(self, description):
     """Test that serialization and deserialization of Description objects work correctly."""
     actual_description = description
     actual_description_pb = actual_description.to_pb(
     )  # type: query_pb2.Query.DataModel
     expected_description = Description.from_pb(actual_description_pb)
     assert actual_description == expected_description
Beispiel #11
0
 def __init__(self, public_key, oef_addr, oef_port, data_model_json,
              service_description_json, data_to_send_json, price):
     OEFAgent.__init__(self, public_key, oef_addr, oef_port)
     self.data_model = modlify(data_model_json)
     self.service = Description(service_description_json, self.data_model)
     self.data = data_to_send_json
     self.price = price
 def test2(self):
     price = 50
     proposed_price = Description({"price": price})
     proposals = [proposed_price]
     data = {
         "msg_id": 102,
         "agent_uri": "wibble1",
         "send_message": {
             "dialogue_id": 101,
             "destination": "wibble2",
             "target_uri": "uri1",
             "source_uri": "uri2",
             "fipa": {
                 "target": 102,
                 "propose": {
                     ("content" if type(proposals) == bytes else None):
                     proposals,
                     ("proposals" if type(proposals) != bytes else None): {
                         "objects": proposals,
                     },
                 }
             }
         }
     }
     oefagent = OefMessageHandler()
     senddata = oefagent.make_message(bytes=None,
                                      json=None,
                                      message_class=agent_pb2.Envelope,
                                      data=data,
                                      pb=None)
    def test1(self):
        weather_service_description = Description(
            {
                "wind_speed": False,
                "temperature": True,
                "air_pressure": True,
                "humidity": True,
            }, WEATHER_DATA_MODEL)

        #        data = {
        #            "msg_id": 1,
        #            "register_service": {
        #                "description": weather_service_description.to_dict()
        #            },
        #        }
        #        pb = agent_pb2.Envelope()
        #        self.tryit(pb, data)

        data = {
            "msg_id": 1,
            "register_service": {
                "description": weather_service_description
            },
        }
        pb = agent_pb2.Envelope()
        self.tryit(pb, data)
Beispiel #14
0
class TransportAgent(OEFAgent):
    """Class that implements the behaviour of the scooter agent."""

    scooter_description = Description(
        {
            "price_per_km": True,
        },
        JOURNEY_MODEL
    )

    def __init__(self, data, *args, **kwargs):
        super(TransportAgent, self).__init__(*args, **kwargs)
        self.data = data
        self._entity = Entity()
        self._address = Address(self._entity)

    #      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('185.91.52.11', 10002)

        # 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))

        price = 1

        # prepare the proposal with a given price.
        proposal = Description({"price_per_km": price})
        print("[{}]: Sending propose at price: {}".format(self.public_key, price))
        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 = {"contract": "data"}

        # Sending contract
        encoded_data = json.dumps(contract).encode("utf-8")
        print("[{0}]: Sending contract to {1}".format(self.public_key, origin))
        self.data['status'] = 'RIDES'
        self.send_message(0, dialogue_id, origin, encoded_data)
Beispiel #15
0
 def on_cfp(self, msg_id: int, dialogue_id: int, origin: str, target: int,
            query: CFP_TYPES):
     print("[{0}]: Received CFP from {1}".format(self.public_key, origin))
     proposal = Description({"price": self.price})
     print("[{}]: Sending propose at price: {}".format(
         self.public_key, self.price))
     self.send_propose(msg_id + 1, dialogue_id, origin, target + 1,
                       [proposal])
    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": self.price})
        print("[{}]: Sending propose at price: {}".format(self.public_key, self.price))
        self.send_propose(msg_id + 1, dialogue_id, origin, target + 1, [proposal])
Beispiel #17
0
    def register(self):
        """
        Register on the OEF as a TAC controller agent.

        :return: None.
        """
        desc = Description({"version": 1}, data_model=self.CONTROLLER_DATAMODEL)
        logger.debug("[{}]: Registering with {} data model".format(self.name, desc.data_model.name))
        self.register_service(0, desc)
Beispiel #18
0
    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))

        #data = self.get_latest(0)
        proposal = Description({"data": True})
        self.send_propose(msg_id + 1, dialogue_id, origin, target + 1,
                          [proposal])
Beispiel #19
0
    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))

        #format the price for number extraction on other agent
        proposal = Description({"price" : self.wanted_price})
        print("[{0}]: Sending propose at price: {1}".format(self.public_key, wanted_price))
        self.send_propose(msg_id + 1, dialogue_id, origin, target + 1, [proposal])
        startBalance = api.tokens.balance(server_agentID)
Beispiel #20
0
    async def loop(self, agent: AgentInterface) -> None:  # noqa: C901
        """
        Event loop to wait for messages and to dispatch the arrived messages to the proper handler.

        :param agent: the implementation of the message handlers specified in AgentInterface.
        :return: ``None``
        """
        while True:
            try:
                data = await self._receive()
            except asyncio.CancelledError:
                logger.debug("Proxy {}: loop cancelled".format(self.public_key))
                break
            msg = agent_pb2.Server.AgentMessage()
            msg.ParseFromString(data)
            case = msg.WhichOneof("payload")
            logger.debug("loop {0}".format(case))
            if case == "agents":
                agent.on_search_result(msg.answer_id, msg.agents.agents)
            elif case == "oef_error":
                agent.on_oef_error(msg.answer_id, OEFErrorOperation(msg.oef_error.operation))
            elif case == "dialogue_error":
                agent.on_dialogue_error(msg.answer_id, msg.dialogue_error.dialogue_id, msg.dialogue_error.origin)
            elif case == "content":
                content_case = msg.content.WhichOneof("payload")
                logger.debug("msg content {0}".format(content_case))
                if content_case == "content":
                    agent.on_message(msg.answer_id, msg.content.dialogue_id, msg.content.origin, msg.content.content)
                elif content_case == "fipa":
                    fipa = msg.content.fipa
                    fipa_case = fipa.WhichOneof("msg")
                    if fipa_case == "cfp":
                        cfp_case = fipa.cfp.WhichOneof("payload")
                        if cfp_case == "nothing":
                            query = None
                        elif cfp_case == "content":
                            query = fipa.cfp.content
                        elif cfp_case == "query":
                            query = Query.from_pb(fipa.cfp.query)
                        else:
                            raise Exception("Query type not valid.")
                        agent.on_cfp(msg.answer_id, msg.content.dialogue_id, msg.content.origin, fipa.target, query)
                    elif fipa_case == "propose":
                        propose_case = fipa.propose.WhichOneof("payload")
                        if propose_case == "content":
                            proposals = fipa.propose.content
                        else:
                            proposals = [Description.from_pb(propose) for propose in fipa.propose.proposals.objects]
                        agent.on_propose(msg.answer_id, msg.content.dialogue_id, msg.content.origin, fipa.target,
                                         proposals)
                    elif fipa_case == "accept":
                        agent.on_accept(msg.answer_id, msg.content.dialogue_id, msg.content.origin, fipa.target)
                    elif fipa_case == "decline":
                        agent.on_decline(msg.answer_id, msg.content.dialogue_id, msg.content.origin, fipa.target)
                    else:
                        logger.warning("Not implemented yet: fipa {0}".format(fipa_case))
def check_inconsistency_checker(schema: List[AttributeSchema],
                                values: Dict[str, ATTRIBUTE_TYPES],
                                exception_string):
    """
    Used to check that that AttributeInconsistencyException is raised with a certain string
    when the two inconsistent schema and values are used to build a Description
    """
    data_model = DataModel("foo", schema, "")
    with pytest.raises(AttributeInconsistencyException,
                       match=exception_string):
        _ = Description(values, data_model)
Beispiel #22
0
    def on_cfp(self, msg_id: int, dialogue_id: int, origin: str, target: int, query: CFP_TYPES):
        """Propose the and start the auction if not already in motion."""
        print("[{0}]: Received CFP from {1}".format(self.public_key, origin))

        price = self.startPrice
        proposal = Description({"auction" : True, "price" : price})
        print("[{0}]: Sending propose at price: {1}".format(self.public_key, price))
        self.send_propose(msg_id + 1, dialogue_id, origin, target + 1, [proposal])
        if self.auction == False:
            x = threading.Timer(5, self.startAuction)
            x.start()
            self.auction = True
Beispiel #23
0
def descriptions(draw, from_data_model=False):

    if from_data_model:
        data_model = draw(data_models())
        attributes = data_model.attribute_schemas
    else:
        data_model = None
        attributes = draw(lists(attributes_schema(), max_size=3))
    attributes_values = draw(schema_instances(attributes))

    d = Description(attributes_values, data_model)
    return d
Beispiel #24
0
 def load_service(self, metadata, load_path):
     dataset_info = metadata['base']
     attributes = description = {}
     for item in dataset_info['tags']:
         attributes[item] = description[item] = 'Tagged: ' + item
     attribute_list = []
     for key, value in attributes.items():
         attribute_list.append(AttributeSchema(key, str, False, value))
     data_model = DataModel(dataset_info['name'], attribute_list, dataset_info['description'])
     service = Description(description, data_model)
     data = Utils.load_json(load_path)
     return service, data
Beispiel #25
0
class WeatherStation(OEFAgent):
    """Class that implements the behaviour of the weather station."""

    weather_service_description = Description(
        {
            "wind_speed": False,
            "temperature": True,
            "air_pressure": True,
            "humidity": True,
        }, WEATHER_DATA_MODEL)

    def on_connection_terminated(self, url=None):
        print("Connection ended.")

    def on_cfp(self,
               msg_id: int,
               dialogue_id: int,
               origin: str = None,
               target: int = None,
               query: CFP_TYPES = None):
        """Send a simple Propose to the sender of the CFP."""
        print("[{0}]: Received CFP from {1}".format(self.public_key, origin))

        info = json.loads(query)

        print(info["where_i_am"])

        # prepare the proposal with a given price.
        price = 50
        proposed_price = Description({"price": price})
        proposals = [proposed_price]
        print("[{}]: Sending propose at price: {}".format(
            self.public_key, price))
        self.send_propose(msg_id + 1, dialogue_id, origin, target + 1,
                          proposals)

    def on_accept(self,
                  msg_id: int,
                  dialogue_id: int,
                  origin: str = None,
                  target: int = None):
        """Once we received an Accept, send the requested data."""
        print("[{0}]: Received accept from {1}.".format(
            self.public_key, origin))

        # send the measurements to the client. for the sake of simplicity, they are hard-coded.
        data = {"temperature": 15.0, "humidity": 0.7, "air_pressure": 1019.0}
        encoded_data = json.dumps(data).encode("utf-8")
        print("[{0}]: Sending data to {1}: {2}".format(self.public_key, origin,
                                                       pprint.pformat(data)))
        self.send_message(0, dialogue_id, origin, encoded_data)
    def test3(self):
        proposal = Description({
            "lat": float(8.9),
            "lon": float(8.11),
            "price": float(123.45),
            "friendly_name": "i am legend",
            "last_detection_time": float(1000.88888),
            "max_spaces": 99,
        })
        proposals = [proposal]
        data = {
            "msg_id": 102,
            "agent_uri": "wibble1",
            "send_message": {
                "dialogue_id": 101,
                "destination": "wibble2",
                "target_uri": "I_AM_URL1",
                "source_uri": "I_AM_URL2",
                "fipa": {
                    "target": 102,
                    "propose": {
                        ("content" if type(proposals) == bytes else None):
                        proposals,
                        ("proposals" if type(proposals) != bytes else None): {
                            "objects": proposals,
                        },
                    }
                }
            }
        }
        oefagent = OefMessageHandler()
        senddata = oefagent.make_message(bytes=None,
                                         json=None,
                                         message_class=agent_pb2.Envelope,
                                         data=data,
                                         pb=None)
        #print(senddata)

        assert b"I_AM_URL1" in senddata
        assert b"I_AM_URL2" in senddata

        inbound = agent_pb2.Envelope()
        inbound.ParseFromString(senddata)
        contents = protoToDict(inbound)
        #print(contents)

        oink = contents
        #print(oink['send_message']['fipa']['propose']['proposals']['objects'])
        assert len(oink) > 1
Beispiel #27
0
    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])
Beispiel #28
0
    def __init__(self, data, *args, **kwargs):
        super(TransportAgent, self).__init__(*args, **kwargs)

        self._entity = Entity()
        self._address = Address(self._entity)

        self.data = {
            'price_per_km': data['price_per_km'],
            'state': "WAIT",
            'location_latitude': data['location'].latitude,
            'location_longitude': data['location'].longitude
        }
        self.transport_description = Description(self.data,
                                                 TRANSPORT_DATAMODEL())
        self.distance_allowed_area = 5
        self.velocity = 0.0005
def makeAgent(preferences):
    idd = str(base58.b58encode("Driver{}".format(preferences["id"]))).replace(
        "'", str(random.randint(0, 9999999999999999999999999999)))
    print(idd)

    OEF_Address = os.environ.get('OEF_ADDRESS')
    OEF_Port = os.environ.get('OEF_PORT')
    print("HERE!", OEF_Address, OEF_Port)  #)
    server_agent = Demo_Agent(
        idd, oef_addr=OEF_Address, oef_port=OEF_Port,
        preferences=preferences)  # oef.economicagents.com
    server_agent.scheme['timezone'] = 2
    server_agent.scheme['id'] = str(uuid.uuid4())
    server_agent.connect()
    # register a service on the OEF
    server_agent.description = Description(server_agent.scheme, TIME_AGENT())
    server_agent.register_service(0, server_agent.description)
    # server_agent.run()
    return server_agent, idd
Beispiel #30
0
def get_goods_quantities_description(good_pbks: List[str],
                                     good_quantities: List[int],
                                     is_supply: bool) -> Description:
    """
    Get the TAC description for supply or demand.

    That is, a description with the following structure:
    >>> description = {
    ...     "tac_good_0": 1,
    ...     "tac_good_1": 0,
    ...     #...
    ...
    ... }
    >>>

     where the keys indicate the good_pbk and the values the quantity.

     >>> desc = get_goods_quantities_description(['tac_good_0', 'tac_good_1', 'tac_good_2', 'tac_good_3'], [0, 0, 1, 2], True)
     >>> desc.data_model.name == TAC_SUPPLY_DATAMODEL_NAME
     True
     >>> desc.values == {
     ...    "tac_good_0": 0,
     ...    "tac_good_1": 0,
     ...    "tac_good_2": 1,
     ...    "tac_good_3": 2}
     ...
     True

    :param good_pbks: the public keys of the goods.
    :param good_quantities: the quantities per good.
    :param is_supply: True if the description is indicating supply, False if it's indicating demand.

    :return: the description to advertise on the Service Directory.
    """
    data_model = build_datamodel(good_pbks, is_supply=is_supply)
    desc = Description(
        {
            good_pbk: quantity
            for good_pbk, quantity in zip(good_pbks, good_quantities)
        },
        data_model=data_model)
    return desc