Exemplo n.º 1
0
def check_file(opt):
    """
    Calculate the CRC of a file.
    This algorithm uses the table_driven CRC algorithm.
    """
    if opt.undefined_crc_parameters:
        sys.stderr.write("{0:s}: error: undefined parameters\n".format(sys.argv[0]))
        sys.exit(1)
    alg = Crc(
        width=opt.width, poly=opt.poly,
        reflect_in=opt.reflect_in, xor_in=opt.xor_in,
        reflect_out=opt.reflect_out, xor_out=opt.xor_out,
        table_idx_width=opt.tbl_idx_width)

    if not opt.reflect_in:
        register = opt.xor_in
    else:
        register = alg.reflect(opt.xor_in, opt.width)

    try:
        with open(opt.check_file, 'rb') as f:
            check_bytes = bytearray(f.read(1024))
            while check_bytes != b"":
                register = crc_file_update(alg, register, check_bytes)
                check_bytes = bytearray(f.read(1024))
    except IOError:
        sys.stderr.write(
            "{0:s}: error: can't open file {1:s}\n".format(sys.argv[0], opt.check_file))
        sys.exit(1)

    if opt.reflect_out:
        register = alg.reflect(register, opt.width)
    register = register ^ opt.xor_out
    return register
Exemplo n.º 2
0
def check_file(opt):
    """
    Calculate the CRC of a file.
    This algorithm uses the table_driven CRC algorithm.
    """
    if opt.UndefinedCrcParameters:
        sys.stderr.write("%s: error: undefined parameters\n" % sys.argv[0])
        sys.exit(1)
    alg = Crc(width = opt.Width, poly = opt.Poly,
        reflect_in = opt.ReflectIn, xor_in = opt.XorIn,
        reflect_out = opt.ReflectOut, xor_out = opt.XorOut,
        table_idx_width = opt.TableIdxWidth)

    try:
        in_file = open(opt.CheckFile, 'rb')
    except IOError:
        sys.stderr.write("%s: error: can't open file %s\n" % (sys.argv[0], opt.CheckFile))
        sys.exit(1)

    if not opt.ReflectIn:
        register = opt.XorIn
    else:
        register = alg.reflect(opt.XorIn, opt.Width)
    # Read bytes from the file.
    check_bytes = in_file.read(1024)
    while check_bytes:
        register = crc_file_update(alg, register, check_bytes)
        check_bytes = in_file.read(1024)
    in_file.close()

    if opt.ReflectOut:
        register = alg.reflect(register, opt.Width)
    register = register ^ opt.XorOut
    return register
Exemplo n.º 3
0
 def __get_table_init(self):
     """
     Return the precalculated CRC table for the table_driven implementation.
     """
     if self.opt.Algorithm != self.opt.Algo_Table_Driven:
         return "0"
     if self.opt.Width == None or self.opt.Poly == None or self.opt.ReflectIn == None:
         return "0"
     crc = Crc(
         width=self.opt.Width,
         poly=self.opt.Poly,
         reflect_in=self.opt.ReflectIn,
         xor_in=0,
         reflect_out=False,
         xor_out=0,  # set unimportant variables to known values
         table_idx_width=self.opt.TableIdxWidth)
     tbl = crc.gen_table()
     if self.opt.Width >= 32:
         values_per_line = 4
     elif self.opt.Width >= 16:
         values_per_line = 8
     else:
         values_per_line = 16
     format_width = max(self.opt.Width, 8)
     out = ""
     for i in range(self.opt.TableWidth):
         if i % values_per_line == 0:
             out += "    "
         if i == (self.opt.TableWidth - 1):
             out += "%s" % self.__pretty_hex(tbl[i], format_width)
         elif i % values_per_line == (values_per_line - 1):
             out += "%s,\n" % self.__pretty_hex(tbl[i], format_width)
         else:
             out += "%s, " % self.__pretty_hex(tbl[i], format_width)
     return out
Exemplo n.º 4
0
 def __get_table_init(self):
     """
     Return the precalculated CRC table for the table_driven implementation.
     """
     if self.opt.Algorithm != self.opt.Algo_Table_Driven:
         return "0"
     if self.opt.Width == None or self.opt.Poly == None or self.opt.ReflectIn == None:
         return "0"
     crc = Crc(width = self.opt.Width, poly = self.opt.Poly,
             reflect_in = self.opt.ReflectIn,
             xor_in = 0, reflect_out = False, xor_out = 0,       # set unimportant variables to known values
             table_idx_width = self.opt.TableIdxWidth)
     tbl = crc.gen_table()
     if self.opt.Width >= 32:
         values_per_line = 4
     elif self.opt.Width >= 16:
         values_per_line = 8
     else:
         values_per_line = 16
     format_width = max(self.opt.Width, 8)
     out  = ""
     for i in range(self.opt.TableWidth):
         if i % values_per_line == 0:
             out += "    "
         if i == (self.opt.TableWidth - 1):
             out += "%s" % self.__pretty_hex(tbl[i], format_width)
         elif i % values_per_line == (values_per_line - 1):
             out += "%s,\n" % self.__pretty_hex(tbl[i], format_width)
         else:
             out += "%s, " % self.__pretty_hex(tbl[i], format_width)
     return out
Exemplo n.º 5
0
def check_file(opt):
    """
    Calculate the CRC of a file.
    This algorithm uses the table_driven CRC algorithm.
    """
    if opt.UndefinedCrcParameters:
        sys.stderr.write("%s: error: undefined parameters\n" % sys.argv[0])
        sys.exit(1)
    alg = Crc(width = opt.Width, poly = opt.Poly,
        reflect_in = opt.ReflectIn, xor_in = opt.XorIn,
        reflect_out = opt.ReflectOut, xor_out = opt.XorOut,
        table_idx_width = opt.TableIdxWidth)

    try:
        in_file = open(opt.CheckFile, 'rb')
    except IOError:
        sys.stderr.write("%s: error: can't open file %s\n" % (sys.argv[0], opt.CheckFile))
        sys.exit(1)

    if not opt.ReflectIn:
        register = opt.XorIn
    else:
        register = alg.reflect(opt.XorIn, opt.Width)
    # Read bytes from the file.
    check_byte_str = in_file.read()
    while check_byte_str:
        register = crc_file_update(alg, register, check_byte_str)
        check_byte_str = in_file.read()
    in_file.close()

    if opt.ReflectOut:
        register = alg.reflect(register, opt.Width)
    register = register ^ opt.XorOut
    return register
Exemplo n.º 6
0
def maxim_ibutton_crc(data):
    crc = Crc(width=8,
              poly=0x31,
              reflect_in=True,
              xor_in=0x00,
              reflect_out=True,
              xor_out=0x00)
    return crc.bit_by_bit(data)
