def testByteAligned(self):
     bitstring.bytealigned = True
     a = BitArray("0x00 ff 0f f")
     l = list(a.findall("0xff"))
     self.assertEqual(l, [8])
     p = a.find("0x0f")[0]
     self.assertEqual(p, 16)
     p = a.rfind("0xff")[0]
     self.assertEqual(p, 8)
     s = list(a.split("0xff"))
     self.assertEqual(s, ["0x00", "0xff0ff"])
     a.replace("0xff", "")
     self.assertEqual(a, "0x000ff")
예제 #2
0
 def testNotByteAligned(self):
     bitstring.bytealigned = False
     a = BitArray('0x00 ff 0f f')
     l = list(a.findall('0xff'))
     self.assertEqual(l, [8, 20])
     p = a.find('0x0f')[0]
     self.assertEqual(p, 4)
     p = a.rfind('0xff')[0]
     self.assertEqual(p, 20)
     s = list(a.split('0xff'))
     self.assertEqual(s, ['0x00', '0xff0', '0xff'])
     a.replace('0xff', '')
     self.assertEqual(a, '0x000')
예제 #3
0
 def testByteAligned(self):
     bitstring.settings.bytealigned = True
     a = BitArray('0x00 ff 0f f')
     l = list(a.findall('0xff'))
     self.assertEqual(l, [8])
     p = a.find('0x0f')[0]
     self.assertEqual(p, 16)
     p = a.rfind('0xff')[0]
     self.assertEqual(p, 8)
     s = list(a.split('0xff'))
     self.assertEqual(s, ['0x00', '0xff0ff'])
     a.replace('0xff', '')
     self.assertEqual(a, '0x000ff')
예제 #4
0
 def testNotByteAligned(self):
     bitstring.bytealigned = False
     a = BitArray('0x00 ff 0f f')
     l = list(a.findall('0xff'))
     self.assertEqual(l, [8, 20])
     p = a.find('0x0f')[0]
     self.assertEqual(p, 4)
     p = a.rfind('0xff')[0]
     self.assertEqual(p, 20)
     s = list(a.split('0xff'))
     self.assertEqual(s, ['0x00', '0xff0', '0xff'])
     a.replace('0xff', '')
     self.assertEqual(a, '0x000')
예제 #5
0
 def testByteAligned(self):
     bitstring.settings.bytealigned = True
     a = BitArray('0x00 ff 0f f')
     l = list(a.findall('0xff'))
     self.assertEqual(l, [8])
     p = a.find('0x0f')[0]
     self.assertEqual(p, 16)
     p = a.rfind('0xff')[0]
     self.assertEqual(p, 8)
     s = list(a.split('0xff'))
     self.assertEqual(s, ['0x00', '0xff0ff'])
     a.replace('0xff', '')
     self.assertEqual(a, '0x000ff')
예제 #6
0
def enumeration_solver(T, K=None, S=None):
    """
   Tries all the possible combinations of flipping:
   At each round are available len(S) - K + 1
   possible flip positions ranging from 
   0 to len(S) - K 
   """
    from bitstring import BitArray
    S = BitArray(bin=S.replace('+', '1').replace('-', '0'))
    solution = '1' * len(S)
    if S.bin == solution:
        return 'Case #{}: {}\n'.format(T, 0)

    #print('Case {}'.format(S.bin))
    cand = [S]
    flip_pos = range(len(S) - K + 1)
    flips = 1
    explored = {S.bin}
    while flips > 0:
        #print('Round {} Candidates {}'.format(flips,len(cand)))
        new_cand = []
        for c in cand:
            for f in flip_pos:
                flipped = BitArray(c)
                flipped.invert(range(f, f + K))
                if flipped.bin == solution:
                    return 'Case #{}: {}\n'.format(T, flips)
                if flipped.bin not in explored:
                    new_cand.append(flipped)
                    explored.add(flipped.bin)
        if len(new_cand) == 0:
            return 'Case #{}: IMPOSSIBLE\n'.format(T)
        cand = new_cand
        flips += 1
예제 #7
0
def write_shadow_regis(data_dir: str, writes: List[Tuple[int, int]]) -> None:
    """Write shadow registers:
    - prepares and burns into FLASH a binary application for initialization of shadow registers
    - the application is launched using "execute" command
    - after registers are written, the application do software reset to return back to boot-loader

    :param data_dir: absolute path of directory with data files
    :param writes: list of show register initialization tuples, that contain:
    - the first parameter is an address of the shadow register
    - second parameter represents 32-bit value (unsigned integer)
    The list may contain maximum 12 tuples
    """
    if TEST_IMG_CONTENT:
        return
    if NO_SHADOWS:
        return

    assert len(writes) <= 12
    write_shadows_app = load_binary(data_dir, "write_shadows",
                                    "write_shadows.bin")
    stack_ptr = int.from_bytes(write_shadows_app[:4], byteorder="little")
    initial_pc = int.from_bytes(write_shadows_app[4:8], byteorder="little")
    # write_shadow is an application, that contains table of 12 writes, for each write 32 bit address and 32-bit value
    write_shadows_arr = BitArray(write_shadows_app)
    # now we construct an existing table content to be replaced
    datatable_old = "0x"
    for index in range(12):
        char = hex(index)[2:]
        datatable_old += "d" + char + "debabe"
        datatable_old += "2" + char + "436587"
    assert len(datatable_old) == 12 * 8 * 2 + 2
    # this is new table content
    datatable_new = bytes()
    for (addr, value) in writes:
        datatable_new += pack("<I", value)
        datatable_new += pack("<I", addr)
    # the table must contain 12 entries, so first entry is repeated, until table is full needed
    for _ in range(12 - len(writes)):
        datatable_new += pack("<I", writes[0][1])  # value
        datatable_new += pack("<I", writes[0][0])  # addr
    assert len(datatable_new) == 12 * 8
    # replace the table in the image
    res = write_shadows_arr.replace(datatable_old,
                                    datatable_new,
                                    bytealigned=True)
    assert res == 1
    # burn image into FLASH
    mboot = burn_img_via_usb_into_flexspi_flash(data_dir,
                                                write_shadows_arr.bytes)
    assert mboot is not None

    assert mboot.execute(initial_pc, 0x8001000, stack_ptr)
    mboot.close()
    sleep(2)  # wait until boot-loader is restarted
 def testReplace(self):
     s = BitArray("0b01")
     s.replace("0b1", "0b11")
     self.assertEqual(s, "0b011")
예제 #9
0
 def testReplace(self):
     s = BitArray('0b01')
     s.replace('0b1', '0b11')
     self.assertEqual(s, '0b011')
예제 #10
0
 def testReplace(self):
     s = BitArray('0b01')
     s.replace('0b1', '0b11')
     self.assertEqual(s, '0b011')
