wsc_device.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import time
  2. from wsc_tools import ParsingTools
  3. from wsc_tools import Switch
  4. from wsc_device_encoder import Encoder
  5. class DeviceManager():
  6. FAIL = 0
  7. SUCCESS = 1
  8. def __init__(self, deviceClass, mqttc, healthSignal=None):
  9. self.__healthSignal = healthSignal
  10. self.__devices = {}
  11. self.__deviceClass = deviceClass
  12. self.__parserTools = ParsingTools()
  13. self.__mqttc = mqttc
  14. def setupMQTT(self):
  15. self.__mqttc.subscribe(self.__deviceClass.DEVICE_HEALTH_TOPIC,
  16. self.__deviceClass.DEVICE_HEALTH_QOS)
  17. self.__mqttc.message_callback_add(self.__deviceClass.DEVICE_HEALTH_TOPIC,
  18. self.mqtt_health_cb)
  19. def mqtt_health_cb(self, mqttc, backend_data, msg):
  20. macID = self.__parserTools.getIDfromTopic(msg.topic)
  21. field = self.__parserTools.getFieldfromTopic(msg.topic)
  22. r = self.updateDevice(macID, field, msg.payload)
  23. if (r == DeviceManager.FAIL):
  24. self.addDevice(macID, mqttc)
  25. self.updateDevice(macID, field, msg.payload)
  26. if (self.__healthSignal):
  27. self.__healthSignal.emit(self.listAliveDevices())
  28. def updateDevice(self, device_id, field, payload):
  29. if device_id in self.__devices.keys():
  30. if (self.__devices[device_id].updateField(field, payload) == self.__deviceClass.SUCCESS):
  31. return DeviceManager.SUCCESS
  32. else:
  33. return DeviceManager.FAIL
  34. def listAliveDevices(self):
  35. tempDict = {}
  36. for device in self.__devices.keys():
  37. e = self.__devices[device]
  38. if (e.getField(self.__deviceClass.ALIVE_TOPIC) == self.__deviceClass.ALIVE_VALUE):
  39. tempDict[device] = e
  40. return tempDict
  41. def listDevices(self):
  42. return self.__devices.keys()
  43. def addDevice(self, device_id, mqttc):
  44. self.__devices[device_id] = self.__deviceClass(device_id, mqttc)
  45. def removeDevice(self, device_id):
  46. if device_id in self.__devices.keys():
  47. self.__devices.pop(device_id)
  48. return DeviceManager.SUCCESS
  49. else:
  50. return DeviceManager.FAIL
  51. def getDevice(self, device_id):
  52. if device_id in self.__devices.keys():
  53. return self.__devices[device_id]
  54. else:
  55. return DeviceManager.FAIL
  56. if __name__ == "__main__":
  57. device_id0 = "12:23:32:32:32:32"
  58. device_id1 = "12:23:32:32:31:32"
  59. dm = DeviceManager(Encoder, None)
  60. print("Updating Nonexistanct Device Result" + str(dm.updateDevice(device_id0, 'ota', b'1')))
  61. print("Adding device:" + str(dm.addDevice(device_id0)))
  62. print("Adding device:" + str(dm.addDevice(device_id1)))
  63. print("Updating Device Result" + str(dm.updateDevice(device_id0, 'ota', '1')))
  64. print("Updating Device Result" + str(dm.updateDevice(device_id1, 'alive', '1')))
  65. print(dm.listAliveDevices())