Exemplo n.º 7
0
def check_string(opt):
    """
    Return the calculated CRC sum of a string.
    """
    error = False
    if opt.undefined_crc_parameters:
        sys.stderr.write("{0:s}: error: undefined parameters\n".format(
            sys.argv[0]))
        sys.exit(1)
    if opt.algorithm == 0:
        opt.algorithm = opt.algo_bit_by_bit | opt.algo_bit_by_bit_fast | opt.algo_table_driven

    alg = Crc(width=opt.width,
              poly=opt.poly,
              reflect_in=opt.reflect_in,
              xor_in=opt.xor_in,
              reflect_out=opt.reflect_out,
              xor_out=opt.xor_out,
              table_idx_width=opt.tbl_idx_width)

    crc = None
    if opt.algorithm & opt.algo_bit_by_bit:
        bbb_crc = alg.bit_by_bit(opt.check_string)
        if crc != None and bbb_crc != crc:
            error = True
        crc = bbb_crc
    if opt.algorithm & opt.algo_bit_by_bit_fast:
        bbf_crc = alg.bit_by_bit_fast(opt.check_string)
        if crc != None and bbf_crc != crc:
            error = True
        crc = bbf_crc
    if opt.algorithm & opt.algo_table_driven:
        # no point making the python implementation slower by using less than 8 bits as index.
        opt.tbl_idx_width = 8
        tbl_crc = alg.table_driven(opt.check_string)
        if crc != None and tbl_crc != crc:
            error = True
        crc = tbl_crc

    if error:
        sys.stderr.write("{0:s}: error: different checksums!\n".format(
            sys.argv[0]))
        if opt.algorithm & opt.algo_bit_by_bit:
            sys.stderr.write(
                "       bit-by-bit:        {0:#x}\n".format(bbb_crc))
        if opt.algorithm & opt.algo_bit_by_bit_fast:
            sys.stderr.write(
                "       bit-by-bit-fast:   {0:#x}\n".format(bbf_crc))
        if opt.algorithm & opt.algo_table_driven:
            sys.stderr.write(
                "       table_driven:      {0:#x}\n".format(tbl_crc))
        sys.exit(1)
    return crc
Exemplo n.º 8
0
def calc_crc(data):
    crc = Crc(width=16,
              poly=0x8005,
              reflect_in=True,
              xor_in=0xffff,
              reflect_out=True,
              xor_out=0x0000)

    my_crc = crc.bit_by_bit_fast(data)
    lsb = my_crc & 0b0000000011111111
    msb = (my_crc & 0b1111111100000000) >> 8
    return [lsb, msb]
Exemplo n.º 9
0
def check_string(opt):
    """
    Return the calculated CRC sum of a string.
    """
    error = False
    if opt.UndefinedCrcParameters:
        sys.stderr.write("%s: error: undefined parameters\n" % sys.argv[0])
        sys.exit(1)
    
    #print(opt.Algorithm)

    if opt.Algorithm == 0:
        opt.Algorithm = opt.Algo_Bit_by_Bit | opt.Algo_Bit_by_Bit_Fast | opt.Algo_Table_Driven

    alg = Crc(width = opt.Width, poly = opt.Poly,
        reflect_in = opt.ReflectIn, xor_in = opt.XorIn,
        reflect_out = opt.ReflectOut, xor_out = opt.XorOut,
        table_idx_width = opt.TableIdxWidth)
    
    opt.Algorithm = opt.Algo_Table_Driven

    crc = None
    if opt.Algorithm & opt.Algo_Bit_by_Bit:
      #print( "bit_by_bit")
        bbb_crc = alg.bit_by_bit(opt.CheckString)
        if crc != None and bbb_crc != crc:
            error = True
        crc = bbb_crc
    if opt.Algorithm & opt.Algo_Bit_by_Bit_Fast:
        bbf_crc = alg.bit_by_bit_fast(opt.CheckString)
        #print( "bit_by_bit_fast")
        if crc != None and bbf_crc != crc:
            error = True
        crc = bbf_crc
    if opt.Algorithm & opt.Algo_Table_Driven:
        # no point making the python implementation slower by using less than 8 bits as index.
        opt.TableIdxWidth = 8
        tbl_crc = alg.table_driven(opt.CheckString)
        if crc != None and tbl_crc != crc:
            error = True
        crc = tbl_crc

    if error:
        sys.stderr.write("%s: error: different checksums!\n" % sys.argv[0])
        if opt.Algorithm & opt.Algo_Bit_by_Bit:
            sys.stderr.write("       bit-by-bit:        0x%x\n" % bbb_crc)
        if opt.Algorithm & opt.Algo_Bit_by_Bit_Fast:
            sys.stderr.write("       bit-by-bit-fast:   0x%x\n" % bbf_crc)
        if opt.Algorithm & opt.Algo_Table_Driven:
            sys.stderr.write("       table_driven:      0x%x\n" % tbl_crc)
        sys.exit(1)
    return crc
Exemplo n.º 10
0
 def __init__(self, slaveAddy, functionCode, registerAddy, numRegisters):
     self.slaveAddy = slaveAddy
     self.functionCode = functionCode
     self.registerAddy = registerAddy
     self.numRegisters = numRegisters
     self.crc = Crc(width=16,
                    poly=0x8005,
                    reflect_in=True,
                    xor_in=0xFFFF,
                    reflect_out=True,
                    xor_out=0x0000)
     self.rplyBytes = 0
     self.rplyData = list()  # list of 16 bit integer data
Exemplo n.º 11
0
def check_string(opt):
    """
    Return the calculated CRC sum of a string.
    """
    error = False
    if opt.UndefinedCrcParameters:
        sys.stderr.write("%s: error: undefined parameters\n" % sys.argv[0])
        sys.exit(1)
    if opt.Algorithm == 0:
        opt.Algorithm = opt.Algo_Bit_by_Bit | opt.Algo_Bit_by_Bit_Fast | opt.Algo_Table_Driven

    alg = Crc(width=opt.Width,
              poly=opt.Poly,
              reflect_in=opt.ReflectIn,
              xor_in=opt.XorIn,
              reflect_out=opt.ReflectOut,
              xor_out=opt.XorOut,
              table_idx_width=opt.TableIdxWidth)

    crc = None
    if opt.Algorithm & opt.Algo_Bit_by_Bit:
        bbb_crc = alg.bit_by_bit(opt.CheckString)
        if crc != None and bbb_crc != crc:
            error = True
        crc = bbb_crc
    if opt.Algorithm & opt.Algo_Bit_by_Bit_Fast:
        bbf_crc = alg.bit_by_bit_fast(opt.CheckString)
        if crc != None and bbf_crc != crc:
            error = True
        crc = bbf_crc
    if opt.Algorithm & opt.Algo_Table_Driven:
        # no point making the python implementation slower by using less than 8 bits as index.
        opt.TableIdxWidth = 8
        tbl_crc = alg.table_driven(opt.CheckString)
        if crc != None and tbl_crc != crc:
            error = True
        crc = tbl_crc

    if error:
        sys.stderr.write("%s: error: different checksums!\n" % sys.argv[0])
        if opt.Algorithm & opt.Algo_Bit_by_Bit:
            sys.stderr.write("       bit-by-bit:        0x%x\n" % bbb_crc)
        if opt.Algorithm & opt.Algo_Bit_by_Bit_Fast:
            sys.stderr.write("       bit-by-bit-fast:   0x%x\n" % bbf_crc)
        if opt.Algorithm & opt.Algo_Table_Driven:
            sys.stderr.write("       table_driven:      0x%x\n" % tbl_crc)
        sys.exit(1)
    return crc
