Last active
May 30, 2023 01:30
-
-
Save zignd/e2dfc4025e05e78ec99577f96da98c0c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| # ASDPC | |
| # Prof. Luiz Lima Jr. | |
| from pika import BlockingConnection | |
| from sys import argv | |
| from enum import Enum | |
| E = Enum("Estado", "INICIADOR OCIOSO ATIVO OK") | |
| if len(argv)<2: | |
| print(f'USO: {argv[0]} <id> <v1> [<v2> ...]') | |
| exit(1) | |
| idx = argv[1] | |
| Nx = argv[2:] | |
| Nt = [] # neighbour tree | |
| estado = E.OCIOSO | |
| def muda_estado(novo): | |
| global estado | |
| estado = novo | |
| def envia(canal, msg, dests): | |
| """ | |
| envia mensagem para lista de destinatarios (dests) | |
| """ | |
| msg = f'{idx}:{msg}' | |
| for d in dests: | |
| canal.basic_publish( | |
| exchange='', | |
| routing_key=d, | |
| body=msg) | |
| def recebendo(canal, msg, origem): | |
| global raiz, cont, pai, estado | |
| if estado == E.OCIOSO: | |
| if msg == 'Q': | |
| raiz = False | |
| pai = origem | |
| Nt.append(origem) | |
| envia(canal, 'Sim', [origem]) | |
| cont = 1 | |
| if cont == len(Nx): | |
| muda_estado(E.OK) | |
| print(Nt) | |
| else: | |
| viz = Nx[:] | |
| viz.remove(origem) | |
| envia(canal, 'Q', viz) | |
| muda_estado(E.ATIVO) | |
| elif estado == E.ATIVO: | |
| if msg == 'Sim': | |
| Nt.append(origem) | |
| cont += 1 | |
| if cont == len(Nx): | |
| muda_estado(E.OK) | |
| print(Nt) | |
| elif msg == 'Q': | |
| cont += 1 | |
| if cont == len(Nx): | |
| muda_estado(E.OK) | |
| print(Nt) | |
| def espontaneamente(canal, msg): | |
| print('iniciador') | |
| global raiz, cont | |
| raiz = True | |
| envia(canal, "Q", Nx) | |
| cont = 0 | |
| muda_estado(E.ATIVO) | |
| def trata_msg(canal, metodo, props, body): | |
| m = body.decode().split(':') | |
| if len(m) < 2: | |
| origem = 'NULL' | |
| msg = m[0] | |
| else: | |
| origem = m[0] | |
| msg = m[1] | |
| if origem == 'STARTER': | |
| muda_estado(E.INICIADOR) | |
| espontaneamente(canal, msg) | |
| else: | |
| recebendo(canal, msg, origem) | |
| with BlockingConnection() as conexao: | |
| with conexao.channel() as canal: | |
| canal.queue_declare(queue=idx, auto_delete=True) | |
| for viz in Nx: | |
| canal.queue_declare(queue=viz, auto_delete=True) | |
| canal.basic_consume(queue=idx, | |
| on_message_callback=trata_msg, | |
| auto_ack=True) | |
| try: | |
| print(f'{idx} aguardando mensagens') | |
| canal.start_consuming() | |
| except KeyboardInterrupt: | |
| canal.stop_consuming() | |
| print('\nFim') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment