PageRenderTime 25ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/pywm_testserial.py

https://github.com/ka010/PyMetaWatch
Python | 124 lines | 121 code | 3 blank | 0 comment | 5 complexity | d9add7091bde1f4fb1eec54f4ef84f68 MD5 | raw file
  1. import serial,sys
  2. from time import sleep,time
  3. class CRC_CCITT:
  4. def __init__(self, inverted=True):
  5. self.inverted=inverted;
  6. self.tab=256*[[]]
  7. for i in xrange(256):
  8. crc=0
  9. c = i << 8
  10. for j in xrange(8):
  11. if (crc ^ c) & 0x8000:
  12. crc = ( crc << 1) ^ 0x1021
  13. else:
  14. crc = crc << 1
  15. c = c << 1
  16. crc = crc & 0xffff
  17. self.tab[i]=crc;
  18. def update_crc(self, crc, c):
  19. c=0x00ff & (c % 256)
  20. if self.inverted: c=self.flip(c);
  21. tmp = ((crc >> 8) ^ c) & 0xffff
  22. crc = (((crc << 8) ^ self.tab[tmp])) & 0xffff
  23. return crc;
  24. def checksum(self,str):
  25. """Returns the checksum of a string.""";
  26. #crcval=0;
  27. crcval=0xFFFF;
  28. for c in str:
  29. crcval=self.update_crc(crcval, ord(c));
  30. return crcval;
  31. def flip(self,c):
  32. """Flips the bit order, because that's what Fossil wants."""
  33. l=[0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15];
  34. return ((l[c&0x0F]) << 4) + l[(c & 0xF0) >> 4];
  35. def test(self):
  36. return True;
  37. def hex(str):
  38. """Returns the hex decoded version of a byte string."""
  39. toret="";
  40. if str==None: return "none";
  41. for c in str:
  42. toret="%s %02x" % (toret,ord(c));
  43. return toret;
  44. def tx(msg,rx=True):
  45. """Transmit a MetaWatch packet. SFD, Length, and Checksum will be added."""
  46. #Prepend SFD, length.
  47. msg="\x01"+chr(len(msg)+4)+msg;
  48. #Append CRC.
  49. crc=CRC.checksum(msg);
  50. msg=msg+chr(crc&0xFF)+chr(crc>>8); #Little Endian
  51. port.write(msg);
  52. print "Sent message: %s" % hex(msg);
  53. tty='/dev/tty.MetaWatch'
  54. CRC=CRC_CCITT();
  55. if len(sys.argv)>1:
  56. tty=sys.argv[1];
  57. else:
  58. print "Usage: $ python pywmserial.py /dev/tty.watch"
  59. exit(1)
  60. port=serial.Serial(tty)
  61. port.flush()
  62. port.flushOutput()
  63. port.flushInput()
  64. if not port:
  65. print "*Error opening serial port!"
  66. sleep(1)
  67. # buzz
  68. port.write("\x01\x0c\x23\x00\x01\xf4\x01\xf4\x01\x01\x81\xb1")
  69. sleep(1)
  70. # load template
  71. port.write("\x01\x07\x44\x00\x01\x18\xce")
  72. sleep(0.5)
  73. # update buffer
  74. port.write("\x01\x07\x43\x10\x00\x08\x76")
  75. sleep(0.5)
  76. # test write buffer
  77. t0 = time()
  78. for i in range(96):
  79. msg = "\x40\x10"+chr(i)+"\xff\xff\xff\xff\x00\x00\x00\xff\xff\xff\xff\xff"
  80. sleep(0.01)
  81. tx(msg)
  82. t1 = time()
  83. delta = t1-t0
  84. print "sent buffer in " + str(delta) + " seconds."
  85. sleep(0.5)
  86. # update buffer
  87. port.write("\x01\x07\x43\x10\x00\x08\x76")
  88. port.flush()
  89. port.flushOutput()
  90. port.flushInput()
  91. port.close()