Exemplo n.º 12
0
    def __get_crc(self, model, check_str='123456789', expected_crc=None):
        """
        Get the CRC for a set of parameters from the Python reference implementation.
        """
        if self.verbose:
            out_str = 'Crc(width = {width:d}, poly = {poly:#x}, reflect_in = {reflect_in}, xor_in = {xor_in:#x}, reflect_out = {reflect_out}, xor_out = {xor_out:#x})'.format(
                **model)
            if expected_crc is not None:
                out_str += ' [check = {0:#x}]'.format(expected_crc)
            print(out_str)
        alg = Crc(width=model['width'],
                  poly=model['poly'],
                  reflect_in=model['reflect_in'],
                  xor_in=model['xor_in'],
                  reflect_out=model['reflect_out'],
                  xor_out=model['xor_out'])
        error = False
        crc = expected_crc

        if self.use_algo_bit_by_bit:
            bbb_crc = alg.bit_by_bit(check_str)
            if crc is None:
                crc = bbb_crc
            error = error or bbb_crc != crc
        if self.use_algo_bit_by_bit_fast:
            bbf_crc = alg.bit_by_bit_fast(check_str)
            if crc is None:
                crc = bbf_crc
            error = error or bbf_crc != crc
        if self.use_algo_table_driven:
            tbl_crc = alg.table_driven(check_str)
            if crc is None:
                crc = tbl_crc
            error = error or tbl_crc != crc

        if error:
            print('error: different checksums!')
            if expected_crc is not None:
                print('       check:             {0:#x}'.format(expected_crc))
            if self.use_algo_bit_by_bit:
                print('       bit-by-bit:        {0:#x}'.format(bbb_crc))
            if self.use_algo_bit_by_bit_fast:
                print('       bit-by-bit-fast:   {0:#x}'.format(bbf_crc))
            if self.use_algo_table_driven:
                print('       table_driven:      {0:#x}'.format(tbl_crc))
            return None
        return crc
Exemplo n.º 13
0
 def __get_init_value(self):
     """
     Return the init value of a C implementation, according to the selected algorithm and
     to the given options.
     If no default option is given for a given parameter, value in the cfg_t structure must be used.
     """
     if self.opt.Algorithm == self.opt.Algo_Bit_by_Bit:
         if self.opt.XorIn == None or self.opt.Width == None or self.opt.Poly == None:
             return None
         crc = Crc(
             width=self.opt.Width,
             poly=self.opt.Poly,
             reflect_in=self.opt.ReflectIn,
             xor_in=self.opt.XorIn,
             reflect_out=self.opt.ReflectOut,
             xor_out=self.opt.XorOut,
             table_idx_width=self.opt.TableIdxWidth,
         )
         init = crc.NonDirectInit
     elif self.opt.Algorithm == self.opt.Algo_Bit_by_Bit_Fast:
         if self.opt.XorIn == None:
             return None
         init = self.opt.XorIn
     elif self.opt.Algorithm == self.opt.Algo_Table_Driven:
         if self.opt.ReflectIn == None or self.opt.XorIn == None or self.opt.Width == None:
             return None
         if self.opt.Poly == None:
             poly = 0
         else:
             poly = self.opt.Poly
         crc = Crc(
             width=self.opt.Width,
             poly=poly,
             reflect_in=self.opt.ReflectIn,
             xor_in=self.opt.XorIn,
             reflect_out=self.opt.ReflectOut,
             xor_out=self.opt.XorOut,
             table_idx_width=self.opt.TableIdxWidth,
         )
         if self.opt.ReflectIn:
             init = crc.reflect(crc.DirectInit, self.opt.Width)
         else:
             init = crc.DirectInit
     else:
         init = 0
     return self.__pretty_hex(init, self.opt.Width)
Exemplo n.º 14
0
    def __get_crc(self, model, check_str="123456789", expected_crc=None):
        """
        Get the CRC for a set of parameters from the Python reference implementation.
        """
        if self.verbose:
            out_str = "Crc(width = %(width)d, poly = 0x%(poly)x, reflect_in = %(reflect_in)s, xor_in = 0x%(xor_in)x, reflect_out = %(reflect_out)s, xor_out = 0x%(xor_out)x)" % model
            if expected_crc is not None:
                out_str += " [check = 0x%x]" % expected_crc
            print(out_str)
        alg = Crc(width=model["width"],
                  poly=model["poly"],
                  reflect_in=model["reflect_in"],
                  xor_in=model["xor_in"],
                  reflect_out=model["reflect_out"],
                  xor_out=model["xor_out"])
        error = False
        crc = expected_crc

        if self.use_algo_bit_by_bit:
            bbb_crc = alg.bit_by_bit(check_str)
            if crc is None:
                crc = bbb_crc
            error = error or bbb_crc != crc
        if self.use_algo_bit_by_bit_fast:
            bbf_crc = alg.bit_by_bit_fast(check_str)
            if crc is None:
                crc = bbf_crc
            error = error or bbf_crc != crc
        if self.use_algo_table_driven:
            tbl_crc = alg.table_driven(check_str)
            if crc is None:
                crc = tbl_crc
            error = error or tbl_crc != crc

        if error:
            print("error: different checksums!")
            if expected_crc is not None:
                print("       check:             0x%x" % expected_crc)
            if self.use_algo_bit_by_bit:
                print("       bit-by-bit:        0x%x" % bbb_crc)
            if self.use_algo_bit_by_bit_fast:
                print("       bit-by-bit-fast:   0x%x" % bbf_crc)
            if self.use_algo_table_driven:
                print("       table_driven:      0x%x" % tbl_crc)
            return None
        return crc
Exemplo n.º 15
0
def check_string(opt):
    """
    Return the calculated CRC sum of a string.
    """
    error = False
    if opt.undefined_crc_parameters:
        sys.stderr.write("{0:s}: error: undefined parameters\n".format(sys.argv[0]))
        sys.exit(1)
    if opt.algorithm == 0:
        opt.algorithm = opt.algo_bit_by_bit | opt.algo_bit_by_bit_fast | opt.algo_table_driven

    alg = Crc(
        width=opt.width, poly=opt.poly,
        reflect_in=opt.reflect_in, xor_in=opt.xor_in,
        reflect_out=opt.reflect_out, xor_out=opt.xor_out,
        table_idx_width=opt.tbl_idx_width)

    crc = None
    if opt.algorithm & opt.algo_bit_by_bit:
        bbb_crc = alg.bit_by_bit(opt.check_string)
        if crc != None and bbb_crc != crc:
            error = True
        crc = bbb_crc
    if opt.algorithm & opt.algo_bit_by_bit_fast:
        bbf_crc = alg.bit_by_bit_fast(opt.check_string)
        if crc != None and bbf_crc != crc:
            error = True
        crc = bbf_crc
    if opt.algorithm & opt.algo_table_driven:
        # no point making the python implementation slower by using less than 8 bits as index.
        opt.tbl_idx_width = 8
        tbl_crc = alg.table_driven(opt.check_string)
        if crc != None and tbl_crc != crc:
            error = True
        crc = tbl_crc

    if error:
        sys.stderr.write("{0:s}: error: different checksums!\n".format(sys.argv[0]))
        if opt.algorithm & opt.algo_bit_by_bit:
            sys.stderr.write("       bit-by-bit:        {0:#x}\n".format(bbb_crc))
        if opt.algorithm & opt.algo_bit_by_bit_fast:
            sys.stderr.write("       bit-by-bit-fast:   {0:#x}\n".format(bbf_crc))
        if opt.algorithm & opt.algo_table_driven:
            sys.stderr.write("       table_driven:      {0:#x}\n".format(tbl_crc))
        sys.exit(1)
    return crc
