示例#1
0
def iniciarConnexioAmbPlataforma():
    conGraph = Graph()
    conGraph.bind('req', REQ)
    con_obj = agn['recomanacio']
    conGraph.add((con_obj, RDF.type, REQ.PeticioIniciarConnexio)) 
    conGraph.add((con_obj, REQ.iniciar, Literal(True)))
        
    missatgeEnviament = build_message(conGraph,perf=ACL.request, sender=Client.uri, msgcnt=0, receiver=PlataformaAgent.uri, content=con_obj)
    response = send_message(missatgeEnviament, PlataformaAgent.address)
示例#2
0
def obtenirFeedback():
    print("Esperant temps per enviar feedback")
    sleep(20)

    print("Ha passat el temps, preparant peticio feedback...")
    feedGraph = Graph()
    feedGraph.bind('req', REQ)
    feed_obj = agn['feedback']
    feedGraph.add((feed_obj, RDF.type, REQ.PeticioFeedback))
    feedGraph.add((feed_obj, REQ.obtenirFeedcack, Literal(True)))

    missatgeFeedback = build_message(feedGraph,
                                     perf=ACL.request,
                                     sender=PlataformaAgent.uri,
                                     msgcnt=0,
                                     receiver=Client.uri,
                                     content=feed_obj)
    response = send_message(missatgeFeedback, Client.address)

    print("Rebem resposta feedback del client")
    query = """
                      SELECT ?marca ?puntuacio 
                      WHERE {
                      ?a REQ:marca ?marca .
                      ?a REQ:puntuacio ?puntuacio .
                      }
                      """
    qres = response.query(query, initNs={'REQ': REQ})

    marca = ''
    puntuacio = 1

    print("Guardant el feedback per millorar recomanacions...")
    for row in qres:
        marca = marca + str(row['marca'])
        puntuacio = int(row['puntuacio'])

    print("Marca:", marca)
    print("Puntuacio: ", puntuacio)

    feedback = {}
    with open('registreFeedback.txt') as json_file:
        feedback = json.load(json_file)

    print('El feedback guardat es:', feedback)
    feedback[marca] = int(feedback[marca]) + puntuacio

    with open('registreFeedback.txt', 'w') as outfile:
        json.dump(feedback, outfile)
示例#3
0
def enviarRecomenacio(connexioClientIniciada):
    print('Intent de connexio: ', connexioClientIniciada.value)
    if connexioClientIniciada.value > 0:
        marca = obtenirRecomenacio()

        producteRec = obtenirProducteRandom(marca)

        recGraph = Graph()
        recGraph.bind('req', REQ)
        rec_obj = agn['recomanacio']
        recGraph.add((rec_obj, RDF.type, REQ.PeticioRecomanacio))
        recGraph.add((rec_obj, REQ.prod, Literal(producteRec)))

        missatgeEnviament = build_message(recGraph,
                                          perf=ACL.request,
                                          sender=PlataformaAgent.uri,
                                          msgcnt=0,
                                          receiver=Client.uri,
                                          content=rec_obj)
        response = send_message(missatgeEnviament, Client.address)
    threading.Timer(80.0, enviarRecomenacio,
                    args=(connexioClientIniciada, )).start()
示例#4
0
    (pref_allotjament_obj, DEM.Tipus_estada, Literal(tipus_estada)))

content_graph.add((pref_obj, DEM.Tipus_activitat, Literal(tipus_activitats)))
content_graph.add((pref_obj, DEM.Preu, Literal(activities_budget)))

gr = Graph()
# building an ACL message
gr = build_message(content_graph,
                   perf=ACL.request,
                   sender=Client.uri,
                   msgcnt=0,
                   receiver=AgentePlanificador.uri,
                   content=viatge_obj)

# sending the message to the agent
res = send_message(gr, AgentePlanificador.address)

# decoding the ACL return message
viatge = res.value(predicate=RDF.type, object=VIA.Viatge)

# print transport info:
transport = res.value(predicate=RDF.type,
                      object=VIA.Transport)  # objecte transport

nom_transport = res.value(subject=transport,
                          predicate=VIA.Nom)  # nom del transport
