clock.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. '''
  2. synchronized clock
  3. '''
  4. import ntplib
  5. from time import ctime
  6. import math
  7. class Clock(object):
  8. def __init__(self, epoch_length=180, ntp_server='europe.pool.ntp.org'):
  9. self.epoch_length=epoch_length #2 minutes
  10. self.ntp_server = ntp_server
  11. self.ntp_client = ntplib.NTPClient()
  12. #TODO validate the server
  13. # when was darkfi birthday? as seconds since the epoch
  14. self.darkfi_epoch=0
  15. self.observers = []
  16. def __repr__(self):
  17. return 'darkfi time: '+ ctime(self.darkfi_time) + ', current synched time: ' + ctime(self.synched_time)
  18. def __get_time_stat(self):
  19. response=None
  20. success=True
  21. while not success:
  22. try:
  23. response = self.ntp_client.request(self.ntp_server, version=3)
  24. success=True
  25. except ntplib.NTPException as e:
  26. print("connection failed: {}".format(e.what()))
  27. return response
  28. @property
  29. def synched_time(self):
  30. state = self.__get_time_stat()
  31. synched_time = state.tx_time
  32. return synched_time
  33. @property
  34. def darkfi_time(self):
  35. return self.synched_time - self.darkfi_epoch
  36. @property
  37. def epoch(self):
  38. return math.floor(self.darkfi_time/self.epoch_length)
  39. def bind(self, callback):
  40. self.observers.append((callback))
  41. def background(self):
  42. current_epoch = self.epoch
  43. while True:
  44. if self.epoch !=current_epoch:
  45. current_epoch = self.epoch
  46. for obs in self.observers:
  47. obs(current_epoch)