Exemplo n.º 16
0
def main():
    string1 = ''
    string2 = "c651ceb5fa05b4195f993513d8bb5381"
    crc = Crc(width = 16, poly = 0x8005,
              reflect_in = True, xor_in = 0x0000,
              reflect_out = True, xor_out = 0x0000)
    crc1 = 'a'
    crc2 = crc.table_driven(string2)
    print datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S') 
    while crc1 != crc2: 
        string1 = ''.join(random.SystemRandom().choice(string.ascii_letters + \
         string.digits) for _ in range(32))
        crc1 = crc.table_driven(string1)
 
    print datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S') 
    print string1
    print string2 
    print "CRC: " + str(crc1)
Exemplo n.º 17
0
    def __get_crc(self, model, check_str = "123456789", expected_crc = None):
        """
        Get the CRC for a set of parameters from the Python reference implementation.
        """
        if self.verbose:
            out_str = "Crc(width = %(width)d, poly = 0x%(poly)x, reflect_in = %(reflect_in)s, xor_in = 0x%(xor_in)x, reflect_out = %(reflect_out)s, xor_out = 0x%(xor_out)x)" % model
            if expected_crc is not None:
                out_str += " [check = 0x%x]" % expected_crc
            print(out_str)
        alg = Crc(width = model["width"], poly = model["poly"],
            reflect_in = model["reflect_in"], xor_in = model["xor_in"],
            reflect_out = model["reflect_out"], xor_out = model["xor_out"])
        error = False
        crc = expected_crc

        if self.use_algo_bit_by_bit:
            bbb_crc = alg.bit_by_bit(check_str)
            if crc is None:
                crc = bbb_crc
            error = error or bbb_crc != crc
        if self.use_algo_bit_by_bit_fast:
            bbf_crc = alg.bit_by_bit_fast(check_str)
            if crc is None:
                crc = bbf_crc
            error = error or bbf_crc != crc
        if self.use_algo_table_driven:
            tbl_crc = alg.table_driven(check_str)
            if crc is None:
                crc = tbl_crc
            error = error or tbl_crc != crc

        if error:
            print("error: different checksums!")
            if expected_crc is not None:
                print("       check:             0x%x" % expected_crc)
            if self.use_algo_bit_by_bit:
                print("       bit-by-bit:        0x%x" % bbb_crc)
            if self.use_algo_bit_by_bit_fast:
                print("       bit-by-bit-fast:   0x%x" % bbf_crc)
            if self.use_algo_table_driven:
                print("       table_driven:      0x%x" % tbl_crc)
            return None
        return crc
Exemplo n.º 18
0
Arquivo: test.py Projeto: mgk/pycrc
    def __get_crc(self, model, check_str = '123456789', expected_crc = None):
        """
        Get the CRC for a set of parameters from the Python reference implementation.
        """
        if self.verbose:
            out_str = 'Crc(width = {width:d}, poly = {poly:#x}, reflect_in = {reflect_in}, xor_in = {xor_in:#x}, reflect_out = {reflect_out}, xor_out = {xor_out:#x})'.format(**model)
            if expected_crc is not None:
                out_str += ' [check = {0:#x}]'.format(expected_crc)
            print(out_str)
        alg = Crc(width = model['width'], poly = model['poly'],
            reflect_in = model['reflect_in'], xor_in = model['xor_in'],
            reflect_out = model['reflect_out'], xor_out = model['xor_out'])
        error = False
        crc = expected_crc

        if self.use_algo_bit_by_bit:
            bbb_crc = alg.bit_by_bit(check_str)
            if crc is None:
                crc = bbb_crc
            error = error or bbb_crc != crc
        if self.use_algo_bit_by_bit_fast:
            bbf_crc = alg.bit_by_bit_fast(check_str)
            if crc is None:
                crc = bbf_crc
            error = error or bbf_crc != crc
        if self.use_algo_table_driven:
            tbl_crc = alg.table_driven(check_str)
            if crc is None:
                crc = tbl_crc
            error = error or tbl_crc != crc

        if error:
            print('error: different checksums!')
            if expected_crc is not None:
                print('       check:             {0:#x}'.format(expected_crc))
            if self.use_algo_bit_by_bit:
                print('       bit-by-bit:        {0:#x}'.format(bbb_crc))
            if self.use_algo_bit_by_bit_fast:
                print('       bit-by-bit-fast:   {0:#x}'.format(bbf_crc))
            if self.use_algo_table_driven:
                print('       table_driven:      {0:#x}'.format(tbl_crc))
            return None
        return crc
Exemplo n.º 19
0
def _get_init_value(opt):
    """
    Return the init value of a C implementation, according to the selected
    algorithm and to the given options.
    If no default option is given for a given parameter, value in the cfg_t
    structure must be used.
    """
    if opt.algorithm == opt.algo_bit_by_bit:
        if opt.xor_in is None or opt.width is None or opt.poly is None:
            return None
        crc = Crc(width=opt.width,
                  poly=opt.poly,
                  reflect_in=opt.reflect_in,
                  xor_in=opt.xor_in,
                  reflect_out=opt.reflect_out,
                  xor_out=opt.xor_out,
                  table_idx_width=opt.tbl_idx_width)
        init = crc.nondirect_init
    elif opt.algorithm == opt.algo_bit_by_bit_fast:
        if opt.xor_in is None:
            return None
        init = opt.xor_in
    elif opt.algorithm == opt.algo_table_driven:
        if opt.reflect_in is None or opt.xor_in is None or opt.width is None:
            return None
        if opt.poly is None:
            poly = 0
        else:
            poly = opt.poly
        crc = Crc(width=opt.width,
                  poly=poly,
                  reflect_in=opt.reflect_in,
                  xor_in=opt.xor_in,
                  reflect_out=opt.reflect_out,
                  xor_out=opt.xor_out,
                  table_idx_width=opt.tbl_idx_width)
        if opt.reflect_in:
            init = crc.reflect(crc.direct_init, opt.width)
        else:
            init = crc.direct_init
    else:
        init = 0
    return _pretty_hex(init, opt.width)
Exemplo n.º 20
0
 def __get_init_value(self):
     """
     Return the init value of a C implementation, according to the selected algorithm and
     to the given options.
     If no default option is given for a given parameter, value in the cfg_t structure must be used.
     """
     if self.opt.Algorithm == self.opt.Algo_Bit_by_Bit:
         if self.opt.XorIn == None or self.opt.Width == None or self.opt.Poly == None:
             return None
         crc = Crc(width=self.opt.Width,
                   poly=self.opt.Poly,
                   reflect_in=self.opt.ReflectIn,
                   xor_in=self.opt.XorIn,
                   reflect_out=self.opt.ReflectOut,
                   xor_out=self.opt.XorOut,
                   table_idx_width=self.opt.TableIdxWidth)
         init = crc.NonDirectInit
     elif self.opt.Algorithm == self.opt.Algo_Bit_by_Bit_Fast:
         if self.opt.XorIn == None:
             return None
         init = self.opt.XorIn
     elif self.opt.Algorithm == self.opt.Algo_Table_Driven:
         if self.opt.ReflectIn == None or self.opt.XorIn == None or self.opt.Width == None:
             return None
         if self.opt.Poly == None:
             poly = 0
         else:
             poly = self.opt.Poly
         crc = Crc(width=self.opt.Width,
                   poly=poly,
                   reflect_in=self.opt.ReflectIn,
                   xor_in=self.opt.XorIn,
                   reflect_out=self.opt.ReflectOut,
                   xor_out=self.opt.XorOut,
                   table_idx_width=self.opt.TableIdxWidth)
         if self.opt.ReflectIn:
             init = crc.reflect(crc.DirectInit, self.opt.Width)
         else:
             init = crc.DirectInit
     else:
         init = 0
     return self.__pretty_hex(init, self.opt.Width)
