From 8a0745d3e6e487e770a197fb88228a781c4926f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sergiusz=20=27q3k=27=20Baza=C5=84ski?= Date: Thu, 19 Sep 2013 18:59:48 +0200 Subject: [PATCH] First commit. --- .gitignore | 3 +++ metawatch/__init__.py | 0 metawatch/protocol.py | 62 +++++++++++++++++++++++++++++++++++++++++++ tests/test_packets.py | 34 ++++++++++++++++++++++++ 4 files changed, 99 insertions(+) create mode 100644 .gitignore create mode 100644 metawatch/__init__.py create mode 100644 metawatch/protocol.py create mode 100644 tests/test_packets.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..276d5cb --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +*pyc +*swp +env diff --git a/metawatch/__init__.py b/metawatch/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/metawatch/protocol.py b/metawatch/protocol.py new file mode 100644 index 0000000..6da3003 --- /dev/null +++ b/metawatch/protocol.py @@ -0,0 +1,62 @@ +import struct +from functools import reduce + +# Adapted & Pythonized from pymetawatch by Travis Goodspeed +class MSPCRC: + """Performs a MSP430-compatible CRC-CCIIT.""" + def __init__(self): + self._tab=256*[[]] + for i in range(256): + crc=0 + c = i << 8 + for j in range(8): + if (crc ^ c) & 0x8000: + crc = ( crc << 1) ^ 0x1021 + else: + crc = crc << 1 + c = c << 1 + crc = crc & 0xffff + self._tab[i] = crc + + def _calculate_crc(self, crc, c): + c = c & 0xFF + c = self._flip(c) + + tmp = ((crc >> 8) ^ c) & 0xffff + crc = (((crc << 8) ^ self._tab[tmp])) & 0xffff + return crc + + def checksum_bytes(self, b): + """Returns the checksum of a bytes object.""" + return reduce(self._calculate_crc, b, 0xFFFF) + + def _flip(self,c): + """Flips the bit order, because that's how the MSP430 rolls..""" + l=[0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15] + return ((l[c & 0x0F]) << 4) + l[(c & 0xF0) >> 4] + +class OutboundPacket: + def _generate(self, _type, options, *args): + """Generates a MetaWatch packet based on a given type, options byte and payload bytes.""" + length = 6 + len(args) + data = [] + data.append(1) # Start Bytes + data.append(length) + data.append(_type) + data.append(options) + data += args + mspcrc = MSPCRC() + crc = mspcrc.checksum_bytes(bytearray(data)) + self._data = bytes(data) + struct.pack("