Example #1
0
 def init(self, port = None):
     """Opens connection to a device. If port is not given, and serial has
     not yet been configured, it will automatically open a valid port. If
     serial was configured, it will try to open the port and find the device
     
     Parameters
     ----------
     port : int or str
         port number or None for default (search for port)           
     """
     logger.info('Initializing C862 controller.')
     self._initialized = False  
     self._info = 'Unknown'
     if port is not None:
         self.serial.port = port
     if self.serial.port is not None:
         if not self.serial.isOpen():
             self.serial.open() 
         if not check_axis(self.serial, self.device):
         #if self.device not in list_axes(self.serial):
             raise InstrError('Device %i not found in port %s' % (self.device, self.serial.port))
     else:
         port = find_port(self.device)
         if port is None:
             raise InstrError('Device %i not found in any port' % self.device)
         self.serial.port = port
         self.serial.open()
     version = _ask(self.serial, self.device, 'VE') #read version
     _write(self.serial, self.device, 'EF') #echo off
     self._info = version[version.find(b'Ver.'):].strip(b'\x03').strip() #only store last part
     self._initialized = True  
Example #2
0
    def init(self, port=None, baudrate=None):
        """Opens connection to a device. If port is not given and serial has
        not yet been configured, it will automatically open a valid port.

		:param port: str
			port number or None for default (search for port)
		:param baudrate: int
		"""
        logger.info('Initializing Magsensor.')
        self._initialized = False
        self._info = 'Unknown'
        if baudrate is not None:
            self.serial.baudrate = baudrate
        if port is not None:
            self.serial.port = port
            if not self.serial.is_open:
                self.serial.open()
            if not _checkPort(self.serial):
                # if self.serial does not meet requrements
                raise InstrError('Port {} does not meet requirements.'.format(
                    self.serial.port))
        else:
            port = findPort()
            if port is None:
                raise InstrError('Sensor not found in any port.')
            self.serial.port = port
            self.serial.open()
            if not _checkPort(self.serial):
                # if self.serial does not meet requrements
                raise InstrError(
                    'Port {} does not meet requirements in second init.'.
                    format(self.serial.port))
        self._info = 'MicroteslaSensor by Natan Osterman'
        self._initialized = True
Example #3
0
def _format_output(string, command):
    r"""Convert raw string data to integer or a list of integers (for multiple data),
    based on the command that was send in. Only works for a single query commands
    (single output strings). On error it logs it and returns None
    
    >>> _format_output('P:+00000\r\n\x03', 'TP')
    0
    >>> _format_output('S:00 0A 4F\r\n\x03', 'TS')
    [0, 10, 79]
    """
    logger.debug('Formatting output %s' % string)
    s = string.strip(b'\x03').strip() #remove white chars
    try:
        id, value = s.split(b':')
        if value == b'':
            raise InstrError('Unexpected string "%s" received. Possible timeout error.' %s)
    except ValueError:
        raise InstrError('Unexpected string "%s" received' %s)
    else:
        identifier = IDENTIFIERS.get(command)
        if id[0] ==  identifier[0] and value != b'': #id can be multichar, just check first one
            if id in (b'S',b'C',b'Z'): #these are in hex format, so convert to int
                values = [int(b'0x'+v,0) for v in value.split()]   
            else:
                values = [int(v) for v in value.split()]
            if len(values) > 1 :
                return values
            else:
                return values[0]
        else:
            raise InstrError('Expected identifier "%s", but string "%s received' %(identifier,s))
Example #4
0
 def ask_value(self, command):
     """ask_value(command)
     Same as ask, but convert output to integer.
     """
     identifier = IDENTIFIERS.get(command)
     if identifier is None:
         if len(command) > 2:
             try:
                 identifier = IDENTIFIERS[command[0:2]] 
             except (KeyError, TypeError):
                 raise InstrError('Unsupported command %s' % command)
         else:
             raise InstrError('Unsupported command %s' % command)
     return _ask_value(self.serial, self.device, command)
Example #5
0
def check_axis(serial, device):
    """Checks whether device exists on a given opened serial port.
    
    Parameters
    ----------
    serial : serial port
        An open serial port.
    device : int
        Device number. Should be between 0-15

    Returns
    -------
    True if it exists, False otherwise
    """
    try:
        out = _ask_value(serial,device,'TB')
    except InstrError: #no device here, just pass
        logger.debug('Device %i not found on port %s.' % (device,serial.port))
        return False
    else:
        if out == device:
            logger.debug('Device %i found on port %s.' % (device,serial.port))
            return True
        else:
            raise InstrError('Device board address %i does not match identifier %i' % (out, device)) 
Example #6
0
def _read(serial, end='\x03'):
    out = ''
    while True:
        c = serial.read()
        if c == end:
            break
        elif c == '':
            raise InstrError(
                'EOL char not received. Is device connected and ready?')
        out += c
    return out
Example #7
0
 def _wait_for_power(self, state):
     """Waits until power is either on or off, determined by the state 
     parameter. Waits max TIMEOUT second, then raises Error
     """
     for i in range(int(TIMEOUT / INTERVAL)):
         time.sleep(INTERVAL)
         status = usmc.get_state(self.device)
         self._powered = bool(status['Power'])
         if self._powered == state:
             return
     raise InstrError('Could not change motor power!')
