clock.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. '''
  2. synchronized NTP clock
  3. '''
  4. import ntplib
  5. from time import ctime
  6. import math
  7. class SynchedNTPClock(object):
  8. def __init__(self, slot_length=60, ntp_server='europe.pool.ntp.org'):
  9. #TODO how long should be the slot length
  10. self.slot_length=slot_length
  11. self.ntp_server = ntp_server
  12. self.ntp_client = ntplib.NTPClient()
  13. #TODO validate the server
  14. # when was darkfi birthday? as seconds since the epoch
  15. self.darkfi_epoch=0
  16. self.offline_cnt=0
  17. def __repr__(self):
  18. return 'darkfi time: '+ ctime(self.darkfi_time) + ', current synched time: ' + ctime(self.synched_time)
  19. def __get_time_stat(self):
  20. response=None
  21. success=False
  22. while not success:
  23. try:
  24. response = self.ntp_client.request(self.ntp_server, version=3)
  25. success=True
  26. #except ntplib.NTPException as e:
  27. except:
  28. pass
  29. #print("connection failed: {}".format(e.what()))
  30. return response
  31. @property
  32. def synched_time(self):
  33. state = self.__get_time_stat()
  34. synched_time = state.tx_time
  35. return synched_time
  36. @property
  37. def darkfi_time(self):
  38. return self.synched_time - self.darkfi_epoch
  39. @property
  40. def offline_time(self):
  41. self.offline_cnt+=1
  42. return self.offline_cnt
  43. @property
  44. def slot(self):
  45. return math.floor(self.darkfi_time/self.slot_length)