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.
 
 
 

41 lines
1.2 KiB

  1. import json
  2. from datetime import datetime
  3. from pika import BlockingConnection, ConnectionParameters, PlainCredentials
  4. from pika.exchange_type import ExchangeType
  5. RMQ_HOST = 'localhost'
  6. RMQ_USER = 'rabbit'
  7. RMQ_PASS = '1234'
  8. EXCHANGE_NAME = 'amq.topic'
  9. ROUTING_KEY = 'co2.sensor'
  10. def main():
  11. connection = BlockingConnection(
  12. ConnectionParameters(
  13. host=RMQ_HOST,
  14. credentials=PlainCredentials(RMQ_USER, RMQ_PASS)
  15. )
  16. )
  17. try:
  18. channel = connection.channel()
  19. result = channel.queue_declare(queue=ROUTING_KEY)
  20. channel.queue_bind(exchange=EXCHANGE_NAME, queue=result.method.queue)
  21. while True:
  22. co2 = int(input('Enter CO2 level: '))
  23. message = json.dumps({'time': str(datetime.utcnow()), 'value': co2})
  24. print(message)
  25. channel.basic_publish(exchange=EXCHANGE_NAME,
  26. routing_key=ROUTING_KEY,
  27. body=message)
  28. connection.close()
  29. except KeyboardInterrupt:
  30. connection.close()
  31. print('Interrupted by user. Shutting down...')
  32. if __name__ == '__main__':
  33. main()