You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

54 lines
1.4 KiB

  1. import json
  2. from pika import BlockingConnection, ConnectionParameters, PlainCredentials
  3. from pika.exchange_type import ExchangeType
  4. RMQ_HOST = 'localhost'
  5. RMQ_USER = 'rabbit'
  6. RMQ_PASS = '1234'
  7. EXCHANGE_NAME = 'amq.topic'
  8. ROUTING_KEY = 'co2.*'
  9. def callback(channel, method, properties, body):
  10. log_file = open('receiver.log', 'a')
  11. log_file.write(body.decode() + '\n')
  12. message = json.loads(body)
  13. status = 'OK'
  14. if message['value'] > 500:
  15. status = 'WARNING'
  16. print(f"{message['time']}: {status}")
  17. log_file.close()
  18. channel.basic_ack(delivery_tag=method.delivery_tag)
  19. def main():
  20. connection = BlockingConnection(
  21. ConnectionParameters(
  22. host=RMQ_HOST,
  23. credentials=PlainCredentials(RMQ_USER, RMQ_PASS)
  24. )
  25. )
  26. try:
  27. channel = connection.channel()
  28. result = channel.queue_declare(queue=ROUTING_KEY)
  29. channel.queue_bind(exchange=EXCHANGE_NAME, queue=result.method.queue)
  30. channel.basic_consume(queue=ROUTING_KEY,
  31. on_message_callback=callback)
  32. print('[*] Waiting for CO2 data. Press CTRL+C to exit')
  33. channel.start_consuming()
  34. connection.close()
  35. except KeyboardInterrupt:
  36. connection.close()
  37. print('Interrupted by user. Shutting down...')
  38. if __name__ == '__main__':
  39. main()