No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 

61 líneas
1.6 KiB

  1. import json
  2. import os
  3. from datetime import datetime
  4. from pika import BlockingConnection, ConnectionParameters, PlainCredentials
  5. from pika.exchange_type import ExchangeType
  6. RMQ_HOST = 'localhost'
  7. RMQ_USER = 'rabbit'
  8. RMQ_PASS = '1234'
  9. EXCHANGE_NAME = 'amq.topic'
  10. ROUTING_KEY = 'rep.*'
  11. def extract_value(dict_line):
  12. return dict_line['value']
  13. def callback(channel, method, properties, body):
  14. log_file = open('receiver.log', 'r')
  15. lines = log_file.readlines()
  16. dict_lines = list(map(json.loads, lines))
  17. if body == b'current':
  18. print(f"{datetime.utcnow()}: Latest CO2 level is {dict_lines[-1]['value']}")
  19. else:
  20. values = list(map(extract_value, dict_lines))
  21. avg = sum(values) / len(values)
  22. print(f"{datetime.utcnow()}: Average CO2 level is {avg}")
  23. log_file.close()
  24. channel.basic_ack(delivery_tag=method.delivery_tag)
  25. def main():
  26. connection = BlockingConnection(
  27. ConnectionParameters(
  28. host=RMQ_HOST,
  29. credentials=PlainCredentials(RMQ_USER, RMQ_PASS)
  30. )
  31. )
  32. try:
  33. channel = connection.channel()
  34. result = channel.queue_declare(queue=ROUTING_KEY)
  35. channel.queue_bind(exchange=EXCHANGE_NAME, queue=result.method.queue)
  36. channel.basic_consume(queue=ROUTING_KEY,
  37. on_message_callback=callback)
  38. print('[*] Waiting for queries from the control tower. Press CTRL+C to exit')
  39. channel.start_consuming()
  40. connection.close()
  41. except KeyboardInterrupt:
  42. connection.close()
  43. print('Interrupted by user. Shutting down...')
  44. if __name__ == '__main__':
  45. main()