#!/usr/bin/env python

# 64 bit preamble (16 bytes)
# Reserved Reserved txdtrtscale enphpwdn manppol enmaninv enmanch enwhite
# EZRADIOPRO_MODULATION_MODE_CONTROL_1 = 0x0D = 0b00 001101
# trclk[1] trclk[0] dtmod[1] dtmod[0] eninv fd[8] modtyp[1] modtyp[0]
# EZRADIOPRO_HEADER_CONTROL_2IOPRO_MODULATION_MODE_CONTROL_2 = 0x23 = 0b00100011
# EZRADIOPRO_HEADER_CONTROL_2 = EZRADIOPRO_HDLEN_2BYTE | EZRADIOPRO_SYNCLEN_2BYTE
# EZRADIOPRO_DATA_ACCESS_CONTROL = EZRADIOPRO_ENPACTX | EZRADIOPRO_ENPACRX | EZRADIOPRO_ENCRC | EZRADIOPRO_CRC_16
# Sync Word: 2A D4
# id = 25
# register_write(EZRADIOPRO_TRANSMIT_HEADER_3, id >> 8);
# register_write(EZRADIOPRO_TRANSMIT_HEADER_2, id & 0xFF);

# txdtrtscale 0
# enphpwdn 0
# manppol 1
# enmaninv 1
# enmanch  0
# enwhite 1

import struct, crc16

from binascii import hexlify

SYNCB0 = 0x2D
SYNCB1 = 0xD4

f = open("output.bin")
data = f.read()
f.close()

pn9 = [
  0x0f, 0x70, 0xb3, 0x6f, 0x43, 0x98, 0x48, 0xae,
  0xbc, 0x97, 0x38, 0x1d, 0xd3, 0xd4, 0xa0, 0x55,
  0x7d, 0x68, 0x37, 0x6d, 0x60, 0xbb, 0xe3, 0xcd,
  0x35, 0xc6, 0x8b, 0xfa, 0x58, 0xa6, 0x30, 0x19,
  0x95, 0x93, 0xf6, 0x92, 0x6f, 0xcb, 0x50, 0xa2,
  0x76, 0x5e, 0xc3, 0x54, 0xe4, 0x31, 0x08, 0x04,
  0x46, 0x47, 0x56, 0xc7, 0x12, 0xa3, 0x67, 0xcf,
  0x16, 0xe5, 0x20, 0x99, 0xd1, 0xf7, 0x83, 0xfe,
  0x1e, 0xe1, 0x66, 0xde, 0x87, 0x30, 0x91, 0x5d,
  0x79, 0x2e, 0x70, 0x3b, 0xa7, 0xa9, 0x40, 0xaa,
  0xfa, 0xd0, 0x6e, 0xda, 0xc1, 0x77, 0xc7, 0x9a,
  0x6b, 0x8d, 0x17, 0xf4, 0xb1, 0x4c, 0x60, 0x33,
  0x2b, 0x27, 0xed, 0x24, 0xdf, 0x96, 0xa1, 0x44,
  0xec, 0xbd, 0x86, 0xa9, 0xc8, 0x62, 0x10, 0x08,
  0x8c, 0x8e, 0xad, 0x8e, 0x25, 0x46, 0xcf, 0x9e,
  0x2d, 0xca, 0x41, 0x33, 0xa3, 0xef, 0x07, 0xfc,
  0x3d, 0xc2, 0xcd, 0xbd, 0x0e, 0x61, 0x22, 0xba,
  0xf2, 0x5c, 0xe0, 0x77, 0x4f, 0x52, 0x81, 0x55,
  0xf5, 0xa0, 0xdd, 0xb5, 0x82, 0xef, 0x8f, 0x34,
  0xd7, 0x1a, 0x2f, 0xe9, 0x62, 0x98, 0xc0, 0x66,
  0x56, 0x4f, 0xda, 0x49, 0xbf, 0x2d, 0x42, 0x89,
  0xd9, 0x7b, 0x0d, 0x53, 0x90, 0xc4, 0x20, 0x11,
  0x19, 0x1d, 0x5b, 0x1c, 0x4a, 0x8d, 0x9f, 0x3c,
  0x5b, 0x94, 0x82, 0x67, 0x47, 0xde, 0x0f, 0xf8,
  0x7b, 0x85, 0x9b, 0x7a, 0x1c, 0xc2, 0x45, 0x75,
  0xe4, 0xb9, 0xc0, 0xee, 0x9e, 0xa5, 0x02, 0xab,
  0xeb, 0x41, 0xbb, 0x6b, 0x05, 0xdf, 0x1e, 0x69,
  0xae, 0x34, 0x5f, 0xd2, 0xc5, 0x31, 0x80, 0xcc,
  0xac, 0x9f, 0xb4, 0x93, 0x7e, 0x5a, 0x85, 0x13,
  0xb2, 0xf6, 0x1a, 0xa7, 0x21, 0x88, 0x40, 0x22,
  0x32, 0x3a, 0xb6, 0x38, 0x95, 0x1b, 0x3e, 0x78,
  0xb7, 0x29, 0x04, 0xce, 0x8f, 0xbc
]