예제 #11
0
def getgps(old_dt):
    #    k = sub.find('0x851200',bytealigned = True)
    #    if len(k) == 0:
    #        gps = 'N/A'
    #        return gps

    try:
        sub.find('0x85000004', bytealigned=True)

        sub.pos += 32
        #read 0x850000 - GPS Ver
        gpsver = sub.read(4 * 8)

        sub.pos += 32
        #read 0x8501 - Latitude Ref (N or S)
        latref = BitArray(sub.read(8))
        latref = latref.tobytes().decode('utf-8')
        sub.pos += 32
        # read 0x8502 - latiture (6 chunks)
        l1 = sub.read(4 * 8).uint
        l2 = sub.read(4 * 8).uint
        l3 = sub.read(4 * 8).uint
        l4 = sub.read(4 * 8).uint
        l5 = sub.read(4 * 8).uint
        l6 = sub.read(4 * 8).uint

        if (l2 == 0 or l4 == 0 or l6 == 0):
            gps = 'N/A'
            return gps

        #write latitute string for text output
        lat = str(l1 / l2) + '°' + str(l3 / l4) + "'" + str(
            float(l5) / float(l6)) + '"'
        latdd = round((float(l1) / float(l2) + (float(l3) / float(l4)) / 60 +
                       (float(l5) / float(l6) /
                        (60 * 60)) * (-1 if latref in ['W', 'S'] else 1)), 7)

        sub.pos += 32
        #read 0x8503 - longtitude ref (E or W)
        lonref = BitArray(sub.read(8))
        lonref = lonref.tobytes().decode('utf-8')
        # read 0x8504 - lontgiture (6 chunks)
        sub.pos += 32
        l1 = sub.read(4 * 8).uint
        l2 = sub.read(4 * 8).uint
        l3 = sub.read(4 * 8).uint
        l4 = sub.read(4 * 8).uint
        l5 = sub.read(4 * 8).uint
        l6 = sub.read(4 * 8).uint

        if (l2 == 0 or l4 == 0 or l6 == 0):
            gps = 'N/A'
            return gps

        #write latitute string for text output
        lon = str(float(l1) / float(l2)) + '°' + str(
            float(l3) / float(l4)) + "'" + str(float(l5) / float(l6)) + '"'
        londd = round((float(l1) / float(l2) + float(l3) / float(l4) / 60 +
                       (float(l5) / float(l6) /
                        (60 * 60)) * (-1 if lonref in ['W', 'S'] else 1)), 7)
        k = sub.find('0x85050001', bytealigned=True)
        if len(k) != 0:
            sub.pos += 32
            #read 0x8505 - 1 bytes = AltitudeRef (0 = above sea level, 1 = below sea level)
            x8505 = sub.read(8).uint

            sub.pos += 32
            #read 0x8506 - 8 bytes ([4]/[4]) - Altitude
            x8506_1 = sub.read(4 * 8).uint
            x8506_2 = sub.read(4 * 8).uint

            x8506 = str(float(x8506_1) / float(x8506_2))
        else:
            x8505 = None

        sub.pos += 32
        # read 0x8507 - timestamp (6 chunks)
        l1 = sub.read(4 * 8).uint
        l2 = sub.read(4 * 8).uint
        l3 = sub.read(4 * 8).uint
        l4 = sub.read(4 * 8).uint
        l5 = sub.read(4 * 8).uint
        l6 = sub.read(4 * 8).uint
        if (l2 == 0 or l4 == 0 or l6 == 0):
            gps = 'N/A'
            return gps
        #write timestamp for text output (hh:mm:ss.xxx)
        gpsts = str(int(float(l1) / float(l2))).zfill(2) + ':' + str(
            int(float(l3) / float(l4))).zfill(2) + ":" + str(
                int(float(l5) / float(l6))).zfill(2)
        #print (gpsts)

        sub.pos += 32
        #read 0x8509 - GPS fix STATUS (not used yet)
        gpsfix = BitArray(sub.read(8))
        gpsfix = gpsfix.tobytes().decode('utf-8')

        sub.pos += 32
        # read 0x850a - GPS Measure mode (2 = 2D, 3 = 3D) - not used yet
        gpsmeasure = BitArray(sub.read(8))
        gpsmeasure = gpsmeasure.tobytes().decode('utf-8')

        sub.pos += 32
        #read 0x850b -  8 bytes ([4]/[4]) -- DOP -not used yet
        x850b_1 = sub.read(4 * 8).uint
        x850b_2 = sub.read(4 * 8).uint

        x850b = str(float(x850b_1) / float(x850b_2))

        if sub.read(4 * 8) == '0x850c0001':
            #read 0x850c -  1 byte - SpeedRef (K = km/h, M = mph, N = knots)
            x850c = BitArray(sub.read(8))
            x850c = x850c.tobytes().decode('utf-8')

            sub.pos += 32
            #read 0x850d - 8 bytes ([4]/[4]???) - SPEED
            x850d_1 = sub.read(4 * 8).uint
            x850d_2 = sub.read(4 * 8).uint

            x850d = round(float(x850d_1) / float(x850d_2), 2)
        else:
            x850d = 'N/A'

        if sub.read(4 * 8) == '0x850e0001':
            #read 0x850e - 1 byte - TrackRef (Direction Reference, T = True direction, M = Magnetic direction)
            x850e = BitArray(sub.read(8))
            x850e = x850e.tobytes().decode('utf-8')

            sub.pos += 32
            #read 0x850f - Course 8 bytes ([4]/[4]) (degrees from 0.0 to 359.99)
            x850f_1 = sub.read(4 * 8).uint
            x850f_2 = sub.read(4 * 8).uint

            x850f = round(float(x850f_1) / float(x850f_2), 2)
        else:
            x850f = 'N/A'

        #write full lat + lon + timestamp for text output

        if latref == None or lonref == None: gps = 'N/A'
        else:
            gps = lat + str(latref) + ' ' + lon + str(lonref) + ' ' + gpsts
        # debug
        #gps = gps + '\n' +str(x8505) + ' ' + str(x8506) + ' ' + str(gpsfix) + ' ' + str(gpsmeasure) + ' ' + str(x850b) + ' ' + str(x850c) + ' ' + str(x850d) + ' ' + str(x850e) + ' ' + str(x850f)
        if x850d != 'N/A' or x850f != 'N/A':
            gps = gps + '\n' 'Speed: ' + str(x850d) + 'km/h   Course: ' + str(
                x850f)

        k = sub.find('0x851d000a', bytealigned=True)
        sub.pos += 32
        gpxdate = BitArray(sub.read(8 * 10))
        gpxdate = gpxdate.tobytes().decode('utf-8')
        gpxdate = gpxdate.replace(':', '-')
        gpxdate = gpxdate + 'T' + gpsts + 'Z'
        dt = datetime.strptime(gpxdate, '%Y-%m-%dT%H:%M:%SZ')

        #print (lat,lon, x850d, x850f)

        #write GPX.

        if (args.gpx
                and 'ExifGPS'.encode() in exifchk) and old_dt < dt.timestamp():
            if x8505 != None:
                gpx_point = gpxpy.gpx.GPXTrackPoint(
                    latdd,
                    londd,
                    position_dilution=x850b,
                    type_of_gpx_fix=(gpsmeasure + 'd'),
                    elevation=(float(x8506) * (-1 if x8505 == 1 else 1)),
                    time=datetime(dt.year, dt.month, dt.day, dt.hour,
                                  dt.minute, dt.second))
            else:
                gpx_point = gpxpy.gpx.GPXTrackPoint(
                    latdd,
                    londd,
                    position_dilution=x850b,
                    type_of_gpx_fix=(gpsmeasure + 'd'),
                    time=datetime(dt.year, dt.month, dt.day, dt.hour,
                                  dt.minute, dt.second))
            gpx_segment.points.append(gpx_point)

            #GPX EXT TEST AREA

            namespace = '{gpxtx}'
            nsmap = {'gpxtpx': namespace[1:-1]}  #
            root = mod_etree.Element(namespace + 'TrackPointExtension')

            subnode1 = mod_etree.SubElement(root, namespace + 'speed')
            subnode2 = mod_etree.SubElement(root, namespace + 'course')
            if x850d != 'N/A' and x850c == 'K':
                subnode1.text = str(round(x850d_1 / x850d_2 / 3.6, 2))
            elif x850d != 'N/A' and x850c == 'M':
                subnode1.text = str(round(x850d_1 / x850d_2 / 2.23694, 2))
            elif x850d != 'N/A' and x850c == 'N':
                subnode1.text = str(round(x850d_1 / x850d_2 / 1.94384, 2))

            if x850f != 'N/A':
                subnode2.text = str(x850f)
            gpx.nsmap = nsmap
            if x850d != 'N/A' or x850f != 'N/A':
                gpx_point.extensions.append(root)
            old_dt = dt.timestamp()

    except (bitstring.ReadError, UnicodeDecodeError):
        return 'N/A'

    return gps, old_dt