示例#1
0
    def syncADC(self):
        #turn on ADC test mode
        print("FEMB_CONFIG--> Start sync ADC")
        reg3 = self.femb.read_reg(3)
        newReg3 = (reg3 | 0x80000000)

        self.femb.write_reg(3, newReg3)  #31 - enable ADC test pattern
        time.sleep(0.1)
        alreadySynced = True
        for a in range(0, self.NASICS, 1):
            print("FEMB_CONFIG--> Test ADC " + str(a))
            unsync = self.testUnsync(a)
            if unsync != 0:
                alreadySynced = False
                print("FEMB_CONFIG--> ADC not synced, try to fix")
                self.fixUnsync(a)
        self.REG_LATCHLOC1_4_data = self.femb.read_reg(self.REG_LATCHLOC1_4)
        self.REG_LATCHLOC5_8_data = self.femb.read_reg(self.REG_LATCHLOC5_8)
        self.REG_CLKPHASE_data = self.femb.read_reg(self.REG_CLKPHASE)
        print("FEMB_CONFIG--> Latch latency " + str(hex(self.REG_LATCHLOC1_4_data)) \
                        + str(hex(self.REG_LATCHLOC5_8_data )) + \
                        "\tPhase " + str(hex(self.REG_CLKPHASE_data)))
        self.femb.write_reg(3, (reg3 & 0x7fffffff))
        self.femb.write_reg(3, (reg3 & 0x7fffffff))
        print("FEMB_CONFIG--> End sync ADC")
        return not alreadySynced, self.REG_LATCHLOC1_4_data, self.REG_LATCHLOC5_8_data, self.REG_CLKPHASE_data
    def checkFirmwareVersion(self):
        #set UDP ports to WIB
        self.wib_reg_enable()

        #check WIB fw version reg
        wibVerReg = self.femb.read_reg(255)
        if wibVerReg == None :
            return False
        wibVerReg = (wibVerReg & 0xFFF)

        #set UDP ports back to normal
        self.selectFemb(self.fembNum)

        fembVerReg = self.femb.read_reg(257)

        if fembVerReg == None :
            return False
        fembVerReg = (fembVerReg & 0xFFF)

        if wibVerReg != 0x122 and wibVerReg != 0x111:
            print("Invalid WIB firmware version detected",hex(wibVerReg),"this configuration requires version 0x108 or 0x111")
            return False
        if fembVerReg != 0x501 :
            print("Invalid FEMB firmware version detected",hex(fembVerReg),"this configuration requires version 0x501")
            return False
        
        print( "WIB Firmware Version: " + str(hex(wibVerReg)) )
        print( "FEMB Firmware Version: " + str(hex(fembVerReg)) )

        #good firmware id
        return True
def make_chisel():
  print('/* Automatically generated by parse_opcodes */')
  print('object Instructions {')
  for name in namelist:
    print_chisel_insn(name)
  print('}')
  print('object Causes {')
  for num, name in causes:
    print('  val %s = %s' % (name.lower().replace(' ', '_'), hex(num)))
  print('  val all = {')
  print('    val res = collection.mutable.ArrayBuffer[Int]()')
  for num, name in causes:
    print('    res += %s' % (name.lower().replace(' ', '_')))
  print('    res.toArray')
  print('  }')
  print('}')
  print('object CSRs {')
  for num, name in csrs+csrs32:
    print('  val %s = %s' % (name, hex(num)))
  print('  val all = {')
  print('    val res = collection.mutable.ArrayBuffer[Int]()')
  for num, name in csrs:
    print('    res += %s' % (name))
  print('    res.toArray')
  print('  }')
  print('  val all32 = {')
  print('    val res = collection.mutable.ArrayBuffer(all:_*)')
  for num, name in csrs32:
    print('    res += %s' % (name))
  print('    res.toArray')
  print('  }')
  print('}')
示例#4
0
def validate_wire_bytestream(bytestream, expected, address_index):
    for i, d in enumerate(bytearray(bytestream.data)):
        print(hex(d), hex(expected[i]))
        if i == address_index:
            assert d == 0
        else:
            assert d == expected[i]
示例#5
0
def get_I2C_devices_list():
    device_list = []
    bus_number = 1  # 1 indicates /dev/i2c-1
    bus = smbus.SMBus(bus_number)
    timeout = 4  #seconds
    now = time.time()
    for device in range(3, 128):
        try:
            bus.write_byte(device, 0)
            device_list.append("{0}".format(hex(device)))

        except:
            print("I2C bus not working")
            a = 1

        later = time.time()
        difference = int(later - now)
        print("I2C address", hex(device), " Scan Time passed", difference)
        if difference > timeout:
            logger.warning("Timeout Error, not able to scan the I2C devices")
            break

    bus.close()
    bus = None
    return device_list
示例#6
0
def make_verilog(match, mask):
    """
    Generate verilog for decoding all of the ISE instructions.
    """

    src_wire = "encoded"
    ise_args = set([])
    dec_wires = set([])

    for instr in namelist:
        wirename = make_dec_wirename(instr)
        tw = "wire %s = " % (wirename.ljust(15))

        tw += "(%s & 32'h%s) == 32'h%s;" % (src_wire, hex(
            mask[instr])[2:], hex(match[instr])[2:])

        dec_wires.add(wirename)

        print(tw)

        for arg in arguments[instr]:
            ise_args.add(arg)

    for field in ise_args:
        wirename = "dec_arg_%s" % field.lower().replace(".", "_")
        wirewidth = (arglut[field][0] - arglut[field][1])
        tw = "wire [%d:0] %s = encoded[%d:%d];" % (
            wirewidth, wirename.ljust(15), arglut[field][0], arglut[field][1])
        print(tw)

    invalidinstr = "wire dec_invalid_opcode = !(" + \
        " || ".join(list(dec_wires)) +  \
        ");"
    print(invalidinstr)
示例#7
0
        def recursive_dump(task_spec, indent):
            if task_spec in done:
                return '[shown earlier] %s (%s:%s)' % (
                    task_spec.name, task_spec.__class__.__name__,
                    hex(id(task_spec))) + '\n'

            done.add(task_spec)
            dump = '%s (%s:%s)' % (task_spec.name, task_spec.__class__.
                                   __name__, hex(id(task_spec))) + '\n'
            if verbose:
                if task_spec.inputs:
                    dump += indent + '-  IN: ' + \
                        ','.join(['%s (%s)' % (t.name, hex(id(t)))
                                  for t in task_spec.inputs]) + '\n'
                if task_spec.outputs:
                    dump += indent + '- OUT: ' + \
                        ','.join(['%s (%s)' % (t.name, hex(id(t)))
                                  for t in task_spec.outputs]) + '\n'
            sub_specs = ([task_spec.spec.start] if hasattr(task_spec, 'spec')
                         else []) + task_spec.outputs
            for i, t in enumerate(sub_specs):
                dump += indent + '   --> ' + \
                    recursive_dump(
                        t, indent + ('   |   ' if i + 1 < len(sub_specs) else
                                     '       '))
            return dump
示例#8
0
    def Get_Packet_CRC(self, packet):
        """
        Receive packet as string and retrun string of CRC (32bit.
        For example:
        packet='00000000000100000000000200000000'
        CRC=f5c7f557
        :param packet: packet
        :type: string
        :return: string
        """
        int_Temp = binascii.crc32(binascii.a2b_hex(packet))
        if int_Temp > 0:
            temp = hex(int_Temp)
        else:
            pos_temp = int_Temp & 0xffffffff
            temp = hex(pos_temp)
        crc = temp[2:]
        if len(crc) < 8:
            crc = '0' * (8 - len(crc)) + crc
        if crc[len(crc) - 1] == 'L':
            crc = crc[:len(crc) - 1]
        h = list(crc)
        for i in range(old_div(len(crc), 2)):
            h[2 * i] = crc[(len(crc) - 1) - (2 * i + 1)]
            h[2 * i + 1] = crc[(len(crc) - 1) - (2 * i)]

        return "".join(h)
示例#9
0
    def update(self, rcv_time, msg):
        # TODO: it may be worth while verifying this is the correct stats
        # response before doing this
        self.reply_pending = False
        jsondict = msg.to_jsondict()

        if self.db_update_counter == self.conf.db_update_counter:
            self.refresh_switchdb()
            switch_object = {
                '_id': str(hex(self.dp.dp_id)),
                'data': {
                    'flows': []
                }
            }
            self.switch_database.insert_update_doc(switch_object, 'data')
            try:
                rows = self.switch_database.get_docs(
                    self.conf.views['switch_view'],
                    key=str(hex(self.dp.dp_id)))
                switch = rows[0]
            except IndexError:
                switch = None

            if switch:
                self.refresh_flowdb()
                for f_msg in jsondict['OFPFlowStatsReply']['body']:
                    flow_object = {'data': f_msg, 'tags': []}
                    flow_id = self.flow_database.insert_update_doc(
                        flow_object, '')
                    switch.value['data']['flows'].append(flow_id)
                    self.switch_database.insert_update_doc(
                        switch.value, 'data')
        self.db_update_counter -= 1
        if not self.db_update_counter:
            self.db_update_counter = self.conf.db_update_counter
示例#10
0
def aes_unwrap_key(kek, wrapped, iv=0xa6a6a6a6a6a6a6a6):
    key, key_iv = aes_unwrap_key_and_iv(kek, wrapped)
    if key_iv != iv:
        raise ValueError(
            "Integrity Check Failed: " + hex(key_iv) + " (expected " + hex(
                iv) + ")")
    return key
示例#11
0
    def __init__(self):

        xbmc.log("Reading Settings.xml")
        if int(xbmc.getInfoLabel('System.BuildVersion')[:2]) < 18:
            XBMC_DIALOG_BUSY_OPEN = "ActivateWindow(busydialog)"
            XBMC_DIALOG_BUSY_CLOSE = "Dialog.Close(busydialog)"

        from uuid import getnode as get_mac

        if hasattr(os, 'uname'):
            system = os.uname()[4]
        else:
            import platform
            system = platform.uname()[5]
        if system == 'armv6l':
            try:
                mac = open('/sys/class/net/eth0/address').readline()
                self.XNEWA_MAC = hex(int('0x' + mac.replace(':', ''), 16))
            except:
                self.XNEWA_MAC = str(hex(get_mac()))
        else:
            self.XNEWA_MAC = str(hex(get_mac()))

        self.loadFromSettingsXML()
        return
示例#12
0
 def acquire(self):
     """ Acquire control from libusb of the AlienFX controller."""
     if self._control_taken:
         return
     self._dev = usb.core.find(
         idVendor=self._controller.vendor_id, 
         idProduct=self._controller.product_id)
     if (self._dev is None):
         msg = "ERROR: No AlienFX USB controller found; tried "
         msg += "VID {}".format(self._controller.vendor_id)
         msg += ", PID {}".format(self._controller.product_id)
         logging.error(msg)
     try:
         self._dev.detach_kernel_driver(0)
     except USBError as exc: 
         logging.error(
             "Cant detach kernel driver. Error : {}".format(exc.strerror))
     try:
         self._dev.set_configuration()
     except USBError as exc: 
         logging.error(
             "Cant set configuration. Error : {}".format(exc.strerror))
     try:
         usb.util.claim_interface(self._dev, 0)
     except USBError as exc: 
         logging.error(
             "Cant claim interface. Error : {}".format(exc.strerror))
     self._control_taken = True
     logging.debug("USB device acquired, VID={}, PID={}".format(
         hex(self._controller.vendor_id), hex(self._controller.product_id)))
示例#13
0
def try_replica_exchange(sampler1, sampler2):
    sm1 = sampler1.sm
    sm2 = sampler2.sm
    sm1e2 = sampler2.energy_function.eval_energy(sm1.bg,
                                                 sampled_stats=sm1.elem_defs)
    sm2e1 = sampler1.energy_function.eval_energy(sm2.bg,
                                                 sampled_stats=sm2.elem_defs)
    sm1e1 = sampler1.prev_energy
    sm2e2 = sampler2.prev_energy
    total_prev_e = sm1e1 + sm2e2
    total_exchanged_e = sm1e2 + sm2e1
    p = np.exp(total_prev_e - total_exchanged_e
               )  #np.exp can return inf instead of raising an Overflow error
    p = min(1, p)
    r = random.random()
    if r <= p:
        sampler1.sm = sm2
        sampler2.sm = sm1
        sampler1.accept(sm2e1)
        sampler2.accept(sm1e2)
        movestring = "RE {}<->{};A".format(hex(id(sampler1)),
                                           hex(id(sampler2)))
    else:
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", NoopRevertWarning)
            sampler1.reject()
            sampler2.reject()
        movestring = "RE {}xxx{};R".format(hex(id(sampler1)),
                                           hex(id(sampler2)))

    for sampler in [sampler1, sampler2]:
        sampler.stats_collector.update_statistics(sampler.sm,
                                                  sampler.prev_energy,
                                                  sampler.prev_constituing,
                                                  movestring)
示例#14
0
def print_recipe(recipe):
    print("Md5sum:", recipe["md5sum"])
    print("Size  :", recipe["size"])
    print("Method:", recipe['method'])
    print("Pieces:", len(recipe['pieces']))
    pos = 0
    dedup_size = 0
    for p in recipe['pieces']:
        print("  Original     :", p['original'])
        print("  Source blob  :", p['source'] if p['source'] else "SELF")
        print("  Source offset:", p['offset'])
        print("  Size         :", p['size'])
        print("  Position     : %s - %s" %
              (hex(pos), hex(pos + p['size'] * p.get('repeat', 1))))
        print("  Repeat       :", p.get('repeat', "(1)"))
        print("  ---------------")
        pos += p['size']
        if p['source'] == None:  # Count the parts we couldn't find elsewhere
            dedup_size += p['size']
    try:
        print("Dedup removed %s%% of original size" % round(
            (100.0 * (1.0 - float(dedup_size) / recipe["size"])), 1))
    except ZeroDivisionError:
        print("Zero size recipe")
        pass
示例#15
0
    def __init__(self):

        xbmc.log("Reading Settings.xml")

        if  int(xbmc.getInfoLabel('System.BuildVersion')[:2]) < 18:
            XBMC_DIALOG_BUSY_OPEN = "ActivateWindow(busydialog)"
            XBMC_DIALOG_BUSY_CLOSE = "Dialog.Close(busydialog)"

        from uuid import getnode as get_mac

        if hasattr(os, 'uname'):
            system = os.uname()[4]
        else:
            import platform
            system = platform.uname()[5]
        if system == 'armv6l':
            try:
                mac = open('/sys/class/net/eth0/address').readline()
                self.XNEWA_MAC = hex(int('0x'+ mac.replace(':',''),16))
            except:
                self.XNEWA_MAC = str(hex(get_mac()))
        else:
            self.XNEWA_MAC = str(hex(get_mac()))

        self.loadFromSettingsXML()
        return
示例#16
0
    def doAdcAsicConfig(self):
        print("Check ADC ASIC SPI")
        for regNum in range(self.REG_ADCSPI_BASE, self.REG_ADCSPI_BASE + 35,
                            1):
            val = self.femb.read_reg(regNum)
            if (val == None) or (val == -1):
                print("Error - FEMB register interface is not working.")
                continue
            print(str(hex(val)))

        #Write ADC ASIC SPI
        print("Program ADC ASIC SPI")
        self.femb.write_reg(self.REG_ASIC_SPIPROG, 1)
        time.sleep(0.1)
        self.femb.write_reg(self.REG_ASIC_SPIPROG, 1)
        time.sleep(0.1)

        print("Check ADC ASIC SPI Readback")
        for regNum in range(self.REG_ADCSPI_RDBACK_BASE,
                            self.REG_ADCSPI_RDBACK_BASE + 35, 1):
            val = self.femb.read_reg(regNum)
            if (val == None) or (val == -1):
                print("Error - FEMB register interface is not working.")
                continue
            print(str(hex(val)))
示例#17
0
    def INA226_write(self, device_address, reg_address, high_byte, low_byte):
        #Because of how the FPGA does I2C, you need to swap the high and low bytes going in and coming back out
        check_value = (high_byte << 8) + low_byte
        low_byte_shift = low_byte << 8
        value = low_byte_shift + high_byte
        self.femb_udp.write_reg(int(self.config["REGISTERS"]["REG_I2C_VALUE"]),
                                value)

        device_reg = (device_address << 16) + (reg_address << 8) + 2
        self.femb_udp.write_reg(
            int(self.config["REGISTERS"]["REG_I2C_CONFIG"]), device_reg)

        self.femb_udp.write_reg(
            int(self.config["REGISTERS"]["REG_I2C_ACTION"]), 1)
        self.femb_udp.write_reg(
            int(self.config["REGISTERS"]["REG_I2C_ACTION"]), 0)

        #The first 4 bits of the INA config register is reserved and can't be changed
        check = self.INA226_read(device_address, reg_address, 2) & 0x0FFF

        if (check != check_value):
            print(
                "config_functions --> I2C Power chip was not correctly written to!  Wanted {}, recieved {}"
                .format(hex(check_value), hex(check)))
        else:
            return True
示例#18
0
    def checkFirmwareVersion(self):
        #set UDP ports to WIB
        self.femb.UDP_PORT_WREG = 32000
        self.femb.UDP_PORT_RREG = 32001
        self.femb.UDP_PORT_RREGRESP = 32002

        #check WIB fw version reg
        wibVerReg = self.femb.read_reg(255)
        if wibVerReg == None:
            return False
        wibVerReg = (wibVerReg & 0xFFF)

        #set UDP ports back to normal
        self.selectFemb(self.fembNum)
        fembVerReg = self.femb.read_reg(257)
        if fembVerReg == None:
            return False
        fembVerReg = (fembVerReg & 0xFFF)
        #print( "FEMB Firmware Version HERE : " + str(hex(fembVerReg)) )
        if wibVerReg != 0x116:
            print("Invalid WIB firmware version detected " +
                  str(hex(wibVerReg)) +
                  ", this configuration requires version 0x116")
            return False
        if fembVerReg != 0x323:
            print("Invalid FEMB firmware version detected " +
                  str(hex(fembVerReg)) +
                  ", this configuration requires version 0x323")
            return False

        print("WIB Firmware Version : " + str(hex(wibVerReg)))
        print("FEMB Firmware Version : " + str(hex(fembVerReg)))

        #good firmware id
        return True
示例#19
0
        def recursive_dump(task_spec, indent):
            if task_spec in done:
                return '[shown earlier] %s (%s:%s)' % (
                    task_spec.name, task_spec.__class__.__name__,
                    hex(id(task_spec))) + '\n'

            done.add(task_spec)
            dump = '%s (%s:%s)' % (
                task_spec.name,
                task_spec.__class__.__name__, hex(id(task_spec))) + '\n'
            if verbose:
                if task_spec.inputs:
                    dump += indent + '-  IN: ' + \
                        ','.join(['%s (%s)' % (t.name, hex(id(t)))
                                  for t in task_spec.inputs]) + '\n'
                if task_spec.outputs:
                    dump += indent + '- OUT: ' + \
                        ','.join(['%s (%s)' % (t.name, hex(id(t)))
                                  for t in task_spec.outputs]) + '\n'
            sub_specs = ([task_spec.spec.start] if hasattr(
                task_spec, 'spec') else []) + task_spec.outputs
            for i, t in enumerate(sub_specs):
                dump += indent + '   --> ' + \
                    recursive_dump(
                        t, indent + ('   |   ' if i + 1 < len(sub_specs) else
                                     '       '))
            return dump
示例#20
0
    def pack(self, directory, output_file):
        total_filepath_lengths = 0
        # walk through dirs and get file paths, file sizes and add lengths of file paths
        for dirpath, dirnames, filenames in os.walk(directory):
            for filename in filenames:
                filepath = os.path.join(dirpath, filename)
                total_filepath_lengths += len(filepath)
                fil = File(filepath, 0, os.path.getsize(filepath), 0)
                self.files.append(fil)

        # start building file
        byte_buffer = self.magic
        byte_buffer += struct.pack("<H", self.version)
        byte_buffer += struct.pack("<I", len(self.files))
        byte_buffer += struct.pack("<I", self.unknown)
        
        # calculate first file offset based on header size
        offset = len(byte_buffer) + total_filepath_lengths + 13*len(self.files)
        print(total_filepath_lengths, hex(offset))

        for fil in self.files:
            fil.offset = offset
            offset += fil.size
            print(fil.path, hex(fil.offset))
            byte_buffer += struct.pack("<B%isIII" % len(fil.path), len(fil.path), fil.path, fil.size, fil.unk, fil.offset)

        with open(output_file, "wb") as f_out:
            f_out.write(byte_buffer)
            for fil in self.files:
                with open(fil.path, "rb") as f_in:
                    f_out.write(f_in.read())
示例#21
0
 def _unpack_colour(pkt):
     """ Unpack a colour value from the given packet and return it as a
     3-member tuple
     """
     red = hex(pkt[0] >> 4)
     green = hex(pkt[0] & 0xf)
     blue = hex(pkt[1] >> 4)
     return (red, green, blue)
示例#22
0
 def _unpack_colour(pkt):
     """ Unpack a colour value from the given packet and return it as a
     3-member tuple
     """
     red = hex(pkt[0] >> 4)
     green = hex(pkt[0] & 0xf)
     blue = hex(pkt[1] >> 4)
     return (red, green, blue)
示例#23
0
    def call_sync_adc(self):
        print("call_sync_adc")
        message = "Sync Error"
        isAlreadySynced, latchloc1, latchloc2, phase = self.femb_config.syncADC()
        if isAlreadySynced: 
           message = "Already Sync'd"
        else:

      	   message = "Sync'd: latch latency " + str(hex(latchloc1)) + str(hex(latchloc2)) + "\tPhase " + str(hex(phase))
        self.adc_sync_result["text"] = message
示例#24
0
def crc_test():
    correct_results = 0
    for number in range(len(utl_pa_au8BYTE_CRC8_LUT_TABLE_C)):
        crc_result = utl_vCalculateCrcFor8Bits(0x00, number)
        if crc_result != utl_pa_au8BYTE_CRC8_LUT_TABLE_C[number]:
            print(hex(crc_result) + ' : ' + hex(utl_pa_au8BYTE_CRC8_LUT_TABLE_C[number]))
        else:
            correct_results += 1

    print("correct_results : " + str(correct_results))
示例#25
0
    def _unpack_colour(pkt):
        """ Unpack a colour value from the given packet and return it as a
        3-member tuple

        TODO: This mist still be bullshit too
        """
        red = hex(pkt[0] >> 4)
        green = hex(pkt[0] & 0xf)
        blue = hex(pkt[1] >> 4)
        return (red, green, blue)
示例#26
0
    def _unpack_colour(self, pkt):
        """ Unpack a colour value from the given packet and return it as a
        3-member tuple

        TODO: This too might need improvement for newer controllers
        """
        red = hex(pkt[0] >> 4)
        green = hex(pkt[0] & 0xf)
        blue = hex(pkt[1] >> 4)
        return (red, green, blue)
示例#27
0
    def fixUnsync(self, asicNum):
        if asicNum == None:
            return None
        asicNumVal = int(asicNum)
        if (asicNumVal < 0) or (asicNumVal >= self.NASICS):
            return None

        initLATCH = self.femb.read_reg(self.REG_LATCHLOC)
        initPHASE = self.femb.read_reg(
            self.REG_ADC_CLK)  # remember bit 16 sample rate
        if (initLATCH == None) or (initPHASE == None):
            return None

        phases = [0, 1, 2, 3]
        #phases = [0,1,2,3,0,3,2,1]
        if self.COLD:
            phases = [0, 1, 2, 3, 0, 3, 2, 1]

        #loop through sync parameters
        for shift in range(4, 7, 1):
            shiftMask = (0xFF << 8 * asicNum)
            testShift = ((initLATCH & ~(shiftMask)) | (shift << 8 * asicNum))
            self.femb.write_reg(self.REG_LATCHLOC, testShift)
            time.sleep(0.01)
            for phase in phases:
                clkMask = (0x3 << 2 * asicNum)
                testPhase = ((initPHASE & ~(clkMask)) | (phase << 2 * asicNum))
                self.femb.write_reg(self.REG_ADC_CLK, testPhase)
                time.sleep(0.01)
                print("try shift: {} phase: {} testingUnsync...".format(
                    hex(testShift), hex(testPhase)))
                #try ADC config with new
                isBad = 0
                for test in range(0, 10, 1):
                    self.doAdcAsicConfig(asicNumVal)
                    self.checkAdcErrorCount(asicNumVal)
                    if self.adcSyncStatus == False:
                        isBad = 1
                        break
                if isBad == 1:
                    continue
                if self.adcSyncStatus == True:
                    print("FEMB_CONFIG--> ADC synchronized")
                    print("FEMB_CONFIG LATCHLOC ", hex(testShift), " , PHASE ",
                          hex(testPhase))
                    return True
        #if program reaches here, sync has failed
        print("Error: FEMB_CONFIG--> ADC SYNC process failed for ADC # " +
              str(asicNumVal))
        print(
            "Setting back to original values: LATCHLOC: {:#010x}, PHASE: {:#010x}"
            .format(initLATCH, initPHASE & 0xF))
        self.femb.write_reg(self.REG_LATCHLOC, initLATCH)
        self.femb.write_reg(self.REG_ADC_CLK, initPHASE)
        self.adcSyncStatus = False
示例#28
0
 def print_texts(self):
     print("key {} texts:".format(self.identifier))
     for pair in self.texts:
         if 'cipher' in pair:
             print("Ciphertext: {}".format(hex(pair['cipher'])), end=", ")
         else:
             print("Ciphertext: null", end=", ")
         if 'plain' in pair:
             print("Plaintext: {} (\"{}\")".format(
                 hex(pair['plain']), i2b(pair['plain'], size=self.size)))
         else:
             print("Plaintext: null")
示例#29
0
 def set_address(self, newaddress):
     commandlist = [0x01, newaddress]
     isok, address = self.get_data(commandlist, 0)
     if isok:
         print(
             "I2C Change address procedure initiated correctly, new address=",
             hex(address))
         time.sleep(5)
         return isok, hex(address)
     else:
         print("not able to read I2C address")
         return isok, 0
def print_verilog_insn(name):
  s = "wire dec_%-18s = " % name.replace('.', '_').lower()

  match_bits = match[name]
  mask_bits  = mask [name]

  match_bits = hex(match_bits)[2:]
  mask_bits  = hex(mask_bits )[2:]

  s += "(s1_instr & 32'h%s) == 32'h%s" % (mask_bits,match_bits)

  print(s + ";")
示例#31
0
def main():
    femb_config = CONFIG()
    femb_config.resetBoard()
    femb_config.initBoard()
    hadToSync, latch1, latch2, phase = femb_config.syncADC()
    femb_config.resetBoard()
    femb_config.initBoard()
    if hadToSync:
        print("Had to sync chips. Please change settings to:")
        print("Latch latency " + str(hex(latch1)) + str(hex(latch2)) +
              "\tPhase " + str(hex(phase)))
    else:
        print("All chips already sync'd")
示例#32
0
文件: evdev.py 项目: ajhager/copycat
    def __init__(self, display, filename):
        self._filename = filename

        fileno = os.open(filename, os.O_RDONLY)
        #event_version = EVIOCGVERSION(fileno).value

        id = EVIOCGID(fileno)
        self.id_bustype = id.bustype
        self.id_vendor = hex(id.vendor)
        self.id_product = hex(id.product)
        self.id_version = id.version

        name = EVIOCGNAME(fileno)
        try:
            name = name.decode('utf-8')
        except UnicodeDecodeError:
            try:
                name = name.decode('latin-1')
            except UnicodeDecodeError:
                pass
            
        try:
            self.phys = EVIOCGPHYS(fileno)
        except OSError:
            self.phys = ''
        try:
            self.uniq = EVIOCGUNIQ(fileno)
        except OSError:
            self.uniq = ''

        self.controls = []
        self.control_map = {}

        event_types_bits = (ctypes.c_byte * 4)()
        EVIOCGBIT(fileno, 0, event_types_bits)
        for event_type in get_set_bits(event_types_bits):
            if event_type not in event_types:
                continue
            max_code = event_types[event_type]
            nbytes = max_code // 8 + 1
            event_codes_bits = (ctypes.c_byte * nbytes)()
            EVIOCGBIT(fileno, event_type, event_codes_bits)
            for event_code in get_set_bits(event_codes_bits):
                control = _create_control(fileno, event_type, event_code)
                if control:
                    self.control_map[(event_type, event_code)] = control 
                    self.controls.append(control)

        os.close(fileno)

        super(EvdevDevice, self).__init__(display, name)
示例#33
0
    def __init__(self, display, filename):
        self._filename = filename

        fileno = os.open(filename, os.O_RDONLY)
        #event_version = EVIOCGVERSION(fileno).value

        id = EVIOCGID(fileno)
        self.id_bustype = id.bustype
        self.id_vendor = hex(id.vendor)
        self.id_product = hex(id.product)
        self.id_version = id.version

        name = EVIOCGNAME(fileno)
        try:
            name = name.decode('utf-8')
        except UnicodeDecodeError:
            try:
                name = name.decode('latin-1')
            except UnicodeDecodeError:
                pass

        try:
            self.phys = EVIOCGPHYS(fileno)
        except OSError:
            self.phys = ''
        try:
            self.uniq = EVIOCGUNIQ(fileno)
        except OSError:
            self.uniq = ''

        self.controls = []
        self.control_map = {}

        event_types_bits = (ctypes.c_byte * 4)()
        EVIOCGBIT(fileno, 0, event_types_bits)
        for event_type in get_set_bits(event_types_bits):
            if event_type not in event_types:
                continue
            max_code = event_types[event_type]
            nbytes = max_code // 8 + 1
            event_codes_bits = (ctypes.c_byte * nbytes)()
            EVIOCGBIT(fileno, event_type, event_codes_bits)
            for event_code in get_set_bits(event_codes_bits):
                control = _create_control(fileno, event_type, event_code)
                if control:
                    self.control_map[(event_type, event_code)] = control
                    self.controls.append(control)

        os.close(fileno)

        super(EvdevDevice, self).__init__(display, name)
示例#34
0
    def drawTextMode(self, qp, row=0, howMany=1):

        # draw background
        qp.fillRect(0, row * self.fontHeight,
                    self.CON_COLUMNS * self.fontWidth,
                    howMany * self.fontHeight + self.SPACER,
                    self.backgroundBrush)

        # set text pen&font
        qp.setFont(self.font)
        qp.setPen(self.textPen)

        cemu = ConsoleEmulator(qp, self.ROWS, self.CON_COLUMNS)

        page = self.transformationEngine.decorate()

        cemu.gotoXY(0, row)

        for i, c in enumerate(
                self.getDisplayablePage()
            [row * self.COLUMNS:(row + howMany) *
             self.COLUMNS]):  # TODO: does not apply all decorators

            w = i + row * self.COLUMNS

            if (w + 1) % self.COLUMNS == 0:
                hex_s = str(hex(c)[2:]).zfill(2)
            else:
                hex_s = str(hex(c)[2:]).zfill(2) + ' '

            qp.setPen(self.transformationEngine.choosePen(w))

            if self.transformationEngine.chooseBrush(w) is not None:
                qp.setBackgroundMode(1)
                qp.setBackground(self.transformationEngine.chooseBrush(w))

            # write hex representation
            cemu.write(hex_s, noBackgroudOnSpaces=True)
            # save hex position
            x, y = cemu.getXY()
            # write text
            cemu.writeAt(self.COLUMNS * 3 + self.gap + (w % self.COLUMNS), y,
                         self.cp437(c))
            # go back to hex chars
            cemu.gotoXY(x, y)
            if (w + 1) % self.COLUMNS == 0:
                cemu.writeLn()

            qp.setBackgroundMode(0)
示例#35
0
文件: m3_gdb.py 项目: mbus/m3-python
    def cmd_M(this, subcmd):
        preamble, data = subcmd.split(':')
        addr,size_bytes= preamble.split(',')
        addr,size_bytes = map(lambda x: int(x, 16), [addr, size_bytes])
        this.log.info('mem write: ' + hex(addr) + ' of ' + str(size_bytes))
        data = binascii.unhexlify(data) 
        while size_bytes > 0:
            b = struct.unpack("B", data[0])[0]
            this.log.debug('Writing ' + hex(b) + ' to ' \
                + hex(addr))

            size_bytes -= wr_size
            addr += wr_size 
            data = data[wr_size:]
        return 'OK'
示例#36
0
    def cmd_M(this, subcmd):
        preamble, data = subcmd.split(':')
        addr, size_bytes = preamble.split(',')
        addr, size_bytes = map(lambda x: int(x, 16), [addr, size_bytes])
        this.log.info('mem write: ' + hex(addr) + ' of ' + str(size_bytes))
        data = binascii.unhexlify(data)
        while size_bytes > 0:
            b = struct.unpack("B", data[0])[0]
            this.log.debug('Writing ' + hex(b) + ' to ' \
                + hex(addr))

            size_bytes -= wr_size
            addr += wr_size
            data = data[wr_size:]
        return 'OK'
示例#37
0
    def collect(self):
        for session, wndsta, clip, handle in self.calculate():
            # If no tagCLIP is provided, we do not know the format
            if not clip:
                fmt = obj.NoneObject("Format unknown")
            else:
                # Try to get the format name, but failing that, print
                # the format number in hex instead.
                if clip.fmt.v() in constants.CLIPBOARD_FORMAT_ENUM:
                    fmt = str(clip.fmt)
                else:
                    fmt = hex(clip.fmt.v())

            # Try to get the handle from tagCLIP first, but
            # fall back to using _HANDLEENTRY.phead. Note: this can
            # be a value like DUMMY_TEXT_HANDLE (1) etc.
            handle_value = clip.hData or handle.phead.h

            clip_data = ""
            if handle and "TEXT" in fmt:
                clip_data = handle.reference_object().as_string(fmt)

            print(handle)

            yield dict(session=session.SessionId,
                       window_station=wndsta.Name,
                       format=fmt,
                       handle=handle_value,
                       object=handle.phead.v(),
                       data=clip_data,
                       hexdump=handle.reference_object().as_hex())
示例#38
0
文件: pcap.py 项目: biddyweb/rohc
    def parse_block(self):
        """read and parse a block"""
        if self.head is not None:
            block_header = self.head + self.infile.read(8 - len(self.head))
            self.head = None
        else:
            block_header = self.infile.read(8)
        if len(block_header) < 8:
            return None
        block_type, block_len = struct.unpack(self.section_info.byteorder + b'II', block_header)

        data = ''
        micro_second = 0
        if block_type == BlockType.SECTION_HEADER:
            self.parse_section_header_block(block_header)
        elif block_type == BlockType.INTERFACE_DESCRIPTION:
            # read link type and capture size
            self.parse_interface_description_block(block_len)
        elif block_type == BlockType.ENHANCED_PACKET:
            micro_second, data = self.parse_enhanced_packet(block_len)
        elif block_type > 0x80000000:
            # private protocol type, ignore
            data = self.infile.read(block_len - 12)
        else:
            self.infile.read(block_len - 12)
            print("unknown block type:%s, size:%d" % (hex(block_type), block_len), file=sys.stderr)

        # read author block_len
        block_len_t = self.infile.read(4)
        block_len_t, = struct.unpack(self.section_info.byteorder + b'I', block_len_t)
        if block_len_t != block_len:
            print("block_len not equal, header:%d, tail:%d." % (block_len, block_len_t),
                  file=sys.stderr)
        return micro_second, data
示例#39
0
def hex(x):
    if isinstance(x, bytes):
        return "0x" + binascii.hexlify(x).decode("utf-8")
    elif isinstance(x, str):
        return "0x" + binascii.hexlify(x.encode("utf-8")).decode("utf-8")
    else:
        return builtins.hex(x)
示例#40
0
文件: m3_mbus.py 项目: mbus/m3-python
 def update_base_addr(this, base_addr):
     '''
     used to update the base pointer of the register file
     '''
     this.log.debug('Update Base Addr: ' + hex(base_addr))
     this.base_addr = base_addr
     this.local = {} # clear local reg cache
示例#41
0
文件: m3_mbus.py 项目: mbus/m3-python
    def __setitem__(this,key,val):
        '''
        note: by default this only caches updates locally
        '''
        this.log.debug("RegWr: " + str(key) + ':' + hex(val))

        if key in this.warn_names:
            this.log.warn('Writing: ' + str(key) + ' as 0')
            return 0
        elif key in this.warn_trans_names:
            this.log.warning('Writing' + str(this.warn_trans_names[key]) + \
                            ' in place of ' + str(key))
            key = this.warn_trans_names[key] 
        elif key in this.trans_names:
            key = this.trans_names[key]

        assert( key in this.names)
        assert( isinstance(val, int))

        if (this.writeback):
            assert(this.base_addr != None)
            mem_addr = this.base_addr + this.offsets[key]
            this.mbus.write_mem(mem_addr,val,32)
        else: 
            this.local[key] = val
示例#42
0
def interpret_com_exception(excp, additional_info={}):  
    d = {}
    d['error_num'] = convert_error_code(excp.args[2][5])
    # for some reason hex() includes the L for long in the hex...
    # however since it's a string, we don't care... 
    # since L would never be in a hex code, we can safely just remove it. 
    d['error_code'] = hex(d['error_num']).rstrip('L')
    if d['error_code'][0:7] == '0x80005':
        if d['error_num'] in list(GENERIC_ADSI_ERRORS.keys()):
            d['exception_type'] = 'known_generic_adsi_error'
            d['error_constant'] = GENERIC_ADSI_ERRORS[d['error_num']][0]
            d['message'] = ' '.join(GENERIC_ADSI_ERRORS[d['error_num']][1:3])
        else:
            # this supposedly should not happen, but I'd rather be ready for
            # the case that Microsoft made a typo somewhere than die weirdly. 
            d['error_constant'] = None
            d['exception_type'] = 'unknown_generic_adsi_error'
            d['message'] = 'unknown generic ADSI error'
            d['exception'] = genericADSIException
    elif d['error_code'][0:6] == '0x8007':
        d['exception_type'] = 'win32_error'
        d['error_constant'] = None
        # returns information about error from winerror.h file... 
        d['message'] = win32api.FormatMessage(d['error_num']) 
    elif d['error_num'] in list(GENERIC_COM_ERRORS.keys()):
        d['exception_type'] = 'generic_com_error'
        d['error_constant'] = GENERIC_COM_ERRORS[d['error_num']][0]
        d['message'] = GENERIC_COM_ERRORS[d['error_num']][1]
    else:
        d['exception_type'] = 'unknown'
        d['error_constant'] = None
        d['message'] = excp.args[2][4]
    d['additional_info'] = additional_info={}
    return d
示例#43
0
 def release(self):
     """ Release control to libusb of the AlienFX controller."""
     if not self._control_taken:
         return
     try:
         usb.util.release_interface(self._dev, 0)
     except USBError as exc: 
         logging.error(
             "Cant release interface. Error : {}".format(exc.strerror))
     try:
         self._dev.attach_kernel_driver(0)
     except USBError as exc: 
         logging.error("Cant re-attach. Error : {}".format(exc.strerror))
     self._control_taken = False
     logging.debug("USB device released, VID={}, PID={}".format(
         hex(self._controller.vendor_id), hex(self._controller.product_id)))
示例#44
0
 def __init__(self, sec=0.010, delay=0, on=1, off=0, address=0x378, pin=2):
     if not have_parallel:
         raise ImportError("could not import parallel (for signaler)")
     super(ParallelVoiceKeySignal, self).__init__(sec, delay, on, off)
     self.id = '({0}, pin={1})'.format(hex(address), pin)
     self.address = address
     self.pin = pin  # 2-9
     self.port = parallel.ParallelPort(address)
示例#45
0
    def handle_emulator_get_cpu_state_request(self, params):
        # this function gets the CPU state on the target device
        assert(self.__target)

        # TODO: fire events?
        ret = {}

        for r in range(13):
            val = self.__target.get_register("r"+str(r))
            ret["cpu_state_"+"r"+str(r)] = hex(val)
        val = self.__target.get_register("sp")
        ret["cpu_state_r13"] = hex(val)
        val = self.__target.get_register("lr")
        ret["cpu_state_r14"] = hex(val)
        val = self.__target.get_register("pc")
        ret["cpu_state_pc"] = hex(val)
        return ret
示例#46
0
    def __init__(self):
        gtk.Bin.__init__(self)

        # Initialize logging
        self.log = getLogger('%s.%s' % (self.__gtype_name__, hex(id(self))))

        # Internal housekeeping
        self._placeholder = None
示例#47
0
文件: m3_gdb.py 项目: mbus/m3-python
 def cmd_P(this, subcmd):
     reg,val = subcmd.split('=')
     reg = int(reg, 16)
     reg = this.regs[ reg]
     # fix endiananess, conver to int
     val = int(binascii.hexlify( binascii.unhexlify(val)[::-1]),16)
     this.log.warn('register write :' + str(reg) + ' = ' + hex(val) )
     return "OK"
示例#48
0
 def get_id(self, grp):
     """
     Return a hash of the tuple of indices that specify the group
     """
     thehash = hex(hash(grp))
     if ISPY3:  # use default encoding to get bytes
         thehash = thehash.encode()
     return self.cache.get(grp, hashlib.sha1(thehash).hexdigest())
示例#49
0
文件: m3_gdb.py 项目: mbus/m3-python
 def cmd_m(this, subcmd):
     addr,size_bytes= subcmd.split(',')
     addr,size_bytes = map(lambda x: int(x, 16), [addr, size_bytes])
     this.log.info('mem read: ' + hex(addr) + ' of ' + str(size_bytes))
     if size_bytes == 4:
         return struct.pack('<I',0x46c046c0).encode('hex') #lit endian hex
     else: 
         return struct.pack('<H',0x46c).encode('hex') #lit endian hex
示例#50
0
文件: m3_gdb.py 项目: mbus/m3-python
 def cmd_z(this, subcmd):
     args = subcmd.split(',')
     brType, addr, size = map(lambda x: int(x,16), args)
     assert(brType == 0)
     assert(size == 2)
     this.log.info("Breakpoint Clear, Type: " + str(brType) + \
                     " Addr:" + hex(addr))
     this.log.debug("Replacing trap with origional instruction @" +\
                     hex(addr) )
     size *= 8 # convert to bites                                
     if (addr,size) not in this.displaced_insts:
         this.log.info( hex(addr) + '('+str(size)+')' + \
             'not a soft-breakpoint')
     else:
         orig_inst = this.displaced_insts[(addr,size)]
         this.mem.forceWrite( (addr,size), orig_inst)
         del this.displaced_insts[(addr,size)]
     return 'OK'
示例#51
0
文件: m3_mbus.py 项目: mbus/m3-python
    def write_reg(this, reg, val):

        this.log.debug('MBUS: writing register: ' + str(reg) + '=' + hex(val) )
        assert( reg < 8)
        assert( val < ((2 ** 24) -1) )

        mbus_regwr = struct.pack(">I", ( this.prc_addr << 4) | 0x0 ) 
        data = struct.pack(">I", reg << 24 | val )
        this.ice.mbus_send(mbus_regwr, data)
示例#52
0
 def sendRaw(self, cmd):
     command = list(cmd)
     hexCommand = list()
     if self.reeltwo == True:
         if __debug__:
            print("ReelTwo Mode");
         hexCommand.append(int(hex(ord('L')), 16))
         hexCommand.append(int(hex(ord('E')), 16))
     for i in command:
         h = int(hex(ord(i)), 16)
         hexCommand.append(h)	
     if __debug__:
         print(hexCommand)
     try:
         self.bus.write_i2c_block_data(int(self.address, 16), hexCommand[0], hexCommand[1:])
     except:
         print("Failed to send bytes")
     return "Ok"
示例#53
0
文件: utils.py 项目: little-dude/tgen
def int2bytes(value, length=0):
    hex_str = hex(value)[2:]
    if len(hex_str) % 2 == 1:
        hex_str = '0{}'.format(hex_str)
    byte_str = binascii.unhexlify(hex_str)
    if length > 0:
        while len(byte_str) < length:
            byte_str = b'\x00' + byte_str
    return byte_str
示例#54
0
文件: m3_gdb.py 项目: mbus/m3-python
 def cmd_Z(this, subcmd):
     args = subcmd.split(',')
     brType, addr, size = map(lambda x: int(x,16), args)
     assert(brType == 0)
     assert(size == 2)
     this.log.info("Breakpoint Set, Type:" + str(brType) + \
                             " Addr: " + hex(addr))
     this.log.debug("Replacing instruction @" + \
                     hex(addr) + " with trap" )
     size *= 8 # convert to bits
     if (addr,size) in this.displaced_insts: 
         this.log.debug( hex(addr) + '('+str(size)+')' + \
             'already a soft-breakpoint')
     else:
         this.displaced_insts[(addr,size)] = \
                 this.mem[(addr,size)]
         this.mem.forceWrite( (addr,16), this.svc_01)
     return 'OK'
示例#55
0
    def _set_power(self, devices, powerOn):
        """ set the power for devices """

        devStr = hex(devices).upper()[2:].zfill(4)
        if powerOn:
            setStr = devStr
        else:
            setStr = "0000"
        self._sendReq("S" + devStr + setStr + "\r")
示例#56
0
    def drawTextMode(self, qp, row=0, howMany=1):

        # draw background
        qp.fillRect(0, row * self.fontHeight, self.CON_COLUMNS * self.fontWidth,
                    howMany * self.fontHeight + self.SPACER, self.backgroundBrush)

        # set text pen&font
        qp.setFont(self.font)
        qp.setPen(self.textPen)

        cemu = ConsoleEmulator(qp, self.ROWS, self.CON_COLUMNS)

        page = self.transformationEngine.decorate()

        cemu.gotoXY(0, row)

        for i, c in enumerate(self.getDisplayablePage()[row * self.COLUMNS:(
            row + howMany) * self.COLUMNS]):  # TODO: does not apply all decorators

            w = i + row * self.COLUMNS

            if (w + 1) % self.COLUMNS == 0:
                hex_s = str(hex(c)[2:]).zfill(2)
            else:
                hex_s = str(hex(c)[2:]).zfill(2) + ' '

            qp.setPen(self.transformationEngine.choosePen(w))

            if self.transformationEngine.chooseBrush(w) is not None:
                qp.setBackgroundMode(1)
                qp.setBackground(self.transformationEngine.chooseBrush(w))

            # write hex representation
            cemu.write(hex_s, noBackgroudOnSpaces=True)
            # save hex position
            x, y = cemu.getXY()
            # write text
            cemu.writeAt(self.COLUMNS * 3 + self.gap + (w % self.COLUMNS), y, self.cp437(c))
            # go back to hex chars
            cemu.gotoXY(x, y)
            if (w + 1) % self.COLUMNS == 0:
                cemu.writeLn()

            qp.setBackgroundMode(0)
示例#57
0
文件: m3_mbus.py 项目: mbus/m3-python
    def write_mem(this, addr, value, size):
        
        this.log.debug('MBUS Writing ' + hex(value) + ' to ' + hex(addr))
        
        assert(isinstance(addr, int))
        assert(isinstance(value, int))
        assert(size in [32,16,8])

        align32 = this._align32(addr,size)

        if size == 32:
            write32 = value

        elif size == 16:
            byte_idx = addr & 0x02
            mask32 = ((2 ** size -1) << (8 * byte_idx))
            mask32n = 0xffffffff - mask32 # bitwise not hack

            orig32 = this.read_mem(align32,32)
            value32 =  value << size | value # just duplicate it
            value32 = value32 & mask32 # and mask it

            write32 = orig32 & mask32n 
            write32 = write32 | value32

        elif size == 8:
            byte_idx = addr & 0x3
            mask32 = ((2 ** size -1) << (8 * byte_idx))
            mask32n = 0xffffffff - mask32 # bitwise not hack
            
            orig32 = this.read_mem(align32,32)
            value32 = (value << (8 * byte_idx)) 
            value32 = value32 & mask32

            write32 = orig32 & mask32n
            write32 = write32 | value32

        this.log.debug("MBUS Writing " + hex(write32) + " @ " + \
                hex(align32))
        prc_memwr = struct.pack(">I", ( this.prc_addr << 4) | 0x2 ) 
        memwr_addr = struct.pack(">I", align32)  
        memwr_data = struct.pack(">I", write32)
        this.ice.mbus_send(prc_memwr, 
            memwr_addr + memwr_data) 
示例#58
0
文件: m3_gdb.py 项目: mbus/m3-python
 def cmd_P(this, subcmd):
     assert(this.prc.isHalted()) 
     reg,val = subcmd.split('=')
     reg = int(reg, 16)
     reg = this.regs[ reg]
     # fix endiananess, conver to int
     val = int(binascii.hexlify( binascii.unhexlify(val)[::-1]),16)
     this.log.info('register write :' + str(reg) + ' = ' + hex(val) )
     this.rf.forceWrite(reg,val)
     return "OK"
示例#59
0
文件: m3_gdb.py 项目: mbus/m3-python
    def cmd_m(this, subcmd):
        assert(this.prc.isHalted()) 
        args = subcmd.split(',')
        addr,size_bytes = map(lambda x: int(x, 16), args)

        this.log.info('mem read: ' + hex(addr) + ' of ' + \
                            str(size_bytes))

        resp = '' 
        while size_bytes > 0:
            read_bytes = 4 if size_bytes >4 else size_bytes
            encode_str = this.encode_str[read_bytes]
            val = this.mem[(addr,read_bytes * 8)]
            this.log.debug('mem read: ' + hex(addr) + ' ' + hex(val))
            val = struct.pack(encode_str, val).encode('hex')#lit endian
            resp += val
            addr += read_bytes
            size_bytes -= read_bytes
        return resp