connection_manager.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. from datetime import datetime, timedelta
  4. import logging
  5. import subprocess
  6. import requests
  7. from threading import Thread
  8. import time
  9. import urllib3
  10. from odoo.modules.module import get_resource_path
  11. from odoo.addons.hw_drivers.main import iot_devices, manager
  12. from odoo.addons.hw_drivers.tools import helpers
  13. _logger = logging.getLogger(__name__)
  14. class ConnectionManager(Thread):
  15. def __init__(self):
  16. super(ConnectionManager, self).__init__()
  17. self.pairing_code = False
  18. self.pairing_uuid = False
  19. def run(self):
  20. if not helpers.get_odoo_server_url() and not helpers.access_point():
  21. end_time = datetime.now() + timedelta(minutes=5)
  22. while (datetime.now() < end_time):
  23. self._connect_box()
  24. time.sleep(10)
  25. self.pairing_code = False
  26. self.pairing_uuid = False
  27. self._refresh_displays()
  28. def _connect_box(self):
  29. data = {
  30. 'jsonrpc': 2.0,
  31. 'params': {
  32. 'pairing_code': self.pairing_code,
  33. 'pairing_uuid': self.pairing_uuid,
  34. }
  35. }
  36. try:
  37. urllib3.disable_warnings()
  38. req = requests.post('https://iot-proxy.odoo.com/odoo-enterprise/iot/connect-box', json=data, verify=False)
  39. result = req.json().get('result', {})
  40. if all(key in result for key in ['pairing_code', 'pairing_uuid']):
  41. self.pairing_code = result['pairing_code']
  42. self.pairing_uuid = result['pairing_uuid']
  43. elif all(key in result for key in ['url', 'token', 'db_uuid', 'enterprise_code']):
  44. self._connect_to_server(result['url'], result['token'], result['db_uuid'], result['enterprise_code'])
  45. except Exception as e:
  46. _logger.error('Could not reach iot-proxy.odoo.com')
  47. _logger.error('A error encountered : %s ' % e)
  48. def _connect_to_server(self, url, token, db_uuid, enterprise_code):
  49. # Save DB URL and token
  50. helpers.save_conf_server(url, token, db_uuid, enterprise_code)
  51. # Notify the DB, so that the kanban view already shows the IoT Box
  52. manager.send_alldevices()
  53. # Restart to checkout the git branch, get a certificate, load the IoT handlers...
  54. helpers.odoo_restart(2)
  55. def _refresh_displays(self):
  56. """Refresh all displays to hide the pairing code"""
  57. for d in iot_devices:
  58. if iot_devices[d].device_type == 'display':
  59. iot_devices[d].action({
  60. 'action': 'display_refresh'
  61. })
  62. connection_manager = ConnectionManager()
  63. connection_manager.daemon = True
  64. connection_manager.start()