Example #8
0
 def save_clip(self, fname, n = 1, wait = True):
     """Starts video stream, Saves raw clip of n frames to a file. By default it waits for video to complete
     and stops the stream. If you speciy waid = False, you should call self.stop() after video is captured
     to stop the stream.
     """
     if self._video_done == False:
         raise InstrError('Still recording video. Stop video streaming first')
     self.set_stream_state(STOP_STREAM)
     self.set_stream_state(START_STREAM)
     self._video_done = False
     execute(PxLGetClip, self._handle, n, fname, self._cb)
     if wait == True:
         self.wait()
Example #9
0
    def __new__(cls, index=0):
        if cls.__system is None:
            cls.__system = PySpin.System.GetInstance()
            cls.__cam_list = cls.__system.GetCameras()
            cls.__num_cameras = cls.__cam_list.GetSize()

        logger.info('Starting bfly camera on index {}'.format(index))

        if index not in range(cls.__num_cameras):
            raise InstrError(
                'Camera number {} too big. Total number {}'.format(
                    index, cls.__num_cameras))
        return BflyCamera(cls.__cam_list.GetByIndex(index), index)
Example #10
0
def _formatInput(line):
    """
	Formats input to get Bx, By, Bz
	:param line: string line
	:return: float Bx, float By, float Bz or None
	"""
    logger.debug('Formatting output {}'.format(line))
    line = line.split(b'(')[-1]
    line = line.split(b')')[0]
    try:
        x, y, z = [float(k.decode()) for k in line.split()]
        return x, y, z
    except ValueError:
        raise InstrError('Not able to split input "{}".'.format(line))
Example #11
0
 def empty_frame(self):
     """Creates an empty image frame. based on camera specifications,
     for filling with the :meth:`.Camera.get_next_frame`"""
     resample, typ = self.get_feature(FEATURE_DECIMATION, as_type = int)
     t,l,b,r = self.get_feature(FEATURE_ROI, as_type = int)
     im_shape = (r-l)/resample, (b-t)/resample 
     format = self.get_feature(FEATURE_PIXEL_FORMAT, as_type = int)[0]
     try:
         color, dt = PIXEL_FORMAT[int(format)]
     except KeyError:
         raise InstrError('Unsupported pixel format %s' % format)
     if color == 'rgb':
         im_shape = im_shape + (3,) 
     return np.empty(im_shape, dtype = dt).newbyteorder(ENDIAN)
Example #12
0
def _read(serial):
    data = ''
    size = serial.inWaiting()
    while True:
        data = data + serial.read(size)
        size = serial.inWaiting()
        if size == 0 and data.endswith('\r'):
            break
        else:
            time.sleep(1)
            size = serial.inWaiting()
            if size == 0:
                raise InstrError('Wrong response form Osciloscope')
    return data
Example #13
0
    def init(self, device=0, reversed=None, step=None):
        """
        Initialize controller and set motor parameters
        
        Parameters
        ----------
        device : int, optional
            device number id. This is alway zero, except if there are multiple 
            devices connected you have to specify it.
        reversed : bool, optional
            defines whether motor movement is reversed or not 
        step : float, optional
            defines motor step size in microns
            
        Returns
        -------
        serial : str
            A string representing a serial number of the selected device 
        """
        logger.info('Initializing')
        if reversed is not None:
            self.reversed = reversed
        if step is not None:
            self.step = step
        self._initialized = False
        self._info = 'Unknown'
        if USMC_LOADED == False:
            raise InstrError(USMC_WARNING)
        self._device = device
        devices = usmc.init()
        try:
            self._info = 'Serial No.: ' + devices[self.device][0].lstrip(
                '0')  #remove leading zeros because there are many zzros
        except IndexError:  #if device out of range it will fail later, so setting serial..
            self._info = 'Unknown'

        mode = {
            'Tr1En': 1,  #limit switch 1 enabled
            'Tr2En': 1,
            'Tr1T': 1,  #limit switch 1 on state
            'Tr2T': 1,
            'ResetD': 0,  #power on
            'PReg': 1  #power reduction on
        }
        mode = usmc.set_mode(device=self.device, **mode)
        self._initialized = True
        self.on()
        return self._info
Example #14
0
 def check_error(self):
     """Raises an InstrumentError in case of an error.
     This method gets called automatically after every get_* or 
     set_* methods. If you use ask, or write methods. You should
     call this afterwards to check if there are any errors reported.
     """
     id, msg = format_error_message(self.ask('*ESR?'))
     if id == 0:
         return None
     else:
         errors = []
         while id != 0:
             errors.append(msg)
             id, msg = format_error_message(self.ask('*ESR?'))
         message = ','.join(errors)
         self.logger.error('Instrument error: %s' % message)
         raise InstrError(message)
Example #15
0
    def __init__(self, CameraPtr, index=0):
        if not isinstance(CameraPtr, PySpin.CameraPtr):
            raise InstrError(
                'Camera class is {} instead of PySpin.CameraPtr'.format(
                    CameraPtr.__class__))
        self._device = index
        self._camera = CameraPtr
        self._info = self._getCameraName()

        self._imageFormat = PySpin.PGM  # default image format PGM = 0

        # filming
        self.__recording_video = False
        self.__recording_paused = False
        self.__video_file = None
        self._frames_recorded = 0
        self.__video_start_time = 0.0
        self.converted_image = None