capacitat = res.value(subject=transport, predicate=VIA.Capacitat)
tipus = res.value(subject=transport, predicate=VIA.MitjaTransport)
preu = res.value(subject=transport, predicate=VIA.Preu)
anada = res.value(subject=transport, predicate=VIA.Data_anada)  # data d'anada
tornada = res.value(subject=transport,
示例#5
0
        content.add((product_obj, REQ.Marca, Literal(var_filtre)))
        var_filtre = input("Introdueix categoria del producte: ")
        while (var_filtre == ""):
            var_filtre = input("Aquest camp es obligatori: ")
        content.add((product_obj, REQ.Categoria, Literal(var_filtre)))

        g = Graph()
        #construim el missatge com una req al agent cercador
        g = build_message(content,
                          perf=ACL.request,
                          sender=Client.uri,
                          msgcnt=0,
                          receiver=AgentVenedorExtern.uri,
                          content=cerca_obj)
        #enviem el msg
        response = send_message(g, AgentVenedorExtern.address)
        print("Producte afegit correctament")

    if (var_input == "2"):
        content = Graph()
        content.bind('req', REQ)
        cerca_obj = agn['producte']

        product_obj = REQ.Properties + '_properties'

        content.add((cerca_obj, RDF.type, REQ.AfegirMarca))
        content.add((cerca_obj, REQ.Properties, product_obj))

        print("Introdueix les propietats de la marca que vols afegir")
        var_filtre = input("Introdueix nom de la marca: ")
        content.add((product_obj, REQ.Nombre, Literal(var_filtre)))
示例#6
0
def comunicacion():
    """
    Entrypoint de comunicacion
    """    
    global dsgraph
    global mss_cnt
    
    
    # Extraemos el mensaje y creamos un grafo con el
    message = request.args['content']
    gm = Graph()
    gm.parse(data=message)

    msgdic = get_message_properties(gm)

    #Mirem si es un msg FIPA ACL
    if not msgdic:
        #Si no ho es, responem not understood
        logger.info('Msg no es FIPA ACL')
        gr = build_message(Graph(),
                           ACL['not-understood'],
                           sender=AgentTesorer.uri,
                           msgcnt=mss_cnt)
    else:
        #Si ho es obtenim la performativa
        if msgdic['performative'] != ACL.request:
            #No es un request, not understood
            logger.info('Msg no es una request')
            gr = build_message(Graph(),
                           ACL['not-understood'],
                           sender=AgentTesorer.uri,
                           msgcnt=mss_cnt)
        else:
            #Mirem tipus request
            content = msgdic['content']
            action = gm.value(subject=content, predicate=RDF.type)
            
            if action == REQ.PeticioTransferenciaAPlataforma:
                content = msgdic['content']
                diners = gm.value(subject=content, predicate=REQ.diners)
                compte = gm.value(subject=content, predicate=REQ.compte)
                nombreProd = gm.value(subject=content, predicate=REQ.np)
                
                esExtern = esProducteExtern(nombreProd)
                
                if esExtern == False:
                
                    print("El client paga a la plataforma ", diners, " usant el compte ", compte)
                    
                    conGraph = Graph()
                    conGraph.bind('req', REQ)
                    con_obj = agn['transferencia']
                    conGraph.add((con_obj, RDF.type, REQ.rebreDiners)) 
                    conGraph.add((con_obj, REQ.diners, Literal(diners)))
                    conGraph.add((con_obj, REQ.compte, Literal(compte)))
            
                    missatgeEnviament = build_message(conGraph,perf=ACL.request, sender=AgentTesorer.uri, msgcnt=0, receiver=PlataformaAgent.uri, content=con_obj)
                    response = send_message(missatgeEnviament, PlataformaAgent.address)
                else:
                    
                    print("El client paga al agent extern")
                    
                    tGraph = Graph()
                    tGraph.bind('req', REQ)
                    t_obj = agn['transferencia']
                    tGraph.add((t_obj, RDF.type, REQ.rebreDiners)) 
                    tGraph.add((t_obj, REQ.diners, Literal(diners)))
                    tGraph.add((t_obj, REQ.compte, Literal(compte)))
            
                    missatgeEnviament2 = build_message(tGraph,perf=ACL.request, sender=AgentTesorer.uri, msgcnt=0, receiver=AgentVenedorExtern.uri, content=t_obj)
                    response = send_message(missatgeEnviament2, AgentVenedorExtern.address)
                
                gr = build_message(Graph(),
                           ACL['inform-done'],
                           sender=AgentTesorer.uri,
                           msgcnt=mss_cnt)
            elif action == REQ.PeticioTransferenciaAClient:
                content = msgdic['content']
                diners = gm.value(subject=content, predicate=REQ.diners)
                print("La plataforma retorna al client els diners:", diners)
                
                transGraph = Graph()
                transGraph.bind('req', REQ)
                trans_obj = agn['transferencia2']
                transGraph.add((trans_obj, RDF.type, REQ.rebreDiners)) 
                transGraph.add((trans_obj, REQ.diners, Literal(diners)))
        
                print("Preparat per enviar a client")
                
                missatgeEnviament2 = build_message(transGraph,perf=ACL.request, sender=AgentTesorer.uri, msgcnt=0, receiver=Client.uri, content=trans_obj)
                response = send_message(missatgeEnviament2, Client.address)
                
                gr = build_message(Graph(),
                           ACL['inform-done'],
                           sender=AgentTesorer.uri,
                           msgcnt=mss_cnt)
            else:
                logger.info('Es una request que no entenem')
                gr = build_message(Graph(),
                           ACL['not-understood'],
                           sender=AgentTesorer.uri,
                           msgcnt=mss_cnt)
                
        mss_cnt += 1
        return gr.serialize(format='xml')

    pass
示例#7
0
def comunicacion():
    """
    Entrypoint de comunicacion
    """

    global dsgraph
    global mss_cnt

    message = request.args['content']
    gm = Graph()
    gm.parse(data=message)
    msgdic = get_message_properties(gm)

    #Mirem si es un msg FIPA ACL
    if not msgdic:
        #Si no ho es, responem not understood
        logger.info('Msg no es FIPA ACL')
        gr = build_message(Graph(),
                           ACL['not-understood'],
                           sender=PlataformaAgent.uri,
                           msgcnt=mss_cnt)
    else:
        #Si ho es obtenim la performativa
        if msgdic['performative'] != ACL.request:
            #No es un request, not understood
            logger.info('Msg no es una request')
            gr = build_message(Graph(),
                               ACL['not-understood'],
                               sender=PlataformaAgent.uri,
                               msgcnt=mss_cnt)
        else:
            #Mirem tipus request
            content = msgdic['content']
            action = gm.value(subject=content, predicate=RDF.type)
            print('La action es:', action)
            print('La action hauria de ser:', REQ.PeticioCompra)

            #placeholder
            if action == REQ.PeticioCompra:
                logger.info('Processem la compra')
                #agafar el nom del producte i la quantitat, i la localitzacio del client
                content = msgdic['content']
                nombreProd = gm.value(subject=content,
                                      predicate=REQ.NombreProducte)
                quant = gm.value(subject=content,
                                 predicate=REQ.QuantitatProducte)
                latClient = gm.value(subject=content,
                                     predicate=REQ.LatitudClient)
                longClient = gm.value(subject=content,
                                      predicate=REQ.LongitudClient)
                idCompra = gm.value(subject=content, predicate=REQ.idCompra)

                #cercar el millor centre logistic que tingui aquest producte
                cl = buscarCentreLogistic(nombreProd, quant, latClient,
                                          longClient)
                resCL = crearRespostaPeticioCompra(cl)
                if cl is None:
                    logger.info('No hi ha aquest producte en ningun centre')
                    print('No hi ha aquest producte en ningun centre')
                    resGraph = Graph()
                    resGraph.bind('req', REQ)
                    res_obj = agn['factura']
                    resGraph.add(
                        (res_obj, RDF.type, REQ.ConfirmacioAmbResposta))
                    resGraph.add((res_obj, REQ.resposta, Literal(resCL)))
                    gr = build_message(resGraph,
                                       ACL['inform-done'],
                                       sender=PlataformaAgent.uri,
                                       msgcnt=mss_cnt)
                    return gr.serialize(format='xml')
                else:
                    print('El millor centre logistic es:', cl)

                #cl sera el reciever del message
                #fer peticio enviament a centre logistic
                actualitzarStock(cl, nombreProd)

                envGraph = Graph()
                envGraph.bind('req', REQ)
                env_obj = agn['delegarEnviament']
                pes = buscarPesProducte(nombreProd)
                envGraph.add((env_obj, RDF.type, REQ.PeticioEnviament))
                envGraph.add((env_obj, REQ.prod, nombreProd))
                envGraph.add((env_obj, REQ.pes, pes))
                envGraph.add((env_obj, REQ.idCompra, idCompra))
                envGraph.add((env_obj, REQ.quant, quant))

                missatgeEnviament = Graph()
                centreReciever = None
                if str(cl) == 'cl1':
                    centreReciever = CentroLogistico1
                elif str(cl) == 'cl2':
                    centreReciever = CentroLogistico2
                elif str(cl) == 'cl3':
                    centreReciever = CentroLogistico3
                elif str(cl) == 'cl4':
                    centreReciever = CentroLogistico4
                elif str(cl) == 'cl5':
                    centreReciever = CentroLogistico5

                #per ara enviarem sempre al mateix centre (segona entrega)
                #centreReciever = CentroLogistico3

                print('\n')
                print('PREPAREM PER DELEGAR ENVIAMENT')
                print('\n')
                missatgeEnviament = build_message(envGraph,
                                                  perf=ACL.request,
                                                  sender=PlataformaAgent.uri,
                                                  msgcnt=0,
                                                  receiver=centreReciever.uri,
                                                  content=env_obj)
                response = send_message(missatgeEnviament,
                                        centreReciever.address)

                resGraph = Graph()
                resGraph.bind('req', REQ)
                res_obj = agn['factura']
                resGraph.add((res_obj, RDF.type, REQ.ConfirmacioAmbResposta))
                resGraph.add((res_obj, REQ.resposta, Literal(resCL)))
                gr = build_message(resGraph,
                                   ACL['inform-done'],
                                   sender=PlataformaAgent.uri,
                                   msgcnt=mss_cnt)
                return gr.serialize(format='xml')

            elif action == REQ.IniciarEnviament:
                content = msgdic['content']

                #response = gm.value(subject=content, predicate=REQ.PreuEnviament)

                print('\n')
                print('REBEM PREU ENVIAMENT')
                print('\n')

                nomE = gm.value(subject=content, predicate=REQ.NomEmpresa)
                preuEnv = gm.value(subject=content, predicate=REQ.Preu)
                idCompra = gm.value(subject=content, predicate=REQ.idCompra)
                nombreProd = gm.value(subject=content, predicate=REQ.NomProd)
                quant = gm.value(subject=content, predicate=REQ.quant)

                print('El preu enviament es:', preuEnv)
                print('El nom empresa es:', nomE)
                print('El idCompra es:', idCompra)
                print('El nom prod es:', nombreProd)
                print('La quant del producte es:', quant)

                preuProducte = buscarPreuProducte(nombreProd)

                print('El preu producte es:', preuProducte)

                preuProducte = Literal(int(preuProducte) * int(quant))
                preuTot = Literal(
                    float(preuEnv) + int(preuProducte * int(quant)))

                print('Registrant compra...')
                registrarCompra(idCompra, nombreProd, preuTot)

                print('Preparant factura...')

                contentFactura = Graph()
                contentFactura.bind('req', REQ)
                factura_obj = agn['factura']
                contentFactura.add(
                    (factura_obj, RDF.type, REQ.ConfirmacioAmbFactura))
                contentFactura.add((factura_obj, REQ.nomP, nombreProd))
                contentFactura.add(
                    (factura_obj, REQ.preuEnviament, Literal(preuEnv)))
                contentFactura.add((factura_obj, REQ.preuProd, preuProducte))
                contentFactura.add((factura_obj, REQ.preuTotal, preuTot))
                contentFactura.add((factura_obj, REQ.nomEmpresa, nomE))
                #El centre logistic hauria de passar el idCompra!!!!!!!!!!!!!!
                contentFactura.add(
                    (factura_obj, REQ.idCompra, Literal(idCompra)))

                print('Factura creada')

                missatgeFactura = build_message(contentFactura,
                                                perf=ACL.request,
                                                sender=PlataformaAgent.uri,
                                                msgcnt=0,
                                                receiver=Client.uri,
                                                content=factura_obj)
                response = send_message(missatgeFactura, Client.address)

                print("Cridar obtenir feedback...")
                obtenirFeedback()

                gr = build_message(Graph(),
                                   ACL['inform-done'],
                                   sender=PlataformaAgent.uri,
                                   msgcnt=mss_cnt)

            elif action == REQ.PeticioDevolucio:
                content = msgdic['content']
                idCompra = gm.value(subject=content, predicate=REQ.idCompra)
                dies = gm.value(subject=content, predicate=REQ.dies)
                print("SENSE TRANSFORMACIO: ", dies)
                print("AMB TRANSFORMACIO: ", int(dies))
                resposta = ""

                print("Preparat per gestionar peticio devolucio")

                if int(dies) >= 0 and int(dies) <= 15:
                    preu = cercarCompra(idCompra)
                    print("Compra cercada")
                    if preu < 0.0:
                        resposta = "NO es possible procedir amb la devolució ja que no existeix un registre d'aquesta compra"
                    else:
                        eliminarRegistreCerca(idCompra)
                        preu = str(preu)
                        resposta = "Peticio ACCEPTADA. L'empresa transportista recollirà el producte en el mateix lloc que l'entrega en un plaç màxim de 3 dies. Es procedirà a fer un reembolsament de " + preu

                        recGraph = Graph()
                        recGraph.bind('req', REQ)
                        rec_obj = agn['recomanacio']
                        recGraph.add((rec_obj, RDF.type,
                                      REQ.PeticioTransferenciaAClient))
                        recGraph.add((rec_obj, REQ.diners, Literal(preu)))

                        print("Preparant comunicacio amb Tresorer...")

                        missatgeEnviament = build_message(
                            recGraph,
                            perf=ACL.request,
                            sender=PlataformaAgent.uri,
                            msgcnt=0,
                            receiver=AgentTesorer.uri,
                            content=rec_obj)
                        response = send_message(missatgeEnviament,
                                                AgentTesorer.address)
                else:
                    resposta = "NO es possible procedir amb la devolució, el període màxim per a la devolució és de 15 dies."

                contentDev = Graph()
                contentDev.bind('req', REQ)
                devo_obj = agn['dev']
                contentDev.add((devo_obj, RDF.type, REQ.RespostaDevolucio))
                contentDev.add((devo_obj, REQ.respostaDev, Literal(resposta)))

                print('Resposta devolucio preparada per enviar')

                gr = build_message(contentDev,
                                   ACL['inform-done'],
                                   sender=PlataformaAgent.uri,
                                   msgcnt=mss_cnt)
            elif action == REQ.PeticioIniciarConnexio:
                iniC = gm.value(subject=content, predicate=REQ.iniciar)

                #                global connexiolientIniciada
                if iniC:
                    connexioClientIniciada.value = 1
                print('ESTAT DE CONNEXIO: ', connexioClientIniciada.value)

                gr = build_message(Graph(),
                                   ACL['inform-done'],
                                   sender=PlataformaAgent.uri,
                                   msgcnt=mss_cnt)

            elif action == REQ.rebreDiners:
                content = msgdic['content']
                diners = gm.value(subject=content, predicate=REQ.diners)

                print("Hem rebut diners: ", diners)

                gr = build_message(Graph(),
                                   ACL['inform-done'],
                                   sender=PlataformaAgent.uri,
                                   msgcnt=mss_cnt)
            else:
                logger.info('Es una request que no entenem')
                gr = build_message(Graph(),
                                   ACL['not-understood'],
                                   sender=PlataformaAgent.uri,
                                   msgcnt=mss_cnt)
    mss_cnt += 1
    return gr.serialize(format='xml')
示例#8
0
def agentbehavior1(q, fileno, consolaEnUs):
    """
    Un comportamiento del agente

    :return:
    """
    sys.stdin = os.fdopen(fileno)
    iniciarConnexioAmbPlataforma()
    print("Instruccions disponibles")
    print("1 - Buscar un producte")
    print("2 - Comprar un producte")
    print("3 - Modificar localitzacio client (Predefinida: 42.2, 2.19)")
    print("4 - Devolucio de un producte")
    print("5 - Eliminar registres de compra, cerca i feedback")

    letters = string.ascii_lowercase
    
    latClient = 42.2
    longClient = 2.19

    while True:
        while consolaEnUs.value > 0:
            asd = 0
        
        var_input = input("Introdueix instruccio: ")
        while(var_input != "1" and var_input != "2" and var_input != "3" and var_input != "4" and var_input != "5"):
            print ("Instruccio desconeguda")
            var_input = input("Introdueix instruccio: ")
        
        if (var_input == "1"):
            content = Graph()
            content.bind('req', REQ)
            cerca_obj = agn['cerca']
            
            filters_obj = REQ.Filters + '_filters'
            
            content.add((cerca_obj, RDF.type, REQ.PeticioCerca))
            content.add((cerca_obj, REQ.Filters, filters_obj))
            
            print("Introdueix els filtres desitjats, apreta enter sense escriure res per no filtrar (Tambe pots escrire un '-' per no filtrar)")
            var_filtre = input("Introdueix categoria del producte: ")
            if (var_filtre != "" and var_filtre != "-"):   
                content.add((filters_obj, REQ.Categoria, Literal(var_filtre)))
            var_filtre = input("Introdueix nom del producte: ")
            if (var_filtre != "" and var_filtre != "-"): 
                content.add((filters_obj, REQ.Nombre, Literal(var_filtre)))
            var_filtre = input("Introdueix preu maxim del producte: ")
            if (var_filtre != "" and var_filtre != "-"): 
                content.add((filters_obj, REQ.Precio, Literal(int(var_filtre))))
            var_filtre = input("Introdueix marca del producte: ")
            if (var_filtre != "" and var_filtre != "-"): 
                content.add((filters_obj, REQ.TieneMarca, Literal(var_filtre)))
            ofile  = open('request.owl', "w")
            encoding = 'iso-8859-1'
            ofile.write(str(content.serialize(), encoding))
            ofile.close()
            
            g = Graph()
            #construim el missatge com una req al agent cercador
            g = build_message(content, perf=ACL.request, sender=Client.uri, msgcnt=0, receiver=AgentCercador.uri, content=cerca_obj)
            #enviem el msg
            response = send_message(g, AgentCercador.address)
            #mirem que hem rebut 
            query = """
            SELECT ?nombre ?precio ?marca ?categoria
            WHERE {
                    ?a REQ:Nombre ?nombre .
                    ?a REQ:Precio ?precio .
                    ?a REQ:Marca ?marca .
                    ?a REQ:Categoria ?categoria .
                    }
            """
            qres = response.query(query, initNs = {'REQ': REQ})  
            for row in qres:
                print("-------------------------------------------")
                print("Nom: " + row['nombre'])
                print("Preu:" + row['precio'])
                print("Marca: " + row['marca'])
                print("Categoria: " + row['categoria'])
            #ho guardem
            ofile  = open('output.owl', "w")
            encoding = 'iso-8859-1'
            ofile.write(str(response.serialize(), encoding))
            ofile.close()
            
        if (var_input == "2"):
            idCompra = ''.join(random.choice(letters) for i in range(32))
            print("Introdueix el nom del producte i la quantitat que vols comprar")
            #enviar peticio compra
        
            contentPeticioCompra = Graph()
            contentPeticioCompra.bind('req', REQ)
            compra_obj = agn['compra']
            contentPeticioCompra.add((compra_obj, RDF.type, REQ.PeticioCompra))
            var_nomP = input("Introdueix el nom del producte: ")
            if (var_nomP != ""):
                contentPeticioCompra.add((compra_obj, REQ.NombreProducte, Literal(str(var_nomP))))
            var_Q = input("Introdueix quantitat del producte (0-5): ")
            if (var_Q != ""):
                contentPeticioCompra.add((compra_obj, REQ.QuantitatProducte, Literal(int(var_Q))))
            contentPeticioCompra.add((compra_obj, REQ.LatitudClient, Literal(float(latClient))))
            contentPeticioCompra.add((compra_obj, REQ.LongitudClient, Literal(float(longClient))))
            contentPeticioCompra.add((compra_obj, REQ.idCompra, Literal(str(idCompra))))
            messageCompra = Graph()
            messageCompra = build_message(contentPeticioCompra, perf=ACL.request, sender=Client.uri, msgcnt=0, receiver=PlataformaAgent.uri, content=compra_obj)
            print('EnviemPeticioCompra')
            response = send_message(messageCompra, PlataformaAgent.address)
            
            query = """
                SELECT ?resposta
                WHERE {
                    ?a REQ:resposta ?resposta
                }
                    """
            qres = response.query(query, initNs = {'REQ': REQ})
            respostaCL = ""
            for row in qres:
                respostaCL = str(row['resposta'])
            print(respostaCL)
        if var_input == "3":
            print("Introdueix la latitud i longitud usant punts i no comes (ex: 40.4555).")
            var_lat = input("Introdueix la latitud: ")
            if var_lat != "":
                latClient = float(var_lat)
            var_long = input("Introdueix la longitud: ")
            if var_long != "":
                longClient = float(var_long)
        if var_input == "4":
            idC = ""
            dies = 0
            print("Introdueix el id de compra, rao de devolucio i quants dies fa que et va arribar el producte")
            var_id = input("Introduir el id de compra:")
            if var_id != "":
                idC = var_id
            var_dies = input("Si la rao de devolucio es un producte defectuos o equivocat, introdueix un 0. Si la rao es que el producte no satisà les vostres espectatives, introdueix el numero de dies que fa des de que us va arribar el producte.")
            if var_dies != "":
                dies = var_dies
            
            contentDevolucio = Graph()
            contentDevolucio.bind('req', REQ)
            dev_obj = agn['devolucio']
            contentDevolucio.add((dev_obj, RDF.type, REQ.PeticioDevolucio))
            contentDevolucio.add((dev_obj, REQ.idCompra, Literal(str(idC))))
            contentDevolucio.add((dev_obj, REQ.dies, Literal(dies)))
            
            messagePeticio = Graph()
            messagePeticio = build_message(contentDevolucio, perf=ACL.request, sender=Client.uri, msgcnt=0, receiver=PlataformaAgent.uri, content=dev_obj)
            print('EnviemPeticioDevolucio')
            response = send_message(messagePeticio, PlataformaAgent.address)
            
            query = """
                          SELECT ?respostaDev
                          WHERE {
                          ?a REQ:respostaDev ?respostaDev .
                          }
                          """
            qres = response.query(query, initNs = {'REQ': REQ})
            
            for row in qres:
                print(row['respostaDev'])
        if var_input == "5":
            eliminarRegistres()
             
    pass
示例#9
0
def comunicacion():
    
    """
    Entrypoint de comunicacion
    """
    
    global dsgraph
    global mss_cnt
        
    message = request.args['content']
    gm = Graph()
    gm.parse(data=message)
    msgdic = get_message_properties(gm)
    
    #Mirem si es un msg FIPA ACL
    if not msgdic:
        #Si no ho es, responem not understood
        logger.info('Msg no es FIPA ACL')
        gr = build_message(Graph(),
                           ACL['not-understood'],
                           sender=Client.uri,
                           msgcnt=mss_cnt)
    else:
        #Si ho es obtenim la performativa
        if msgdic['performative'] != ACL.request:
            #No es un request, not understood
            logger.info('Msg no es una request')
            gr = build_message(Graph(),
                           ACL['not-understood'],
                           sender=Client.uri,
                           msgcnt=mss_cnt)
        else:
            #Mirem tipus request
            content = msgdic['content']
            action = gm.value(subject=content, predicate=RDF.type)
            print('-------------------La action es:', action)
#            print('La action hauria de ser:', REQ.PeticioCompra)
            
            #placeholder
            if action == REQ.ConfirmacioAmbFactura:
                content = msgdic['content']
                print('-------------------FACTURA--------------------')
                nombreProd = gm.value(subject=content, predicate=REQ.nomP)
                preuProd = gm.value(subject=content, predicate=REQ.preuProd)
                preuEnv = gm.value(subject=content, predicate=REQ.preuEnviament)
                preuTotal = gm.value(subject=content, predicate=REQ.preuTotal)
                nomEmpresa = gm.value(subject=content, predicate=REQ.nomEmpresa)
                idCompra = gm.value(subject=content, predicate=REQ.idCompra)
                print('NomProducte:',nombreProd)
                print('PreuEnviament:',preuEnv)
                print('PreuProducte:',preuProd)
                print('PreuTotal:',preuTotal)
                print('NomEmpresa:',nomEmpresa)
                print('idCompra:', idCompra)
                print('FinalitzemPeticioCompra')
                
                print("Proces pagament")
                consolaEnUs.value = 1
                compte = ""
                compte = input("Introdueix el teu compte")
                while compte == "":
                    compte = input("Introdueix un compte vàlid")
                
                consolaEnUs.value = 0
                
                conGraph = Graph()
                conGraph.bind('req', REQ)
                con_obj = agn['transferencia']
                conGraph.add((con_obj, RDF.type, REQ.PeticioTransferenciaAPlataforma)) 
                conGraph.add((con_obj, REQ.diners, Literal(preuTotal)))
                conGraph.add((con_obj, REQ.compte, Literal(compte)))
                conGraph.add((con_obj, REQ.np, Literal(nombreProd)))
        
                missatgeEnviament = build_message(conGraph,perf=ACL.request, sender=Client.uri, msgcnt=0, receiver=AgentTesorer.uri, content=con_obj)
                response = send_message(missatgeEnviament, AgentTesorer.address)
                
                gr = build_message(Graph(),
                           ACL['inform-done'],
                           sender=PlataformaAgent.uri,
                           msgcnt=mss_cnt)
                
            elif action == REQ.PeticioRecomanacio:
                content = msgdic['content']
                consolaEnUs.value = 1
                print('-------------------RECOMANACIO--------------------')
                nombreProd = gm.value(subject=content, predicate=REQ.prod)
                print("Potser t'interessa el producte " + str(nombreProd))
                consolaEnUs.value = 0
                
                gr = build_message(Graph(),
                           ACL['inform-done'],
                           sender=Client.uri,
                           msgcnt=mss_cnt)
            
            elif action == REQ.PeticioFeedback:
                content = msgdic['content']
                pucObtenirFeedback = gm.value(subject=content, predicate=REQ.obtenirFeedcack)
                pucObtenirFeedback = bool(pucObtenirFeedback)
                
                if pucObtenirFeedback == True:
                    print('-------------------FEEDBACK D\'USUARI--------------------')
                    print("p - Phone")
                    print("v - Blender")
                    print("c - Computer")
                    
                    consolaEnUs.value = 1
                    
                    var_marca = input("Introdueix la categoria que has comprat recentment")
                    while var_marca != "p" and var_marca != "v" and var_marca != "c":
                        var_marca = input("No es una marca. Introdueix una marca:")
                    
                    var_puntuacio = input("Introdueix una valoracio s, a, b")
                    while var_puntuacio != "s" and var_puntuacio != "a" and var_puntuacio != "b":
                        var_puntuacio = input("Valor invalid: Introdueix la puntuacio una altre vegada:")
                    
                    consolaEnUs.value = 0
                    
                    if var_marca == "p":
                        var_marca = "Phone"
                    elif var_marca == "v":
                        var_marca = "Blender"
                    else:
                        var_marca = "Computer"
                        
                    punts = 0
                        
                    if var_puntuacio == "s":
                        punts = 10
                    elif var_puntuacio == "a":
                        punts = 5
                    else:
                        punts = 0
                        
                    contentFeed = Graph()
                    contentFeed.bind('req', REQ)
                    feed_obj = agn['feed']
                    contentFeed.add((feed_obj, RDF.type, REQ.RespostaFeedback))
                    contentFeed.add((feed_obj, REQ.marca, Literal(var_marca)))
                    contentFeed.add((feed_obj, REQ.puntuacio, Literal(punts)))
                    
                    gr = build_message(contentFeed,
                           ACL['inform-done'],
                           sender=PlataformaAgent.uri,
                           msgcnt=mss_cnt)
                    
            elif action == REQ.rebreDiners:
                content = msgdic['content']
                diners = gm.value(subject=content, predicate=REQ.diners)
                        
                print("Hem rebut diners: ", diners)
    
                gr = build_message(Graph(),
                       ACL['inform-done'],
                       sender=Client.uri,
                       msgcnt=mss_cnt)
            else:
                logger.info('Es una request que no entenem')
                gr = build_message(Graph(),
                           ACL['not-understood'],
                           sender=Client.uri,
                           msgcnt=mss_cnt)
#                return gr.serialize(format='xml')
    mss_cnt += 1
    return gr.serialize(format='xml')