Exemplo n.º 21
0
    class Helper(object):
        CRC = Crc(
            width=16,
            poly=0x8005,
            reflect_in=False,
            xor_in=0xFFFF,
            reflect_out=False,
            xor_out=0x0000
        )  # specification is slightly unclear, figured out by trial-and-error

        @staticmethod
        def unitTest():
            assert ESSPDevice.Helper.crc([0x80, 0x01, 0x01]) == [0x06, 0x02]
            assert ESSPDevice.Helper.crc([0x80, 0x01, 0xF0]) == [0x23, 0x80]

        @classmethod
        def splitBytes(cls, uint16):
            # uint16 -> [lowByte, highByte]
            return [uint16 & 0xFF, uint16 >> 8]

        @classmethod
        def crc(cls, data):
            c = cls.CRC.bit_by_bit(data)
            return cls.splitBytes(c)

        @classmethod
        def Unsigned32ToBytes(cls, x):
            # return little-endian representation
            return ESSPDevice.Helper.UnsignedToBytes(x, n=4)

        @staticmethod
        def Unsigned64ToBytes(x):
            # return little-endian representation
            return ESSPDevice.Helper.UnsignedToBytes(x, n=8)

        @staticmethod
        def UnsignedToBytes(x, n):
            r = []
            for _ in range(n):
                r.append(x & 0xFF)
                x = x >> 8
            return r

        @classmethod
        def AsciiToBytes(cls, x):
            return [ord(c) for c in x]

        @staticmethod
        def byteArrayToString(data):
            return b''.join([chr(x) for x in data])

        @staticmethod
        def stringToByteArray(string):
            return ([ord(x) for x in string])
Exemplo n.º 22
0
def _get_table_init(opt):  # TODO: change to return a list
    """
    Return the precalculated CRC table for the table_driven implementation.
    """
    if opt.algorithm != opt.algo_table_driven:
        return "0"
    if opt.width is None or opt.poly is None or opt.reflect_in is None:
        return "0"
    crc = Crc(
        width=opt.width,
        poly=opt.poly,
        reflect_in=opt.reflect_in,
        xor_in=0,
        reflect_out=False,
        xor_out=0,  # set unimportant variables to known values
        table_idx_width=opt.tbl_idx_width,
        slice_by=opt.slice_by)
    crc_tbl = crc.gen_table()
    if opt.width > 32:
        values_per_line = 4
    elif opt.width >= 16:
        values_per_line = 8
    else:
        values_per_line = 16
    format_width = max(opt.width, 8)
    if opt.slice_by == 1:
        indent = 4
    else:
        indent = 8

    out = [''] * opt.slice_by
    for i in range(opt.slice_by):
        out[i] = _get_simple_table(opt, crc_tbl[i], values_per_line,
                                   format_width, indent)
    fixed_indent = ' ' * (indent - 4)
    out = '{0:s}{{\n'.format(fixed_indent) + \
        '\n{0:s}}},\n{0:s}{{\n'.format(fixed_indent).join(out) + \
        '\n{0:s}}}'.format(fixed_indent)
    if opt.slice_by == 1:
        return out
    return '{\n' + out + '\n}'
Exemplo n.º 23
0
 def __get_crc_bwe_bitmask_minterms(self):
     """
     Return a list of (bitmask, minterms), for all bits.
     """
     crc = Crc(width = self.opt.Width, poly = self.opt.Poly,
             reflect_in = self.opt.ReflectIn, xor_in = self.opt.XorIn,
             reflect_out = self.opt.ReflectOut, xor_out = self.opt.XorOut,
             table_idx_width = self.opt.TableIdxWidth)
     qm = QuineMcCluskey(use_xor = True)
     crc_tbl = crc.gen_table()
     bm_mt = []
     for bit in range(max(self.opt.Width, 8)):
         ones = [i for i in range(self.opt.TableWidth) if crc_tbl[i] & (1 << bit) != 0]
         terms = qm.simplify(ones, [])
         if self.opt.Verbose:
             print("bit %02d: %s" % (bit, terms))
         if terms != None:
             for term in terms:
                 shifted_term = '.' * bit + term + '.' * (self.opt.Width - bit - 1)
                 bm_mt.append((1 << bit, shifted_term))
     return bm_mt
Exemplo n.º 24
0
def check_file(opt):
    """
    Calculate the CRC of a file.
    This algorithm uses the table_driven CRC algorithm.
    """
    if opt.undefined_crc_parameters:
        sys.stderr.write("{0:s}: error: undefined parameters\n".format(
            sys.argv[0]))
        sys.exit(1)
    alg = Crc(width=opt.width,
              poly=opt.poly,
              reflect_in=opt.reflect_in,
              xor_in=opt.xor_in,
              reflect_out=opt.reflect_out,
              xor_out=opt.xor_out,
              table_idx_width=opt.tbl_idx_width)

    try:
        in_file = open(opt.check_file, 'rb')
    except IOError:
        sys.stderr.write("{0:s}: error: can't open file {1:s}\n".format(
            sys.argv[0], opt.check_file))
        sys.exit(1)

    if not opt.reflect_in:
        register = opt.xor_in
    else:
        register = alg.reflect(opt.xor_in, opt.width)
    # Read bytes from the file.
    check_bytes = in_file.read(1024)
    while check_bytes:
        register = crc_file_update(alg, register, check_bytes)
        check_bytes = in_file.read(1024)
    in_file.close()

    if opt.reflect_out:
        register = alg.reflect(register, opt.width)
    register = register ^ opt.xor_out
    return register
    def __init__(self, port, queue):
        import sys
        sys.path.append('.\pycrc-0.7.7')
        import threading        
        from crc_algorithms import Crc
        import serial

        self.xport_serial = serial.Serial(port, 115200, timeout=5.0)
        self.crc = Crc(width = 16, poly = 0x1021, reflect_in = True, xor_in = 0xffff, reflect_out = False, xor_out = 0x0000)
        self.reading = threading.Event()
        """
        We spawn a new thread for the worker.
        """
        self.queue = queue
        # Set up the thread to do asynchronous I/O
        # More can be made if necessary
        self.running = 1
        self.thread1 = threading.Thread(target=self.worker_thread)
        self.thread1.start()
Exemplo n.º 26
0
    def __init__(self, fname):
        print "Loading track image: %s..." % fname
        f = open(fname, "r")
        self.data = bytearray(f.read())
        f.close()

        self.samples = []
        self.gaps = []
        self.gap_hist = {}
        self.clock = []
        self.a1 = []

        self.a1_mark = [0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1]
        self.a1_buf = []
        self.a1_clk = []
        self.a1_pos = 0

        self.crc = Crc(width = 16, poly = 0x1021, reflect_in = False, xor_in = 0xffff, reflect_out = False, xor_out = 0x0000);
        #self.crc = Crc(width = 16, poly = 0x140a0445, reflect_in = False, xor_in = 0xffffffff, reflect_out = False, xor_out = 0x0000);

        print "Unpacking..."
        self.explode()
