Example #1
0
void* DLLEXPORT SignalGenerator_Reset ( int hInstrumentHandle )
{
	STD_ERROR		StdError							=	{0};
	
	tsHandle		*pLocalHandle						=	{0};

	int				handle								=	0;
	
	IF (( hInstrumentHandle == 0 ) , "Handle is empty" );
	
	handle = hInstrumentHandle;
	
	CHK_CMT ( CmtGetTSVPtr ( handle , &pLocalHandle ));
	
	CHK_VSA ( viPrintf( pLocalHandle->sessionHandle ,"*CLS\n" ));
					
	CHK_VSA ( viPrintf( pLocalHandle->sessionHandle ,"*RST\n" ));
					
	WaitForOperationCompletion( pLocalHandle->sessionHandle , pLocalHandle->lfTimeout  ,  pLocalHandle->lfOpcLowLevelTimeout );  
	
Error:
	
	if ( handle )
		CmtReleaseTSVPtr ( handle );
	
	return SignalGenerator_GetErrorTextMessage(hInstrumentHandle,StdError.error,NULL);
}
Example #2
0
void* DLLEXPORT SignalGenerator_Config ( int hInstrumentHandle , int channel , double lfFrequency , double lfAmplitude )
{
	STD_ERROR		StdError							=	{0};
	
	tsHandle		*pLocalHandle						=	{0};

	int				handle								=	0;
	
	IF (( hInstrumentHandle == 0 ) , "Handle is empty" );
	
	handle = hInstrumentHandle;
	
	CHK_CMT ( CmtGetTSVPtr ( handle , &pLocalHandle ));
	
	CHK_VSA ( viPrintf( pLocalHandle->sessionHandle ,"freq %lf\n" , lfFrequency ));
	
	WaitForOperationCompletion( pLocalHandle->sessionHandle , pLocalHandle->lfTimeout  ,  pLocalHandle->lfOpcLowLevelTimeout );  
	
	CHK_VSA ( viPrintf( pLocalHandle->sessionHandle ,"pow %lf\n" , lfAmplitude ));
					
	WaitForOperationCompletion( pLocalHandle->sessionHandle , pLocalHandle->lfTimeout  ,  pLocalHandle->lfOpcLowLevelTimeout );  
	
Error:
	
	if ( handle )
		CmtReleaseTSVPtr ( handle );
	
	return SignalGenerator_GetErrorTextMessage(hInstrumentHandle,StdError.error,NULL);
}
Example #3
0
void scan_meas_cnt(ViSession *pvi, FILE *fp)
{
	int cnt = 0;
	int actualCnt;
	int i;

	viPrintf(*pvi, "init\n");
	do{
		Sleep(10);
		viPrintf(*pvi, "*trg\n");
		Sleep(MEAS_INTERVAL);
		while(get_cnt(pvi) < NUMOFSLAVES){
			Sleep(10);
		}
		cnt++;

		viPrintf(*pvi, "r?\n");
		viRead (*pvi, (ViBuf)buf, bufLen, &len);
		buf[len]='\0';
		for(i = 0; i < len; ++i){
			if(buf[i] == ',')
				buf[i] = ' ';
		}
		fprintf(fp, "%s", buf + 2 + buf[1] - '0');

	}while(cnt != MEAS_CNT);
}
Example #4
0
void init_equipment(ViSession *pvi)
{
	int slotNum;
	/*if( (slotNum = set_slot_num(pvi)) == -1){
		printf("error finding route\n");
		exit(-1);

	}*/

	viPrintf(*pvi, "*rst\n");
/*
	//setup routes
	if(NUMOFSLAVES == 1){
		sprintf(visa_cmd, rout_scan_form0, slotNum, begNUm);
	}
	else{
		//sprintf(visa_cmd, rout_scan_form, slotNum, begNUm, slotNum, begNUm + NUMOFSLAVES - 1);
		sprintf(visa_cmd, rout_scan_formSep, slotNum, 11, slotNum, 14);
	}

	viPrintf(*pvi, visa_cmd);
	Sleep(500);*/

	//setup trig source
	//viPrintf(*pvi, "trig:sour bus\n");

	//setup trig count
	sprintf(visa_cmd, trig_coun_form, MEAS_CNT);
	viPrintf(*pvi, visa_cmd);
}
Example #5
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;
}
bool MeasurementThread::initFreqGen()
{
	viOpenDefaultRM (&defaultRM);
	viOpen (defaultRM, fGenID.toAscii().data(), VI_NULL,VI_NULL, &vi);
	viPrintf (vi, (ViString)"*RST\n");
	viPrintf (vi, (ViString)"FUNC SIN\n");
	QString amplStr = QString ("VOLT %1\n").arg(amplitude/1000.0);
	viPrintf (vi, amplStr.toAscii().data());
	QString strFreq = QString ("FREQ %1\n").arg(fList[0]);
	viPrintf (vi, strFreq.toAscii().data());
	viPrintf (vi, (ViString)"OUTP ON\n");
	return true;
}
void EITMeasurementThread::cleanup()
{
        /* Close visa session */
    viPrintf (viSwMat, (ViString)"*RST\n");
    viClose (viSwMat);

    viPrintf (viSiGen, (ViString)"OUTP OFF\n");
    viClose (viSiGen);

    viClose (defaultRM);

    if (_data != 0) cbWinBufFree(_data);
}
bool EITMeasurementThread::openSwitch(int si) {
    char buf [1000] = {0};
    viPrintf (viSwMat, (ViString)CMD_SWITCH_OPEN[si]);
    this->msleep(exp->SWITCHING_DELAY);

    int test_count = 0;
    while (test_count < 5) {
        viPrintf (viSwMat, (ViString)CMD_SWITCH_OPEN_TEST[si]);
        viScanf (viSwMat, (ViString)"%t", &buf);
        if (strlen(buf) == 0)   return false;
        else if (buf[0] == '1') return true;
        test_count++;
    }
    return false;
}
Example #9
0
void CatDeviceManager::Uinitialize()
{
	try
	{
		ViSession session,defrm;
		int overcurron;
		float voltsetting,currsetting,overvoltsetting;

		char add[]="USB0::0x0957::0x0807::N5765A-US12N5190H::0::INSTR";
		//The default resource manager manages initializes the VISA system
		viOpenDefaultRM(&defrm);

		//opens a communication session with the instrument at address "add"
		viOpen(defrm,add,VI_NULL,VI_NULL,&session);

		//Enable the output
		viPrintf(session,"OUTP OFF \n");

		//This frees up all of the resources
		viClose(session);
		viClose(defrm);

		Get34980()->Close();
		Get34411()->Close();
	}
	catch(_com_error& e)
	{}
}
Example #10
0
int send_ps_command(char *command,char *response)
{
	int status;
	char buffer[RESP_BUF_SIZE];
	int count;
	
	sprintf(buffer,"%s\r\n",command);
	
	/***************************************************************************
	if (g_use_rs232_power)
	{
		status = serial_send(ps_com_port,buffer,strlen(buffer));
		if (status!=SUCCESS) return status;
	
		if (strchr(command,'?'))
		{
			status = serial_waitfor(ps_com_port,"\r\n",response,ps_timeout_value);
		}
	}
	***********************************************************************************/
//	else
//	{
	if (ps_handle==0) return 0;
	
	status = viPrintf(ps_handle,"%s\n",command);
	if (strchr(command,'?'))
	{
		status = viRead(ps_handle,(ViPBuf)response,256,(ViPUInt32)&count);
	}				 
//	}
	
	return status;
}
void MeasurementThread::cleanup()
{
	/* Close visa session */
	viPrintf (vi, (ViString)"OUTP OFF\n");
	viClose (vi);
	viClose (defaultRM);
	if (_data != 0) cbWinBufFree(_data);
}
Example #12
0
int get_cnt(ViSession *pvi)
{
	int res;
	viPrintf(*pvi, "data:poin?\n");
	viRead (*pvi, (ViBuf)buf, bufLen, &len);
	buf[len]=0;
	sscanf(buf, "%d", &res);
	return res;
}
Example #13
0
int set_slot_num(ViSession *pvi)
{
	char cmd[] = "rout:scan (@101)\n";
	int res = 0;
	ViStatus status = -1;

	do{
		++res;
		if(res == 4)
			return -1;
		cmd[12] = res + '0';
		status = viPrintf(*pvi, cmd);
	}while(anyErr(pvi) > 0);

	viPrintf(*pvi, "*rst\n");

	return res;

}
Example #14
0
/**
 * @brief ICS_SetPortConfiguration
 *
 * @param[in] Handle (int) - handle 
 * @param[in] ucPortNumber (unsigned char) - the specific port
 * @param[in] ucPortPolarity (unsigned char) - the configuration pins to set polarity.
 */
