test_send_mqtt_lb.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #!/usr/bin/env python3
  2. """Send a single MQTT message to the Traefik LB IP to verify external MQTT connectivity.
  3. Defaults to host 153.92.153.32, port 1883, topic mqtt/test, message "test message", user: user, pass: changeme.
  4. Exits 0 on success, non-zero on failure.
  5. """
  6. import sys
  7. import time
  8. import argparse
  9. import paho.mqtt.client as mqtt
  10. def main():
  11. p = argparse.ArgumentParser()
  12. p.add_argument('--host', default='153.92.153.32')
  13. p.add_argument('--port', type=int, default=1883)
  14. p.add_argument('--topic', default='mqtt/test')
  15. p.add_argument('--message', default='hello from test_send_mqtt_lb')
  16. p.add_argument('--username', default='user')
  17. p.add_argument('--password', default='changeme')
  18. p.add_argument('--timeout', type=int, default=10)
  19. args = p.parse_args()
  20. connected = False
  21. published = False
  22. def on_connect(client, userdata, flags, rc):
  23. nonlocal connected
  24. connected = (rc == 0)
  25. print(f'on_connect rc={rc}, success={connected}')
  26. def on_publish(client, userdata, mid):
  27. nonlocal published
  28. published = True
  29. print(f'on_publish mid={mid}')
  30. client = mqtt.Client()
  31. client.username_pw_set(args.username, args.password)
  32. client.on_connect = on_connect
  33. client.on_publish = on_publish
  34. try:
  35. client.connect(args.host, args.port, keepalive=60)
  36. except Exception as e:
  37. print('connect failed:', e)
  38. return 2
  39. client.loop_start()
  40. # wait for connection
  41. waited = 0
  42. while not connected and waited < args.timeout:
  43. time.sleep(0.2)
  44. waited += 0.2
  45. if not connected:
  46. print('failed to connect within timeout')
  47. client.loop_stop()
  48. return 3
  49. try:
  50. result, mid = client.publish(args.topic, args.message, qos=1)
  51. print('publish result:', result, 'mid:', mid)
  52. except Exception as e:
  53. print('publish failed:', e)
  54. client.loop_stop()
  55. return 4
  56. # wait for on_publish
  57. waited = 0
  58. while not published and waited < args.timeout:
  59. time.sleep(0.2)
  60. waited += 0.2
  61. client.loop_stop()
  62. client.disconnect()
  63. if published:
  64. print('message sent')
  65. return 0
  66. else:
  67. print('message not confirmed published')
  68. return 5
  69. if __name__ == '__main__':
  70. sys.exit(main())