SPI.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # COPYRIGHT: Openmoko Inc. 2009
  4. # LICENSE: GPL Version 3 or later
  5. # DESCRIPTION: Simple FLASH programmer
  6. # AUTHOR: Christopher Hall <hsw@openmoko.com>
  7. import sys
  8. import time
  9. import Dump
  10. COMMAND_BOARD_REVISION = 'A'
  11. COMMAND_SPI_WRITE = 'W'
  12. COMMAND_SPI_READ = 'R'
  13. COMMAND_SPI_DESELECT = 'H'
  14. COMMAND_SPI_SELECT= 'L'
  15. def local_len(item):
  16. if str == type(item):
  17. return len(item)
  18. elif list == type(item):
  19. return sum(map(local_len, item))
  20. elif int == type(item):
  21. return 1
  22. return 0
  23. class SPI:
  24. def __init__(self, port):
  25. self.s = port
  26. def version(self):
  27. self.deselect()
  28. self.internal_send(COMMAND_BOARD_REVISION)
  29. time.sleep(0.1)
  30. buffer = self.s.read(2)
  31. return buffer
  32. def command(self, buffer):
  33. self.select()
  34. self.internal_write(buffer)
  35. self.deselect()
  36. def transact(self, write_buffer, skip_length, read_length):
  37. self.select()
  38. self.internal_write(write_buffer)
  39. self.internal_read(skip_length)
  40. result = self.internal_read(read_length)
  41. self.deselect()
  42. return result
  43. # private functions below here
  44. def select(self):
  45. self.internal_send(COMMAND_SPI_SELECT)
  46. def deselect(self):
  47. self.internal_send(COMMAND_SPI_DESELECT)
  48. def internal_write(self, buffer):
  49. length = local_len(buffer)
  50. if 0 >= length:
  51. return
  52. assert length < 65536, "Write Length: %d too big" % length
  53. self.internal_send([COMMAND_SPI_WRITE, length, (length >> 8), buffer])
  54. def internal_read(self, length):
  55. if 0 >= length:
  56. return
  57. assert length < 65536, "Read Length: %d too big" % length
  58. self.internal_send([COMMAND_SPI_READ, length, length >> 8])
  59. buffer = self.s.read(length)
  60. return buffer
  61. def internal_send(self, item):
  62. if str == type(item):
  63. for c in item:
  64. self.s.write(c)
  65. elif list == type(item):
  66. for x in item:
  67. self.internal_send(x)
  68. elif int == type(item):
  69. self.s.write(chr(item & 0xff))
  70. else:
  71. assert True, 'Invalid send item: %s' % type(item)