Esempio n. 1
0
/**
 * Create an instance of a Serial Port class.
 * 
 * @param baudRate The baud rate to configure the serial port.  The cRIO-9074 supports up to 230400 Baud.
 * @param dataBits The number of data bits per transfer.  Valid values are between 5 and 8 bits.
 * @param parity Select the type of parity checking to use.
 * @param stopBits The number of stop bits to use as defined by the enum StopBits.
 */
SerialPort::SerialPort(UINT32 baudRate, UINT8 dataBits, SerialPort::Parity parity, SerialPort::StopBits stopBits):m_resourceManagerHandle(0),
    m_portHandle
    (0)
{
    ViStatus status = VI_SUCCESS;
    status = viOpenDefaultRM((ViSession *) & m_resourceManagerHandle);
    wpi_assertCleanStatus(status);

    status =
        viOpen(m_resourceManagerHandle, "ASRL1::INSTR", VI_NULL, VI_NULL,
               (ViSession *) & m_portHandle);
    wpi_assertCleanStatus(status);

    status = viSetAttribute(m_portHandle, VI_ATTR_ASRL_BAUD, baudRate);
    wpi_assertCleanStatus(status);
    status = viSetAttribute(m_portHandle, VI_ATTR_ASRL_DATA_BITS, dataBits);
    wpi_assertCleanStatus(status);
    status = viSetAttribute(m_portHandle, VI_ATTR_ASRL_PARITY, parity);
    wpi_assertCleanStatus(status);
    status = viSetAttribute(m_portHandle, VI_ATTR_ASRL_STOP_BITS, stopBits);
    wpi_assertCleanStatus(status);

    // Set the default timeout to 5 seconds.
    SetTimeout(5.0f);

    // Don't wait until the buffer is full to transmit.
    SetWriteBufferMode(kFlushOnAccess);

    EnableTermination();

    //viInstallHandler(m_portHandle, VI_EVENT_IO_COMPLETION, ioCompleteHandler, this);
    //viEnableEvent(m_portHandle, VI_EVENT_IO_COMPLETION, VI_HNDLR, VI_NULL);
}
Esempio n. 2
0
void serialEnableTermination(uint8_t port, char terminator, int32_t *status) {
	viSetAttribute(m_portHandle[port], VI_ATTR_TERMCHAR_EN, VI_TRUE);
	viSetAttribute(m_portHandle[port], VI_ATTR_TERMCHAR, terminator);
	*status = viSetAttribute(m_portHandle[port], VI_ATTR_ASRL_END_IN, VI_ASRL_END_TERMCHAR);
	if(*status > 0)
		*status = 0;
}
Esempio n. 3
0
int		WaitForOperationCompletion( int sessionHandle , double lfTimeout , double lfLowLevelTimeout )
{
	double			lfStartTime						=	0.0,
					lfCurrentTime					=	0.0;

	int				iOpcStatus						=	0;
	
	char			szReadFeedback[LOW_STRING]		=	{0};
	
	int				count							=	0;
	
	int				iTimeout						=	0;
	
	int				iError							=	0;
	
	viGetAttribute ( sessionHandle , VI_ATTR_TMO_VALUE , &iTimeout );   
	
	SetBreakOnLibraryErrors (0); 
	
	viSetAttribute ( sessionHandle , VI_ATTR_TMO_VALUE , (lfLowLevelTimeout*1E3) );  
	
	GetCurrentDateTime(&lfStartTime);
	
	do
	{
		viPrintf( sessionHandle , "*OPC?\n" );
						
		viRead( sessionHandle, szReadFeedback , (LOW_STRING-1) , &count );
	
		iOpcStatus = atoi(szReadFeedback);
		
		if ( iOpcStatus )
			break;
		
		GetCurrentDateTime(&lfCurrentTime);
		
	} while((lfCurrentTime-lfStartTime) < lfTimeout );
	
	if ( iOpcStatus )
	{
		viPrintf( sessionHandle , ":SYST:ERR?\n" );
		SetBreakOnLibraryErrors (0);
		viRead( sessionHandle, szReadFeedback , LOW_STRING , &count );
		SetBreakOnLibraryErrors (1);
	
		iError = atoi(szReadFeedback);
	
		if ( iError == -420 )
		{
			viPrintf( sessionHandle , "*CLS\n" );  
		}
	}
	
	viSetAttribute ( sessionHandle , VI_ATTR_TMO_VALUE , iTimeout );  
	
	SetBreakOnLibraryErrors (1); 
	
	return iOpcStatus;
}
Esempio n. 4
0
/**
 * Disable termination behavior.
 */
void SerialPort::DisableTermination()
{
	if (!m_consoleModeEnabled)
	{
		viSetAttribute(m_portHandle, VI_ATTR_TERMCHAR_EN, VI_FALSE); 
		viSetAttribute(m_portHandle, VI_ATTR_ASRL_END_IN, VI_ASRL_END_NONE);
	}
}
Esempio n. 5
0
/**
 * Enable termination and specify the termination character.
 * 
 * Termination is currently only implemented for receive.
 * When the the terminator is recieved, the Read() or Scanf() will return
 *   fewer bytes than requested, stopping after the terminator.
 * 
 * @param terminator The character to use for termination.
 */
void SerialPort::EnableTermination(char terminator)
{
	if (!m_consoleModeEnabled)
	{
		viSetAttribute(m_portHandle, VI_ATTR_TERMCHAR_EN, VI_TRUE); 
		viSetAttribute(m_portHandle, VI_ATTR_TERMCHAR, terminator);
		viSetAttribute(m_portHandle, VI_ATTR_ASRL_END_IN, VI_ASRL_END_TERMCHAR);
	}
}
Esempio n. 6
0
/**
 * Clears UART receive buffer.
 *
 * @param[in]   port      UART port to access
 * @return      int32_t   Error/success status
 */