Exemplo n.º 27
0
class Honeywell3300ReadRegisterCmd:
    """Only class in this interface thus far.  We are only reading from these units."""
    def __init__(self, slaveAddy, functionCode, registerAddy, numRegisters):
        self.slaveAddy = slaveAddy
        self.functionCode = functionCode
        self.registerAddy = registerAddy
        self.numRegisters = numRegisters
        self.crc = Crc(width=16,
                       poly=0x8005,
                       reflect_in=True,
                       xor_in=0xFFFF,
                       reflect_out=True,
                       xor_out=0x0000)
        self.rplyBytes = 0
        self.rplyData = list()  # list of 16 bit integer data

    def performCRC(self, data):
        return self.crc.bit_by_bit(data)

    def createPacket(self):
        buffer = struct.pack("B", self.slaveAddy)
        buffer += struct.pack("B", self.functionCode)
        buffer += struct.pack("BB", self.registerAddy[0], self.registerAddy[1])
        buffer += struct.pack(">H", self.numRegisters)
        buffer += struct.pack(">H", self.performCRC(buffer))
        return buffer

    def processReply(self, rplyBuf):
        startPos = rplyBuf.tell()

        rplySaveAddy = ord(rplyBuf.read(1))
        rplyFunctionCode = ord(rplyBuf.read(1))
        # TODO: addy and function code
        self.rplyBytes = ord(rplyBuf.read(1))
        # TODO: test length against expected length
        for i in range(len(self.numRegisters)):
            self.rplyData.append(int(struct.unpack(">H", rplyBuf.read(2))))
Exemplo n.º 28
0
        0xee00, 0x0000, 0x0080, 0xfe7f, 0x0000, 0x8900, 0x8900, 0x550d, 0x0601,
        0x0601, 0x2200, 0x5500, 0xab1a, 0xca08, 0x6400, 0x6400, 0x9001, 0x2823
    ]
]
crcs = [0xC0F8, 0x72F8, 0x95EE]
initialValue = 0x3132

# 4e00ffff26ec14091600a018303931323031313131303039303031323031303030303131313030393030313230313030303031313130303930303132303130303030ffff225e343331324f313537
# 6400000000000000808080808080000000000000
# e001eb00130105000e010500bc029001900190013c00280046002800a816681040012b001e004f000200bb0080018000330100c0000599990100000033b3cd4c00600601ae070a575c0fc3b5d7634a0f1f8548a1b81e5c8f333300c0f6286009aec7852b5238cd4c3200b80b3700d801880422018002e80334000032890100000000cd664801830048013d0a040114006400c201bbfe3c0071027e010f00dc0500003403dc05cd4c33339a19dc052400b81e7b1466e6a4f0ffffdb034821d703a410f6280000480166e66f126f1271fd71fde7f30040250000000000000000005e80a27fb89e856bd5010004660285034200200024053200640032001900f40129180000080001002602a0000a00c800320028000a001400fa035613821428000002000096009600d007000027005000b004540014006400fa00220be2045e016400dc05800c28000a000500140573007300e1031c00ee0000000080fe7f000089008900550d0601060122005500ab1aca086400640090012823

from crc_algorithms import Crc

crcer = Crc(width=16,
            poly=0xaabd,
            reflect_in=False,
            xor_in=initialValue,
            reflect_out=False,
            xor_out=0xd706)
print("0x%x" % crcer.bit_by_bit(datas[0]))
print("0x%x" % crcer.bit_by_bit(datas[1]))
print("0x%x" % crcer.bit_by_bit(datas[2]))