void*    ICS_SetPortConfiguration( int Handle , unsigned char ucPortNumber , unsigned char ucPortPolarity )
{
	STD_ERROR		StdError							=	{0};
	
	tsHandle		*pLocalHandle						=	NULL; 

	char			szString[128]						=	{0},
					szReadFeedback[LOW_STRING]			=	{0};
	
	unsigned char 	ucPortPolarityRead					=	0;
	
	int				iActualSize							=	0;
	
	IF (( Handle == 0 ) , "Empty Handle" );
	
	CHK_CMT( CmtGetTSVPtr ( Handle , &pLocalHandle  ));
	
	sprintf( szString , "OP%d %d\n" , ucPortNumber , ucPortPolarity );
	
	CHK_VSA ( viPrintf( pLocalHandle->sessionHandle ,szString ));
	
	sprintf( szString , "P%d\n" , ucPortNumber );   
	
	CHK_VSA ( viPrintf( pLocalHandle->sessionHandle ,szString ));
	
	SetBreakOnLibraryErrors (0);
	viRead( pLocalHandle->sessionHandle, szReadFeedback , (LOW_STRING-1) , &iActualSize );
	SetBreakOnLibraryErrors (1);
		
	ucPortPolarityRead = atoi(szReadFeedback);
	
	IF (( ucPortPolarityRead != ucPortPolarity ) , "Can't set polarity of the port." );
	
Error:	
	
	if( Handle ) 
		CmtReleaseTSVPtr ( Handle );
	
	return ICS_GetErrorTextMessage(Handle,StdError.error,NULL);
}
Example #15
0
// ================================================================================================
// FUNCTION  : LeCroyInspectInt
// ------------------------------------------------------------------------------------------------
// Purpose   : Query a parameter value
// Parameters: Session -- VISA instrument session handle
//             trace   -- {"TA".."TD","M1".."M4","C1".."C4"}
//             param   -- parameter name to be insepected
//             pval    -- return value (by reference)
// ================================================================================================
static int LeCroyInspectInt(ViSession Session, char *trace, char *param, int *pval)
{
    char buf[256], *cptr;
    
    VICHK( viPrintf(Session, "%s:INSP? '%s'\n",trace, param) );
    VICHK( viRead  (Session, buf, 256, NULL) );
    
    if((cptr=strstr(buf, param)) == NULL) return -1; cptr += strlen(param);
    if((cptr=strchr(cptr, ':' )) == NULL) return -1; cptr++;
    while(*cptr==' ') cptr++; // skip whitespace
    *pval = strtol(cptr, NULL, 0);

    return 0;
}
Example #16
0
// ================================================================================================
// FUNCTION  : LeCroyInspectReal
// ------------------------------------------------------------------------------------------------
// Purpose   : Query a parameter value
// Parameters: Session -- VISA instrument session handle
//             trace   -- {"TA".."TD","M1".."M4","C1".."C4"}
//             param   -- parameter name to be insepected
//             pval    -- return value (by reference)
// ================================================================================================
static int LeCroyInspectReal(ViSession Session, char *trace, char *param, double *pval)
{
    unsigned char buf[256], *cptr;
    
    VICHK( viPrintf(Session, "%s:INSP? '%s'\n",trace, param) );
    VICHK( viRead  (Session, buf, 256, NULL) );
    
    if((cptr=strstr(buf, param)) == NULL) return -1; cptr += strlen(param);
    if((cptr=strchr(cptr, ':' )) == NULL) return -1; cptr++;
    while(*cptr==' ') cptr++;
    *pval = strtod(cptr, NULL);

    return 0;
}
Example #17
0
int anyErr(ViSession *pvi)
{

  ViStatus err;
  static char buf[1024]={0};
  int err_no;
  int err_cnt = 0;
  err=viPrintf(*pvi, "SYSTEM:ERR?\n");


  err=viScanf (*pvi, "%d%t", &err_no, &buf);


  if(err_no >0){
	++err_cnt;
  }

  err=viFlush(*pvi, VI_READ_BUF);
  err=viFlush(*pvi, VI_WRITE_BUF);
  viPrintf(*pvi, "*rst\n");
  return err_cnt;

}
bool MeasurementThread::measureStep(int ns, int fi)
{
    // static char buf [1000] = {0};
    //qDebug() << "MeasurementStep: ns = " << ns << ", fi = " << fi;
    if (fList.size() > 1 || ns == 0) {
        QString strFreq = QString ("FREQ %1\n").arg(fList[fi]);
        viPrintf (vi, strFreq.toAscii().data());
        // allocate buffer
    }
    long DATA_BUFFER_SIZE = calculateBufferSize(fi);
    int e_code;
    e_code = cbALoadQueue (BOARD_NUM, _ChanArray, _GainArray, NUM_CHANNELS);
    if (e_code != 0) {
            bool response =	createSweepErrorMsg(ns, fi, "Error in cbLoadQueue()");
            cbWinBufFree(_data); return response;
    }
    long actualSamplingRate = sRList[fi];

//    if (fList.size() > 1 || ns == 0) {
//        viPrintf(vi, (ViString)"FREQ?\n");
//        /* Read results */
//        viScanf (vi, (ViString)"%t", &buf);
//    }

    //qDebug() << "Starting Scan. Requested fs = " << actualSamplingRate;
    int startTime = LoggerTime::timer();
    e_code = cbAInScan (BOARD_NUM, 0, 15, DATA_BUFFER_SIZE, &actualSamplingRate,
                            _GainArray[0], _data, CONVERTDATA + DMAIO);
    int endTime = LoggerTime::timer();
    //qDebug() << "Ending Scan. Actual fs = " << actualSamplingRate;
    if (e_code != 0) {
            bool response = createSweepErrorMsg(ns, fi, "Error in cbInScan()");
            cbWinBufFree(_data); return response;
    }
    ImpedanceMeasurement m = iCal.processData((WORD*)_data,
                    DATA_BUFFER_SIZE, fList[fi], actualSamplingRate);
    //qDebug() << "Finished Impedance Measurement";

    m.t = (startTime + endTime)/2;
    pMLst->append(m);
    //qDebug() << "Appended Impedance Measurement";
    return true;
}
Example #19
0
int		Delay_LastComplete( int handle )
{
	double		lfCurrentTime		=	0.0,
				lfTimeOut			=	10.0, 
				lfStartTime			=	0.0;
	
	int			iOpcValue			=	0;
	
	int			status				=	0;
	
	ViAttrState	attrValue			=	0;
		
	if ( viGetAttribute ( handle , VI_ATTR_TMO_VALUE , &attrValue ) == 0 )
		lfTimeOut = attrValue / 1E3;

	GetCurrentDateTime ( &lfStartTime );
	GetCurrentDateTime ( &lfCurrentTime ); 
	
	while(( lfCurrentTime - lfStartTime ) < lfTimeOut ) 
	{
		
		GetCurrentDateTime ( &lfCurrentTime );  
		
		status = viPrintf ( handle , "*OPC?\n");
	
		if ( status )
			continue;
		
		Delay ( 0.2 );
		
		status = viScanf ( handle , "%d" , &iOpcValue);

		if ( status )
			continue;
		
		if ( iOpcValue == 1 )
			return 0;
	}
	
	return -1;	
}
Example #20
0
void scan_meas_cnt(ViSession *pvi, FILE *fp)
{
	int cnt = 0;
	int actualCnt;
	int i;
	if(!fpAll){
		sprintf(buf, "%s%c%c%s", mydatedir, '\\', '\\', "allData.txt");
		fpAll = fopen("buf", "w");
	}
	sprintf(visa_cmd, trig_coun_form, MEAS_CNT);
	viPrintf(*pvi, visa_cmd);Sleep(10);
	viPrintf(*pvi, "trig:sour bus\n");Sleep(10);
	viPrintf(*pvi, "init\n");

	do{
		Sleep(10);
		viPrintf(*pvi, "*trg\n");
		Sleep(MEAS_INTERVAL);
		while(get_cnt(pvi) < 1){
			Sleep(10);
		}
		cnt++;

		//////////////////////////////////////////////////////////////////////////注意器件过多或者重复次数过多可能会导致存储器溢出

	}while(cnt != MEAS_CNT);

	viPrintf(*pvi, "fetc?\n");
	//viPrintf(*pvi, "r?\n");
	viRead (*pvi, (ViBuf)buf, bufLen, &len);
	buf[len]='\0';

	for(i = 0; i < len; ++i){
		if(buf[i] == ',')
			buf[i] = '\n';
	}
	fprintf(fp, "%s", buf);//////////////////////////////////////////////////////////////////////////
	viPrintf(*pvi, "*rst\n");

	for(i = 0; i < len; ++i){
		if(buf[i] == '\n')
			buf[i] = ' ';
	}
	fprintf(fpAll, "%s -- %s\n", strToSend2, buf);
	fflush(fpAll);
}
bool EITMeasurementThread::initSwitchMatrix()
{
    viOpenDefaultRM (&defaultRM);
    viOpen (defaultRM, swMatID.toAscii().data(), VI_NULL,VI_NULL, &viSwMat);
    viPrintf (viSwMat, (ViString)"*RST\n");

    viOpen (defaultRM, siGenID.toAscii().data(), VI_NULL,VI_NULL, &viSiGen);
    viPrintf (viSiGen, (ViString)"*RST\n");
    viPrintf (viSiGen, (ViString)"FUNC SIN\n");
    QString amplStr = QString ("VOLT %1\n").arg(amplitude/1000.0);
    viPrintf (viSiGen, amplStr.toAscii().data());
    QString strFreq = QString ("FREQ %1\n").arg(fcarr);
    viPrintf (viSiGen, strFreq.toAscii().data());
    viPrintf (viSiGen, (ViString)"OUTP ON\n");
    this->msleep(1000);
    return true;
}
Example #22
0
void*  ICS_GetErrorTextMessage ( int hInstrumentHandle , int iError , char *pErrorMessage )
{
	STD_ERROR		StdError							=	{0};
	
	tsHandle		*pLocalHandle						=	{0};

	int				handle								=	0;
	
	char			szCommand[LOW_STRING]				=	{0},
					szReadBuffer[LOW_STRING]			=	{0},
					szErrorDescription[LOW_STRING]		=	{0};
	
	int				count								=	0;
	
	char			*pTemp								=	NULL;
	
	IF (( hInstrumentHandle == 0 ) , "Handle is empty" );
	
	handle = hInstrumentHandle;
	
	CHK_CMT ( CmtGetTSVPtr ( handle , &pLocalHandle ));
	
	strcpy( szCommand , ":SYST:ERR?\n" );
	
	CHK_VSA( viPrintf( pLocalHandle->sessionHandle , szCommand ));
	
	SetBreakOnLibraryErrors (0);
	viRead( pLocalHandle->sessionHandle, szReadBuffer , LOW_STRING , &count );
	SetBreakOnLibraryErrors (1);
	
	iError = atoi(szReadBuffer);
	
	pTemp = strchr( szReadBuffer , '"' );
	
	if ( pTemp )
	{
		pTemp++;
		
		strcpy( szErrorDescription , pTemp );  
		
		pTemp = strchr( szErrorDescription , '"' );
		
		if ( pTemp )
			*pTemp = 0;
	}
	
	viPrintf( pLocalHandle->sessionHandle , "*CLS\n" );
	
	if ( pErrorMessage )
	{
		strcpy( pErrorMessage , szErrorDescription ); 
	}

	StdError.error = iError;
	
	if ( iError )
	{
		CALLOC_COPY_STRING( StdError.pszErrorDescription , szErrorDescription );
	}
	
Error:

	if ( handle )
		CmtReleaseTSVPtr ( handle );
	
	RETURN_STDERR_POINTER;	
}
Example #23
0
void*	DLLEXPORT		Equipment_Info ( int hLowLevelHandle , char *pAddress , char **pVendor , char **pSerialNumber , char **pModel , char **pFirmware )
{
	STD_ERROR						StdError									=	{0};
	
	int								iCount										=	0, 
									status										=	0, 
									//iIndex										=	0, 
									//bSupport									=	0, 
									defaultRM									=	0,
									hConnectionHandle							=	0;
	
	char							szIdentificationText[LOW_STRING]			=	{0},
									szIdentificationUpperText[LOW_STRING]		=	{0},
									*pTemp										=	NULL;

	if ( hLowLevelHandle == 0 )
	{
		viOpenDefaultRM (&defaultRM);

		SetBreakOnLibraryErrors (0);
	
		status = viOpen ( defaultRM , pAddress , NULL, NULL, &hConnectionHandle );
	}
	else
	{
		hConnectionHandle = hLowLevelHandle;	
	}
		
	if ( status == 0 )
	{	
		status = viPrintf ( hConnectionHandle , "*IDN?\n" );
	
		if ( status == 0 )
		{
			viRead ( hConnectionHandle , szIdentificationText , (LOW_STRING-1) , &iCount );
			RemoveSurroundingWhiteSpace (szIdentificationText); 
		}
	}
		
	if (( hLowLevelHandle == 0 ) && hConnectionHandle )
		viClose(hConnectionHandle); 
		
	SetBreakOnLibraryErrors (1);

	do
	{
		strcpy( szIdentificationUpperText , szIdentificationText );
		StringUpperCase (szIdentificationUpperText);
		
		IF ((( strstr( szIdentificationUpperText , "AGILENT TECHNOLOGIES" ) == NULL ) && ( strstr( szIdentificationUpperText ,"HEWLETT-PACKARD") == NULL )) , "Is not supported" );
	
		pTemp = strrchr( szIdentificationText , ',' );

		if ( pTemp )
		{
			*pTemp = 0;
			pTemp++;
	
			if ( pFirmware )
			{
				CALLOC_COPY_STRING( *pFirmware , pTemp );
			}
		}
		else
			break;
	
		pTemp = strrchr( szIdentificationText , ',' );

		if ( pTemp )
		{
			*pTemp = 0;
			pTemp++;
	
			if ( pSerialNumber )
			{
				CALLOC_COPY_STRING( *pSerialNumber , pTemp );
			}
		}
		else
			break;
	
		pTemp = strrchr( szIdentificationText , ',' );

		if ( pTemp )
		{
			*pTemp = 0;
			pTemp++;
	
			if ( pModel )
			{
				CALLOC_COPY_STRING( *pModel , pTemp );
			}
		}
		else
			break;
	
		if ( pVendor )
		{
			CALLOC_COPY_STRING( *pVendor , szIdentificationText );  
		}
		
	} while(0);
		
Error:
		
	RETURN_STDERR_POINTER;
}
Example #24
0
void*	DLLEXPORT		Equipment_IsSupported ( int hLowLevelHandle , char *pAddress , char *pID_String , char *pIdentificationText , int *pbSupporting , void **pLocalData )
{
	STD_ERROR						StdError									=	{0};
	
	int								iCount										=	0, 
									status										=	0, 
									bSupport									=	0, 
									defaultRM									=	0,
									hConnectionHandle							=	0;
	
	char							szIdentificationText[LOW_STRING]			=	{0},
									szIdentificationUpperText[LOW_STRING]		=	{0}; 
	
	if (( pIdentificationText == NULL ) || ( strlen(pIdentificationText) < 10 ))
	{
		SetBreakOnLibraryErrors (0);   
		
		if ( hLowLevelHandle == 0 )
		{
			viOpenDefaultRM (&defaultRM);

			SetBreakOnLibraryErrors (0);
	
			status = viOpen ( defaultRM , pAddress , NULL, NULL, &hConnectionHandle );
		}
		else
		{
			hConnectionHandle = hLowLevelHandle;	
		}
		
		if ( status == 0 )
		{	
			status = viPrintf ( hConnectionHandle , "*IDN?\n" );
		
			if ( status == 0 )
			{
				viRead ( hConnectionHandle , szIdentificationText , (LOW_STRING-1) , &iCount );
				RemoveSurroundingWhiteSpace (szIdentificationText); 
			}
		}
		
		if (( hLowLevelHandle == 0 ) && hConnectionHandle )
			viClose(hConnectionHandle); 
		
		SetBreakOnLibraryErrors (1);  	
	}
	else
	{
		if ( strlen(pIdentificationText) < LOW_STRING )
			strcpy( szIdentificationText , pIdentificationText );
		else
			memcpy( szIdentificationText , pIdentificationText , (LOW_STRING-1) );  
	}
		
	do
	{
		strcpy( szIdentificationUpperText , szIdentificationText );
		StringUpperCase (szIdentificationUpperText);
		
		if (( strstr( szIdentificationUpperText , "AGILENT TECHNOLOGIES" ) == NULL ) && ( strstr( szIdentificationUpperText ,"HEWLETT-PACKARD") == NULL ))
			break;	
	
		if ( strstr( szIdentificationText , ",E441" ))
		{
			bSupport = 1;
			break;
		}
					
	}while(0);
	
	if (pbSupporting)
		*pbSupporting = bSupport;
	
	RETURN_STDERR_POINTER;
}
Example #25
0
STD_ERROR   DLLEXPORT	DRV_FunctionGenerator_Init ( char *pszDriverLocation , char *pszAddressString , int *pHandle )
{		   					
	STD_ERROR                                   StdError                                    =   {0};
	
	tsDriverInfo								*pDriverInfo							=	NULL;
	
	CmtTSVHandle 								VariableHandle							=	0;
	
	CmtThreadLockHandle 						LockHandle								=	0;
	
	pfFunctionGenerator_Init					pWrapperFunction						=	NULL;
	
	char										szCurrentDirectory[STD_STRING]			=	{0},
												szDriverLocation[STD_STRING]			=	{0},
												szMessage[STD_STRING]					=	{0},
												*pTemp									=	NULL;
	
	int											iTry									=	0,
												bHandleExists							=	0;
	
	int											bLocked									=	0;
	
	char										*pTempString							=	NULL;

	pfSTD_Config_Install_CommentCallback        pConfig_Install_CommentCallback			=	NULL;
	pfSTD_Config_Install_ConfigValueCallback    pConfig_Install_ConfigValueCallback		=	NULL;
	pfSTD_Config_Install_CheckForBreakCallback  pConfig_Install_CheckForBreakCallback	=	NULL;
	pfSTD_Config_Copy_STD_CallBackSet			pConfig_Copy_STD_CallBackSet			=	NULL;

	HINSTANCE									LibraryHandle							=	NULL;
	
	if (( pszDriverLocation == NULL ) || ( pszAddressString == NULL ))
		{STD_ERR (DRV_ERROR_PASSED_NULL);}
	
	strcpy( szDriverLocation , pszDriverLocation );
	
	do
	{
		pTemp = strstr( pszDriverLocation , ":\\" );
	
		if ( pTemp )
			break;
		
		pTemp = strchr( pszDriverLocation , '\\' ); 
		
		if ( pTemp == NULL )
			break;
			
		GetModuleDir( __CVIUserHInst , szCurrentDirectory ); 
		
		if ( pTemp == pszDriverLocation )
			sprintf( szDriverLocation , "%s%s" , szCurrentDirectory , pszDriverLocation );
		else
			sprintf( szDriverLocation , "%s\\%s" , szCurrentDirectory , pszDriverLocation ); 
		
	} while(0);
	
	if ( FileExists(szDriverLocation,NULL) == 0 )
	{
		sprintf( szMessage , "Loading Function Generator Driver\n\"%s\"\n\nFailed, File has not found." , szDriverLocation );
		ShowMessage ( INSTR_TYPE_CONTINUE , "Equipment driver file error..." , szMessage , NULL );
		
		FORCE_ERR(-5,szMessage);
	}
			 
	if ( pHandle )
	{
		if ( CmtNewTSV ( sizeof(tsDriverInfo) , &VariableHandle ) != 0 )
			{STD_ERR (DRV_ERROR_CREATE_TSV_HANDLE);}

		if ( VariableHandle == 0 )
			{STD_ERR (DRV_ERROR_CREATE_TSV_HANDLE);}
	
		do
		{
			*pHandle = VariableHandle;
	
			if ( CmtGetTSVPtr ( VariableHandle , &pDriverInfo ) < 0 )
			{
				{STD_ERR (DRV_ERROR_GET_TSV_POINTER);}
				break;
			}
	
			pDriverInfo->InstrumentType = DRIVER_TYPE_FUNCTION_GENERATOR;
	
			CALLOC_COPY_STRING( pDriverInfo->pInstrumentAddress , pszAddressString );  
		
			bHandleExists = DRIVER_MANAGER_IsConnectionExists( pszAddressString , &(pDriverInfo->InstrumentHandle) , &(pDriverInfo->InstrumentLockHandle) );

			//--------- Load Library ---------------------//
	
			pDriverInfo->LibraryHandle = LoadLibrary(szDriverLocation);

			CALLOC_COPY_STRING( pDriverInfo->pDriverFileName,szDriverLocation);
		
			if ( pDriverInfo->LibraryHandle == 0 )
			{
				{STD_ERR (DRV_ERROR_DLL_FILE_NOT_OPENED);}
				break;
			}	
		
		
			//--------------- Load functions ------------------//
			pDriverInfo->tInstrDB.functionGeneratorDriverFunctions.Config_Install_CommentCallback								= (pfSTD_Config_Install_CommentCallback) GetProcAddress( pDriverInfo->LibraryHandle , 		"Config_Install_CommentCallback");      
			pDriverInfo->tInstrDB.functionGeneratorDriverFunctions.Config_Install_ConfigValueCallback							= (pfSTD_Config_Install_ConfigValueCallback) GetProcAddress( pDriverInfo->LibraryHandle , 	"Config_Install_ConfigValueCallback");  
			pDriverInfo->tInstrDB.functionGeneratorDriverFunctions.Config_Install_CheckForBreakCallback							= (pfSTD_Config_Install_CheckForBreakCallback) GetProcAddress( pDriverInfo->LibraryHandle , "Config_Install_CheckForBreakCallback");
			pDriverInfo->tInstrDB.functionGeneratorDriverFunctions.Config_LOG_SetAllowState										= (pfSTD_Config_LOG_SetAllowState) GetProcAddress( pDriverInfo->LibraryHandle , "Config_LOG_SetAllowState");
			pDriverInfo->tInstrDB.functionGeneratorDriverFunctions.Config_Copy_STD_CallBackSet									= (pfSTD_Config_Copy_STD_CallBackSet) GetProcAddress( pDriverInfo->LibraryHandle , "Config_Copy_STD_CallBackSet");
			
			pDriverInfo->tInstrDB.functionGeneratorDriverFunctions.FunctionGenerator_GetErrorTextMessage     					= (pfFunctionGenerator_GetErrorTextMessage) GetProcAddress( pDriverInfo->LibraryHandle , "FunctionGenerator_GetErrorTextMessage");         
			pDriverInfo->tInstrDB.functionGeneratorDriverFunctions.FunctionGenerator_Init                        				= (pfFunctionGenerator_Init) GetProcAddress( pDriverInfo->LibraryHandle , "FunctionGenerator_Init");                        
			pDriverInfo->tInstrDB.functionGeneratorDriverFunctions.FunctionGenerator_Close                       				= (pfFunctionGenerator_Close) GetProcAddress( pDriverInfo->LibraryHandle , "FunctionGenerator_Close");                       
			pDriverInfo->tInstrDB.functionGeneratorDriverFunctions.FunctionGenerator_Reset										= (pfFunctionGenerator_Reset) GetProcAddress( pDriverInfo->LibraryHandle , "FunctionGenerator_Reset"); 
		
			pDriverInfo->tInstrDB.functionGeneratorDriverFunctions.FunctionGenerator_Initiate              						= (pfFunctionGenerator_Initiate) GetProcAddress( pDriverInfo->LibraryHandle , "FunctionGenerator_Initiate");                    
		    pDriverInfo->tInstrDB.functionGeneratorDriverFunctions.FunctionGenerator_Signel_Off           						= (pfFunctionGenerator_Signel_Off) GetProcAddress( pDriverInfo->LibraryHandle , "FunctionGenerator_Signel_Off");                 
			pDriverInfo->tInstrDB.functionGeneratorDriverFunctions.FunctionGenerator_Signel_On            						= (pfFunctionGenerator_Signel_On) GetProcAddress( pDriverInfo->LibraryHandle , "FunctionGenerator_Signel_On");            
			pDriverInfo->tInstrDB.functionGeneratorDriverFunctions.FunctionGenerator_Save_State     							= (pfFunctionGenerator_Save_State) GetProcAddress( pDriverInfo->LibraryHandle , "FunctionGenerator_Save_State");     
			pDriverInfo->tInstrDB.functionGeneratorDriverFunctions.FunctionGenerator_Load_State      							= (pfFunctionGenerator_Load_State) GetProcAddress( pDriverInfo->LibraryHandle , "FunctionGenerator_Load_State");      
		
			pDriverInfo->tInstrDB.Equipment_Info      																			= (pfSTD_Equipment_Info) GetProcAddress( pDriverInfo->LibraryHandle , "Equipment_Info");      
			pDriverInfo->tInstrDB.Equipment_IsSupported																			= (pfSTD_Equipment_IsSupported) GetProcAddress( pDriverInfo->LibraryHandle , "Equipment_IsSupported");   
		
			pDriverInfo->tInstrDB.Equipment_SendStateFile																		= (pfSTD_Equipment_SendStateFile) GetProcAddress( pDriverInfo->LibraryHandle , "Equipment_SendStateFile");
			pDriverInfo->tInstrDB.Equipment_ReceiveStateFile																	= (pfSTD_Equipment_ReceiveStateFile) GetProcAddress( pDriverInfo->LibraryHandle , "Equipment_ReceiveStateFile");
			pDriverInfo->tInstrDB.Equipment_GetFileCatalog																		= (pfSTD_Equipment_GetFileCatalog) GetProcAddress( pDriverInfo->LibraryHandle , "Equipment_GetFileCatalog");
			pDriverInfo->tInstrDB.Equipment_MakeFileCatalog																		= (pfSTD_Equipment_MakeFileCatalog) GetProcAddress( pDriverInfo->LibraryHandle , "Equipment_MakeFileCatalog"); 			
			pDriverInfo->tInstrDB.Equipment_DeleteFileCatalog																	= (pfSTD_Equipment_DeleteFileCatalog) GetProcAddress( pDriverInfo->LibraryHandle , "Equipment_DeleteFileCatalog");
			pDriverInfo->tInstrDB.Equipment_DeleteStateFile																		= (pfSTD_Equipment_DeleteStateFile) GetProcAddress( pDriverInfo->LibraryHandle , "Equipment_DeleteStateFile");
			
			pDriverInfo->tInstrDB.Config_SetAttribute																			= (pfSTD_Config_SetAttribute) GetProcAddress( pDriverInfo->LibraryHandle , "Config_SetAttribute"); 		
			
			pWrapperFunction = pDriverInfo->tInstrDB.functionGeneratorDriverFunctions.FunctionGenerator_Init;
	
			if ( pWrapperFunction == NULL )
			{
				char	szMessage[LOW_STRING]	= {0};
				
				sprintf( szMessage , "Method \"%s\"\nis not implemented in driver:\n%s" , "FunctionGenerator_Init" , pDriverInfo->pDriverFileName );
				
				ShowMessage ( INSTR_TYPE_CONTINUE , "Implementation Error . . ." , szMessage , NULL );
			
				{STD_ERR (DRV_ERROR_WRONG_WRAPPER);}
			}
		
			if ( !bHandleExists )
				DRIVER_MANAGER_AddConnection( pszAddressString , &(pDriverInfo->InstrumentHandle) , DRIVER_TYPE_FUNCTION_GENERATOR , &(pDriverInfo->InstrumentLockHandle) );
		
			LockHandle = pDriverInfo->InstrumentLockHandle;
		
			if ( LockHandle == 0 )
				{STD_ERR (DRV_ERROR_CREATE_LOCK_HANDLE);}
		
			CHK_PROCCESS_GET_LOCK ( LockHandle );
		
			DRIVER_MANAGER_IsConnectionExists( pszAddressString, &(pDriverInfo->InstrumentHandle) , NULL );
		
			//===================== Install Calbacks ==========================================================================================//
			pConfig_Install_CommentCallback = pDriverInfo->tInstrDB.functionGeneratorDriverFunctions.Config_Install_CommentCallback;		
			pConfig_Install_ConfigValueCallback	= pDriverInfo->tInstrDB.functionGeneratorDriverFunctions.Config_Install_ConfigValueCallback;		
			pConfig_Install_CheckForBreakCallback = pDriverInfo->tInstrDB.functionGeneratorDriverFunctions.Config_Install_CheckForBreakCallback;		
			pConfig_Copy_STD_CallBackSet = pDriverInfo->tInstrDB.functionGeneratorDriverFunctions.Config_Copy_STD_CallBackSet;
		
			DRIVER_MANAGER_GetCopyCallbacksStructure( VariableHandle , &(pDriverInfo->ptCallbacks) , 1 , pszAddressString ); 
			
			if ( pConfig_Copy_STD_CallBackSet && ( pDriverInfo->ptCallbacks ))
			{
				FREE_STDERR_COPY_ERR( pConfig_Copy_STD_CallBackSet( &pDriverInfo->InstrumentHandle , pDriverInfo->ptCallbacks ));
				
				pDriverInfo->ptCallbacks = NULL;
			}
			else
			{
				if ( pConfig_Install_CommentCallback && ( pDriverInfo->ptCallbacks ))
				{
					FREE_STDERR_COPY_ERR( pConfig_Install_CommentCallback( &pDriverInfo->InstrumentHandle , (pDriverInfo->ptCallbacks)->fCommentCallback , (pDriverInfo->ptCallbacks)->pCommentCallbackData , (pDriverInfo->ptCallbacks)->commentType ));
				}
				
				if ( pConfig_Install_ConfigValueCallback && ( pDriverInfo->ptCallbacks ))
				{
					FREE_STDERR_COPY_ERR( pConfig_Install_ConfigValueCallback( &pDriverInfo->InstrumentHandle , (pDriverInfo->ptCallbacks)->fConfigValueCallback , (pDriverInfo->ptCallbacks)->pConfigValueCallbackData , (pDriverInfo->ptCallbacks)->configType ));
				}
		
				if ( pConfig_Install_CheckForBreakCallback && ( pDriverInfo->ptCallbacks ))
				{
					FREE_STDERR_COPY_ERR( pConfig_Install_CheckForBreakCallback( &pDriverInfo->InstrumentHandle , (pDriverInfo->ptCallbacks)->fCheckForBreakCallback , (pDriverInfo->ptCallbacks)->pCheckForBreakCallbackData , (pDriverInfo->ptCallbacks)->breakType ));
				}
			}
		
			if (pDriverInfo->ptCallbacks)
				pDriverInfo->bDemoMode = (pDriverInfo->ptCallbacks)->bDemoMode;
			//=================================================================================================================================//
		
			for ( iTry = 0 ; iTry < 3 ; iTry++ )
			{
				if ( pDriverInfo->bDemoMode == 1 )
				{
					pDriverInfo->bConnected = 1;
					break;
				}
			
				if ( pWrapperFunction )
				{
					FREE_STDERR_COPY( pWrapperFunction( pDriverInfo->InstrumentHandle , pszAddressString , &pDriverInfo->InstrumentHandle , &pDriverInfo->bConnected , &pDriverInfo->ChannelQuantity )); 
				}
				else
					break;
			
				if ( StdError.error )
					if ( ShowMessage ( INSTR_TYPE_YES_NO , "Function Genrator Error !!!", "Check connection and Power On the Device." , NULL ) )
						continue;
			
				break;
			}
		
			CHK_STDERR(StdError);
		
			if (pDriverInfo->bConnected == 0)
				{STD_ERR (DRV_ERROR_CONNECTION);}
	
			if ( !bHandleExists ) 
				DRIVER_MANAGER_UpdateConnection( pszAddressString , pDriverInfo->InstrumentHandle , NULL );
		
		} while (0);
	}
	else
	{
		pfSTD_Equipment_IsSupported					pWrapperFunction							=	NULL;
		int											iCount										=	0, 
													status										=	0, 
													bSupport									=	0, 
													defaultRM									=	0,
													hConnectionHandle							=	0;
		char										szReadBuffer[LOW_STRING]					=	{0};
		//------------------ Checking for driver supporting ------------------------//
		
		viOpenDefaultRM (&defaultRM);

		SetBreakOnLibraryErrors (0);
		
		status = viOpen ( defaultRM , pszAddressString , NULL, NULL, &hConnectionHandle );
		
		if ( status == 0 )
		{	
			status = viPrintf ( hConnectionHandle , "*IDN?\n" );
		
			if ( status == 0 )
			{
				viRead ( hConnectionHandle , szReadBuffer , (LOW_STRING-1) , &iCount );
			}
		}
		
		if ( hConnectionHandle )
			viClose(hConnectionHandle); 
		
		SetBreakOnLibraryErrors (1);  
		
		LibraryHandle = LoadLibrary(szDriverLocation);
		
		if ( LibraryHandle == 0 )
		{
			sprintf( szMessage , "Loading Driver File\n\"%s\"\n\nFailed, File corrupted." , szDriverLocation );
			ShowMessage ( INSTR_TYPE_CONTINUE , "Equipment driver file error..." , szMessage , NULL );
		
			FORCE_ERR(-6,szMessage);
		}
		
		pWrapperFunction = (pfSTD_Equipment_IsSupported) GetProcAddress( LibraryHandle , "Equipment_IsSupported");   
	
		if ( pWrapperFunction )
		{
			FREE_STDERR_COPY_ERR( pWrapperFunction( 0, pszAddressString , NULL , szReadBuffer , &bSupport , NULL )); 
			
			IF (( bSupport == 0 ) , "This driver is not support the current Equipment." );
		}
		else
		{
			char	szMessage[LOW_STRING]	= {0};
		
			sprintf( szMessage , "Method \"%s\"\nis not implemented in driver:\n%s" , "Equipment_IsSupported" , szDriverLocation );
		
			ShowMessage ( INSTR_TYPE_CONTINUE , "Implementation Error . . ." , szMessage , NULL );
		}			
	}
	
Error:
	
	if ( LibraryHandle )
		FreeLibrary(LibraryHandle); 

	if ( LockHandle && bLocked ) 
		CmtReleaseLock (LockHandle);
	
	if ( VariableHandle ) 
		CmtReleaseTSVPtr ( VariableHandle );

	if ( StdError.error )
	{
		DRV_FunctionGenerator_GetErrorTextMessage ( VariableHandle , StdError.error , &pTempString );
		
		if ( pTempString && ( strlen(pTempString)))
		{
			SET_DESCRIPTION(pTempString);
		}
		
		FREE(pTempString);
		DRV_FunctionGenerator_Close( &VariableHandle ); 
		
		if ( pHandle )
			*pHandle = 0;
	}
	
	return StdError;
}
Example #26
0
bool CatDeviceManager::Initialize()
{
	try
	{
		ViSession session,defrm;
		ViStatus VISAstatus;
		int overcurron;
		float voltsetting,currsetting,overvoltsetting;

		char add[]="USB0::0x0957::0x0807::N5765A-US12N5190H::0::INSTR";

		voltsetting=12; //in volts                   //输出电压

		currsetting=30; //in amps                 //输出电流

		overvoltsetting=13.5;  //in volts           //输出电压保护

		overcurron=1;                            //输出电流保护状态:打开

		//The default resource manager manages initializes the VISA system
		VISAstatus=viOpenDefaultRM(&defrm);
		if (VISAstatus!=VI_SUCCESS) 
		{
			return false;
		}
		//opens a communication session with the instrument at address "add"
		VISAstatus=viOpen(defrm,add,VI_NULL,VI_NULL,&session);
		if (VISAstatus!=VI_SUCCESS) 
		{
			return false;
		}

		//Set voltage
		viPrintf(session,"VOLT %f \n",voltsetting);

		//Set the over voltage level
		viPrintf(session,"VOLT:PROT:LEV %f \n",overvoltsetting);

		//Turn on over current protection 
		viPrintf(session,"CURR:PROT:STAT %d \n",overcurron);

		//Set current level
		viPrintf(session,"CURR %f \n",currsetting);

		//Enable the output
		viPrintf(session,"OUTP ON \n");

		//This frees up all of the resources
		viClose(session);
		viClose(defrm);

		IAgilent34980A2Ptr ptr34980 = Get34980();
		ptr34980->Initialize("USB0::0x0957::0x0507::MY52490246::0::INSTR", VARIANT_FALSE, VARIANT_TRUE, strStandardInitOptions);
		ptr34980->Status->Clear();

		IAgilent34410Ptr ptr34411 = Get34411();
		ptr34411->Initialize("USB0::0x0957::0x0A07::MY53000110::0::INSTR", VARIANT_FALSE, VARIANT_TRUE, strStandardInitOptions);
		ptr34411->Status->Clear();
		return true;
	}
	catch(_com_error& e)
	{
		return false;
	}
}
Example #27
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.");
}
Example #28
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;
}
Example #29
0
void pressure () 
{ 
	/* Open communication with DataAcqu using usb-rs232 com address "7" */ 
	viOpenDefaultRM (&defaultRM); 
	viOpen (defaultRM,"ASRL07::INSTR",VI_NULL,VI_NULL, &DataAcqu); 
	
	viQueryf(DataAcqu, "*IDN?\n","%t",reply_string);
	printf ("Instrument identification string: %s\n",reply_string);
	
	/* Reset instrument to power-on and clear the Status Byte */ 
	viPrintf (DataAcqu, "*RST;*CLS\n");
	
	viPrintf (DataAcqu, "STAT:OPER:ENAB 272\n");
	viPrintf (DataAcqu, "*ESE 1\n");
	viPrintf (DataAcqu, "*SRE 255\n");
	
	viPrintf (DataAcqu, "CONF:CURR 0.1, 1e-5, (@121)\n");
	viPrintf (DataAcqu, "CALC:SCAL:GAIN 37500, (@121)\n");
	viPrintf (DataAcqu, "CALC:SCAL:OFFS -148.4, (@121)\n");	
	viPrintf (DataAcqu, "CALC:SCAL:UNIT 'KPA', (@121)\n");
	
	viPrintf (DataAcqu, "CALC:SCAL:STAT ON, (@121)\n");
	viPrintf (DataAcqu, "ROUT:SCAN (@121)\n");
	viPrintf (DataAcqu, "TRIG:SOUR TIM\n"); 
	viPrintf (DataAcqu, "TRIG:TIMER 5\n");
	viPrintf (DataAcqu, "TRIG:COUNT 5\n"); 
	viPrintf (DataAcqu, "INIT;*OPC\n"); 		
	
	for (count = 0; count <5; count++) 
	{
	/* Query the Status of Standard Operation Register
	   after the sweep done, the five bit position will set to 1 */		
	loop:			
		viPrintf(DataAcqu, "STAT:OPER?\n");
		viScanf(DataAcqu,"%d",&status);
		//printf("stat:oper= %d ", status);
		bool value;
		value = status & 0x10;
		//printf("value = %d ",value);
		
		
	if ( !value )  //if not set, keep query
		goto loop;
	else //show the query data
	{
		viPrintf(DataAcqu, "SYST:TIME?\n");
		viScanf(DataAcqu,"%s",&reply_string);
		printf("Time = %s ", reply_string);
		
		viPrintf (DataAcqu,"DATA:READ?\n"); /* Get all the readings */ 
		viScanf(DataAcqu,"%s",&temp);/* Put readings into an array */
		printf("Data = %s\n",  temp); 
	}
	
	}
	
	viClose (DataAcqu); /* Close the communication port */ 
	viClose (defaultRM); 
}
Example #30
0
void*	DLLEXPORT		Equipment_IsSupported ( int hLowLevelHandle , char *pAddress , char *pID_String , char *pIdentificationText , int *pbSupporting , void **pLocalData )
{
	STD_ERROR						StdError									=	{0};
	
	int								iCount										=	0, 
									status										=	0, 
									iIndex										=	0, 
									bSupport									=	0, 
									defaultRM									=	0,
									hConnectionHandle							=	0;
	
	char							szIdentificationText[LOW_STRING]			=	{0},
									vszSupportdedModels[][12]					=	{{"E4428C"},{"E4438C"},{"N5181A"},{"N5182A"},{"N5183A"},{"N5171B"},{"N5181B"},{"N5172B"},{"N5173B"},{"N5182B"},{"E8241A"},{"E8244A"},{"E8251A"},{"E8254A"},{"E8247C"},{"E8257C"},{"E8267C"},{"E8257D"},{"E8267D"},{"E8663B"},{"E8257N"}};
									
	if (( pIdentificationText == NULL ) || ( strlen(pIdentificationText) < 10 ))
	{
		SetBreakOnLibraryErrors (0);   
		
		if ( hLowLevelHandle == 0 )
		{
			viOpenDefaultRM (&defaultRM);

			SetBreakOnLibraryErrors (0);
	
			status = viOpen ( defaultRM , pAddress , NULL, NULL, &hConnectionHandle );
		}
		else
		{
			hConnectionHandle = hLowLevelHandle;	
		}
		
		if ( status == 0 )
		{	
			status = viPrintf ( hConnectionHandle , "*IDN?\n" );
		
			if ( status == 0 )
			{
				viRead ( hConnectionHandle , szIdentificationText , (LOW_STRING-1) , &iCount );
				RemoveSurroundingWhiteSpace (szIdentificationText); 
			}
		}
		
		if (( hLowLevelHandle == 0 ) && hConnectionHandle )
			viClose(hConnectionHandle); 
		
		SetBreakOnLibraryErrors (1);  	
	}
	else
	{
		if ( strlen(pIdentificationText) < LOW_STRING )
			strcpy( szIdentificationText , pIdentificationText );
		else
			memcpy( szIdentificationText , pIdentificationText , (LOW_STRING-1) );  
	}
		
	do
	{
		if ( strstr( szIdentificationText , "Agilent Technologies" ) == NULL ) 
			break;
	
		for ( iIndex = 0; iIndex < (sizeof(vszSupportdedModels) / sizeof(vszSupportdedModels[0])); iIndex++ )
			if ( strstr( szIdentificationText , vszSupportdedModels[iIndex]) )
			{
				bSupport = 1; 
				break;
			}
					
	}while(0);
	
	if (pbSupporting)
		*pbSupporting = bSupport;
	
	RETURN_STDERR_POINTER;	
}