int32_t Uart_Clear(MyRio_Uart* port)
{
    int32_t status = VI_SUCCESS;
    int32_t oldTimeout = 0;
    uint8_t read[0xFF] = {0};
    ViUInt32 nRead = 0;

    /*
     * Get timeout.
     */
    status = viGetAttribute(port->session, VI_ATTR_TMO_VALUE, &oldTimeout);
    if (status < VI_SUCCESS)
    {
        return status;
    }

    /*
     * Set timeout to 1 ms.
     */
    status = viSetAttribute(port->session, VI_ATTR_TMO_VALUE, 1);
    if (status < VI_SUCCESS)
    {
        return status;
    }

    /*
     * Read input buffer, up to 255 bytes at a time, until timeout occurs.
     */
    while((status = viRead(port->session, (ViBuf)read, (ViUInt32)0xFF,
          &nRead)) >= VI_SUCCESS);
    if (status == VI_ERROR_TMO)
    {
        /*
         * Timeout expected.
         */
        status = VI_SUCCESS;
    }

    /*
     * Reset timeout to previous value.
     */
    status = viSetAttribute(port->session, VI_ATTR_TMO_VALUE, oldTimeout);
    if (status < VI_SUCCESS)
    {
        return status;
    }

    return status;
}
Esempio n. 7
0
/**
 * Set the type of flow control to enable on this port.
 * 
 * By default, flow control is disabled.
 */
void SerialPort::SetFlowControl(SerialPort::FlowControl flowControl)
{
    if (!m_consoleModeEnabled)
    {
        ViStatus localStatus = viSetAttribute (m_portHandle, VI_ATTR_ASRL_FLOW_CNTRL, flowControl);
        wpi_setError(localStatus);
    }
}
Esempio n. 8
0
/**
 * Specify the flushing behavior of the output buffer.
 * 
 * When set to kFlushOnAccess, data is synchronously written to the serial port
 *   after each call to either Printf() or Write().
 * 
 * When set to kFlushWhenFull, data will only be written to the serial port when
 *   the buffer is full or when Flush() is called.
 * 
 * @param mode The write buffer mode.
 */
void SerialPort::SetWriteBufferMode(SerialPort::WriteBufferMode mode)
{
    if (!m_consoleModeEnabled)
    {
        ViStatus localStatus = viSetAttribute(m_portHandle, VI_ATTR_WR_BUF_OPER_MODE, mode);
        wpi_setError(localStatus);
    }
}
Esempio n. 9
0
/**
 * Configure the timeout of the serial port.
 * 
 * This defines the timeout for transactions with the hardware.
 * It will affect reads and very large writes.
 * 
 * @param timeout The number of seconds to to wait for I/O.
 */
void SerialPort::SetTimeout(float timeout)
{
    if (!m_consoleModeEnabled)
    {
        ViStatus localStatus = viSetAttribute(m_portHandle, VI_ATTR_TMO_VALUE, (UINT32)(timeout * 1e3));
        wpi_setError(localStatus);
    }
}
Esempio n. 10
0
/**
 * Configure the timeout of the serial port.
 * 
 * This defines the timeout for transactions with the hardware.
 * It will affect reads and very large writes.
 * 
 * @param timeout The number of seconds to to wait for I/O.
 */
void SerialPort::SetTimeout(float timeout)
{
	if (!m_consoleModeEnabled)
	{
		ViStatus status = viSetAttribute(m_portHandle, VI_ATTR_TMO_VALUE, (UINT32)(timeout * 1e3));
		wpi_assertCleanStatus(status);
	}
}
Esempio n. 11
0
/**
 * Specify the flushing behavior of the output buffer.
 * 
 * When set to kFlushOnAccess, data is synchronously written to the serial port
 *   after each call to either Printf() or Write().
 * 
 * When set to kFlushWhenFull, data will only be written to the serial port when
 *   the buffer is full or when Flush() is called.
 * 
 * @param mode The write buffer mode.
 */
void SerialPort::SetWriteBufferMode(SerialPort::WriteBufferMode mode)
{
	if (!m_consoleModeEnabled)
	{
		ViStatus status = viSetAttribute(m_portHandle, VI_ATTR_WR_BUF_OPER_MODE, mode);
		wpi_assertCleanStatus(status);
	}
}
Esempio n. 12
0
/**
 * Set the type of flow control to enable on this port.
 * 
 * By default, flow control is disabled.
 */
void SerialPort::SetFlowControl(SerialPort::FlowControl flowControl)
{
	if (!m_consoleModeEnabled)
	{
		ViStatus status = viSetAttribute (m_portHandle, VI_ATTR_ASRL_FLOW_CNTRL, flowControl);
		wpi_assertCleanStatus(status);
	}
}
Esempio n. 13
0
/**
 * Create an instance of a Serial Port class.
 * 
 * @param baudRate The baud rate to configure the serial port.  The cRIO-9074 supports up to 230400 Baud.
 * @param dataBits The number of data bits per transfer.  Valid values are between 5 and 8 bits.
 * @param parity Select the type of parity checking to use.
 * @param stopBits The number of stop bits to use as defined by the enum StopBits.
 */