def reverseBits(n):
        result = 0
        for i in range(8):
            result <<= 1
            result |= n & 1
            n >>= 1
        return result

def updatecrc16(acc, input):
  POLY = 0x8005
  acc = (acc ^ (input << 8)) & 0xFFFF
  for i in range(8):
    if acc & 0x8000 == 0x8000:
      acc = (acc << 1) & 0xFFFF
      acc ^= POLY
    else:
      acc = (acc << 1) & 0xFFFF
  return acc & 0xFFFF

def crc16(data, init=0):
  data = bytearray(data)
  acc = init
  for i in range(len(data)):
    acc = updatecrc16(acc, data[i])

  return acc

def bitsToByte(bits):
  return int("0b" + "".join(str(x) for x in bits), 2)

def derandomize(data, offset=0):
  data = bytearray(data)
  for i in range(len(data) - offset):
    data[i+offset] = data[i+offset] ^ pn9[i%len(pn9)]
  return data

def parseFrame(bits):
  s = bits[8*2:8*5]
  data = bytearray(" " * 3)
  for i in range(3):
    data[i] = bitsToByte(s[8*i:8*(i+1)]) ^ pn9[i]

  netId, size = struct.unpack(">HB", data)
  bitSize = size * 8
  if len(bits) - 5*8 < bitSize:
    print "Not enough bits."
    exit(1)

  consumed = bitSize + 8*5

  frameBits = bits[8*5:]
  frame = bytearray(" " * size)

  crcframe = bytearray(" " * (size + 3 + 2))
  crcFrameBits = bits[8*2:]

  for i in range(size + 3 + 2):
    crcframe[i] = bitsToByte(crcFrameBits[8*i:8*(i+1)]) ^ pn9[i % len(pn9)]

  crc = struct.unpack(">H", crcframe[len(crcframe)-2:])[0]
  frame = crcframe[:len(crcframe)-2]
  crc = crc16(frame) == crc
  frame = crcframe[3:]

  return netId, size, consumed, frame, crc


preamble = [ int(x) for x in ("10" * 4 * 4)]

bits = [ ord(x) for x in data ]
offset = 0
syncWord = False

skipHeads = 0
skipped = 0

while len(bits) > 0:
  if len(bits) <= len(preamble):
    #print "None found"
    exit(1)
  for i in range(len(bits) - len(preamble)):
    found = True
    for z in range(len(preamble)):
      if bits[i+z] != preamble[z]:
        found = False
        break
    if found:
      offset = i
      break

  #print "Preamble start at %s" %offset

  offset += len(preamble)
  bits = bits[offset:]
  offset = 0

  #print "Searching for sync word"
  searchLen = 512
  for i in range(len(bits)-16):
    b0 = bits[i:i+8]
    b1 = bits[i+8:i+16]
    if bitsToByte(b0) == SYNCB0 and bitsToByte(b1) == SYNCB1:
      #print "FOUND"
      netId, size, consumed, frame, crc = parseFrame(bits[i:])
      if crc:
        print " HexFrame: %s" %hexlify(frame)
        print " Frame: %s" %frame
      bits = bits[consumed:]
      break

    if i > searchLen:
      break