for data, crc in zip(datas, crcs):
    print("Looking for checksum of 0x%x in 0x%x bytes..." %
          (crc, len(data) * 2))
    for poly in range(0x0000, 0xFFFF):
        crcer = Crc(width=16,
                    poly=poly,
                    reflect_in=False,
                    xor_in=initialValue,
                    reflect_out=False,
Exemplo n.º 29
0
	def parse(self):
		data = None
		self.title = '[empty]'
		for idx,s in enumerate(self.sig):
			if s[0:6] == "TITLE:":
				self.title = s[6:].replace(':', ';')
				continue
			if s[0:5] == "TYPE:":
				self.typeDesc = TypeDesc(s[5:])
				continue
			if s[0:5] == "DATA:":
				data = self.sig[idx+1:]
				continue
		if not data:
			raise DataException('error in data of signature at line ' + str(self.sigLineNumber) + ' named: ' + self.title)
		try:
			self.data = DataParser(self.typeDesc, data)
		except DataException as de:
			raise DataException('error in data of signature at line ' + str(self.sigLineNumber) + ' named: ' + self.title + ' child info:' + de.value)

		#debugRewrite("TITLE:"+self.title.replace(';',':')+"\n\n")
		#debugRewrite("TYPE:"+str(self.typeDesc)+"\n")
		#debugRewrite("DATA:\n");
		#debugRewrite(str(self.data));
		#debugRewrite("\n----\n\n")

		if self.typeDesc.isSimple():
			for bitWidth in self.typeDesc.values:
				# lil endian
				b,l = self.dumpData(bitWidth, Little_Endian, self.data)
				self.generateSigName(self.ndb, bitWidth, Little_Endian, b, l)

				if bitWidth == 8:
					continue

				# big endian
				b,l = self.dumpData(bitWidth, Big_Endian, self.data)
				self.generateSigName(self.ndb, bitWidth, Big_Endian, b, l)

		# currently if "CRC:" is specified only one width is allowed
		elif self.typeDesc.isCrc:
			for Do_Reflect in [True, False]:
				bitWidth = self.typeDesc.values.keys()[0]
				crc = Crc(width = bitWidth, poly = self.data.values[0], reflect_in = Do_Reflect, xor_in = 0, reflect_out = Do_Reflect, xor_out = 0)
				dummyData = DummyData(crc.gen_table(), False)

				b,l = self.dumpData(bitWidth, Little_Endian, dummyData)
				self.generateCrcSigName(bitWidth, Little_Endian, Do_Reflect, b)
				if bitWidth != 8:
					b,l = self.dumpData(bitWidth, Big_Endian, dummyData)
					self.generateCrcSigName(bitWidth, Big_Endian, Do_Reflect, b)

		elif self.typeDesc.isLog:
			for bitWidth in self.typeDesc.values:
				if bitWidth == 8:
					print "\n [!] WARNING, generated byte-based logical signatures is a bad, BAD idea\n"
				b = self.dumpLogicalSignature(bitWidth, Little_Endian, self.data)
				self.generateSigName(self.ldb, bitWidth, Little_Endian, b, 0)

				if bitWidth != 8:
					b = self.dumpLogicalSignature(bitWidth, Big_Endian, self.data)
					self.generateSigName(self.ldb, bitWidth, Big_Endian, b, 0)
Exemplo n.º 30
0
import collections

import datetime

from packet_definitions import *
from crc_algorithms import Crc
from cryptograph import *
from keystore import *

crc = Crc(width=16,
          poly=0x1021,
          reflect_in=True,
          xor_in=0xffff,
          reflect_out=False,
          xor_out=0x0000)


def pretty_parsed(x):
    print pretty_parsed_string(x)


def pretty_parsed_string(x):
    if x is None: return
    result = ''
    if (x['status'] == "identified"):
        result += pretty_string(x['records'])
    else:
        result += x['reason'] + "\n"
    if ('valid' in x):
        result += "         valid:  " + str(x['valid'])
    return result
Exemplo n.º 31
0
datas = [
	[0x4e00,0xffff,0x26ec,0x1409,0x1600,0xa018,0x3039,0x3132,0x3031,0x3131,0x3130,0x3039,0x3030,0x3132,0x3031,0x3030,0x3030,0x3131,0x3130,0x3039,0x3030,0x3132,0x3031,0x3030,0x3030,0x3131,0x3130,0x3039,0x3030,0x3132,0x3031,0x3030,0x3030,0xffff,0x225e,0x3433,0x3132,0x4f31,0x3537],
	[0x6400,0x0000,0x0000,0x0000,0x8080,0x8080,0x8080,0x0000,0x0000,0x0000],
	[0xe001,0xeb00,0x1301,0x0500,0x0e01,0x0500,0xbc02,0x9001,0x9001,0x9001,0x3c00,0x2800,0x4600,0x2800,0xa816,0x6810,0x4001,0x2b00,0x1e00,0x4f00,0x0200,0xbb00,0x8001,0x8000,0x3301,0x00c0,0x0005,0x9999,0x0100,0x0000,0x33b3,0xcd4c,0x0060,0x0601,0xae07,0x0a57,0x5c0f,0xc3b5,0xd763,0x4a0f,0x1f85,0x48a1,0xb81e,0x5c8f,0x3333,0x00c0,0xf628,0x6009,0xaec7,0x852b,0x5238,0xcd4c,0x3200,0xb80b,0x3700,0xd801,0x8804,0x2201,0x8002,0xe803,0x3400,0x0032,0x8901,0x0000,0x0000,0xcd66,0x4801,0x8300,0x4801,0x3d0a,0x0401,0x1400,0x6400,0xc201,0xbbfe,0x3c00,0x7102,0x7e01,0x0f00,0xdc05,0x0000,0x3403,0xdc05,0xcd4c,0x3333,0x9a19,0xdc05,0x2400,0xb81e,0x7b14,0x66e6,0xa4f0,0xffff,0xdb03,0x4821,0xd703,0xa410,0xf628,0x0000,0x4801,0x66e6,0x6f12,0x6f12,0x71fd,0x71fd,0xe7f3,0x0040,0x2500,0x0000,0x0000,0x0000,0x0000,0x5e80,0xa27f,0xb89e,0x856b,0xd501,0x0004,0x6602,0x8503,0x4200,0x2000,0x2405,0x3200,0x6400,0x3200,0x1900,0xf401,0x2918,0x0000,0x0800,0x0100,0x2602,0xa000,0x0a00,0xc800,0x3200,0x2800,0x0a00,0x1400,0xfa03,0x5613,0x8214,0x2800,0x0002,0x0000,0x9600,0x9600,0xd007,0x0000,0x2700,0x5000,0xb004,0x5400,0x1400,0x6400,0xfa00,0x220b,0xe204,0x5e01,0x6400,0xdc05,0x800c,0x2800,0x0a00,0x0500,0x1405,0x7300,0x7300,0xe103,0x1c00,0xee00,0x0000,0x0080,0xfe7f,0x0000,0x8900,0x8900,0x550d,0x0601,0x0601,0x2200,0x5500,0xab1a,0xca08,0x6400,0x6400,0x9001,0x2823]
]
crcs = [0xC0F8,0x72F8,0x95EE]
initialValue = 0x3132

# 4e00ffff26ec14091600a018303931323031313131303039303031323031303030303131313030393030313230313030303031313130303930303132303130303030ffff225e343331324f313537
# 6400000000000000808080808080000000000000
# e001eb00130105000e010500bc029001900190013c00280046002800a816681040012b001e004f000200bb0080018000330100c0000599990100000033b3cd4c00600601ae070a575c0fc3b5d7634a0f1f8548a1b81e5c8f333300c0f6286009aec7852b5238cd4c3200b80b3700d801880422018002e80334000032890100000000cd664801830048013d0a040114006400c201bbfe3c0071027e010f00dc0500003403dc05cd4c33339a19dc052400b81e7b1466e6a4f0ffffdb034821d703a410f6280000480166e66f126f1271fd71fde7f30040250000000000000000005e80a27fb89e856bd5010004660285034200200024053200640032001900f40129180000080001002602a0000a00c800320028000a001400fa035613821428000002000096009600d007000027005000b004540014006400fa00220be2045e016400dc05800c28000a000500140573007300e1031c00ee0000000080fe7f000089008900550d0601060122005500ab1aca086400640090012823

from crc_algorithms import Crc

crcer = Crc(width = 16, poly = 0xaabd, reflect_in = False, xor_in = initialValue, reflect_out = False, xor_out = 0xd706)
print("0x%x" % crcer.bit_by_bit(datas[0]))
print("0x%x" % crcer.bit_by_bit(datas[1]))
print("0x%x" % crcer.bit_by_bit(datas[2]))

for data, crc in zip(datas, crcs):
	print("Looking for checksum of 0x%x in 0x%x bytes..." % (crc, len(data) * 2))
	for poly in range(0x0000, 0xFFFF):
		crcer = Crc(width = 16, poly = poly, reflect_in = False, xor_in = initialValue, reflect_out = False, xor_out = 0xd706)
		res = crcer.bit_by_bit_fast(data)	
		if res == crc:
			print("Solved for 0x%x! polynomial: 0x%x" % (crc, poly))
#   See the License for the specific language governing permissions and
#   limitations under the License.
import serial
import struct
import math
import sys
from crc_algorithms import Crc
import serial
import StringIO

slvAddy = int(sys.argv[1])
boardNum = int(sys.argv[2])

crc = Crc(width=8,
          poly=0x8005,
          reflect_in=True,
          xor_in=0xFFFF,
          reflect_out=True,
          xor_out=0x0000)

# for slvAddy in range(63):
if True:
    # slvAddy = 0x01
    # boardNum = 0x08

    ser = serial.Serial(port="/dev/ttyUSB0",
                        parity=serial.PARITY_NONE,
                        baudrate=9600,
                        stopbits=serial.STOPBITS_ONE,
                        timeout=30)
    # ser.open()
    print "poopy1"
class GatewayInterface:
    def __init__(self, port, queue):
        import sys
        sys.path.append('.\pycrc-0.7.7')
        import threading        
        from crc_algorithms import Crc
        import serial

        self.xport_serial = serial.Serial(port, 115200, timeout=5.0)
        self.crc = Crc(width = 16, poly = 0x1021, reflect_in = True, xor_in = 0xffff, reflect_out = False, xor_out = 0x0000)
        self.reading = threading.Event()
        """
        We spawn a new thread for the worker.
        """
        self.queue = queue
        # Set up the thread to do asynchronous I/O
        # More can be made if necessary
        self.running = 1
        self.thread1 = threading.Thread(target=self.worker_thread)
        self.thread1.start()
        
    def stop(self):
        self.running = 0
        self.reading.wait(5.0)
        self.xport_serial.close()
    def get_msg(self, queue):
        self.reading.clear()
        raw_msg = bytearray()
        raw_msg.extend(self.xport_serial.read(1))
        if len(raw_msg) > 0:
            print("MSG RECV", raw_msg[0])
            try:
                msg = msg_id_dict[raw_msg[0]]()
            except KeyError:
                print("Unkown msg", raw_msg[0])
            else:
                #Success
                raw_msg.extend(self.xport_serial.read(1))
                raw_msg.extend(self.xport_serial.read(raw_msg[1]-2))
                #parse msg
                msg.parse_raw(raw_msg)
                #remove crc bytes for end of raw and then calc crc
                calc_crc = self.crc.bit_by_bit_fast_array(raw_msg[0:len(raw_msg) - 2])
                #response
                resp_msg = bytearray(2)
                resp_msg[0] = 0x80 | raw_msg[0]
                if(calc_crc == msg.recv_crc):
                    resp_msg[1] = 0xA5
                    queue.put(msg)
                else:
                    print("CRC fail")
                    resp_msg[1] = 0x00
                #send resp is expected
                if(msg.Response() == True):               
                    write_len = self.xport_serial.write(resp_msg)
                    print("RESP_MSG: len", len(resp_msg), write_len, resp_msg)
                self.reading.set()
                return True
            self.reading.set()
        return False
    
    def worker_thread(self):
        """
        This is where we handle the asynchronous I/O. For example, it may be
        a 'select()'.
        One important thing to remember is that the thread has to yield
        control.
        """
        while self.running:
            if self.get_msg(self.queue) == False:
                print("Timeout waiting for read")
        """
Exemplo n.º 34
0
class mfm_track:

    # -------------------------------------------------------------------
    def __init__(self, fname):
        print "Loading track image: %s..." % fname
        f = open(fname, "r")
        self.data = bytearray(f.read())
        f.close()

        self.samples = []
        self.gaps = []
        self.gap_hist = {}
        self.clock = []
        self.a1 = []

        self.a1_mark = [0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1]
        self.a1_buf = []
        self.a1_clk = []
        self.a1_pos = 0

        self.crc = Crc(width = 16, poly = 0x1021, reflect_in = False, xor_in = 0xffff, reflect_out = False, xor_out = 0x0000);
        #self.crc = Crc(width = 16, poly = 0x140a0445, reflect_in = False, xor_in = 0xffffffff, reflect_out = False, xor_out = 0x0000);

        print "Unpacking..."
        self.explode()

    # -------------------------------------------------------------------
    def explode(self):
        for byte in self.data:
            for bit in [7, 6, 5, 4, 3, 2, 1, 0]:
                v = (byte >> bit) & 1
                # [value, clock, a1, cell, validdbit, bit, validbyte, byte, crcok]
                self.samples.append([v, 0, 0, 0, 0, 0, 0, 0, 0])

    # -------------------------------------------------------------------
    def clock_regen(self, clock_period, early_clock_margin, clock_offset=0):
        counter = 0
        ov = 1
        next_clock = 0

        while counter < len(self.samples):
            v = self.samples[counter][0]
            self.samples[counter] = [v, 0, 0, 0, 0, 0, 0, 0, 0]

            # each rising edge restarts clock
            if (ov == 0) and (v == 1):
                # clock cleanup - remove previously inserted early clock ticks
                if early_clock_margin and not clock_offset:
                    prev_clock_tick = self.clock[len(self.clock)-1]
                    if counter - prev_clock_tick <= early_clock_margin:
                        self.clock.pop()
                        self.samples[prev_clock_tick][1] = 0

                if not clock_offset:
                    next_clock = counter + clock_period
                    self.clock.append(counter)
                    self.samples[counter][1] = 1
                else:
                    next_clock = counter + clock_offset

            # is it time for next clock tick?
            if counter >= next_clock:
                self.samples[counter][1] = 1
                self.clock.append(counter)
                next_clock = counter + clock_period

            ov = v
            counter += 1

    # -------------------------------------------------------------------
    def a1_match(self, clock):
        bit = self.samples[clock][0]
        self.a1_buf.append(bit)
        self.a1_clk.append(clock)

        if len(self.a1_buf) == 16:
            if self.a1_buf == self.a1_mark:
                clk = self.a1_clk[0]
                self.a1_buf = []
                self.a1_clk = []
                return clk
            else:
                self.a1_buf.pop(0)
                self.a1_clk.pop(0)

        return 0

    # -------------------------------------------------------------------
    def a1_search(self):
        clk = 0
        while clk < len(self.clock):
            a1beg = self.a1_match(self.clock[clk])
            if a1beg:
                self.a1.append(clk)
                self.samples[a1beg][2] = 1
                self.samples[self.clock[clk+1]][2] = 2
            clk += 1

    # -------------------------------------------------------------------
    def calc_gaps(self):
        ls = 0
        pos = opos = 0
        for (s,c,a1,cell,valbit,bit,valbyte,byte,crcok) in self.samples:
            if (s != ls) and (s == 1):
                diff = pos-opos
                self.gaps.append(diff)
                if (self.gap_hist.has_key(diff)):
                    self.gap_hist[diff] += 1
                else:
                    self.gap_hist[diff] = 1
                opos = pos
            pos += 1
            ls = s

    # -------------------------------------------------------------------
    def read_bytes(self, clkpos, b):
        bit = 7
        char = 0
        data = [ 0xa1 ]
        cellmark = 1
        crcok = False
        crc = 0
        while b > 0:
            # prepare 0, +1 and +2 clocks
            clk0 = self.clock[clkpos]
            clk1 = self.clock[clkpos+1]
            clk2 = self.clock[clkpos+2]

            # mark cell start
            self.samples[clk0][3] = cellmark
            cellmark *= -1

            # mark bit end
            self.samples[clk2][4] = 1
            self.samples[clk2][5] = self.samples[clk1][0]

            # shift bit value into the byte
            char |= self.samples[clk1][0] << bit
            bit -= 1

            if bit < 0:
                # append only data, not CRC
                if b > 2:
                    data.append(char)
                elif b == 2:
                    crc = self.crc.table_driven(''.join([chr(x) for x in data]))
                    print "%x" % crc
                    if char == (crc & 0xff00) >> 8:
                        self.samples[clk2][8] = 1
                        crcok = True
                    else:
                        self.samples[clk2][8] = 2
                        crcok = False
                elif b == 1:
                    if char == crc & 0xff:
                        self.samples[clk2][8] = 1
                        crcok &= True
                    else:
                        self.samples[clk2][8] = 2
                        crcok = False

                # mark and store byte
                self.samples[clk2][6] = 1
                self.samples[clk2][7] = char

                bit = 7
                b -= 1
                char = 0

            clkpos += 2
        self.samples[clk2][3] = 2
        return data, crcok

    # -------------------------------------------------------------------
    def analyze(self, clock, margin, offset):

        self.gaps = []
        self.gap_hist = {}
        self.clock = []
        self.a1 = []

        print "Regenerating clock..."
        self.clock_regen(clock, margin, offset)

        print "Analyzing signal gaps..."
        self.calc_gaps()

        print "Looking for sector header/data marks..."
        self.a1_search()
        print "%i A1 marks found." % len(self.a1)

        print "Analyzing sectors..."
        count = 0
        while count < len(self.a1):
            try:
                data, crcok = self.read_bytes(self.a1[count]+1, 6)
                print ''.join([chr(x) for x in data])
                print "---- CRC: %s --------------------------------------------------------" % str(crcok)
            except Exception, e:
                print str(e)
                pass
            count += 1
            try:
                data, crcok = self.read_bytes(self.a1[count]+1, 512 + 3)
                print ''.join([chr(x) for x in data])
                print "---- CRC: %s --------------------------------------------------------" % str(crcok)
            except Exception, e:
                print str(e)
                pass
            count += 1