bitcell.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. # greaseweazle/bitcell.py
  2. #
  3. # Written & released by Keir Fraser <keir.xen@gmail.com>
  4. #
  5. # This is free and unencumbered software released into the public domain.
  6. # See the file COPYING for more details, or visit <http://unlicense.org>.
  7. import binascii
  8. from bitarray import bitarray
  9. class Bitcell:
  10. def __init__(self):
  11. self.clock = 2 / 1000000
  12. self.clock_max_adj = 0.10
  13. self.pll_period_adj = 0.05
  14. self.pll_phase_adj = 0.60
  15. def __str__(self):
  16. s = ""
  17. rev = 0
  18. for b, _ in self.revolution_list:
  19. s += "Revolution %u: " % rev
  20. s += str(binascii.hexlify(b.tobytes())) + "\n"
  21. rev += 1
  22. return s[:-1]
  23. def read_flux(self, flux):
  24. index_list, freq = flux.index_list, flux.sample_freq
  25. clock = self.clock
  26. clock_min = self.clock * (1 - self.clock_max_adj)
  27. clock_max = self.clock * (1 + self.clock_max_adj)
  28. ticks = 0.0
  29. # Per-revolution list of bitcells and bitcell times.
  30. self.revolution_list = []
  31. # Initialise bitcell lists for the first revolution.
  32. bits, times = bitarray(), []
  33. to_index = index_list[0] / freq
  34. index_list = index_list[1:]
  35. for x in flux.list:
  36. # Gather enough ticks to generate at least one bitcell.
  37. ticks += x / freq
  38. if ticks < clock/2:
  39. continue
  40. # Clock out zero or more 0s, followed by a 1.
  41. zeros = 0
  42. while True:
  43. # Check if we cross the index mark.
  44. to_index -= clock
  45. if to_index < 0:
  46. self.revolution_list.append((bits, times))
  47. if not index_list:
  48. return
  49. bits, times = bitarray(), []
  50. to_index = index_list[0] / freq
  51. index_list = index_list[1:]
  52. ticks -= clock
  53. times.append(clock)
  54. if ticks >= clock/2:
  55. zeros += 1
  56. bits.append(False)
  57. else:
  58. bits.append(True)
  59. break
  60. # PLL: Adjust clock frequency according to phase mismatch.
  61. if zeros <= 3:
  62. # In sync: adjust clock by a fraction of the phase mismatch.
  63. clock += ticks * self.pll_period_adj
  64. else:
  65. # Out of sync: adjust clock towards centre.
  66. clock += (self.clock - clock) * self.pll_period_adj
  67. # Clamp the clock's adjustment range.
  68. clock = min(max(clock, clock_min), clock_max)
  69. # PLL: Adjust clock phase according to mismatch.
  70. new_ticks = ticks * (1 - self.pll_phase_adj)
  71. times[-1] += ticks - new_ticks
  72. ticks = new_ticks
  73. self.revolution_list.append((bits, times))
  74. # Local variables:
  75. # python-indent: 4
  76. # End: