Beispiel #1
0
 def _lowLevelClearDataBuffer(self, channel, segmentIndex):
     m = self.lib.ps3000aSetDataBuffer(c_int16(self.handle),
                                       c_enum(channel),
                                       c_void_p(), c_uint32(0),
                                       c_uint32(segmentIndex),
                                       c_enum(0))
     self.checkResult(m)
Beispiel #2
0
    def checksum(self, data, seed):
        """Calculate the checksum for system and data pages

        Args:
            data (bytes): Data buffer
            seed (int): Seed value

        Returns:
            Checksum value (int)
        """
        sum1 = ctypes.c_uint32(seed & 0xFFFF).value
        sum2 = ctypes.c_uint32(seed >> 0x10).value
        pos  = 0
        size = len(data)

        while size != 0:
            chunk_size = min(0x15B0, size)
            size -= chunk_size
            for idx in range(chunk_size):
                sum1 += data[pos]
                pos += 1
                sum2 += sum1
            sum1 %= 0xFFF1
            sum2 %= 0xFFF1

        sum = ctypes.c_uint32((sum2 << 0x10) | (sum1 & 0xFFFF)).value
        return sum
Beispiel #3
0
    def val(self):
        """
        The current value of this property
        """
        if self._name == "white_balance":
            # white has its own call since it returns 2 values
            blue = c_uint32()
            red = c_uint32()
            self._dll.dc1394_feature_whitebalance_get_value(
                    self._cam.cam, byref(blue), byref(red)
            )
            return blue.value, red.value

        if self._absolute_capable:
            val = c_float()
            self._dll.dc1394_feature_get_absolute_value(
                    self._cam.cam, self._id, byref(val)
            )

            if self._name == "shutter":
                # We want shutter in ms -> if it is absolute capable.
                val.value *= 1000.
        else:
            val = c_uint32()
            self._dll.dc1394_feature_get_value(
                    self._cam.cam, self._id, byref(val)
            )
        return val.value
Beispiel #4
0
def	init_by_array(init_key):
	key_length = len(init_key)

	#print("init_by_array len", key_length)

	init_genrand(19650218)
	i = 1
	j = 0
	k = N if N > key_length else key_length
	while (k > 0):
		mt[i] = ctypes.c_uint32((mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525)) + init_key[j] + j).value
		i += 1
		j += 1
		if (i >= N):
			mt[0] = mt[N - 1]
			i = 1
		if (j >= key_length):
			j = 0
		k -= 1

	k = N - 1
	while (k > 0):
		mt[i] = ctypes.c_uint32((mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941)) - i).value
		i += 1
		if (i >= N):
			mt[0] = mt[N - 1]
			i = 1
		k -= 1
	mt[0] = 0x80000000	# MSB is 1; assuring non-zero initial array
Beispiel #5
0
    def rtt_read_channel_info(self, channel_index, direction):
        """
        Reads the info from one RTT channel.

        @param int channel_index: RTT channel to request info.
        @param int, string, or RTTChannelDirection(IntEnum) direction: Direction of the channel to request info.
        @return string: Channel name.
        """
        if not self._is_u32(channel_index):
            raise ValueError('The channel_index parameter must be an unsigned 32-bit value.')

        if not self._is_enum(direction, RTTChannelDirection):
            raise ValueError('Parameter direction must be of type int, str or RTTChannelDirection enumeration.')

        direction = self._decode_enum(direction, RTTChannelDirection)
        if direction is None:
            raise ValueError('Parameter direction must be of type int, str or RTTChannelDirection enumeration.')

        channel_index = ctypes.c_uint32(channel_index)
        direction = ctypes.c_int(direction.value)
        name_len = ctypes.c_uint32(32)
        name = (ctypes.c_uint8 * 32)()
        size = ctypes.c_uint32()

        result = self._lib.NRFJPROG_rtt_read_channel_info(channel_index, direction, ctypes.byref(name), name_len, ctypes.byref(size))
        if result != NrfjprogdllErr.SUCCESS:
            raise APIError(result)

        return ''.join(chr(i) for i in name if i != 0), size.value
Beispiel #6
0
    def write(self, addr, data, control):
        """
        Writes data from the array into the device starting at the given address.

        @param int addr: Start address of the memory block to write.
        @param [int] data: List of values to write.
        @param boolean control: True for automatic control of NVMC by the function.
        """
        if not self._is_u32(addr):
            raise ValueError('The addr parameter must be an unsigned 32-bit value.')

        if not self._is_valid_buf(data):
            raise ValueError('The data parameter must be a tuple or a list with at least one item.')

        if not self._is_bool(control):
            raise ValueError('The control parameter must be a boolean value.')

        addr = ctypes.c_uint32(addr)
        data_len = ctypes.c_uint32(len(data))
        data = (ctypes.c_uint8 * data_len.value)(*data)
        control = ctypes.c_bool(control)

        result = self._lib.NRFJPROG_write(addr, ctypes.byref(data), data_len, control)
        if result != NrfjprogdllErr.SUCCESS:
            raise APIError(result)
Beispiel #7
0
    def raw_number_neg(self, num):
        """
        >>> p = Parser('')
        >>> p.raw_number_neg(-1)
        255
        >>> p.raw_number_neg(-12)
        244
        >>> p.raw_number_neg(-126)
        130
        >>> p.raw_number_neg(-127)
        65409
        >>> p.raw_number_neg(-200)
        65336
        >>> p.raw_number_neg(-40000) # doctest: +ELLIPSIS
        4294927296...
        >>> p.raw_number_neg(1) # doctest: +ELLIPSIS +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
        ...
        ValueError: Invalid logic, number should not be positive
        """
        if num >= 0:
            raise ValueError('Invalid logic, number should not be positive')

        #print (ctypes.c_uint8(-num).value, -num, int(0xff/2))
        if ctypes.c_uint8(-num).value == -num and -num < int(0xff/2):
            return ctypes.c_uint8(num).value
        if ctypes.c_uint16(-num).value == -num and -num < int(0xffff/2):
            return ctypes.c_uint16(num).value
        if ctypes.c_uint32(-num).value == -num and -num < int(0xffffffff/2):
            return ctypes.c_uint32(num).value

        return ctypes.c_uint64(num).value
def vc_get_dlimit(filename, xid):
    """Calls libvserver.vc_get_dlimit to get dlimit values for xid.

    Dlimits are applied to a specific directory path.

    Args:
      filename: str, path to slice root dir, where quota limits are applied.
      xid: int, xid of vserver.

    Returns:
      list of int, [space_used, space_total, inodes_used, inodes_total, reserved]
    """
    if _LIBVSERVER is None:
        if not init_libvserver():
            raise LibVserverError('Failed to initialize libvserver.')

    c_limit = vc_ctx_dlimit()
    c_filename = ctypes.c_char_p(filename)
    c_xid = ctypes.c_uint32(xid)

    err = _LIBVSERVER.vc_get_dlimit(c_filename, c_xid, ctypes.c_uint32(0),
                                    ctypes.byref(c_limit))

    if err != 0:
        raise LibVserverError('Failed to get dlimits for xid %s: %s' %
                              (xid, err))

    # '-1' means no quota.
    ret = [c_limit.space_used,
           c_limit.space_total,
           c_limit.inodes_used,
           -1 if (2**32) - 1 == c_limit.inodes_total else c_limit.inodes_total,
           c_limit.reserved]  # yapf: disable
    return ret
Beispiel #9
0
    def _lowLevelMemorySegments(self, nSegments):
        nMaxSamples = c_uint32()

        m = self.lib.ps6000MemorySegments(c_int16(self.handle), c_uint32(nSegments), byref(nMaxSamples))
        self.checkResult(m)

        return nMaxSamples.value
Beispiel #10
0
 def _rand_int(self):
     temp = self.a ^ ctypes.c_uint32(self.a << 11).value
     self.a = self.b
     self.b = self.c
     self.c = self.d
     self.d = ctypes.c_uint32((self.d ^ (self.d >> 19)) ^ (temp ^ (temp >> 8))).value
     return self.d
Beispiel #11
0
	def encode_transaction(self, input_num = None):

		# Start transaction
		trans = bytearray()
		trans += ctypes.c_uint32(self.version)
		trans += ctypes.c_uint8(len(self.inputs))

		# Go through inputs
		x=0
		for item in self.inputs:
			trans += item['txid'][::-1]
			trans += ctypes.c_uint32(item['vout'])

			if input_num == None or input_num == x:
				trans += self.encode_vint(len(item['sigscript']))
				trans += item['sigscript']
			else:
				trans += unhexlify('00')

			trans += item['sequence']
			x += 1

		# Go through outputs
		trans += ctypes.c_uint8(len(self.outputs))
		for item in self.outputs:

			# Add output
			trans += ctypes.c_uint64(int(item['amount'] * 1e8))
			trans += self.encode_vint(len(item['script']))
			trans += item['script']

		# Finish encoding
		trans += self.timelock
		return trans
Beispiel #12
0
    def _lowLevelSetAWGSimpleDeltaPhase(self, waveform, deltaPhase,
                                        offsetVoltage, pkToPk, indexMode,
                                        shots, triggerType, triggerSource):
        """ waveform should be an array of shorts. """

        waveformPtr = waveform.ctypes.data_as(POINTER(c_int16))

        m = self.lib.ps6000SetSigGenArbitrary(
            c_int16(self.handle),
            c_uint32(int(offsetVoltage * 1E6)),  # offset voltage in microvolts
            c_uint32(int(pkToPk * 1E6)),         # pkToPk in microvolts
            c_uint32(int(deltaPhase)),           # startDeltaPhase
            c_uint32(int(deltaPhase)),           # stopDeltaPhase
            c_uint32(0),                         # deltaPhaseIncrement
            c_uint32(0),                         # dwellCount
            waveformPtr,                         # arbitraryWaveform
            c_int32(len(waveform)),              # arbitraryWaveformSize
            c_enum(0),                           # sweepType for deltaPhase
            c_enum(0),            # operation (adding random noise and whatnot)
            c_enum(indexMode),                   # single, dual, quad
            c_uint32(shots),
            c_uint32(0),                         # sweeps
            c_uint32(triggerType),
            c_uint32(triggerSource),
            c_int16(0))                          # extInThreshold
        self.checkResult(m)
def create(volpath, kvDict):
    disk = c_uint32(0)
    objHandle = c_uint32(0)

    disk = volOpenPath(volpath)

    if disk == c_uint32(0):
        return False

    if useSideCarCreate:
        res = lib.DiskLib_SidecarCreate(disk, DVOL_KEY, KV_CREATE_SIZE,
                                        KV_SIDECAR_CREATE, byref(objHandle))
    else:
        res = lib.DiskLib_SidecarOpen(disk, DVOL_KEY, KV_SIDECAR_CREATE,
                                      byref(objHandle))

    if res != 0:
        logging.warning("Side car create for %s failed - %x", volpath, res)
        lib.DiskLib_Close(disk)
        return False

    lib.DiskLib_SidecarClose(disk, DVOL_KEY, byref(objHandle))
    lib.DiskLib_Close(disk)

    return save(volpath, kvDict)
def delete(volpath):
    """
    Delete the side car for the given volume.
    """
    vol_type = c_uint32(0)
    res = lib.ObjLib_PathToType(volpath.encode(), byref(vol_type))
    if res != 0:
        logging.warning("KV delete - could not determine type of volume %s, error - %x", volpath, res)
        return False
    if vol_type.value == c_uint32(KV_VOL_VIRTUAL).value:
        meta_file = lib.DiskLib_SidecarMakeFileName(volpath.encode(), DVOL_KEY.encode())
        if os.path.exists(meta_file):
            os.unlink(meta_file)
            return True

    # Other volume types are storage specific sidecars.
    dhandle = vol_open_path(volpath)
    if not disk_is_valid(dhandle):
        return False
    res = lib.DiskLib_SidecarDelete(dhandle, DVOL_KEY.encode())
    if res != 0:
        logging.warning("Side car delete for %s failed - %x", volpath, res)
        lib.DiskLib_Close(dhandle)
        return False

    lib.DiskLib_Close(dhandle)
    return True
Beispiel #15
0
    def call(self, friend_number, audio_bit_rate, video_bit_rate):
        """
        Call a friend. This will start ringing the friend.

        It is the client's responsibility to stop ringing after a certain timeout, if such behaviour is desired. If the
        client does not stop ringing, the library will not stop until the friend is disconnected. Audio and video
        receiving are both enabled by default.

        :param friend_number: The friend number of the friend that should be called.
        :param audio_bit_rate: Audio bit rate in Kb/sec. Set this to 0 to disable audio sending.
        :param video_bit_rate: Video bit rate in Kb/sec. Set this to 0 to disable video sending.
        :return: True on success.
        """
        toxav_err_call = c_int()
        result = self.libtoxav.toxav_call(self._toxav_pointer, c_uint32(friend_number), c_uint32(audio_bit_rate),
                                           c_uint32(video_bit_rate), byref(toxav_err_call))
        toxav_err_call = toxav_err_call.value
        if toxav_err_call == TOXAV_ERR_CALL['OK']:
            return bool(result)
        elif toxav_err_call == TOXAV_ERR_CALL['MALLOC']:
            raise MemoryError('A resource allocation error occurred while trying to create the structures required for '
                              'the call.')
        elif toxav_err_call == TOXAV_ERR_CALL['SYNC']:
            raise RuntimeError('Synchronization error occurred.')
        elif toxav_err_call == TOXAV_ERR_CALL['FRIEND_NOT_FOUND']:
            raise ArgumentError('The friend number did not designate a valid friend.')
        elif toxav_err_call == TOXAV_ERR_CALL['FRIEND_NOT_CONNECTED']:
            raise ArgumentError('The friend was valid, but not currently connected.')
        elif toxav_err_call == TOXAV_ERR_CALL['FRIEND_ALREADY_IN_CALL']:
            raise ArgumentError('Attempted to call a friend while already in an audio or video call with them.')
        elif toxav_err_call == TOXAV_ERR_CALL['INVALID_BIT_RATE']:
            raise ArgumentError('Audio or video bit rate is invalid.')
Beispiel #16
0
    def __init__(self):
       DISPLAY_ID = 0
       
       # create an EGL window surface, passing context width/height
       width = c_uint32(0)
       height = c_uint32(0)
       status = graphics_get_display_size(DISPLAY_ID, ctypes.byref(width), ctypes.byref(height))
       if status < 0:
           raise Exception("cannot obtain display size")
       self.width = width.value
       self.height = height.value

       dst_rect = VC_RECT_T(0, 0, self.width, self.height)
       src_rect = VC_RECT_T(0, 0, self.width << 16, self.height << 16)

       alpha = VC_DISPMANX_ALPHA_T(flags=DISPMANX_FLAGS_ALPHA_FIXED_ALL_PIXELS, opacity=255, mask=None)

       dispman_display = vc_dispmanx_display_open(DISPLAY_ID)
       dispman_update = vc_dispmanx_update_start(0)
             
       dispman_element = vc_dispmanx_element_add(dispman_update, dispman_display,
          0, ctypes.byref(dst_rect), 0,
          ctypes.byref(src_rect), DISPMANX_PROTECTION_NONE, ctypes.byref(alpha), None, 0)
          
       vc_dispmanx_update_submit_sync(dispman_update);

       self.window = EGL_DISPMANX_WINDOW_T(dispman_element, self.width, self.height)
Beispiel #17
0
    def set_dst(self, dst):
        if dst[0] == "!":
            self.entry.ip.invflags |= ipt_ip.IPT_INV_DSTIP
            dst = dst[1:]
        else:
            self.entry.ip.invflags &= ~ipt_ip.IPT_INV_DSTIP & \
                  ipt_ip.IPT_INV_MASK

        slash = dst.find("/")
        if slash == -1:
            addr = dst
            netm = "255.255.255.255"
        else:
            addr = dst[:slash]
            netm = dst[slash + 1:]

        try:
            daddr = _a_to_i(socket.inet_pton(socket.AF_INET, addr))
        except socket.error as e:
            raise ValueError("invalid address %s" % (addr))
        ina = in_addr()
        ina.s_addr = ct.c_uint32(daddr)
        self.entry.ip.dst = ina

        try:
            nmask = _a_to_i(socket.inet_pton(socket.AF_INET, netm))
        except socket.error as e:
            raise ValueError("invalid netmask %s" % (netm))
        neta = in_addr()
        neta.s_addr = ct.c_uint32(nmask)
        self.entry.ip.dmsk = neta
Beispiel #18
0
    def answer(self, friend_number, audio_bit_rate, video_bit_rate):
        """
        Accept an incoming call.

        If answering fails for any reason, the call will still be pending and it is possible to try and answer it later.
        Audio and video receiving are both enabled by default.

        :param friend_number: The friend number of the friend that is calling.
        :param audio_bit_rate: Audio bit rate in Kb/sec. Set this to 0 to disable audio sending.
        :param video_bit_rate: Video bit rate in Kb/sec. Set this to 0 to disable video sending.
        :return: True on success.
        """
        toxav_err_answer = c_int()
        result = self.libtoxav.toxav_answer(self._toxav_pointer, c_uint32(friend_number), c_uint32(audio_bit_rate),
                                             c_uint32(video_bit_rate), byref(toxav_err_answer))
        toxav_err_answer = toxav_err_answer.value
        if toxav_err_answer == TOXAV_ERR_ANSWER['OK']:
            return bool(result)
        elif toxav_err_answer == TOXAV_ERR_ANSWER['SYNC']:
            raise RuntimeError('Synchronization error occurred.')
        elif toxav_err_answer == TOXAV_ERR_ANSWER['CODEC_INITIALIZATION']:
            raise RuntimeError('Failed to initialize codecs for call session. Note that codec initiation will fail if '
                               'there is no receive callback registered for either audio or video.')
        elif toxav_err_answer == TOXAV_ERR_ANSWER['FRIEND_NOT_FOUND']:
            raise ArgumentError('The friend number did not designate a valid friend.')
        elif toxav_err_answer == TOXAV_ERR_ANSWER['FRIEND_NOT_CALLING']:
            raise ArgumentError('The friend was valid, but they are not currently trying to initiate a call. This is '
                                'also returned if this client is already in a call with the friend.')
        elif toxav_err_answer == TOXAV_ERR_ANSWER['INVALID_BIT_RATE']:
            raise ArgumentError('Audio or video bit rate is invalid.')
Beispiel #19
0
def _decode_tile_data(codec, tidx, data, data_size, stream):
    """Reads tile data.

    Wraps the openjp2 library function opj_decode_tile_data.

    Parameters
    ----------
    codec : _codec_t_p
        The JPEG2000 codec
    tile_index : int
        The index of the tile being decoded
    data : array
        Holds a memory block into which data will be decoded.
    data_size : int
        The size of data in bytes
    stream : _stream_t_p
        The stream to decode.

    Raises
    ------
    RuntimeError
        If the OpenJPEG library routine opj_decode fails.
    """
    datap = data.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8))
    _OPENJP2.opj_decode_tile_data(codec,
                                  ctypes.c_uint32(tidx),
                                  datap,
                                  ctypes.c_uint32(data_size),
                                  stream)
    return codec
Beispiel #20
0
    def set_src(self, src):
        if src[0] == "!":
            self.entry.ip.invflags |= ipt_ip.IPT_INV_SRCIP
            src = src[1:]
        else:
            self.entry.ip.invflags &= ~ipt_ip.IPT_INV_SRCIP & \
                  ipt_ip.IPT_INV_MASK

        slash = src.find("/")
        if slash == -1:
            addr = src
            netm = "255.255.255.255"
        else:
            addr = src[:slash]
            netm = src[slash + 1:]

        try:
            saddr = _a_to_i(socket.inet_pton(socket.AF_INET, addr))
        except socket.error as e:
            raise ValueError("invalid address %s" % (addr))
        ina = in_addr()
        ina.s_addr = ct.c_uint32(saddr)
        self.entry.ip.src = ina

        try:
            nmask = _a_to_i(socket.inet_pton(socket.AF_INET, netm))
        except socket.error as e:
            raise ValueError("invalid netmask %s" % (netm))
        neta = in_addr()
        neta.s_addr = ct.c_uint32(nmask)
        self.entry.ip.smsk = neta
Beispiel #21
0
    def __init__(self,
                 year=None,
                 month=None,
                 day=None,
                 hour=None,
                 minute=None,
                 second=None,
                 microseconds=None,
                 utc=None):
        if year is None and \
           month is None and \
           day is None and \
           hour is None and \
           minute is None and \
           second is None and \
           microseconds is None and \
           utc is None:
            MI_Datetime.__init__(self, None)
        else:
            MI_Datetime.__init__(self, True)

        if year is None:
            self.year = ctypes.c_uint(0)
        else:
            self.year = ctypes.c_uint(year)

        if month is None:
            self.month = ctypes.c_uint(0)
        else:
            self.month = ctypes.c_uint(month)

        if day is None:
            self.day = ctypes.c_uint(0)
        else:
            self.day = ctypes.c_uint(day)

        if hour is None:
            self.hour = ctypes.c_uint(0)
        else:
            self.hour = ctypes.c_uint(hour)

        if minute is None:
            self.minute = ctypes.c_uint(0)
        else:
            self.minute = ctypes.c_uint(minute)

        if second is None:
            self.second = ctypes.c_uint(0)
        else:
            self.second = ctypes.c_uint(second)

        if microseconds is None:
            self.microseconds = ctypes.c_uint32(0)
        else:
            self.microseconds = ctypes.c_uint32(microseconds)

        if utc is None:
            self.utc = ctypes.c_int(0)
        else:
            self.utc = ctypes.c_int(int(utc))
Beispiel #22
0
def _write_tile(codec, tile_index, data, data_size, stream):
    """Wraps openjp2 library function opj_write_tile.

    Write a tile into an image.

    Parameters
    ----------
    codec : _codec_t_p
        The jpeg2000 codec
    tile_index : int
        The index of the tile to write, zero-indexing assumed
    data : array
        Image data arranged in usual C-order
    data_size : int
        Size of a tile in bytes
    stream : _stream_t_p
        The stream to write data to

    Raises
    ------
    RuntimeError
        If the OpenJPEG library routine opj_write_tile fails.
    """
    datap = data.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8))
    _OPENJP2.opj_write_tile(codec,
                            ctypes.c_uint32(int(tile_index)),
                            datap,
                            ctypes.c_uint32(int(data_size)),
                            stream)
Beispiel #23
0
 def getTimeBase(self, name, dtype=numpy.float32, tBegin=None, tEnd=None):
     """ Return timebase corresponding to name. """
     if not self.status:
         raise Exception('Shotfile not open!')
     info = self.getSignalInfo(name)
     tInfo = self.getTimeBaseInfo(name)
     if tBegin==None:
         tBegin = tInfo.tBegin
     if tEnd==None:
         tEnd = tInfo.tEnd
     typ = ctypes.c_uint32(__type__[dtype])
     error = ctypes.c_int32(0)
     lsigname = ctypes.c_uint64(len(name))
     k1, k2 = self.getTimeBaseIndices(name, tBegin, tEnd)
     if dtype not in [numpy.float32, numpy.float64]:
         dtype = numpy.float32
     data = numpy.zeros(k2-k1+1, dtype=dtype)
     lbuf = ctypes.c_uint32(data.size)
     k1 = ctypes.c_uint32(k1)
     k2 = ctypes.c_uint32(k2)
     length = ctypes.c_uint32(0)
     try:
         sigName = ctypes.c_char_p(name)
     except TypeError:
         sigName = ctypes.c_char_p(name.encode())
     result = __libddww__.ddtbase_(ctypes.byref(error), ctypes.byref(self.diaref), sigName, ctypes.byref(k1), 
                                   ctypes.byref(k2), ctypes.byref(typ), ctypes.byref(lbuf), data.ctypes.data_as(ctypes.c_void_p), 
                                   ctypes.byref(length) ,lsigname)
     getError(error.value)
     return data
Beispiel #24
0
 def getTimeBaseIndices(self, name, tBegin, tEnd):
     """ Return time indices of name corresponding to tBegin and tEnd """
     if not self.status:
         raise Exception('Shotfile not open!')
     try:
         sigName = ctypes.c_char_p(name)
     except TypeError:
         sigName = ctypes.c_char_p(name.encode())
     error = ctypes.c_int32(0)
     info = self.getTimeBaseInfo(name)
     if tEnd < tBegin:
         temp = tEnd
         tEnd = tBegin
         tBegin = temp
     if tBegin < info.tBegin:
         tBegin = info.tBegin
     if tEnd > info.tEnd:
         tEnd = info.tEnd
     try:
         time1 = ctypes.c_float(tBegin)
     except TypeError:
         time1 = ctypes.c_float(tBegin.value)
     try:
         time2 = ctypes.c_float(tEnd)
     except TypeError:
         time2 = ctypes.c_float(tEnd.value)
     k1 = ctypes.c_uint32(0)
     k2 = ctypes.c_uint32(0)
     lname = ctypes.c_uint64(len(name))
     __libddww__.ddtindex_(ctypes.byref(error), ctypes.byref(self.diaref), sigName, ctypes.byref(time1), 
                           ctypes.byref(time2), ctypes.byref(k1), ctypes.byref(k2), lname)
     getError(error.value)
     return numpy.uint32(k1.value), numpy.uint32(k2.value)
Beispiel #25
0
    def testEncodingWithExtension(self):
        msg=ClientMessage()
        vr=0
        optype=200
        corrID=0
        parID=-1

        msg.version=vr
        msg.optype=optype
        msg.correlation=corrID
        msg.partition=parID
        msg.addExtension(bytearray(ctypes.c_uint32(4203239)))
        frame = bytearray()
        #Create a byte array of size 18


        frame+=bytearray(ctypes.c_int32(18+4))
        frame+=bytearray(ctypes.c_uint8(vr))
        frame+=bytearray(ctypes.c_uint8(192))
        frame+=bytearray(ctypes.c_uint16(optype))
        frame+=bytearray(ctypes.c_int32(corrID))
        frame+=bytearray(ctypes.c_int32(parID))
        frame+=bytearray(ctypes.c_uint16(22))
        frame+=bytearray(ctypes.c_uint32(4203239))

        encodedMsg=msg.encodeMessage()


        self.assertEqual(frame,encodedMsg)
Beispiel #26
0
 def getSignalGroup(self, name, dtype=None, tBegin=None, tEnd=None):       
     """ Return uncalibrated signalgroup. If dtype is specified the data is
     converted accordingly, else the data is returned in the format used 
     in the shotfile. """
     if not self.status:
         raise Exception('Shotfile not open!')
     info = self.getSignalInfo(name)
     try:
         tInfo = self.getTimeBaseInfo(name)
         if tBegin==None:
             tBegin = tInfo.tBegin
         if tEnd==None:
             tEnd = tInfo.tEnd
         k1, k2 = self.getTimeBaseIndices(name, tBegin, tEnd)
         if info.index[0]!=tInfo.ntVal:
             k1 = 1
             k2 = info.index[0]
     except Exception:
         k1 = 1
         k2 = info.index[0]
     size = info.size/info.index[0]*(k2-k1+1)
     try:
         typ = ctypes.c_uint32(__type__[dtype])
         data = numpy.zeros(size, dtype=dtype)
     except KeyError, Error:
         dataformat = self.getObjectValue(name, 'dataformat')
         typ = ctypes.c_uint32(0)
         data = numpy.zeros(size, dtype=__dataformat__[dataformat])
Beispiel #27
0
def get_selected_window():
    """
    Ugly workaround to get the selected window, can't use gtk/gdk =/
    from: http://unix.stackexchange.com/a/16157
    """

    from ctypes import CDLL, c_int, c_uint32, c_uint, byref, c_void_p

    Xlib = CDLL("libX11.so.6")
    Xlib.XOpenDisplay.restype = c_void_p

    display = c_void_p(Xlib.XOpenDisplay(None))

    if display == 0:
        return None

    w = Xlib.XRootWindow(display, c_int(0))

    root_id, child_id = (c_uint32(), c_uint32())
    root_x, root_y, win_x, win_y = [c_int()] * 4

    mask = c_uint()
    ret = Xlib.XQueryPointer(display, c_uint32(w),
                             byref(root_id), byref(child_id),
                             byref(root_x), byref(root_y),
                             byref(win_x), byref(win_y),
                             byref(mask))
    if ret == 0:
        return None

    value = child_id.value
    # if 0 is root
    if value == 0:
        value = root_id.value
    return value
Beispiel #28
0
    def feature_line(self, corpus, guess, sentence):
        if self._sentence_hash != hash(sentence):
            self._sentence_hash = hash(sentence)
            tokenized = list(self.tokenize_and_censor(sentence))
            self._sentence_length = len(tokenized)
            assert self._sentence_length < kMAX_TEXT_LENGTH
            for ii, ww in enumerate(tokenized):
                self._sentence[ii] = ww

        norm_title = self.normalize_title(corpus, guess)
        if norm_title not in self._corpora or self._sentence_length == 0:
            return ""
        else:
            guess_id = self._corpora[norm_title]
            if guess_id not in self._loaded_lms:
                self._lm.read_counts("%s/%i" % (self._datafile, guess_id))
                self._loaded_lms.add(guess_id)

            feat = self._lm.feature(corpus, guess_id, self._sentence, self._sentence_length)

            if self._hash_names:
                result = []
                for ii in feat.split():
                    if "_" in ii:
                        if ":" in ii:
                            name, val = ii.split(":")
                            hashed_name = ctypes.c_uint32(hash(name)).value
                            result.append("%i:%s" % (hashed_name, val))
                        else:
                            result.append("%i" % ctypes.c_uint32(hash(ii)).value)
                    else:
                        result.append(ii)
                return " ".join(result)
            else:
                return feat
Beispiel #29
0
 def enumerate_table_next(self, enumeration_state):
     key_length = ctypes.c_uint32()
     data_length = ctypes.c_uint32()
     data = ctypes.c_void_p()
     key = ctypes.c_void_p()
     s = so.rc_enumerateTableNext(
         self.client,
         enumeration_state,
         ctypes.byref(key_length),
         ctypes.byref(key),
         ctypes.byref(data_length),
         ctypes.byref(data),
     )
     key_l = key_length.value
     data_l = data_length.value
     dataPtr = ctypes.cast(data, ctypes.POINTER(ctypes.c_char))
     keyPtr = ctypes.cast(key, ctypes.POINTER(ctypes.c_char))
     data_s = ""
     key_s = ""
     if key_l != 0:
         for i in range(0, data_l):
             data_s = data_s + dataPtr[i]
         for i in range(0, key_l):
             key_s = key_s + keyPtr[i]
     self.handle_error(s)
     return (key_s, data_s)
Beispiel #30
0
 def rng(self):
     temp = self.a ^ ctypes.c_uint32(self.a << 7).value
     self.a = self.b
     self.b = self.c
     self.c = self.d
     self.d = (self.d ^ (self.d >> 22)) ^ (temp ^ (temp >> 16))
     return ctypes.c_uint32(self.d).value
Beispiel #31
0
def stou(i):
    return ctypes.c_uint32(i).value
def callback(cube, sphere_cloud):
    print(frame_id, 'points received')

    points = []
    colors = []
    if frame_id == 'teapot_points' or frame_id == 'table_points' or frame_id == 'meat_points' or frame_id == 'bottle_points' \
        or frame_id == 'potato_points' or frame_id == 'tomato_points' or frame_id == 'tomato2_points' or frame_id == 'veggie_points':
        print(frame_id, density)
        for idx, p in enumerate(
                pc2.read_points(sphere_cloud,
                                field_names=("x", "y", "z", "rgb"),
                                skip_nans=True)):
            if idx % density == 0:
                point = np.array([p[0], p[1], p[2]])
                point = np.array(point)
                points.append(point)

                test = p[3]
                s = struct.pack('>f', test)
                i = struct.unpack('>l', s)[0]
                pack = ctypes.c_uint32(i).value
                r = (pack & 0x00FF0000) >> 16
                g = (pack & 0x0000FF00) >> 8
                b = (pack & 0x000000FF)
                colors.append([r / 255.0, g / 255.0, b / 255.0])
    else:
        for idx, p in enumerate(
                pc2.read_points(sphere_cloud,
                                field_names=("x", "y", "z"),
                                skip_nans=True)):
            if idx % density == 0:
                point = np.array([p[0], p[1], p[2]])
                if frame_id == "cylinder_points":
                    point = r.apply(point)
                points.append(point)
                if frame_id == 'sphere1_points' or frame_id == 'sphere4_points' or frame_id == 'sphere5_points' or frame_id == 'sphere6_points':
                    colors.append([50.0 / 255, 205.0 / 255, 50.0 / 255])
                elif frame_id == 'sphere2_points' or frame_id == 'sphere7_points':
                    colors.append([102 / 255.0, 221 / 255.0, 229 / 255.0])
                elif frame_id == 'sphere3_points':
                    colors.append([218 / 255.0, 165 / 255.0, 32 / 255.0])
                elif frame_id == 'bunny_points':
                    colors.append([0, 172.0 / 255, 223.0 / 255])
                else:
                    colors.append([1, 1, 0])
    points = np.array(points)
    points[:, 0] = points[:, 0] - points[:, 0].mean()
    points[:, 1] = points[:, 1] - points[:, 1].mean()
    points[:, 2] = points[:, 2] - points[:, 2].mean()
    points = points / scale
    if frame_id == 'teapot_points' or frame_id == 'table_points' or frame_id == 'meat_points' or frame_id == 'bottle_points' \
        or frame_id == 'potato_points' or frame_id == 'veggie_points':
        points = rot.apply(points)
    else:
        points = rot2.apply(points)
    cube_x = cube.pose.position.x
    cube_y = cube.pose.position.z
    cube_z = cube.pose.position.y
    msg = xyzrgb_array_to_pointcloud2(points,
                                      np.array(colors),
                                      stamp=rospy.get_rostime(),
                                      frame_id=frame_id,
                                      seq=None)
    pub.publish(msg)
    euler = tf.transformations.euler_from_quaternion([
        cube.pose.orientation.x, -cube.pose.orientation.z,
        cube.pose.orientation.y, cube.pose.orientation.w
    ])
    br.sendTransform(
        (cube_x, -cube_y, cube_z),
        tf.transformations.quaternion_from_euler(0, euler[2], euler[1]),
        rospy.Time.now(), frame_id, 'ar_frame')

    br.sendTransform(
        (cube_x, -cube_y, cube_z),
        tf.transformations.quaternion_from_euler(euler[0], euler[2], euler[1]),
        rospy.Time.now(), link_name, 'ar_frame')
    rate.sleep()
Beispiel #33
0
def fx3_load_ram(device, path):

    global verbose

    bBuf = ct.POINTER(ct.c_ubyte)
    hBuf = (ct.c_ubyte * 4)()
    blBuf = (ct.c_ubyte * 4)()
    rBuf = (ct.c_ubyte * 4096)()

    try:
        image = open(path, "rb")
    except:
        logerror("unable to open '{}' for input\n", path)
        return -2

    if verbose:
        logerror("open firmware image {} for RAM upload\n", path)

    with image:

        # Read header
        if image.readinto(hBuf) != ct.sizeof(hBuf):
            logerror("could not read image header")
            return -3

        # check "CY" signature byte and format
        if hBuf[0] != 'C' or hBuf[1] != 'Y':
            logerror("image doesn't have a CYpress signature\n")
            return -3

        # Check bImageType
        bImageType = hBuf[3]
        if bImageType == 0xB0:
            if verbose:
                logerror("normal FW binary {} image with checksum\n",
                         "data" if hBuf[2] & 0x01 else "executable")
        elif bImageType == 0xB1:
            logerror("security binary image is not currently supported\n")
            return -3
        elif bImageType == 0xB2:
            logerror("VID:PID image is not currently supported\n")
            return -3
        else:
            logerror("invalid image type {:#04X}\n", hBuf[3])
            return -3

        # Read the bootloader version
        if verbose:
            if ezusb_read(device, "read bootloader version", RW_INTERNAL,
                          0xFFFF0020, blBuf, 4) < 0:
                logerror("Could not read bootloader version\n")
                return -8
            logerror("FX3 bootloader version: {:#04X}{:02X}{:02X}{:02X}\n",
                     blBuf[3], blBuf[2], blBuf[1], blBuf[0])

        if verbose:
            logerror("writing image...\n")

        dLength = ct.c_uint32()
        dAddress = ct.c_uint32()
        dCheckSum = 0  # ct.c_uint32
        while True:
            if ((image.fread(ct.byref(dLength), ct.sizeof(ct.c_uint32)) !=
                 ct.sizeof(ct.c_uint32)) or  # read dLength
                (image.fread(ct.byref(dAddress), ct.sizeof(ct.c_uint32)) !=
                 ct.sizeof(ct.c_uint32))):  # read dAddress
                logerror("could not read image")
                return -3
            if dLength == 0:
                break  # done

            # coverity[tainted_data]
            try:
                #dImageBuf = ct.POINTER(ct.c_uint32)()
                dImageBuf = ct.cast(calloc(dLength, ct.sizeof(ct.c_uint32)),
                                    ct.POINTER(ct.c_uint32))
            except:
                logerror("could not allocate buffer for image chunk\n")
                return -4

            # read sections
            if image.fread(dImageBuf,
                           ct.sizeof(ct.c_uint32) *
                           dLength) != ct.sizeof(ct.c_uint32) * dLength:
                logerror("could not read image")
                return -3

            for i in range(dLength):
                dCheckSum += dImageBuf[i]

            dLength <<= 2  # convert to Byte length
            bBuf = ct.cast(dImageBuf, ct.POINTER(ct.c_ubyte))
            while dLength > 0:

                #dLen  # ct.c_uint32
                dLen = min(dLength, 4096)  # 4K max
                if (ezusb_write(device, "write firmware", RW_INTERNAL,
                                dAddress, bBuf, dLen) < 0
                        or ezusb_read(device, "read firmware", RW_INTERNAL,
                                      dAddress, rBuf, dLen) < 0):
                    logerror("R/W error\n")
                    return -5

                # Verify data: rBuf with bBuf
                for i in range(dLen):
                    if rBuf[i] != bBuf[i]:
                        logerror("verify error")
                        return -6

                dLength -= dLen
                bBuf += dLen
                dAddress += dLen

        # read pre-computed checksum data
        dExpectedCheckSum = ct.c_uint32()
        if (image.fread(ct.byref(dExpectedCheckSum), ct.sizeof(ct.c_uint32)) !=
                ct.sizeof(ct.c_uint32) or dCheckSum != dExpectedCheckSum):
            logerror("checksum error\n")
            return -7

        # transfer execution to Program Entry
        if not ezusb_fx3_jump(device, dAddress):
            return -6

    return 0
Beispiel #34
0
def parse_ihex(image, context, is_external, poke):

    global verbose

    data = (ct.c_ubyte * 1023)()

    # Read the input file as an IHEX file, and report the memory segments
    # as we go.  Each line holds a max of 16 bytes, but uploading is
    # faster (and EEPROM space smaller) if we merge those lines into larger
    # chunks.  Most hex files keep memory segments together, which makes
    # such merging all but free.  (But it may still be worth sorting the
    # hex files to make up for undesirable behavior from tools.)
    #
    # Note that EEPROM segments max out at 1023 bytes; the upload protocol
    # allows segments of up to 64 KBytes (more than a loader could handle).

    data_len = 0  # ct.c_size_t
    data_addr = ct.c_uint32(0)
    external = False  # bool

    first_line = True
    while True:

        buf = bytearray(b"\0" * 512)
        try:
            image.readinto(buf)
        except:
            logerror("EOF without EOF record!\n")
            break

        # EXTENSION: "# comment-till-end-of-line", for copyrights etc
        if buf[0] == ord('#'):
            continue

        if buf[0] != ord(':'):
            logerror("not an ihex record: {}", buf)
            return -2

        # ignore any newline
        #cp # char*
        cp = strchr(buf, '\n')
        if cp != NULL:
            cp[0] = 0

        if verbose >= 3:
            logerror("** LINE: {}\n", buf)

        # Read the length field (up to 16 bytes)
        tmp = buf[3]
        buf[3] = 0
        #size # ct.c_size_t
        size = strtoul(buf[1:], NULL, 16)
        buf[3] = tmp

        # Read the target offset (address up to 64KB)
        tmp = buf[7]
        buf[7] = 0
        #off # unsigned
        off = int(strtoul(buf[3:], NULL, 16))
        buf[7] = tmp

        # Initialize data_addr
        if first_line:
            data_addr = off
            first_line = False

        # Read the record type
        tmp = buf[9]
        buf[9] = 0
        #rec_type # char
        rec_type = char(strtoul(buf[7:], NULL, 16))
        buf[9] = tmp

        # If this is an EOF record, then make it so.
        if rec_type == 1:
            if verbose >= 2:
                logerror("EOF on hexfile\n")
            break

        if rec_type != 0:
            logerror("unsupported record type: %u\n", rec_type)
            return -3

        if size * 2 + 11 > strlen(buf):
            logerror("record too short?\n")
            return -4

        # FIXME check for _physically_ contiguous not just virtually
        # e.g. on FX2 0x1f00-0x2100 includes both on-chip and external
        # memory so it's not really contiguous

        # flush the saved data if it's not contiguous,
        # or when we've buffered as much as we can.

        if (data_len != 0 and (off != (data_addr + data_len) or
                               # not merge or
                               (data_len + size) > ct.sizeof(data))):
            if is_external: external = is_external(data_addr, data_len)
            rc = poke(context, data_addr, external, data, data_len)
            if rc < 0:
                return -1
            data_addr = off
            data_len = 0

        # append to saved data, flush later
        cp = buf + 9
        for idx in range(size):
            tmp = cp[2]
            cp[2] = 0
            data[data_len + idx] = ct.c_uint8(strtoul(cp, NULL, 16))
            cp[2] = tmp
            cp += 2

        data_len += size

    # flush any data remaining
    if data_len != 0:
        if is_external: external = is_external(data_addr, data_len)
        rc = poke(context, data_addr, external, data, data_len)
        if rc < 0:
            return -1

    return 0
Beispiel #35
0
 def RsTOREG(self):
     self.dll.DLLRsTOREG(ct.c_uint32(self.board_number))
Beispiel #36
0
    def py_rtlsdr_get_device_usb_strings(self, device_index=0):
        """
        Returns the USB device strings.

        Parameters
        ----------
        * device_index                  : (int) Device index.

        Returns
        -------
        * mid                           : (str) Device manufacturer.
        * pid                           : (str) Device product ID.
        * serial                        : (str) Device serial ID.

        Raises
        ------
        * TypeError
                                        * If device index is negative.
                                        * If device index is greater than or
                                        equal to the number of connected 
                                        supported devices.
        """
        if not self.__apis_init_stat['py_rtlsdr_get_device_usb_strings']:
            f = self.clib.rtlsdr_get_device_usb_strings
            f.restype, f.argstypes = c_int, [
                c_uint32,
                POINTER(c_ubyte),
                POINTER(c_ubyte),
                POINTER(c_ubyte)
            ]
            self.__apis_init_stat['py_rtlsdr_get_device_usb_strings'] = True

        self.__check_for_rtlsdr_devices()

        if int(device_index) != device_index:
            print_error_msg("Expected device index to be int. Got: %d" %
                            (type(device_index)))
            raise ValueError

        device_index = int(device_index)

        if device_index < 0:
            print_error_msg("Device index must be non-negative.")
            raise ValueError

        if device_index >= self.py_rtlsdr_get_device_count():
            print_error_msg(
                "Expected device index < %d. Got device index: %d." %
                (self.py_rtlsdr_get_device_count(), device_index))
            raise ValueError

        mid = (c_ubyte * 256)()
        pid = (c_ubyte * 256)()
        serial = (c_ubyte * 256)()
        result = self.clib.rtlsdr_get_device_usb_strings(
            c_uint32(device_index), mid, pid, serial)
        if (result != 0):
            print_error_msg(
                "Failed tp fetch USB device strings for device indexed as %d."
                % (device_index))
            raise ValueError
        return c_ubyte_ptr_to_string(mid, 256), c_ubyte_ptr_to_string(
            pid, 256), c_ubyte_ptr_to_string(serial, 256)
Beispiel #37
0
def to_uint32(n: int) -> int:
    return ctypes.c_uint32(n).value
Beispiel #38
0
 def _lowLevelClearDataBuffers(self, channel):
     m = self.lib.ps4000aSetDataBuffers(c_int16(self.handle),
                                        c_enum(channel), c_void_p(),
                                        c_void_p(), c_uint32(0))
     self.checkResult(m)
Beispiel #39
0
 def _lowLevelClearDataBuffer(self, channel, segmentIndex):
     m = self.lib.ps3000aSetDataBuffer(c_int16(self.handle),
                                       c_enum(channel), c_void_p(),
                                       c_uint32(0), c_uint32(segmentIndex),
                                       c_enum(0))
     self.checkResult(m)
Beispiel #40
0
 def setUUIRTConfig(self, config):
     """Wraps UUIRTSetUUIRTConfig, config is an int()."""
     if not self.__opened:
         raise Exception
     uconfig = ctypes.c_uint32(config)
     return (self.__UUIRTSetUUIRTConfig(self.__dev_handle, uconfig) == 1)
Beispiel #41
0
 def WaitforTelapsed(self, t_us):
     success = self.dll.DLLWaitforTelapsed(ct.c_uint32(t_us))
     return bool(success)
Beispiel #42
0
 def WriteLongS0(self, val, offset):
     success = self.dll.DLLWriteLongS0(ct.c_uint32(self.board_number),
                                       ct.c_uint32(val),
                                       ct.c_uint32(offset))
     return print('set dat ' + str(bool(success)))
Beispiel #43
0
 def TempGood(self, channel):
     self.dll.DLLTempGood(ct.c_uint32(self.board_number),
                          ct.c_uint32(channel))
Beispiel #44
0
 def Voff(self):
     self.dll.DLLVoff(ct.c_uint32(self.board_number))
Beispiel #45
0
 def SetupVCLK(self):
     self.dll.DLLSetupVCLK(ct.c_uint32(self.board_number),
                           ct.c_uint32(self.fft_lines),
                           ct.c_uint8(self.vfreq))
Beispiel #46
0
 def StartTimer(self, exposure_time):
     self.dll.DLLStartTimer(ct.c_uint32(self.board_number),
                            ct.c_uint32(exposure_time))
Beispiel #47
0
 def SetupDelay(self, delay):
     self.dll.DLLSetupDELAY(ct.c_uint32(self.board_number),
                            ct.c_uint32(delay))
Beispiel #48
0
 def SetupHAModule(self, fft_lines):
     self.dll.DLLSetupHAModule(ct.c_uint32(self.board_number),
                               ct.c_uint32(fft_lines))
Beispiel #49
0
 def SetOvsmpl(self):
     self.dll.DLLSetOvsmpl(ct.c_uint32(self.board_number),
                           ct.c_uint32(self.zadr))
Beispiel #50
0
 def SetTemp(self, level):
     self.dll.DLLSetTemp(ct.c_uint32(self.board_number), ct.c_uint32(level))
Beispiel #51
0
 def SetIntTrig(self):
     self.dll.DLLSetIntTrig(ct.c_uint32(self.board_number))
Beispiel #52
0
 def SetISPDA(self, _set):
     self.dll.DLLSetISPDA(ct.c_uint32(self.board_number), ct.c_uint8(_set))
Beispiel #53
0
 def SetAD16Default(self):
     self.dll.DLLSetAD16Default(ct.c_uint32(self.board_number),
                                ct.c_uint32(1))
Beispiel #54
0
 def StopFFTimer(self):
     self.dll.DLLStopFFTimer(ct.c_uint32(self.board_number))
Beispiel #55
0
    def get_settings(self, verbose=True):
        if verbose:
            print "Retrieving settings from camera..."
        wSensor = ctypes.c_uint16(0)
        PCO_api.PCO_GetSensorFormat(self.camera_handle, ctypes.byref(wSensor))
        mode_names = {0: "standard", 1: "extended"}
        if verbose:
            print " Sensor format is", mode_names[wSensor.value]

        dwWarn, dwErr, dwStatus = (ctypes.c_uint32(), ctypes.c_uint32(),
                                   ctypes.c_uint32())
        PCO_api.PCO_GetCameraHealthStatus(self.camera_handle,
                                          ctypes.byref(dwWarn),
                                          ctypes.byref(dwErr),
                                          ctypes.byref(dwStatus))
        if verbose:
            print " Camera health status (0 0 0 means healthy):",
            print dwWarn.value, dwErr.value, dwStatus.value

        ccdtemp, camtemp, powtemp = (ctypes.c_int16(), ctypes.c_int16(),
                                     ctypes.c_int16())
        PCO_api.PCO_GetTemperature(self.camera_handle, ctypes.byref(ccdtemp),
                                   ctypes.byref(camtemp),
                                   ctypes.byref(powtemp))
        if verbose:
            print " CCD temperature:", ccdtemp.value * 0.1, "C"
            print " Camera temperature:", camtemp.value, "C"
            print " Power supply temperature:", powtemp.value, "C"
        """
        0x0000 = [auto trigger]
        A new image exposure is automatically started best possible
        compared to the readout of an image. If a CCD is used and the
        images are taken in a sequence, then exposures and sensor readout
        are started simultaneously. Signals at the trigger input (<exp
        trig>) are irrelevant.
        - 0x0001 = [software trigger]:
        An exposure can only be started by a force trigger command.
        - 0x0002 = [extern exposure & software trigger]:
        A delay / exposure sequence is started at the RISING or FALLING
        edge (depending on the DIP switch setting) of the trigger input
        (<exp trig>).
        - 0x0003 = [extern exposure control]:
        The exposure time is defined by the pulse length at the trigger
        input(<exp trig>). The delay and exposure time values defined by
        the set/request delay and exposure command are ineffective.
        (Exposure time length control is also possible for double image
        mode; exposure time of the second image is given by the readout
        time of the first image.)
        """
        trigger_mode_names = {
            0: "auto trigger",
            1: "software trigger",
            2: "external trigger/software exposure control",
            3: "external exposure control"
        }
        mode_name_to_number = dict((v, k) for k, v in mode_names.iteritems())
        wTriggerMode = ctypes.c_uint16()
        PCO_api.PCO_GetTriggerMode(self.camera_handle,
                                   ctypes.byref(wTriggerMode))
        if verbose:
            print " Trigger mode is", trigger_mode_names[wTriggerMode.value]

        wStorageMode = ctypes.c_uint16()
        PCO_api.PCO_GetStorageMode(self.camera_handle,
                                   ctypes.byref(wStorageMode))
        mode_names = {
            0: "Recorder",
            1: "FIFO buffer"
        }  #Not critical for pco.edge
        if verbose:
            print "Storage mode:", mode_names[wStorageMode.value]

        wRecSubmode = ctypes.c_uint16(1)
        PCO_api.PCO_GetRecorderSubmode(self.camera_handle,
                                       ctypes.byref(wRecSubmode))
        mode_names = {0: "sequence", 1: "ring buffer"}
        if verbose:
            print " Recorder submode:", mode_names[wRecSubmode.value]

        wAcquMode = ctypes.c_uint16(0)
        PCO_api.PCO_GetAcquireMode(self.camera_handle, ctypes.byref(wAcquMode))
        mode_names = {
            0: "auto",
            1: "external (static)",
            2: "external (dynamic)"
        }
        if verbose:
            print " Acquire mode:", mode_names[wAcquMode.value]

        dwPixelRate = ctypes.c_uint32(286000000)
        PCO_api.PCO_GetPixelRate(self.camera_handle, ctypes.byref(dwPixelRate))
        if verbose:
            print " Pixel rate:", dwPixelRate.value

        dwDelay = ctypes.c_uint32(0)
        wTimeBaseDelay = ctypes.c_uint16(0)
        dwExposure = ctypes.c_uint32(0)
        wTimeBaseExposure = ctypes.c_uint16(1)
        PCO_api.PCO_GetDelayExposureTime(self.camera_handle,
                                         ctypes.byref(dwDelay),
                                         ctypes.byref(dwExposure),
                                         ctypes.byref(wTimeBaseDelay),
                                         ctypes.byref(wTimeBaseExposure))
        mode_names = {0: "nanoseconds", 1: "microseconds", 2: "milliseconds"}
        if verbose:
            print " Exposure:", dwExposure.value, mode_names[
                wTimeBaseExposure.value]
            print " Delay:", dwDelay.value, mode_names[wTimeBaseDelay.value]

        wRoiX0, wRoiY0, wRoiX1, wRoiY1 = (ctypes.c_uint16(), ctypes.c_uint16(),
                                          ctypes.c_uint16(), ctypes.c_uint16())
        PCO_api.PCO_GetROI(self.camera_handle, ctypes.byref(wRoiX0),
                           ctypes.byref(wRoiY0), ctypes.byref(wRoiX1),
                           ctypes.byref(wRoiY1))
        if verbose:
            print " Camera ROI:"
            """We typically use 841 to 1320 u/d, 961 to 1440 l/r"""
            print "  From pixel", wRoiX0.value, "to pixel", wRoiX1.value, "(left/right)"
            print "  From pixel", wRoiY0.value, "to pixel", wRoiY1.value, "(up/down)"
            print

        trigger = trigger_mode_names[wTriggerMode.value]
        """Exposure is in microseconds"""
        exposure = dwExposure.value * 10.**(3 * wTimeBaseExposure.value - 3)
        roi = (wRoiX0.value, wRoiY0.value, wRoiX1.value, wRoiY1.value)
        return (trigger, exposure, roi)
Beispiel #56
0
 def SetADAmpRed(self, gain):
     self.dll.DLLSetADAmpRed(ct.c_uint32(self.board_number),
                             ct.c_uint32(gain))
Beispiel #57
0
    def record_to_file(self,
                       num_images,
                       preframes=0,
                       file_name='image.raw',
                       save_path=None,
                       verbose=False,
                       poll_timeout=2e8):
        """Call this any number of times, after arming the camera once"""

        if save_path is None:
            save_path = os.getcwd()
        save_path = str(save_path)

        dw1stImage, dwLastImage = ctypes.c_uint32(0), ctypes.c_uint32(0)
        wBitsPerPixel = ctypes.c_uint16(16)  #16 bits for the pco.edge, right?
        dwStatusDll, dwStatusDrv = ctypes.c_uint32(), ctypes.c_uint32()
        print "Saving:", repr(os.path.join(save_path, file_name))
        file_pointer = ctypes.c_void_p(
            libc.fopen(os.path.join(save_path, file_name), "wb"))
        bytes_per_pixel = ctypes.c_uint32(2)
        pixels_per_image = ctypes.c_uint32(self.wXRes.value * self.wYRes.value)
        for which_im in range(num_images):
            which_buf = which_im % len(self.buffer_numbers)
            PCO_api.PCO_AddBufferEx(self.camera_handle, dw1stImage,
                                    dwLastImage,
                                    self.buffer_numbers[which_buf], self.wXRes,
                                    self.wYRes, wBitsPerPixel)

            num_polls = 0
            while True:
                num_polls += 1
                PCO_api.PCO_GetBufferStatus(self.camera_handle,
                                            self.buffer_numbers[which_buf],
                                            ctypes.byref(dwStatusDll),
                                            ctypes.byref(dwStatusDrv))
                time.sleep(0.00005)  #50 microseconds
                if dwStatusDll.value == 0xc0008000:
                    if verbose:
                        print "After", num_polls, "polls, buffer",
                        print self.buffer_numbers[which_buf].value, "is ready."
                    break
                if num_polls > poll_timeout:
                    libc.fclose(file_pointer)
                    raise UserWarning("After %i polls, no buffer." %
                                      poll_timeout)

            if which_im >= preframes:
                response = libc.fwrite(self.buffer_pointers[which_buf],
                                       bytes_per_pixel, pixels_per_image,
                                       file_pointer)
                if response != pixels_per_image.value:
                    raise UserWarning("Not enough data written to image file.")
                    libc.fclose(file_pointer)

        libc.fclose(file_pointer)
        print "Saving:", repr(
            os.path.splitext(os.path.join(save_path, file_name))[0] + '.txt')
        file_info = open(
            os.path.splitext(os.path.join(save_path, file_name))[0] + '.txt',
            'wb')
        file_info.write('Left/right: %i pixels\r\n' % (self.wXRes.value))
        file_info.write('Up/down: %i pixels\r\n' % (self.wYRes.value))
        file_info.write('Number of images: %i\r\n' % (num_images - preframes))
        file_info.write('Data type: 16-bit unsigned integers\r\n')
        file_info.write('Byte order: Intel (little-endian)')
        file_info.close()

        print num_images, "images recorded."
        return None