SerialPort::SerialPort(uint32_t baudRate, uint8_t dataBits, SerialPort::Parity parity, SerialPort::StopBits stopBits)
	: m_resourceManagerHandle (0)
	, m_portHandle (0)
	, m_consoleModeEnabled (false)
{
	ViStatus localStatus = VI_SUCCESS;
	localStatus = viOpenDefaultRM((ViSession*)&m_resourceManagerHandle);
	wpi_setError(localStatus);

	localStatus = viOpen(m_resourceManagerHandle, const_cast<char*>("ASRL1::INSTR"), VI_NULL, VI_NULL, (ViSession*)&m_portHandle);
	wpi_setError(localStatus);
	if (localStatus != 0)
	{
		m_consoleModeEnabled = true;
		return;
	}

	localStatus = viSetAttribute(m_portHandle, VI_ATTR_ASRL_BAUD, baudRate);
	wpi_setError(localStatus);
	localStatus = viSetAttribute(m_portHandle, VI_ATTR_ASRL_DATA_BITS, dataBits);
	wpi_setError(localStatus);
	localStatus = viSetAttribute(m_portHandle, VI_ATTR_ASRL_PARITY, parity);
	wpi_setError(localStatus);
	localStatus = viSetAttribute(m_portHandle, VI_ATTR_ASRL_STOP_BITS, stopBits);
	wpi_setError(localStatus);

	// Set the default timeout to 5 seconds.
	SetTimeout(5.0f);

	// Don't wait until the buffer is full to transmit.
	SetWriteBufferMode(kFlushOnAccess);

	EnableTermination();

	//viInstallHandler(m_portHandle, VI_EVENT_IO_COMPLETION, ioCompleteHandler, this);
	//viEnableEvent(m_portHandle, VI_EVENT_IO_COMPLETION, VI_HNDLR, VI_NULL);

	nUsageReporting::report(nUsageReporting::kResourceType_SerialPort, 0);
}
Esempio n. 14
0
void* DLLEXPORT PowerMeter_OPC( int hInstrumentHandle , double lfTimeOut , int *state )
{
	STD_ERROR					StdError					=	{0};

	ViAttrState					attrValue					=	0;
	
	attrValue = lfTimeOut * 1E3;
	
	viSetAttribute ( hInstrumentHandle , VI_ATTR_TMO_VALUE , lfTimeOut );
		
	if ( state )
		*state = Delay_LastComplete( hInstrumentHandle );
		
Error:	
	
	RETURN_STDERR_POINTER;
}
Esempio n. 15
0
void* DLLEXPORT PowerMeter_OPC( int hInstrumentHandle , double lfTimeOut , int *state )
{
	errEV					ret					=	{0};
	errEV					*pRet				=	NULL;

	ViAttrState				attrValue			=	0;
	
	attrValue = lfTimeOut * 1E3;
	
	viSetAttribute ( hInstrumentHandle , VI_ATTR_TMO_VALUE , lfTimeOut );
		
	if ( state )
		*state = Delay_LastComplete( hInstrumentHandle );
		
Error:	
	
	CALLOC_COPY(pRet,1,sizeof(errEV),&ret,sizeof(errEV));
	
	return ((void*)pRet);
}
Esempio n. 16
0
void serialSetBaudRate(uint8_t port, uint32_t baud, int32_t *status) {
	*status = viSetAttribute(m_portHandle[port], VI_ATTR_ASRL_BAUD, baud);
	if(*status > 0)
		*status = 0;
}
Esempio n. 17
0
void HAL_SetSerialParity(int32_t port, int32_t parity, int32_t* status) {
  *status = viSetAttribute(m_portHandle[port], VI_ATTR_ASRL_PARITY, parity);
  if (*status > 0) *status = 0;
}
Esempio n. 18
0
void HAL_SetSerialWriteMode(int32_t port, int32_t mode, int32_t* status) {
  *status = viSetAttribute(m_portHandle[port], VI_ATTR_WR_BUF_OPER_MODE, mode);
  if (*status > 0) *status = 0;
}
Esempio n. 19
0
void HAL_SetSerialFlowControl(int32_t port, int32_t flow, int32_t* status) {
  *status = viSetAttribute(m_portHandle[port], VI_ATTR_ASRL_FLOW_CNTRL, flow);
  if (*status > 0) *status = 0;
}
Esempio n. 20
0
void HAL_SetSerialTimeout(int32_t port, double timeout, int32_t* status) {
  *status = viSetAttribute(m_portHandle[port], VI_ATTR_TMO_VALUE,
                           static_cast<uint32_t>(timeout * 1e3));
  if (*status > 0) *status = 0;
}
Esempio n. 21
0
 void VisaEmitter::EIO_Open(GenericBaton* data) {
   char temp[QUERY_STRING_SIZE];
   ViStatus status = -1;
   if (this->isConnected)
   {
     _snprintf(temp, sizeof(temp), "Already connected %s", session);
     ErrorCodeToString(temp, status, data->errorString);
     return;
   }
   status = viOpenDefaultRM(&defaultRM);
   if (status < VI_SUCCESS) {
     _snprintf(temp, sizeof(temp), "Opening RM");
     ErrorCodeToString(temp, status, data->errorString);
     return;
   }
   status = viOpen(defaultRM, data->command, VI_NULL, this->timeoutMiliSeconds, &session);
   if (status < VI_SUCCESS) {
     _snprintf(temp, sizeof(temp), "Opening session %s", data->command);
     ErrorCodeToString(temp, status, data->errorString);
     return;
   }
   status = viSetAttribute(session, VI_ATTR_TMO_VALUE, this->timeoutMiliSeconds);
   if (status < VI_SUCCESS) {
     _snprintf(temp, sizeof(temp), "Setting timeout to %d", this->timeoutMiliSeconds);
     ErrorCodeToString(temp, status, data->errorString);
     return;
   }
   
   
   this->isConnected = true;
   // status = viSetAttribute(instr, VI_ATTR_SEND_END_EN, VI_TRUE);
   // terminate reads on a carriage return  0x0a 0x0d
   // LF (Line feed, '\n', 0x0A, 10 in decimal) 
   // Carriage return, '\r', 0x0D, 13 in decimal
   
   // status = viSetAttribute(session, VI_ATTR_TERMCHAR, 0x0A);
   //status = viSetAttribute(session, VI_ATTR_TERMCHAR_EN, VI_TRUE);
   
   if (this->assertREN) {
     viGpibControlREN(session, VI_GPIB_REN_ASSERT);
   }
   
   if (this->enableSRQ)  
   {
     m_async = uv_async_t();
     m_async.data = this;    
     uv_async_init(uv_default_loop(), &m_async, reinterpret_cast<uv_async_cb>(aCallback));
     isAsyncInitialized = true;
     
     status = viInstallHandler(session, VI_EVENT_SERVICE_REQ, callback, this->uniqueSRQhandlerIdentification);
     if (status >= VI_SUCCESS) {
       status = viEnableEvent(session, VI_EVENT_SERVICE_REQ, VI_HNDLR, VI_NULL);
     }  
     if (status < VI_SUCCESS) {
       _snprintf(temp, sizeof(temp), "Post AfterOpenSuccess session %s", data->command);
       ErrorCodeToString(temp, status, data->errorString);
       return;
     }        
     this->installedSRQHanlder = true;
   }    
   _snprintf_s(data->result, _countof(data->result), _TRUNCATE, "%d", session);
 }
