connect.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. demeter mqtt
  5. name:connect.py
  6. author:rabin
  7. """
  8. from demeter import *
  9. import paho.mqtt.client as mqtt
  10. #from gevent import monkey; monkey.patch_all()
  11. #import gevent
  12. class Connect(object):
  13. def __init__(self, act):
  14. act.connect = self
  15. self.client = mqtt.Client()
  16. self.client.on_connect = self.connect
  17. state = hasattr(act, 'message')
  18. if state:
  19. self.client.on_message = act.message
  20. self.client.connect(Demeter.config['mqtt']['host'], Demeter.config['mqtt']['port'], int(Demeter.config['mqtt']['timeout']))
  21. if state:
  22. self.client.loop_forever()
  23. def __del__(self):
  24. pass
  25. def getClient(self):
  26. return self.client
  27. def connect(self, client, userdata, flags, rc):
  28. #print("Connected with result code "+str(rc))
  29. #client.subscribe("sensor/#")
  30. client.subscribe("pic/#")
  31. """
  32. gevent.joinall([
  33. gevent.spawn(self.subscribe, client, 'sensor/#'),
  34. gevent.spawn(self.subscribe, client, 'pic/#'),
  35. gevent.spawn(self.subscribe, client, 'msg/#'),
  36. ])
  37. """
  38. @staticmethod
  39. def subscribe(client, key):
  40. client.subscribe(key)
  41. def handle(self, key, value):
  42. Demeter.record(key, value)