IdeasXWSCBackend.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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. self.keyEmulator = IdeasXKeyEmulator()
  70. # MQTT Client Object
  71. self._mqttc = mqtt.Client(self.__clientID, clean_session=True, userdata=None, protocol='MQTTv311')
  72. # Setup Callback Functions for each device type
  73. for device in self.__DEVICETYPE:
  74. self._mqttc.message_callback_add(device+self.__HEALTHTOPIC, self.mqtt_on_health)
  75. self._mqttc.message_callback_add(device+self.__DATATOPIC, self.mqtt_on_data)
  76. #self._mqttc.message_callback_add(device+self.__COMMANDTOPIC, self.mqtt_on_command)
  77. self._mqttc.on_connect = self.mqtt_on_connect
  78. self._mqttc.on_disconnect = self.mqtt_on_disconnect
  79. #self._mqttc.on_subscribe = self.mqtt_on_subscribe
  80. #self._mqttc.on_unsubscribe = self.mqtt_on_unsubscribe
  81. if self.__mqttDebug:
  82. self._mqttc.on_log = self.mqtt_on_log
  83. #------------------------------------------------------------------------------
  84. # callback functions
  85. def mqtt_on_connect(self, mqttc, backend_data, flags, rc):
  86. if rc == 0:
  87. self.printInfo('Connected to %s: %s' % (mqttc._host, mqttc._port))
  88. else:
  89. self.printInfo('rc: ' + str(rc))
  90. self.printLine()
  91. def mqtt_on_disconnect(self, mqttc, backend_data, rc):
  92. if self.__debug:
  93. if rc != 0:
  94. self.printError("Client disconnected and its a mystery why!")
  95. else:
  96. self.printInfo("Client successfully disconnected.")
  97. self.printLine()
  98. def mqtt_on_log(self, mqttc, backend_data, level, string):
  99. print(string)
  100. self.printLine()
  101. def mqtt_on_data(self, mqttc, backend_data, msg):
  102. self.printInfo("Data Message")
  103. self.printLine()
  104. try:
  105. self._dataParser.ParseFromString(msg.payload)
  106. print("GPIO States: " + bin(self._dataParser.button))
  107. #self.__keyEmulator.emulateKey( self._parserTools.getModuleIDfromTopic(msg.topic),self._dataParser.button)
  108. except:
  109. self.printError("Failure to parse message")
  110. if self.__debug:
  111. print("Raw Message: %s" %msg.payload)
  112. self.printLine()
  113. def mqtt_on_health(self, mqttc, backend_data, msg):
  114. self.printInfo("Health Message")
  115. self.printLine()
  116. try:
  117. self._healthParser.ParseFromString(msg.payload)
  118. macID = self._parserTools.macToString(self._healthParser.module_id)
  119. if self._healthParser.alive:
  120. temp_list = []
  121. for field in self._healthParser.ListFields():
  122. temp_list.append((field[0].name, field[1]))
  123. temp_list.append(('time', time.time()))
  124. self.encoders[macID] = collections.OrderedDict(temp_list)
  125. self.encoderUpdate.emit(self.getDevices())
  126. else:
  127. try:
  128. self.encoders.pop(macID)
  129. self.encoderUpdate.emit()
  130. except KeyError:
  131. self.printError("Encoder ID " +macID+" is not stored")
  132. if self.__debug:
  133. for encoder, fields in zip(self.encoders.keys(), self.encoders.values()):
  134. print(str(encoder) +" : "+ str(fields))
  135. self.printLine()
  136. except:
  137. self.printError("Error: Failure to parse message")
  138. if self.__debug:
  139. print("Raw Message: %s" %msg.payload)
  140. self.printLine()
  141. try:
  142. self.encoders.pop(msg.topic.split('/')[2])
  143. self.encoderUpdate.emit(self.getDevices())
  144. except:
  145. print("This is a fucking joke anyway")
  146. #----------------------------------------------thy--------------------------------
  147. # General API Calls
  148. def cmdStartWorkstationClient(self, ip="server.ideasX.tech", port=1883, keepAlive=60):
  149. self.ip = ip
  150. self.port = port
  151. self.keepAlive = keepAlive
  152. self.printLine()
  153. self.printInfo("Starting Workstation Client (WSC)")
  154. self.printLine()
  155. try:
  156. self._mqttc.connect(self.ip, self.port, self.keepAlive) # connect to broker
  157. for device in self.__DEVICETYPE:
  158. self._mqttc.subscribe(device + self.__HEALTHTOPIC, 1)
  159. self._mqttc.loop_forever() # need to use blocking loop otherwise python will kill process
  160. except:
  161. self.printError("There was a fucking mistake here.")
  162. sys.exit(1)
  163. def guiStartWorkstationClient(self, ip="server.ideasx.tech", port=1883, keepAlive=60):
  164. self.ip = ip
  165. self.port = port
  166. self.keepAlive = keepAlive
  167. self.printLine()
  168. self.printInfo("Starting Workstation Client (WSC)")
  169. self.printLine()
  170. try:
  171. self._mqttc.connect(self.ip, self.port, self.keepAlive)
  172. for device in self.__DEVICETYPE:
  173. self._mqttc.subscribe(device + self.__HEALTHTOPIC, 0)
  174. self._mqttc.subscribe(device + self.__DATATOPIC, 0)
  175. self._mqttc.loop_start() # start MQTT Client Thread
  176. except:
  177. self.printError("There was a fucking mistake here.")
  178. sys.exit(1)
  179. def restartWSC(self):
  180. self.printInfo("This really doesn't do anything")
  181. def killWSC(self):
  182. self._mqttc.loop_stop()
  183. self.printInfo("Murdered MQTT thread.")
  184. def attachRefreshCallback(self, cb):
  185. self.__refreshCb = cb
  186. def getDevices(self):
  187. return self.encoders
  188. def activateEncoder(self, deviceMACAddress, deviceType=None):
  189. '''
  190. Subscribe to device's data topic and send activate command if device
  191. is not active.
  192. * Currently does not confirm subscribe is successful
  193. * Currently does not send the activate command as it does not exist
  194. deviceType = str
  195. deviceMACAddress = str(MAC_ID)
  196. '''
  197. if deviceMACAddress in self.encoders.keys():
  198. if deviceType == None:
  199. deviceDataTopic = self.__DEVICETYPE[0] + deviceMACAddress + self.__DATATOPIC
  200. else:
  201. deviceDataTopic = deviceType + deviceMACAddress + self.__DATATOPIC
  202. self._mqttc.subscribe(deviceDataTopic, 1)
  203. self.subscribedEncoders.append(deviceMACAddress)
  204. if self.__debug:
  205. self.printInfo("Device " + deviceMACAddress + " data topic was subscribed")
  206. else:
  207. self.printError("Device " + deviceMACAddress + " is not currently in the IdeasX system.")
  208. def deactivateEncoder(self, deviceMACAddress, deviceType=None, forceAction=False):
  209. '''
  210. Unsubscribe from device's data topic and send deactive command if no other WSC are using device.
  211. * Currently does not confirm unsubscribe is successful
  212. * Currently does not send the deactive command as it does not exist and I don't know how to sync that shit.
  213. '''
  214. if (deviceMACAddress in self.encoders.keys()) or (forceAction):
  215. if deviceType == None:
  216. deviceDataTopic = self.__DEVICETYPE[0] + deviceMACAddress + self.__DATATOPIC
  217. else:
  218. deviceDataTopic = deviceType + deviceMACAddress + self.__DATATOPIC
  219. self._mqttc.unsubscribe(deviceDataTopic)
  220. self.subscribedEncoders.remove(deviceMACAddress)
  221. if self.__debug:
  222. self.printInfo("Device " + deviceMACAddress + " data topic was unsubscribed")
  223. else:
  224. self.printError("Device " + deviceMACAddress + " is not currently in the IdeasX System")
  225. def shutdownDevice(self, deviceMACAddress, deviceType=None):
  226. self._commandParser.command = self._commandParser.SHUT_DOWN
  227. self._mqttc.publish(self.__DEVICETYPE[0][:-1] + deviceMACAddress + self.__COMMANDTOPIC,
  228. self._commandParser.SerializeToString().decode('utf-8') ,
  229. qos=1,
  230. retain=False)
  231. self.printInfo("Send Shutdown Command to Encoder " + deviceMACAddress)
  232. def printLine(self):
  233. print('-'*70)
  234. def printError(self, errorStr):
  235. self.__errorIndex = self.__errorIndex + 1
  236. print("WSC Error #" + str(self.__errorIndex) + ": " + errorStr)
  237. def printInfo(self, msgStr):
  238. print("WSC: " + msgStr)
  239. from pykeyboard import PyKeyboard
  240. class IdeasXKeyEmulator():
  241. def __init__(self):
  242. self.__system = sys.platform
  243. self.printInfo("Detected system is " + self.__system)
  244. self.__k = PyKeyboard()
  245. self.switchOne = 0
  246. self.switchTwo = 1
  247. self.switchAdaptive = 2
  248. self.__assignedKeys = {'default': {self.switchOne: ["1", True],
  249. self.switchTwo: ["2", True],
  250. self.switchAdaptive: ["3", True]}}
  251. self.__activeEncoders = []
  252. def activateEncoder(self, encoder):
  253. if encoder not in self.__activeEncoders:
  254. self.__activeEncoders.append(encoder)
  255. def deactivateEncoder(self, encoder):
  256. if encoder in self.__activeEncoders:
  257. self.__activeEncoders.pop(encoder)
  258. def assignKey(self, encoder, switch, key, active=True):
  259. if switch not in [self.switchOne, self.switchTwo, self.switchAdaptive]:
  260. raise ValueError("Must be IdeasXKeyEmulator() provided switch")
  261. if encoder not in self.__assignedKeys.keys():
  262. self.__assignedKeys[encoder] = self.__assignedKeys['default']
  263. self.__assignedKeys[encoder][switch] = [key, active]
  264. if active == False:
  265. self.__k.release_key(key)
  266. def getAssignedKey(self, encoder, switch):
  267. if encoder not in self.__assignedKeys.keys():
  268. encoder = 'default'
  269. return self.__assignedKeys[encoder][switch]
  270. def emulateKey(self, encoder, buttonPayload, deviceType=None):
  271. '''
  272. This is horrible and needs to be improved
  273. '''
  274. if encoder in self.__activeEncoders or True:
  275. if encoder not in self.__assignedKeys.keys():
  276. encoder = 'default'
  277. assignedKeys = self.__assignedKeys[encoder]
  278. for switch in [self.switchOne, self.switchTwo, self.switchAdaptive]:
  279. if (buttonPayload&(1<<switch)!=0):
  280. self.__k.press_key(assignedKeys[switch][0])
  281. else:
  282. self.__k.release_key(assignedKeys[switch][0])
  283. def printInfo(self, msg):
  284. print("EM: " + msg)
  285. #def emulatePress(self, buttonPayload):
  286. if __name__ == "__main__":
  287. Host = "ideasx.dnuckdns.org"
  288. # Host = "192.168.0.101"
  289. # Host = "10.42.0.1"
  290. Port = 1883
  291. KeepAlive = 30
  292. msgFlag = False;
  293. deviceID = None;
  294. cmdPayload = None;
  295. cmdArg = None;
  296. cmdTest = False;
  297. encodeId = '23:34'
  298. km = IdeasXKeyEmulator()
  299. km.activateEncoder(encodeId)
  300. km.emulateKey(encodeId, 1)
  301. time.sleep(0.1)
  302. km.emulateKey(encodeId, 0)
  303. time.sleep(0.1)
  304. km.emulateKey(encodeId, 2)
  305. time.sleep(0.1)
  306. km.emulateKey(encodeId, 0)
  307. time.sleep(0.1)
  308. km.emulateKey(encodeId, 4)
  309. time.sleep(0.1)
  310. km.emulateKey(encodeId, 0)
  311. # wsc = WorkstationClientClass()
  312. #
  313. # if cmdTest:
  314. # wsc.cmdStartWorkstationClient(Host, Port, KeepAlive)
  315. # else:
  316. # wsc.guiStartWorkstationClient(Host, Port, KeepAlive)
  317. # time.sleep(3)
  318. # wsc.activateEncoder('18:fe:34:f1:f2:8d')
  319. # print(wsc.subscribedEncoders)
  320. # time.sleep(2)
  321. # wsc.deactivateEncoder('18:fe:34:f1:f2:8d')
  322. # print(wsc.subscribedEncoders)
  323. # time.sleep(10)
  324. # wsc.killWSC()