Esempio n. 22
0
void serialDisableTermination(uint8_t port, int32_t *status) {
	viSetAttribute(m_portHandle[port], VI_ATTR_TERMCHAR_EN, VI_FALSE);
	*status = viSetAttribute(m_portHandle[port], VI_ATTR_ASRL_END_IN, VI_ASRL_END_NONE);
	if(*status > 0)
		*status = 0;
}
Esempio n. 23
0
void serialSetTimeout(uint8_t port, float timeout, int32_t *status) {
	*status = viSetAttribute(m_portHandle[port], VI_ATTR_TMO_VALUE, (uint32_t)(timeout * 1e3));
	if(*status > 0)
		*status = 0;
}
Esempio n. 24
0
void serialSetWriteMode(uint8_t port, uint8_t mode, int32_t *status) {
	*status = viSetAttribute(m_portHandle[port], VI_ATTR_WR_BUF_OPER_MODE, mode);
	if(*status > 0)
		*status = 0;
}	
Esempio n. 25
0
void serialSetFlowControl(uint8_t port, uint8_t flow, int32_t *status) {
	*status = viSetAttribute(m_portHandle[port], VI_ATTR_ASRL_FLOW_CNTRL, flow);
	if(*status > 0)
		*status = 0;
}
Esempio n. 26
0
void serialSetStopBits(uint8_t port, uint8_t stopBits, int32_t *status) {
	*status = viSetAttribute(m_portHandle[port], VI_ATTR_ASRL_STOP_BITS, stopBits);
	if(*status > 0)
		*status = 0;
}
Esempio n. 27
0
void serialSetParity(uint8_t port, uint8_t parity, int32_t *status) {
	*status = viSetAttribute(m_portHandle[port], VI_ATTR_ASRL_PARITY, parity);
	if(*status > 0)
		*status = 0;
}
Esempio n. 28
0
void serialSetDataBits(uint8_t port, uint8_t bits, int32_t *status) {
	*status = viSetAttribute(m_portHandle[port], VI_ATTR_ASRL_DATA_BITS, bits);
	if(*status > 0)
		*status = 0;
}
Esempio n. 29
0
// ================================================================================================
// FUNCTION  : mexVISA
// ------------------------------------------------------------------------------------------------
// Purpose   : Implement basic VISA functions for a MATLAB toolbox
// Parameters: passed from MATLAB mexFunction
// Returns   : {0=success, -1=failure}
// ================================================================================================
int mexVISA(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    ViStatus Status;      // returned status from called VISA function
    char *tcmd, cmd[256]; // passed command parameter

    // ----------------------
    // Get the command string
    // ----------------------
    if(nrhs<1) mexErrMsgTxt("A string argument must be given as the first parameter.");
    tcmd = ViMexUtil_GetStringValue(prhs[0],0);
    strncpy(cmd, tcmd, 256); mxFree(tcmd); cmd[255] = 0; // copied and free tcmd as it is not free'd below

    // ******************************************
    // *****                                *****
    // *****   COMMAND LOOKUP-AND-EXECUTE   *****
    // *****                                *****
    // ******************************************

    // --------------
    // viOpen
    // --------------
    if(!strcmp(cmd, "viOpen()"))
    {
        ViSession RMSession, Session = 0;
        ViString  Resource; ViUInt32 Timeout;

        if( (nrhs!=3) && (nrhs!=4) )
            mexErrMsgTxt("Incorrect number of input parameters (needs to be 3 or 4)");
        if( nlhs != 2)
            mexErrMsgTxt("2 output terms were expected\n");

        if(!mexVISA_GetViRM(&RMSession))
        {
            Resource = ViMexUtil_GetStringValue(prhs[1], 0);
            Timeout  = (ViUInt32)ViMexUtil_GetUIntValue(prhs[2]);
            
            if(ResourceChecking)
            {
                if(mexVISA_ResourceIsOpen(Resource, &Session))
                {
                    if(AllowSharedSessions) 
                        Status = VI_SUCCESS;
                    else
                        mexErrMsgTxt(" Resource is already open");
                }
            }
            if(!Session)
            {
                Status = viOpen(RMSession, Resource, VI_NULL, Timeout, &Session);
                if(ResourceChecking && (Status == VI_SUCCESS))
                {
                    if(nrhs == 3)
                        mexVISA_InsertSession(Session, Resource, "no stack trace available\n");
                    else
                    {

                        ViString StackTrace = ViMexUtil_GetStringValue(prhs[3], 0);
                        mexVISA_InsertSession(Session, Resource, StackTrace);
                        mxFree(StackTrace);
                    }
                }
            }
            ViMexUtil_PutIntValue(Status, &plhs[0]);
            ViMexUtil_PutUIntValue((unsigned)Session, &plhs[1]);
            mxFree(Resource);
            return 0;
        }
        else mexErrMsgTxt("mexVISA: Call to viOpenDefaultRM prior to viOpen failed.");
    }
    // ---------------
    // viClose
    // ---------------
    if(!strcmp(cmd, "viClose()"))
    {
        ViSession Session;
        ViMexUtil_CheckParameters(nlhs,nrhs,1,2);
        Session = (ViSession)ViMexUtil_GetUIntValue(prhs[1]);
        Status = viClose(Session);
        if(ResourceChecking && (Status == VI_SUCCESS))
            mexVISA_RemoveSession(Session);
        ViMexUtil_PutIntValue((int)Status, &plhs[0]);
        return 0;
    }
    // ---------------
    // viWrite
    // ---------------
    if(!strcmp(cmd, "viWrite()"))
    {
        ViSession Session;
        ViUInt32 Count, Return_Count;
        ViBuf Buffer; char *Message;

        ViMexUtil_CheckParameters(nlhs,nrhs,2,3);
        Session = (ViSession)ViMexUtil_GetUIntValue(prhs[1]);
        Buffer  = (ViBuf)ViMexUtil_GetStringValue(prhs[2], ((ViUInt32 *)&Count));
        Message = (char *)mxCalloc(Count+2, sizeof(char));
        if(!Message) mexErrMsgTxt("Memory allocation error.");
        sprintf(Message,"%s",Buffer);
        Status = viWrite(Session, Message, Count-1, &Return_Count);
        ViMexUtil_PutIntValue((int)Status, &plhs[0]);
        ViMexUtil_PutUIntValue(Return_Count, &plhs[1]);
        mxFree(Message); mxFree((char *)Buffer);
        return 0;
    }
    // ---------------
    // viWriteBinary
    // ---------------
    if(!strcmp(cmd, "viWriteBinary()"))
    {
        ViSession Session;
        ViUInt32 Count, Return_Count;
        ViBuf Buffer;

        ViMexUtil_CheckParameters(nlhs,nrhs,2,3);
        Session = (ViSession)ViMexUtil_GetUIntValue(prhs[1]);
        Buffer  = (ViBuf)ViMexUtil_GetBinaryArray(prhs[2], ((ViUInt32 *)&Count));
        Status = viWrite(Session, Buffer, Count, &Return_Count);
        ViMexUtil_PutIntValue((int)Status, &plhs[0]);
        ViMexUtil_PutUIntValue(Return_Count, &plhs[1]);
        mxFree((char *)Buffer);
        return 0;
    }
    // ---------------
    // viPrintf
    // ---------------
    if(!strcmp(cmd, "viPrintf()"))
    {
        ViSession Session;
        ViUInt32 Count;
        ViBuf Buffer;

        ViMexUtil_CheckParameters(nlhs,nrhs,1,3);
        Session = (ViSession)ViMexUtil_GetUIntValue(prhs[1]);
        Buffer  = (ViBuf)ViMexUtil_GetStringValue(prhs[2], ((ViUInt32 *)&Count));
        Status = viPrintf(Session,"%s",Buffer);
        ViMexUtil_PutIntValue((int)Status, &plhs[0]);
        mxFree((char *)Buffer);
        return 0;
    }
    // --------------
    // viRead
    // --------------
    if(!strcmp(cmd, "viRead()"))
    {
        ViSession Session;
        ViUInt32 Count, Return_Count;
        unsigned char *Buffer;

        ViMexUtil_CheckParameters(nlhs,nrhs,2,3);
        Session = (ViSession)ViMexUtil_GetUIntValue(prhs[1]);
        Count   = (ViUInt32)ViMexUtil_GetUIntValue(prhs[2]);
        Buffer  = (unsigned char *)mxCalloc(Count+1,sizeof(char));
        if(!Buffer) mexErrMsgTxt("Memory Allocation Failed.\n");
        Status = viRead(Session, Buffer, Count, &Return_Count);
        if(Return_Count < Count) Buffer[Return_Count-1] = '\0';
        ViMexUtil_PutIntValue((int)Status, &plhs[0]);
        ViMexUtil_PutString(Buffer, &plhs[1]);
        mxFree(Buffer); // removed 6/4/04 for debug
        return 0;
    }
    // --------------
    // viReadBinary
    // --------------
    if(!strcmp(cmd, "viReadBinary()"))
    {
        ViSession Session;
        ViUInt32 Count, Return_Count;
        unsigned char *Buffer;

        ViMexUtil_CheckParameters(nlhs,nrhs,2,3);
        Session = (ViSession)ViMexUtil_GetUIntValue(prhs[1]);
        Count   = (ViUInt32)ViMexUtil_GetUIntValue(prhs[2]);
        Buffer  = (unsigned char *)mxCalloc(Count+1,sizeof(char));
        if(!Buffer) mexErrMsgTxt("Memory Allocation Failed.\n");
        Status = viRead(Session, Buffer, Count, &Return_Count);
        ViMexUtil_PutIntValue((int)Status, &plhs[0]);
        ViMexUtil_PutBinaryArray(Return_Count, Buffer, &plhs[1]);
        mxFree(Buffer);
        return 0;
    }
    // -------
    // viClear
    // -------
    if(!strcmp(cmd, "viClear()"))
    {
        ViSession Session;

        ViMexUtil_CheckParameters(nlhs,nrhs,1,2);
        Session = (ViSession)ViMexUtil_GetUIntValue(prhs[1]);
        Status = viClear(Session);
        ViMexUtil_PutIntValue((int)Status, &plhs[0]);
        return 0;
    }
    // ---------
    // viReadSTB
    // ---------
    if(!strcmp(cmd, "viReadSTB()"))
    {
        ViSession Session;
        ViUInt16 Status_Byte;

        ViMexUtil_CheckParameters(nlhs,nrhs,2,2);
        Session = (ViSession)ViMexUtil_GetUIntValue(prhs[1]);
        Status = viReadSTB(Session, &Status_Byte);
        ViMexUtil_PutIntValue((int)Status, &plhs[0]);
        ViMexUtil_PutUIntValue((unsigned)Status_Byte, &plhs[1]);
        return 0;
    }
    // ---------------
    // viAssertTrigger
    // ---------------
    if(!strcmp(cmd, "viAssertTrigger()"))
    {
        ViSession Session;
        ViUInt16 Protocol;
        char *ProtocolString;

        ViMexUtil_CheckParameters(nlhs,nrhs,1,3);
        Session = (ViSession)ViMexUtil_GetUIntValue(prhs[1]);
        ProtocolString = ViMexUtil_GetStringValue(prhs[2], 0);

             if(!strcmp(ProtocolString, "VI_TRIG_PROT_DEFAULT")) Protocol = VI_TRIG_PROT_DEFAULT;
        else if(!strcmp(ProtocolString, "VI_TRIG_PROT_ON"))      Protocol = VI_TRIG_PROT_ON;
        else if(!strcmp(ProtocolString, "VI_TRIG_PROT_OFF"))     Protocol = VI_TRIG_PROT_OFF;
        else if(!strcmp(ProtocolString, "VI_TRIG_PROT_SYNC"))    Protocol = VI_TRIG_PROT_SYNC;  
        else 
        {
            mxFree(ProtocolString);
            mexErrMsgTxt("Unrecognized protocol definition");
        }
        Status = viAssertTrigger(Session, Protocol);
        ViMexUtil_PutIntValue((int)Status, &plhs[0]);
        mxFree(ProtocolString);
        return 0;
    }
    // ------------
    // viStatusDesc
    // ------------
    if(!strcmp(cmd, "viStatusDesc()"))
    {
        ViSession Session;
        char *Description;

        ViMexUtil_CheckParameters(nlhs,nrhs,2,3);
        Session = (ViSession)ViMexUtil_GetUIntValue(prhs[1]);
        Status  = (ViStatus) ViMexUtil_GetIntValue(prhs[2]);
        Description = (char *)mxCalloc(256,sizeof(char));
        Status = viStatusDesc(Session, Status, Description);
        ViMexUtil_PutIntValue((int)Status, &plhs[0]);
        ViMexUtil_PutString(Description, &plhs[1]);
        //mxFree(Description);
        return 0;
    }
    // --------------
    // viGetAttribute
    // --------------
    if(!strcmp(cmd, "viGetAttribute()"))
    {
        ViSession Session;
        ViAttr Attribute; char *AttrString;
        int Type; double dVal; char buffer[256];

        ViMexUtil_CheckParameters(nlhs,nrhs,2,3);
        Session = (ViSession)ViMexUtil_GetUIntValue(prhs[1]);
        AttrString = ViMexUtil_GetStringValue(prhs[2], 0);

        if(mexVISA_Get_VI_ATTR(AttrString, &Attribute, &Type)) {
            mxFree(AttrString);
            mexErrMsgTxt("Unrecognized/unsupported VISA Attribute type.");
        }
        Status = viGetAttribute(Session, Attribute, ((void *)buffer));
        ViMexUtil_PutIntValue((int)Status, &plhs[0]);

        if(Status >= 0)
        {
            switch(Type)
            {
                case TYPE_ViString    : break; // handle below
                case TYPE_ViStatus    : dVal = (double)(*((ViStatus    *)buffer)); break;
                case TYPE_ViBoolean   : dVal = (double)(*((ViBoolean   *)buffer)); break;
                case TYPE_ViInt8      : dVal = (double)(*((ViInt8      *)buffer)); break;
                case TYPE_ViInt16     : dVal = (double)(*((ViInt16     *)buffer)); break;
                case TYPE_ViInt32     : dVal = (double)(*((ViInt32     *)buffer)); break;
                case TYPE_ViUInt8     : dVal = (double)(*((ViUInt8     *)buffer)); break;
                case TYPE_ViUInt16    : dVal = (double)(*((ViUInt16    *)buffer)); break;
                case TYPE_ViUInt32    : dVal = (double)(*((ViUInt32    *)buffer)); break;
                case TYPE_ViSession   : dVal = (double)(*((ViSession   *)buffer)); break;
                case TYPE_ViBusAddress: dVal = (double)(*((ViBusAddress*)buffer)); break;
                case TYPE_ViBusSize   : dVal = (double)(*((ViBusSize   *)buffer)); break;
                case TYPE_ViVersion   : dVal = (double)(*((ViVersion   *)buffer)); break;
                case TYPE_ViAccessMode: dVal = (double)(*((ViAccessMode*)buffer)); break;
                case TYPE_ViEventType : dVal = (double)(*((ViEventType *)buffer)); break;
                case TYPE_ViJobId     : dVal = (double)(*((ViJobId     *)buffer)); break;
                default: 
                {
                    mxFree(AttrString);
                    mexErrMsgTxt("Unhandled case in mexVISA.c under viGetAttribute.");
                }
            }
            if(Type == TYPE_ViString) {
                ViMexUtil_PutString(buffer, &plhs[1]);
            }
            else
                ViMexUtil_PutRealValue(dVal, &plhs[1]);
        }
        else ViMexUtil_PutRealValue(-1.0, &plhs[1]);
        mxFree(AttrString);
        return 0;
    }
    // --------------
    // viSetAttribute
    // --------------
    if(!strcmp(cmd, "viSetAttribute()"))
    {
        ViSession Session;
        ViAttr Attribute; char *AttrString; 
        double dVal; int Type;

        ViMexUtil_CheckParameters(nlhs,nrhs,1,4);
        Session = (ViSession)ViMexUtil_GetUIntValue(prhs[1]);
        AttrString = ViMexUtil_GetStringValue(prhs[2], 0);

        if(mexVISA_Get_VI_ATTR(AttrString, &Attribute, &Type)) {
            mxFree(AttrString);
            mexErrMsgTxt("Unrecognized/unsupported VISA Attribute type.");
        }
        if(Type != TYPE_ViString) {
            dVal = ViMexUtil_GetRealValue(prhs[3]);
        }
        switch(Type)
        {
            case TYPE_ViInt8:
            case TYPE_ViInt16:
            case TYPE_ViInt32:
            {
                ViAttrState attrState = (ViAttrState)((ViInt32)dVal);
                Status = viSetAttribute(Session, Attribute, attrState);
            }  break;
 
            case TYPE_ViStatus:
            case TYPE_ViBoolean:
            case TYPE_ViUInt8:
            case TYPE_ViUInt16:
            case TYPE_ViUInt32:
            case TYPE_ViSession:
            case TYPE_ViBusAddress:
            case TYPE_ViBusSize:
            case TYPE_ViVersion:
            case TYPE_ViAccessMode:
            case TYPE_ViEventType:
            case TYPE_ViJobId:
            {
                ViAttrState attrState = (ViAttrState)((ViUInt32)dVal);
                Status = viSetAttribute(Session, Attribute, attrState);
            }  break;

            case TYPE_ViString:
            {
                mxFree(AttrString);
                mexErrMsgTxt("Setting string attributes is not allowed.");
            }  break;

            default: 
            {
                mxFree(AttrString);
                mexErrMsgTxt("Unhandled case in mexVISA.c under viGetAttribute.");
            }
        }
        ViMexUtil_PutIntValue((int)Status, &plhs[0]);
        mxFree(AttrString);
        return 0;
    }
    // -------------
    // viEnableEvent
    // -------------
    if(!strcmp(cmd, "viEnableEvent()"))
    {
        ViSession Session;
        ViEventType Event; char *EventString;
        ViUInt16 Mechanism;

        ViMexUtil_CheckParameters(nlhs,nrhs,1,4);
        Session     = (ViSession)ViMexUtil_GetUIntValue(prhs[1]);
        EventString = ViMexUtil_GetStringValue(prhs[2], 0);
        Mechanism   = (ViUInt16)ViMexUtil_GetIntValue(prhs[3]);

        if(Mechanism != 1) {
            mxFree(EventString);
            mexErrMsgTxt("EventMechanism must be VI_QUEUE = 1");
        }
        if(mexVISA_Get_VI_EVENT(EventString, &Event)) {
            mxFree(EventString);
            mexErrMsgTxt("Unrecognized/unsupported VISA Event type.");
        }
        Status = viEnableEvent(Session, Event, Mechanism, VI_NULL);
        ViMexUtil_PutIntValue((int)Status, &plhs[0]);
        mxFree(EventString);
        return 0;
    }
    // ---------------------
    // viDisableEvent
    // ---------------------
    if(!strcmp(cmd, "viDisableEvent()"))
    {
        ViSession Session;
        ViEventType Event; char *EventString;
        ViUInt16 Mechanism;

        ViMexUtil_CheckParameters(nlhs,nrhs,1,4);
        Session     = (ViSession)ViMexUtil_GetUIntValue(prhs[1]);
        EventString = ViMexUtil_GetStringValue(prhs[2], 0);
        Mechanism   = (ViUInt16)ViMexUtil_GetIntValue(prhs[3]);

        if(Mechanism != 1) 
        {
            mxFree(EventString);
            mexErrMsgTxt("EventMechanism must be VI_QUEUE = 1");
        }
        if(mexVISA_Get_VI_EVENT(EventString, &Event)) 
        {
            mxFree(EventString);
            mexErrMsgTxt("Unrecognized/unsupported VISA Event type.");
        }
        Status = viDisableEvent(Session, Event, Mechanism);
        ViMexUtil_PutIntValue((int)Status, &plhs[0]);
        mxFree(EventString);
        return 0;
    }
    // ---------------
    // viDiscardEvents
    // ---------------
    if(!strcmp(cmd, "viDiscardEvents()"))
    {
        ViSession Session;
        ViEventType Event; char *EventString;
        ViUInt16 Mechanism;

        ViMexUtil_CheckParameters(nlhs,nrhs,1,4);
        Session     = (ViSession)ViMexUtil_GetUIntValue(prhs[1]);
        EventString = ViMexUtil_GetStringValue(prhs[2], 0);
        Mechanism   = (ViUInt16)ViMexUtil_GetIntValue(prhs[3]);

        if(Mechanism != 1) 
        {
            mxFree(EventString);
            mexErrMsgTxt("EventMechanism must be VI_QUEUE = 1");
        }
        if(mexVISA_Get_VI_EVENT(EventString, &Event)) 
        {
            mxFree(EventString);
            mexErrMsgTxt("Unrecognized/unsupported VISA Event type.");
        }
        Status = viDiscardEvents(Session, Event, Mechanism);
        ViMexUtil_PutIntValue((int)Status, &plhs[0]);
        mxFree(EventString);
        return 0;
    }
    // -------------
    // viWaitOnEvent
    // -------------
    if(!strcmp(cmd, "viWaitOnEvent()"))
    {
        ViSession Session;
        ViEventType Event, OutEventType; char *EventString;
        ViEvent EventHandle;
        ViUInt32 Timeout;

        ViMexUtil_CheckParameters(nlhs,nrhs,3,4);
        Session     = (ViSession)ViMexUtil_GetUIntValue(prhs[1]);
        EventString = ViMexUtil_GetStringValue(prhs[2], 0);
        Timeout     = (ViUInt32)ViMexUtil_GetUIntValue(prhs[3]);

        if(mexVISA_Get_VI_EVENT(EventString, &Event)) 
        {
            mxFree(EventString);
            mexErrMsgTxt("Unrecognized/unsupported VISA Event type.");
        }
        Status = viWaitOnEvent(Session, Event, Timeout, &OutEventType, &EventHandle);
        ViMexUtil_PutIntValue((int)Status, &plhs[0]);
        ViMexUtil_PutUIntValue((unsigned)OutEventType, &plhs[1]);
        ViMexUtil_PutUIntValue((unsigned)EventHandle, &plhs[2]);
        mxFree(EventString);
        return 0;
    }
    // ******************************************************************
    // -------------------
    // No Command Found...
    // -------------------
    return -1;
}
Esempio n. 30
0
// ================================================================================================
// FUNCTION  : mexFunction
// ------------------------------------------------------------------------------------------------
// Purpose   : Entry point for calls from MATLAB
// Parameters: nlhs -- Number of passed left-hand-side parameters
//             plhs -- Pointer to the left-hand-side parameter list
//             nrhs -- Number of passed right-hand-side arguments
//             prhs -- Pointer to the right-hand-side argument list
// ================================================================================================
void __cdecl mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    char *cmd;  // passed command parameter

    // --------------
    // Check for Init
    // --------------
    if( !mexVISA_IsInitialized ) mexVISA_Init();

    // ------------------
    // Dummy library call
    // ------------------
    if( !nrhs && !nlhs ) 
    {
        mexPrintf("\n");
        mexPrintf("   MATLAB VISA/GPIB Toolbox (%s %s)\n",__DATE__,__TIME__);
        mexPrintf("   Copyright 2007 DSP Group, Inc. All Rights Reserved.\n");
        mexPrintf("\n");
        return;
    }
    // ----------------------
    // Get the command string
    // ----------------------
    if( nrhs<1 ) mexErrMsgTxt("A string argument must be given as the first parameter.");
    cmd = ViMexUtil_GetStringValue(prhs[0],0);

    // ******************************************
    // *****                                *****
    // *****   COMMAND LOOKUP-AND-EXECUTE   *****
    // *****                                *****
    // ******************************************

    //----- mexVISA_*() Functions ----------------
    //--------------------------------------------
    if(strstr(cmd, "vi"))
    {
        if(!mexVISA(nlhs, plhs, nrhs, prhs))
            return;
    }
    //----- mexVISA_DisplaySessionList() ---------
    //--------------------------------------------
    if(!strcmp(cmd, "mexVISA_DisplaySessionList()"))
    {
        mexVISA_DisplaySessionList();
        return;
    }
    //----- EnableResourceChecking ---------------
    //--------------------------------------------
    if(!strcmp(cmd, "EnableResourceChecking"))
    {
        ResourceChecking = VI_TRUE;
        return;
    }
    //----- DisableResourceChecking --------------
    //--------------------------------------------
    if(!strcmp(cmd, "DisableResourceChecking"))
    {
        ResourceChecking = VI_FALSE;
        return;
    }
    //----- EnableSharedSession ------------------
    //--------------------------------------------
    if(!strcmp(cmd, "EnableSharedSessions"))
    {
        AllowSharedSessions = VI_TRUE;
        return;
    }
    //----- DisableSharedSession -----------------
    //--------------------------------------------
    if(!strcmp(cmd, "DisableSharedSessions"))
    {
        AllowSharedSessions = VI_FALSE;
        return;
    }
    //----- CloseAllSessions ---------------------
    //--------------------------------------------
    if(!strcmp(cmd, "CloseAllSessions"))
    {
        if(!ResourceChecking) 
            mexErrMsgTxt("CloseAllSessions requires ResourceChecking to be enabled.");

        while( pSessionList )
        {
            if(pSessionList->Prev) free(pSessionList->Prev);
            mexPrintf(" mexVISA: closing 0x%08X \"%s\"\n",pSessionList->Session,pSessionList->Resource);
            viClose(pSessionList->Session);
            pSessionList = pSessionList->Next;
        }         
        return;
    }
    //----- mexVISA_ReadLeCroyWaveform() ---------
    //--------------------------------------------
    if(!strcmp(cmd,"mexVISA_ReadLeCroyWaveform()"))
    {
        ViSession rmSession, Session;
        int       i, pts, cnt, MaxLength = 16000000;
        char     *buf, *resource, *trace, readbuf[64];
        double   *y, ygain, yofs, dt, t0;

        //- Get input parameters ------------------------------------------------
        ViMexUtil_CheckParameters(nlhs,nrhs,3,3);
        resource = ViMexUtil_GetStringValue(prhs[1], NULL);
        trace    = ViMexUtil_GetStringValue(prhs[2], NULL);

        //- Open instrument session ---------------------------------------------
        mexVISA_GetViRM(&rmSession);
        VICHK( viOpen(rmSession, resource, VI_NULL, VI_NULL, &Session) );

        //- Configure VISA Formatted I/O ----------------------------------------
        VICHK( viSetAttribute(Session, VI_ATTR_TMO_VALUE, 1000) );
        VICHK( viSetBuf      (Session, VI_READ_BUF|VI_WRITE_BUF, 4000) );
        VICHK( viSetAttribute(Session, VI_ATTR_WR_BUF_OPER_MODE, VI_FLUSH_ON_ACCESS) );
        VICHK( viSetAttribute(Session, VI_ATTR_RD_BUF_OPER_MODE, VI_FLUSH_ON_ACCESS) );
        VICHK( viSetAttribute(Session, VI_ATTR_TERMCHAR_EN, VI_FALSE) );

        VICHK( viPrintf(Session,"COMM_ORDER HI\n") );
        VICHK( viPrintf(Session,"COMM_FORMAT DEF9,BYTE,BIN\n") );
        VICHK( viPrintf(Session,"WFSU SP,1,NP,%d,FP,0,SN,0\n",MaxLength) );
        
        MXERR(LeCroyInspectReal(Session, trace, "HORIZ_INTERVAL",  &dt   ) );
        MXERR(LeCroyInspectReal(Session, trace, "HORIZ_OFFSET",    &t0   ) );
        MXERR(LeCroyInspectReal(Session, trace, "VERTICAL_GAIN",   &ygain) );
        MXERR(LeCroyInspectReal(Session, trace, "VERTICAL_OFFSET", &yofs ) );
        MXERR(LeCroyInspectInt (Session, trace, "WAVE_ARRAY_COUNT",&pts  ) );

        if(pts > MaxLength) pts = MaxLength;
        if(!pts) 
        {
            viClose(Session); mxFree(resource); mxFree(trace);
            mexErrMsgTxt("Trace contains no data.");
        }
        buf = (char *)mxCalloc(pts+16, sizeof(char));
        if(!buf) mexErrMsgTxt("Memory allocation failed.");

        VICHK( viSetAttribute(Session, VI_ATTR_TMO_VALUE, 30000) );
        VICHK( viPrintf(Session, "CFMT IND0,BYTE,BIN;CHDR OFF;CORD LO\n") );
        VICHK( viPrintf(Session, "%s:WF? DAT1\n",trace) );
        VICHK( viRead  (Session, readbuf, 7, NULL) );
        VICHK( viRead  (Session, buf, pts, &cnt) );

        y = (double *)mxCalloc(pts, sizeof(double));
        if(!y) mexErrMsgTxt("Memory allocation failed.");

        // ------------------------------
        // Convert Sample Values to Volts
        // ------------------------------
        for(i=0; i<pts; i++)   
        {
            y[i] = ygain * (double)buf[i] - yofs;
        }
        mxFree(buf);
        ViMexUtil_PutRealArray(pts, y, plhs+0);
        ViMexUtil_PutRealValue(dt, plhs+1);
        ViMexUtil_PutRealValue(t0, plhs+2);
        mxFree(trace); mxFree(resource);
        viClose(Session);
        return;
    }
    // ******************************************************************
    // --------------------------------------------
    // No Command Found...Generate an Error Message
    // --------------------------------------------
    mexErrMsgTxt("mexLab: Unrecognized command in the first argument.");
}