IdeasXWorkstationClient.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. '''
  2. Title: IdeasXWorkstationClient Class
  3. Author: Tyler Berezowsky
  4. Description:
  5. '''
  6. import sys
  7. import os
  8. import getopt
  9. try:
  10. import paho.mqtt.client as mqtt
  11. import paho.mqtt.publish as mqtt_pub
  12. except ImportError:
  13. # This part is only required to run the example from within the examples
  14. # directory when the module itself is not installed.
  15. #
  16. # If you have the module installed, just use "import paho.mqtt.client"
  17. import os
  18. import inspect
  19. cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"../src")))
  20. if cmd_subfolder not in sys.path:
  21. sys.path.insert(0, cmd_subfolder)
  22. import paho.mqtt.client as mqtt
  23. try:
  24. from protocolbuffers import IdeasXMessages_pb2 as IdeasXMessages
  25. import IdeasXDatabaseManager
  26. except ImportError:
  27. print("The python classes for IdeasX are missing. Try running the Makefile in" +
  28. "ideasX-messages.")
  29. data = []
  30. #------------------------------------------------------------------------------
  31. # Sniffer Client Class
  32. class IdeasXWorkstationClient():
  33. def __init__(self):
  34. self.command_topic = "/encoder/+/command"
  35. self.data_topic = "/encoder/+/data"
  36. self.health_topic = "/encoder/+/health"
  37. self.mqttdebug = False
  38. self.debug = False
  39. self.dmb = IdeasXDatabaseManager.IdeasXDatabaseManager()
  40. self._mqttc = mqtt.Client(clean_session=True, userdata=None,
  41. protocol='MQTTv311')
  42. self._mqttc.message_callback_add(self.health_topic, self.mqtt_on_health)
  43. #self._mqttc.message_callback_add(self.data_topic, self.mqtt_on_data)
  44. #self._mqttc.message_callback_add(self.command_topic, self.mqtt_on_command)
  45. self._mqttc.on_connect = self.mqtt_on_connect
  46. self._mqttc.on_disconnect = self.mqtt_on_disconnect
  47. if self.mqttdebug:
  48. self._mqttc.on_log = self.mqtt_on_log
  49. #------------------------------------------------------------------------------
  50. # callback functions
  51. def mqtt_on_connect(self, mqttc, backend_data, flags, rc):
  52. if rc == 0:
  53. print('Connected to %s: %s' % (mqttc._host, mqttc._port))
  54. else:
  55. print('rc: ' + str(rc))
  56. print('-'*70)
  57. def mqtt_on_disconnect(self, mqttc, backend_data, rc):
  58. if self.debug:
  59. if rc != 0:
  60. print("Client disconnected and its a mystery why!")
  61. else:
  62. print("Client successfully disconnected.")
  63. self.print_line()
  64. def mqtt_on_health(self, mqttc, backend_data, msg):
  65. '''
  66. try:
  67. self.dmb.parseHealthMessage(msg.payload)
  68. except:
  69. print("Error: Failure to parse message")
  70. if self.debug:
  71. print("Raw Message: %s\n" %msg.payload)
  72. '''
  73. self.dmb.parseHealthMessage(msg.payload)
  74. self.print_line()
  75. def mqtt_on_log(self, mqttc, backend_data, level, string):
  76. print(string)
  77. self.print_line()
  78. #------------------------------------------------------------------------------
  79. # General API Calls
  80. def startWorkstationClient(self, ip="server.ideasX.tech", port=1883, keepalive=60):
  81. self.ip = ip
  82. self.port = port
  83. self.keepalive = keepalive
  84. self._mqttc.connect(ip, port, keepalive) # connect to broker
  85. #self._mqttc.subscribe(self.command_topic, 2)
  86. self._mqttc.subscribe(self.health_topic, 1)
  87. #self._mqttc.subscribe(self.data_topic, 2)
  88. self._mqttc.loop_forever() # need to use blocking loop otherwise python will kill process
  89. def print_line(self):
  90. print('-'*70)
  91. if __name__ == "__main__":
  92. argv = sys.argv[1:]
  93. wsc = IdeasXWorkstationClient()
  94. Host = "ideasx.duckdns.org"
  95. Port = 1883
  96. KeepAlive = 30
  97. msgFlag = False;
  98. deviceID = None;
  99. cmdPayload = None;
  100. cmdArg = None;
  101. try:
  102. opts, args = getopt.getopt(argv, "d:h:k:p:t:c:o:",
  103. ['device-id','host', 'keepalive',
  104. 'port', 'topic(s)','command', 'payload'])
  105. except getopt.GetoptError as s:
  106. sys.exit(2)
  107. for opt, arg in opts:
  108. if opt in ("-h", "--host", "--hostname"):
  109. Host = arg
  110. elif opt in ("-d", "--device-id"):
  111. deviceID = arg
  112. elif opt in ("-k", "--keepalive"):
  113. KeepAlive = arg
  114. elif opt in ("-p", "--port"):
  115. Port = arg
  116. elif opt in ("-o", "--payload"):
  117. cmdPayload = arg.encode('utf-8')
  118. elif opt in ("-c", "--command"):
  119. msgFlag = True
  120. cmdArg = arg
  121. if msgFlag:
  122. if cmdArg in IdeasXMessages._COMMANDMESSAGE_COMMAND.values_by_name.keys():
  123. msg = IdeasXMessages.CommandMessage();
  124. msg.command = IdeasXMessages.CommandMessage.Command.Value(cmdArg)
  125. if cmdPayload != None:
  126. msg.payload = cmdPayload
  127. if deviceID != None:
  128. pubTopic = "/modules/"+deviceID+"/command"
  129. else:
  130. sys.exit(2)
  131. # sc.print_line()
  132. # print("Preparing Message...")
  133. # sc.print_line()
  134. # print("Device ID: "+str(deviceID))
  135. # sc.print_line()
  136. # print(msg.__str__()[:-1])
  137. mqtt_pub.single(topic=pubTopic,
  138. payload=msg.SerializeToString().decode('utf-8'),
  139. retain = False,
  140. qos=2,
  141. hostname=Host,
  142. port=Port)
  143. wsc.print_line()
  144. print("Message Sent")
  145. wsc.print_line()
  146. sys.exit(0)
  147. else:
  148. sys.exit(2)
  149. else:
  150. wsc.startWorkstationClient(ip = Host, port = Port, keepalive = KeepAlive)