Beispiel #58
0
    def apply_settings_deprecated(self,
                                  trigger='auto trigger',
                                  exposure_time_microseconds=2200,
                                  region_of_interest=(961, 841, 1440, 1320),
                                  wBin=1,
                                  verbose=True):
        """
        'trigger' can be:
         'auto trigger'
         'software trigger'
         'external trigger/software exposure control'
         'external exposure control'
        See the comment block below for explanation of what these mean.

        'exposure_time_microseconds' can be as low as 500 and as high
        as 1000000
        """

        self.disarm(verbose=verbose)
        PCO_api.PCO_ResetSettingsToDefault(self.camera_handle)

        wSensor = ctypes.c_uint16(0)
        if verbose:
            print "Setting sensor format..."
        PCO_api.PCO_SetSensorFormat(self.camera_handle, wSensor)
        PCO_api.PCO_GetSensorFormat(self.camera_handle, ctypes.byref(wSensor))
        mode_names = {0: "standard", 1: "extended"}
        if verbose:
            print " Sensor format is", mode_names[wSensor.value]

        if verbose:
            print "Getting camera health status..."
        dwWarn, dwErr, dwStatus = (ctypes.c_uint32(), ctypes.c_uint32(),
                                   ctypes.c_uint32())
        response = PCO_api.PCO_GetCameraHealthStatus(self.camera_handle,
                                                     ctypes.byref(dwWarn),
                                                     ctypes.byref(dwErr),
                                                     ctypes.byref(dwStatus))
        if verbose:
            print " Camera health status (0 0 0 means healthy):",
            print dwWarn.value, dwErr.value, dwStatus.value
        if dwWarn.value != 0 or dwErr.value != 0 or dwStatus.value != 0:
            raise UserWarning(
                "Camera unhealthy: %x %x %x %i" %
                (dwWarn.value, dwErr.value, dwStatus.value, response))

        if verbose:
            print "Reading temperatures..."
        ccdtemp, camtemp, powtemp = (ctypes.c_int16(), ctypes.c_int16(),
                                     ctypes.c_int16())
        PCO_api.PCO_GetTemperature(self.camera_handle, ctypes.byref(ccdtemp),
                                   ctypes.byref(camtemp),
                                   ctypes.byref(powtemp))
        if verbose:
            print " CCD temperature:", ccdtemp.value * 0.1, "C"
            print " Camera temperature:", camtemp.value, "C"
            print " Power supply temperature:", powtemp.value, "C"
        """
        0x0000 = [auto trigger]
        A new image exposure is automatically started best possible
        compared to the readout of an image. If a CCD is used and the
        images are taken in a sequence, then exposures and sensor readout
        are started simultaneously. Signals at the trigger input (<exp
        trig>) are irrelevant.
        - 0x0001 = [software trigger]:
        An exposure can only be started by a force trigger command.
        - 0x0002 = [extern exposure & software trigger]:
        A delay / exposure sequence is started at the RISING or FALLING
        edge (depending on the DIP switch setting) of the trigger input
        (<exp trig>).
        - 0x0003 = [extern exposure control]:
        The exposure time is defined by the pulse length at the trigger
        input(<exp trig>). The delay and exposure time values defined by
        the set/request delay and exposure command are ineffective.
        (Exposure time length control is also possible for double image
        mode; exposure time of the second image is given by the readout
        time of the first image.)
        """
        trigger_mode_names = {
            0: "auto trigger",
            1: "software trigger",
            2: "external trigger/software exposure control",
            3: "external exposure control"
        }
        mode_name_to_number = dict(
            (v, k) for k, v in trigger_mode_names.iteritems())
        if verbose:
            print "Setting trigger mode..."
        wTriggerMode = ctypes.c_uint16(mode_name_to_number[trigger])
        PCO_api.PCO_SetTriggerMode(self.camera_handle, wTriggerMode)
        PCO_api.PCO_GetTriggerMode(self.camera_handle,
                                   ctypes.byref(wTriggerMode))
        if verbose:
            print " Trigger mode is", trigger_mode_names[wTriggerMode.value]

        wStorageMode = ctypes.c_uint16()
        PCO_api.PCO_GetStorageMode(self.camera_handle,
                                   ctypes.byref(wStorageMode))
        mode_names = {
            0: "Recorder",
            1: "FIFO buffer"
        }  #Not critical for pco.edge
        if verbose:
            print "Storage mode:", mode_names[wStorageMode.value]

        if verbose:
            print "Setting recorder submode..."
        wRecSubmode = ctypes.c_uint16(1)
        PCO_api.PCO_SetRecorderSubmode(self.camera_handle, wRecSubmode)
        PCO_api.PCO_GetRecorderSubmode(self.camera_handle,
                                       ctypes.byref(wRecSubmode))
        mode_names = {0: "sequence", 1: "ring buffer"}
        if verbose:
            print " Recorder submode:", mode_names[wRecSubmode.value]

        if verbose:
            print "Setting acquire mode..."
        wAcquMode = ctypes.c_uint16(0)
        PCO_api.PCO_SetAcquireMode(self.camera_handle, wAcquMode)
        PCO_api.PCO_GetAcquireMode(self.camera_handle, ctypes.byref(wAcquMode))
        mode_names = {
            0: "auto",
            1: "external (static)",
            2: "external (dynamic)"
        }
        if verbose:
            print " Acquire mode:", mode_names[wAcquMode.value]


#        if verbose:
#            print "Setting pixel rate..."
#        if self.pco_edge_type == '4.2':
#            dwPixelRate = ctypes.c_uint32(272250000)
#        elif self.pco_edge_type == '5.5':
#            dwPixelRate = ctypes.c_uint32(286000000)
#        else:
#            raise UserWarning("Unknown PCO edge type")
#        PCO_api.PCO_SetPixelRate(self.camera_handle, dwPixelRate)
#        PCO_api.PCO_GetPixelRate(self.camera_handle, ctypes.byref(dwPixelRate))
#        if verbose:
#            print " Pixel rate:", dwPixelRate.value

        if verbose:
            print "Setting delay and exposure time..."
        if 500 > exposure_time_microseconds < 2500000:
            raise UserWarning(
                "exposure_time_microseconds must be between 500 and 2500000")
        dwDelay = ctypes.c_uint32(0)
        wTimeBaseDelay = ctypes.c_uint16(0)
        dwExposure = ctypes.c_uint32(int(exposure_time_microseconds))
        wTimeBaseExposure = ctypes.c_uint16(1)
        PCO_api.PCO_SetDelayExposureTime(self.camera_handle, dwDelay,
                                         dwExposure, wTimeBaseDelay,
                                         wTimeBaseExposure)
        PCO_api.PCO_GetDelayExposureTime(self.camera_handle,
                                         ctypes.byref(dwDelay),
                                         ctypes.byref(dwExposure),
                                         ctypes.byref(wTimeBaseDelay),
                                         ctypes.byref(wTimeBaseExposure))
        mode_names = {0: "nanoseconds", 1: "microseconds", 2: "milliseconds"}
        if verbose:
            print " Exposure:", dwExposure.value, mode_names[
                wTimeBaseExposure.value]
            print " Delay:", dwDelay.value, mode_names[wTimeBaseDelay.value]

        x0, y0, x1, y1 = enforce_roi(region_of_interest,
                                     pco_edge_type=self.pco_edge_type,
                                     verbose=verbose)

        wRoiX0, wRoiY0, wRoiX1, wRoiY1 = (ctypes.c_uint16(x0),
                                          ctypes.c_uint16(y0),
                                          ctypes.c_uint16(x1),
                                          ctypes.c_uint16(y1))
        if verbose:
            print "Setting sensor ROI..."
        PCO_api.PCO_SetROI(self.camera_handle, wRoiX0, wRoiY0, wRoiX1, wRoiY1)
        PCO_api.PCO_GetROI(self.camera_handle, ctypes.byref(wRoiX0),
                           ctypes.byref(wRoiY0), ctypes.byref(wRoiX1),
                           ctypes.byref(wRoiY1))
        if verbose:
            print " Camera ROI:"
            """We typically use 841 to 1320 u/d, 961 to 1440 l/r  for the 5.5"""
            print "  From pixel", wRoiX0.value,
            print "to pixel", wRoiX1.value, "(left/right)"
            print "  From pixel", wRoiY0.value,
            print "to pixel", wRoiY1.value, "(up/down)"
            print

        if hasattr(self, '_prepared_to_record'):
            del self._prepared_to_record

        if verbose:
            print "Setting sensor binning..."
        PCO_api.PCO_SetBinning(self.camera_handle, ctypes.c_uint16(wBin),
                               ctypes.c_uint16(wBin))

        trigger = trigger_mode_names[wTriggerMode.value]
        """Exposure is in microseconds"""
        exposure = dwExposure.value * 10.**(3 * wTimeBaseExposure.value - 3)
        roi = (wRoiX0.value, wRoiY0.value, wRoiX1.value, wRoiY1.value)
        return (trigger, exposure, roi)
Beispiel #59
0
iWait_ms = ctypes.c_ulong(5000)
iComPort = ctypes.c_uint(4)

#to double check that connection with com_port_auto returns the same result (handle) as the one with a known port
com_port_auto=ctypes.c_int(0xFFFF)
# handle = lib.QLIB_ConnectServer(iComPort)
handle = lib.QLIB_ConnectServerWithWait(iComPort, iWait_ms)
gResourceContext = HANDLE(handle)
print('wait for connection 5s')
time.sleep(3)

#################################################################################################

#Set the WLAN module type if not called assumes a wrong module
eModuletype = ctypes.c_uint32(1)
lib.QLIB_FTM_WLAN_SetModuleType(gResourceContext, eModuletype)

#try creating string_buffer and pass byref
#dllID = ctypes.c_wchar_p('qc6180')
dllID = ctypes.create_string_buffer(b"qc6180")
chipID = ctypes.c_uint(255)
#try creating string_buffer and pass byref
#bin_file = ctypes.c_wchar_p('C:\\Qualcomm\\WCN\\ProdTests\\refDesigns\\BoardData\\fakeBoardData_AR6180.bin')
bin_file = ctypes.create_string_buffer(b"C:\\Qualcomm\\WCN\\ProdTests\\refDesigns\\BoardData\\fakeBoardData_AR6180.bin")
iNVMem = ctypes.c_int(5)
# the call below should return 1 if returns zero, load is not successfull
lib.QLIB_FTM_WLAN_Atheros_LoadDUT(gResourceContext, dllID, bin_file,iNVMem, chipID)


# ################################################################################################
Beispiel #60
0
 def RSFifo(self):
     self.dll.DLLRSFifo(ct.c_uint32(self.board_number))