Guest User

Untitled

a guest
Dec 8th, 2018
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. import getopt
  2. import mosquitto
  3. import sys
  4.  
  5. final_mid = 0
  6.  
  7. def on_connect(mosq, userdata, rc):
  8. if userdata == True:
  9. print("rc: "+str(rc))
  10.  
  11. def on_message(mosq, userdata, msg):
  12. global final_mid
  13. if msg.retain == 0:
  14. pass
  15. #sys.exit()
  16. else:
  17. if userdata == True:
  18. print("Clearing topic "+msg.topic)
  19. (rc, final_mid) = mosq.publish(msg.topic, None, 1, True)
  20.  
  21. def on_publish(mosq, userdata, mid):
  22. global final_mid
  23. if mid == final_mid:
  24. sys.exit()
  25.  
  26. def on_log(mosq, userdata, level, string):
  27. print(string)
  28.  
  29. def print_usage():
  30. print("mqtt_clear_retain.py [-d] [-h hostname] [-i clientid] [-k keepalive] [-p port] [-u username [-P password]] [-v] -t topic")
  31.  
  32. def main(argv):
  33. debug = False
  34. host = "localhost"
  35. client_id = None
  36. keepalive = 60
  37. port = 1883
  38. password = None
  39. topic = None
  40. username = None
  41. verbose = False
  42.  
  43. try:
  44. opts, args = getopt.getopt(argv, "dh:i:k:p:P:t:u:v", ["debug", "id", "keepalive", "port", "password", "topic", "username", "verbose"])
  45. except getopt.GetoptError as s:
  46. print_usage()
  47. sys.exit(2)
  48. for opt, arg in opts:
  49. if opt in ("-d", "--debug"):
  50. debug = True
  51. elif opt in ("-h", "--host"):
  52. host = arg
  53. elif opt in ("-i", "--id"):
  54. client_id = arg
  55. elif opt in ("-k", "--keepalive"):
  56. keepalive = int(arg)
  57. elif opt in ("-p", "--port"):
  58. port = int(arg)
  59. elif opt in ("-P", "--password"):
  60. password = arg
  61. elif opt in ("-t", "--topic"):
  62. topic = arg
  63. print(topic)
  64. elif opt in ("-u", "--username"):
  65. username = arg
  66. elif opt in ("-v", "--verbose"):
  67. verbose = True
  68.  
  69. if topic == None:
  70. print("You must provide a topic to clear.")
  71. sys.exit(2)
  72.  
  73. mqttc = mosquitto.Mosquitto(client_id)
  74. mqttc._userdata = verbose
  75. mqttc.on_message = on_message
  76. mqttc.on_publish = on_publish
  77. mqttc.on_connect = on_connect
  78. if debug:
  79. mqttc.on_log = on_log
  80.  
  81. if username:
  82. mqttc.username_pw_set(username, password)
  83. mqttc.connect(host, port, keepalive)
  84. mqttc.subscribe(topic)
  85. mqttc.loop_forever()
  86.  
  87. if __name__ == "__main__":
  88. main(sys.argv[1:])
Add Comment
Please, Sign In to add comment