IdeasXWSCBackend.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. '''
  2. Title: IdeasXDatabaseManager Class
  3. Author: Tyler Berezowsky
  4. Description:
  5. This class requires the following functionality:
  6. 1) Connect to the IdeasX system (MQTT Client)
  7. - Connect using the devices MAC Address as the Client ID
  8. - Autoreconnect if the device failts
  9. - The abililty to start a broker in a seperate thread if no broker is available
  10. - The ability to store settings in a SQLite File or setting .txt file.
  11. 2) The ability to induce a system wide keypress in the following systems:
  12. - Windows
  13. - Mac
  14. - Linux
  15. 3) Create a table in memory of the IdeasX devices currently in the system
  16. 4) Parse IdeasX messages types given nothing more than a protofile
  17. 5) Subscribe to IdeasX devices
  18. 6) Invoke keystrokes if proper messages in a command is sent.
  19. '''
  20. import sys
  21. import time
  22. import collections
  23. from ParsingTools import ParsingTools
  24. try:
  25. import paho.mqtt.client as mqtt
  26. import paho.mqtt.publish as mqtt_pub
  27. except ImportError:
  28. # This part is only required to run the example from within the examples
  29. # directory when the module itself is not installed.
  30. #
  31. # If you have the module installed, just use "import paho.mqtt.client"
  32. import os
  33. import inspect
  34. cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"../src")))
  35. if cmd_subfolder not in sys.path:
  36. sys.path.insert(0, cmd_subfolder)
  37. import paho.mqtt.client as mqtt
  38. try:
  39. from protocolbuffers import IdeasXMessages_pb2 as IdeasXMessages
  40. except ImportError:
  41. print("The python classes for IdeasX are missing. Try running the Makefile in" +
  42. "ideasX-messages.")
  43. from PyQt5.QtCore import QObject, pyqtSignal
  44. class IdeasXWSCNetworkThread(QObject):
  45. # define Qt signals (I don't understand why this is here)
  46. encoderUpdate = pyqtSignal([dict], name='encoderUpdate')
  47. def __init__(self, settingFile=None, clientID = None, debug=True, mqttdebug=True):
  48. super(IdeasXWSCNetworkThread, self).__init__()
  49. # Private Class Flags and Variables
  50. self.__clientID = clientID
  51. self.__settingFile = settingFile
  52. self.__debug = debug
  53. self.__mqttDebug = mqttdebug
  54. self.__errorIndex = 0
  55. self.__refreshCb = None
  56. # MQTT Topics
  57. self.__DEVICETYPE = ["/encoder/+"]
  58. self.__COMMANDTOPIC = "/command"
  59. self.__DATATOPIC = "/data"
  60. self.__HEALTHTOPIC = "/health"
  61. # Data Structure for Encoders / Actuators
  62. self.encoders = {}
  63. self.subscribedEncoders = []
  64. # IdeasX Parsers
  65. self._healthParser = IdeasXMessages.HealthMessage()
  66. self._dataParser = IdeasXMessages.DataMessage()
  67. self._commandParser = IdeasXMessages.CommandMessage()
  68. self._parserTools = ParsingTools()
  69. # MQTT Client Object
  70. self._mqttc = mqtt.Client(self.__clientID, clean_session=True, userdata=None, protocol='MQTTv311')
  71. # Setup Callback Functions for each device type
  72. for device in self.__DEVICETYPE:
  73. self._mqttc.message_callback_add(device+self.__HEALTHTOPIC, self.mqtt_on_health)
  74. self._mqttc.message_callback_add(device+self.__DATATOPIC, self.mqtt_on_data)
  75. #self._mqttc.message_callback_add(device+self.__COMMANDTOPIC, self.mqtt_on_command)
  76. self._mqttc.on_connect = self.mqtt_on_connect
  77. self._mqttc.on_disconnect = self.mqtt_on_disconnect
  78. #self._mqttc.on_subscribe = self.mqtt_on_subscribe
  79. #self._mqttc.on_unsubscribe = self.mqtt_on_unsubscribe
  80. if self.__mqttDebug:
  81. self._mqttc.on_log = self.mqtt_on_log
  82. #------------------------------------------------------------------------------
  83. # callback functions
  84. def mqtt_on_connect(self, mqttc, backend_data, flags, rc):
  85. if rc == 0:
  86. self.printInfo('Connected to %s: %s' % (mqttc._host, mqttc._port))
  87. else:
  88. self.printInfo('rc: ' + str(rc))
  89. self.printLine()
  90. def mqtt_on_disconnect(self, mqttc, backend_data, rc):
  91. if self.__debug:
  92. if rc != 0:
  93. self.printError("Client disconnected and its a mystery why!")
  94. else:
  95. self.printInfo("Client successfully disconnected.")
  96. self.printLine()
  97. def mqtt_on_log(self, mqttc, backend_data, level, string):
  98. print(string)
  99. self.printLine()
  100. def mqtt_on_data(self, mqttc, backend_data, msg):
  101. self.printInfo("Data Message")
  102. self.printLine()
  103. try:
  104. self._dataParser.ParseFromString(msg.payload)
  105. print("GPIO States: " + bin(self._dataParser.button))
  106. except:
  107. self.printError("Failure to parse message")
  108. if self.__debug:
  109. print("Raw Message: %s" %msg.payload)
  110. self.printLine()
  111. def mqtt_on_health(self, mqttc, backend_data, msg):
  112. self.printInfo("Health Message")
  113. self.printLine()
  114. try:
  115. self._healthParser.ParseFromString(msg.payload)
  116. macID = self._parserTools.macToString(self._healthParser.module_id)
  117. if self._healthParser.alive:
  118. temp_list = []
  119. for field in self._healthParser.ListFields():
  120. temp_list.append((field[0].name, field[1]))
  121. temp_list.append(('time', time.time()))
  122. self.encoders[macID] = collections.OrderedDict(temp_list)
  123. self.encoderUpdate.emit(self.getDevices())
  124. else:
  125. try:
  126. self.encoders.pop(macID)
  127. self.encoderUpdate.emit()
  128. except KeyError:
  129. self.printError("Encoder ID " +macID+" is not stored")
  130. if self.__debug:
  131. for encoder, fields in zip(self.encoders.keys(), self.encoders.values()):
  132. print(str(encoder) +" : "+ str(fields))
  133. self.printLine()
  134. except:
  135. self.printError("Error: Failure to parse message")
  136. if self.__debug:
  137. print("Raw Message: %s" %msg.payload)
  138. self.printLine()
  139. try:
  140. self.encoders.pop(msg.topic.split('/')[2])
  141. self.encoderUpdate.emit(self.getDevices())
  142. except:
  143. print("This is a fucking joke anyway")
  144. #----------------------------------------------thy--------------------------------
  145. # General API Calls
  146. def cmdStartWorkstationClient(self, ip="server.ideasX.tech", port=1883, keepAlive=60):
  147. self.ip = ip
  148. self.port = port
  149. self.keepAlive = keepAlive
  150. self.printLine()
  151. self.printInfo("Starting Workstation Client (WSC)")
  152. self.printLine()
  153. try:
  154. self._mqttc.connect(self.ip, self.port, self.keepAlive) # connect to broker
  155. for device in self.__DEVICETYPE:
  156. self._mqttc.subscribe(device + self.__HEALTHTOPIC, 1)
  157. self._mqttc.loop_forever() # need to use blocking loop otherwise python will kill process
  158. except:
  159. self.printError("There was a fucking mistake here.")
  160. sys.exit(1)
  161. def guiStartWorkstationClient(self, ip="server.ideasx.tech", port=1883, keepAlive=60):
  162. self.ip = ip
  163. self.port = port
  164. self.keepAlive = keepAlive
  165. self.printLine()
  166. self.printInfo("Starting Workstation Client (WSC)")
  167. self.printLine()
  168. try:
  169. self._mqttc.connect(self.ip, self.port, self.keepAlive)
  170. for device in self.__DEVICETYPE:
  171. self._mqttc.subscribe(device + self.__HEALTHTOPIC, 0)
  172. self._mqttc.subscribe(device + self.__DATATOPIC, 0)
  173. self._mqttc.loop_start() # start MQTT Client Thread
  174. except:
  175. self.printError("There was a fucking mistake here.")
  176. sys.exit(1)
  177. def restartWSC(self):
  178. self.printInfo("This really doesn't do anything")
  179. def killWSC(self):
  180. self._mqttc.loop_stop()
  181. self.printInfo("Murdered MQTT thread.")
  182. def attachRefreshCallback(self, cb):
  183. self.__refreshCb = cb
  184. def getDevices(self):
  185. return self.encoders
  186. def activateEncoder(self, deviceMACAddress, deviceType=None):
  187. '''
  188. Subscribe to device's data topic and send activate command if device
  189. is not active.
  190. * Currently does not confirm subscribe is successful
  191. * Currently does not send the activate command as it does not exist
  192. deviceType = str
  193. deviceMACAddress = str(MAC_ID)
  194. '''
  195. if deviceMACAddress in self.encoders.keys():
  196. if deviceType == None:
  197. deviceDataTopic = self.__DEVICETYPE[0] + deviceMACAddress + self.__DATATOPIC
  198. else:
  199. deviceDataTopic = deviceType + deviceMACAddress + self.__DATATOPIC
  200. self._mqttc.subscribe(deviceDataTopic, 1)
  201. self.subscribedEncoders.append(deviceMACAddress)
  202. if self.__debug:
  203. self.printInfo("Device " + deviceMACAddress + " data topic was subscribed")
  204. else:
  205. self.printError("Device " + deviceMACAddress + " is not currently in the IdeasX system.")
  206. def deactivateEncoder(self, deviceMACAddress, deviceType=None, forceAction=False):
  207. '''
  208. Unsubscribe from device's data topic and send deactive command if no other WSC are using device.
  209. * Currently does not confirm unsubscribe is successful
  210. * Currently does not send the deactive command as it does not exist and I don't know how to sync that shit.
  211. '''
  212. if (deviceMACAddress in self.encoders.keys()) or (forceAction):
  213. if deviceType == None:
  214. deviceDataTopic = self.__DEVICETYPE[0] + deviceMACAddress + self.__DATATOPIC
  215. else:
  216. deviceDataTopic = deviceType + deviceMACAddress + self.__DATATOPIC
  217. self._mqttc.unsubscribe(deviceDataTopic)
  218. self.subscribedEncoders.remove(deviceMACAddress)
  219. if self.__debug:
  220. self.printInfo("Device " + deviceMACAddress + " data topic was unsubscribed")
  221. else:
  222. self.printError("Device " + deviceMACAddress + " is not currently in the IdeasX System")
  223. def shutdownDevice(self, deviceMACAddress, deviceType=None):
  224. self._commandParser.command = self._commandParser.SHUT_DOWN
  225. self._mqttc.publish(self.__DEVICETYPE[0][:-1] + deviceMACAddress + self.__COMMANDTOPIC,
  226. self._commandParser.SerializeToString().decode('utf-8') ,
  227. qos=1,
  228. retain=False)
  229. self.printInfo("Send Shutdown Command to Encoder " + deviceMACAddress)
  230. def printLine(self):
  231. print('-'*70)
  232. def printError(self, errorStr):
  233. self.__errorIndex = self.__errorIndex + 1
  234. print("WSC Error #" + str(self.__errorIndex) + ": " + errorStr)
  235. def printInfo(self, msgStr):
  236. print("WSC: " + msgStr)
  237. class IdeasXDeviceTypes():
  238. def __init__(self):
  239. self.encoder = 'encoder'
  240. self.actuator = 'actuator'
  241. if __name__ == "__main__":
  242. Host = "ideasx.duckdns.org"
  243. # Host = "192.168.0.101"
  244. # Host = "10.42.0.1"
  245. Port = 1883
  246. KeepAlive = 30
  247. msgFlag = False;
  248. deviceID = None;
  249. cmdPayload = None;
  250. cmdArg = None;
  251. cmdTest = False;
  252. wsc = WorkstationClientClass()
  253. if cmdTest:
  254. wsc.cmdStartWorkstationClient(Host, Port, KeepAlive)
  255. else:
  256. wsc.guiStartWorkstationClient(Host, Port, KeepAlive)
  257. time.sleep(3)
  258. wsc.activateEncoder('18:fe:34:f1:f2:8d')
  259. print(wsc.subscribedEncoders)
  260. time.sleep(2)
  261. wsc.deactivateEncoder('18:fe:34:f1:f2:8d')
  262. print(wsc.subscribedEncoders)
  263. time.sleep(10)
  264. wsc.killWSC()