event_manager.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. import json
  4. from threading import Event
  5. import time
  6. from odoo.http import request
  7. class EventManager(object):
  8. def __init__(self):
  9. self.events = []
  10. self.sessions = {}
  11. def _delete_expired_sessions(self, max_time=70):
  12. '''
  13. Clears sessions that are no longer called.
  14. :param max_time: time a session can stay unused before being deleted
  15. '''
  16. now = time.time()
  17. expired_sessions = [
  18. session
  19. for session in self.sessions
  20. if now - self.sessions[session]['time_request'] > max_time
  21. ]
  22. for session in expired_sessions:
  23. del self.sessions[session]
  24. def add_request(self, listener):
  25. self.session = {
  26. 'session_id': listener['session_id'],
  27. 'devices': listener['devices'],
  28. 'event': Event(),
  29. 'result': {},
  30. 'time_request': time.time(),
  31. }
  32. self._delete_expired_sessions()
  33. self.sessions[listener['session_id']] = self.session
  34. return self.sessions[listener['session_id']]
  35. def device_changed(self, device):
  36. event = {
  37. **device.data,
  38. 'device_identifier': device.device_identifier,
  39. 'time': time.time(),
  40. 'request_data': json.loads(request.params['data']) if request and 'data' in request.params else None,
  41. }
  42. self.events.append(event)
  43. for session in self.sessions:
  44. if device.device_identifier in self.sessions[session]['devices'] and not self.sessions[session]['event'].isSet():
  45. self.sessions[session]['result'] = event
  46. self.sessions[session]['event'].set()
  47. event_manager = EventManager()