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) {} }
/** * 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); }
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); }
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; }
void initGpib() { char deviceName[256]; FindRSrc(deviceName); viOpenDefaultRM (&defaultRM); viOpen (defaultRM, deviceName, VI_NULL,VI_NULL, &vi); pvi = &vi; init_equipment(pvi); }
//int init_power_supply(int comport,int gpib_address) int init_power_supply(int gpib_address) { //char comport_str[64]={0}; int status=SUCCESS; char response[RESP_BUF_SIZE]; char ps_desc[64]; /******************************************* if (g_use_rs232_power) { ps_com_port = comport; status = serial_open(comport,9600); } *********************************************/ // else // { sprintf(ps_desc,"GPIB0::%d::INSTR",gpib_address); if (!visaRM) { status = viOpenDefaultRM (&visaRM); } if (!ps_handle) { status = viOpen (visaRM, ps_desc, VI_NULL, VI_NULL, &ps_handle); } // } if (status==SUCCESS) { send_ps_command("*IDN?",response); send_ps_command("DIG:FUNC DIG",response); /********************************************** if (TestItems.PROGRAM_BOOTLOADER) { ps_enable_bootloader(TRUE); } else { ps_enable_bootloader(FALSE); } ******************************************/ } return status; }
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; }
bool SA_fsup::Init(ViRsrc rsrcName) { if (m_isInitialized) { return true; } if ((viOpenDefaultRM(&m_defaultRM) < VI_SUCCESS)) { return false; } if (viOpen(m_defaultRM, rsrcName, VI_NULL, 5000, &m_hVisa) < VI_SUCCESS) { m_isInitialized = false; // viClose(m_defaultRM); return false; } // viClose(m_defaultRM); m_isInitialized = true; return true; }
int Query_Instrument() { status = viOpenDefaultRM (&defaultRM); if (status < VI_SUCCESS) { printf ("Open Instrument Failed!\n",reply_string); return -1; } /* "ASRL07::INSTR" where 07 is the usb com address */ status = viOpen (defaultRM,"ASRL07::INSTR",VI_NULL,VI_NULL, &DataAcqu); if (status < VI_SUCCESS) { printf ("Open Instrument failed!\n",reply_string); return -1; } /* *IDN? is the scpi command ask the Intrument serial number */ status = viQueryf(DataAcqu, "*IDN?\n","%t",reply_string); printf ("Instrument identification string: %s\n",reply_string); // Query the slot status of Intrument which will return: 2638A-100,1,2638A-100,0,NONE,0 // 2638A-001 stands for the first slot status = viQueryf(DataAcqu, "*OPT?\n","%t",reply_string); printf ("Slots status is: %s\n",reply_string); // Query the calibration date of 2638A, return formats:2013,1,1 viQueryf(DataAcqu, "CALibrate:DATE? \n","%t",reply_string); printf ("2638A calibration date is: %s\n",reply_string); // Query the slot's calibration date of 2638A, return format:2013,1,1 viQueryf(DataAcqu, "CALibrate:MODule:DATE? 1\n","%t",reply_string); printf ("Slot 1 calibration DATE is: %s\n",reply_string); viQueryf(DataAcqu, "CALibrate:MODule:DATE? 2\n","%t",reply_string); printf ("Slot 2 calibration DATE is: %s\n",reply_string); // Query the slot's serial nubmer, return format:12345678 viQueryf(DataAcqu, "SYSTem:MODule:CONFigure:SNUM? 1\n","%t",reply_string); printf ("Slot 1 serial Number is: %s\n",reply_string); viQueryf(DataAcqu, "SYSTem:MODule:CONFigure:SNUM? 2\n","%t",reply_string); printf ("Slot 2 serial Number is: %s\n",reply_string); viClose (DataAcqu); /* Close the communication port */ viClose (defaultRM); }
void serialInitializePort(uint8_t port, int32_t *status) { char const * portName; if (m_resourceManagerHandle ==0) viOpenDefaultRM((ViSession*)&m_resourceManagerHandle); if(port == 0) portName = "ASRL1::INSTR"; else if (port == 1) portName = "ASRL2::INSTR"; else portName = "ASRL3::INSTR"; *status = viOpen(m_resourceManagerHandle, const_cast<char*>(portName), VI_NULL, VI_NULL, (ViSession*)&m_portHandle[port]); if(*status > 0) *status = 0; }
void HAL_InitializeSerialPort(int32_t port, int32_t* status) { char const* portName; if (m_resourceManagerHandle == 0) viOpenDefaultRM(reinterpret_cast<ViSession*>(&m_resourceManagerHandle)); if (port == 0) portName = "ASRL1::INSTR"; else if (port == 1) portName = "ASRL2::INSTR"; else portName = "ASRL3::INSTR"; *status = viOpen(m_resourceManagerHandle, const_cast<char*>(portName), VI_NULL, VI_NULL, reinterpret_cast<ViSession*>(&m_portHandle[port])); if (*status > 0) *status = 0; }
bool VISAInstrument::Initialize() { char desc[256]; char error_desc[512]; //check visa system status if(!VISASystemManager::Status()){ fErrorCode="Can't Initialize VISA system"; fStatus=VI_STATE_UNKNOWN; return false; } //find exactly the unique specified instr,no findlist int length=fRsrcName.size()+1; char *rsrcname=new char[length]; fRsrcName.copy(rsrcname,length-1); rsrcname[length-1]='\0'; fStatus = viFindRsrc(fDefaultRM,rsrcname,VI_NULL,VI_NULL,desc); delete[] rsrcname; if(fStatus < VI_SUCCESS){ viStatusDesc(fViSession,fStatus,error_desc); fErrorCode=error_desc; return false; } //viopen,default timeout 2s,default access mode fStatus = viOpen(fDefaultRM,desc,fAccessMode,fOpenTimeout,&fViSession); if(fStatus < VI_SUCCESS){ viStatusDesc(fViSession,fStatus,error_desc); fErrorCode=error_desc; return false; } //register this instrument if(!VISASystemManager::GetInstance()->Register(this)){ fStatus=VI_STATE_UNKNOWN; fErrorCode="Error! DeviceName Duplication.Please Choose Another DeviceName"; Close(); return false; } fRsrcDesc=desc; return true; }
/** * 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); }
void* ICS_Init ( int hParentInstrumentHandle , ViRsrc szRsrcAddress , int *vhInstrumentHandle ) { STD_ERROR StdError = {0}; tsHandle *pLocalHandle = {0}; CmtTSVHandle handle = 0; IF (( szRsrcAddress == NULL ) , "Address string is empty" ); if ( hParentInstrumentHandle == 0 ) { CHK_CMT ( CmtNewTSV ( sizeof(tsHandle) , &handle )); } else handle = hParentInstrumentHandle; if ( vhInstrumentHandle ) *vhInstrumentHandle = handle; CHK_CMT ( CmtGetTSVPtr ( handle , &pLocalHandle )); if ( pLocalHandle->defaultRM == 0 ) { CHK_VSA ( viOpenDefaultRM (&(pLocalHandle->defaultRM))); } if ( pLocalHandle->sessionHandle == 0 ) { CHK_VSA ( viOpen ( pLocalHandle->defaultRM , szRsrcAddress , VI_NULL, VI_NULL, &(pLocalHandle->sessionHandle))); } Error: if ( handle ) CmtReleaseTSVPtr ( handle ); return ICS_GetErrorTextMessage(handle,StdError.error,NULL); }
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; }
int initKeithley(void){ /* * First we open a session to the VISA resource manager. We are * returned a handle to the resource manager session that we must * use to open sessions to specific instruments. */ status = viOpenDefaultRM (&defaultRM); if (status < VI_SUCCESS) { printf("Could not open a session to the VISA Resource Manager!\n"); exit (EXIT_FAILURE); return 1; } /* * Next we use the resource manager handle to open a session to a * GPIB instrument at address 2. A handle to this session is * returned in the handle inst. */ status = viOpen (defaultRM, "GPIB::2::INSTR", VI_NULL, VI_NULL, &inst); if (status < VI_SUCCESS) { printf("Could not open a session to the device simulator"); return 1; } /* Now we must enable the service request event so that VISA * will receive the events. Note: one of the parameters is * VI_QUEUE indicating that we want the events to be handled by * a synchronous event queue. The alternate mechanism for handling * events is to set up an asynchronous event handling function using * the VI_HNDLR option. The events go into a queue which by default * can hold 50 events. This maximum queue size can be changed with * an attribute but it must be called before the events are enabled. */ status = viEnableEvent (inst, VI_EVENT_SERVICE_REQ, VI_QUEUE, VI_NULL); if (status < VI_SUCCESS) { printf("The SRQ event could not be enabled\n"); return 1; } /* * Now the VISA write command is used to send a request to the * instrument to generate a sine wave and assert the SRQ line * when it is finished. Notice that this is specific to one * particular instrument. */ KeithWrite("*RST\n"); KeithOn(); KeithWrite(":SOUR:FUNC VOLT\n"); KeithWrite(":SOUR:VOLT:RANG 210\n"); KeithWrite(":SOUR:VOLT:AUTO 0\n"); KeithSetVoltage(0); //float val = KeithGetVoltage(); //printf("Here is the data: %f\n", val); return 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; } }
void* DLLEXPORT SignalGenerator_Init ( int hParentInstrumentHandle , ViRsrc szRsrcAddress , int *vhInstrumentHandle , int *InstrumentConnectStatus , int *InstrumentChannelsQuantity ) { STD_ERROR StdError = {0}; tsHandle *pLocalHandle = {0}; CmtTSVHandle handle = 0; int supported = 0; tsSTD_CallBackSet tSTD_CallBackSet = {0}; double lfTimeout = 0.0, lfStateFileDelay = 1.0, lfStateFileTimeout = 10.0, lfDefaultTimeout = 5.0; IF (( szRsrcAddress == NULL ) , "Address string is empty" ); if ( hParentInstrumentHandle == 0 ) { CHK_CMT ( CmtNewTSV ( sizeof(tsHandle) , &handle )); } else handle = hParentInstrumentHandle; if ( vhInstrumentHandle ) *vhInstrumentHandle = handle; CHK_CMT ( CmtGetTSVPtr ( handle , &pLocalHandle )); if ( pLocalHandle->defaultRM == 0 ) { CHK_VSA ( viOpenDefaultRM (&(pLocalHandle->defaultRM))); } if ( pLocalHandle->sessionHandle == 0 ) { CHK_VSA ( viOpen ( pLocalHandle->defaultRM , szRsrcAddress , VI_NULL, VI_NULL, &(pLocalHandle->sessionHandle))); } WaitForOperationCompletion( pLocalHandle->sessionHandle , 20.0 , 0.5 ); CHK_VSA ( viSetAttribute ( pLocalHandle->sessionHandle , VI_ATTR_TMO_VALUE , 500 )); FREE_STDERR_COPY_ERR( Equipment_IsSupported ( pLocalHandle->sessionHandle , NULL , NULL , NULL , &supported , &pLocalHandle )); IF (( supported == 0 ) , "This device has not supported." ); FREE_STDERR_COPY_ERR( Equipment_Info ( pLocalHandle->sessionHandle , NULL , &pLocalHandle->pVendor , &pLocalHandle->pSerialNumber , &pLocalHandle->pModel , &pLocalHandle->pFirmware )); STDF_UPDATE_CALLBACK_DATA(pLocalHandle->ptCallbacks); viPrintf( pLocalHandle->sessionHandle ,"*CLS\n" ); STDF_CONFIG_VALUE("Timeout", VAL_DOUBLE , 1 , lfTimeout , lfDefaultTimeout ); if ( lfTimeout == 0.0 ) lfTimeout = lfDefaultTimeout; viSetAttribute ( pLocalHandle->sessionHandle , VI_ATTR_TMO_VALUE , (lfTimeout*1E3) ); STDF_CONFIG_VALUE("OPC_Timeout", VAL_DOUBLE , 1 , (pLocalHandle->lfTimeout) , lfDefaultTimeout ); if ( pLocalHandle->lfTimeout == 0.0 ) pLocalHandle->lfTimeout = lfDefaultTimeout; STDF_CONFIG_VALUE("OPC_LowLevel_Timeout", VAL_DOUBLE , 1 , (pLocalHandle->lfOpcLowLevelTimeout) , lfDefaultTimeout ); if ( pLocalHandle->lfOpcLowLevelTimeout == 0.0 ) pLocalHandle->lfOpcLowLevelTimeout = lfDefaultTimeout; STDF_CONFIG_VALUE("State_File_Timeout", VAL_DOUBLE , 1 , (pLocalHandle->lfStateFileTimeout) , lfStateFileTimeout ); if ( pLocalHandle->lfStateFileTimeout == 0.0 ) pLocalHandle->lfStateFileTimeout = lfStateFileTimeout; STDF_CONFIG_VALUE("State_File_Delay", VAL_DOUBLE , 1 , (pLocalHandle->lfStateFileDelay) , lfStateFileDelay ); if ( pLocalHandle->lfStateFileDelay == 0.0 ) pLocalHandle->lfStateFileDelay = lfStateFileDelay; Error: if ( InstrumentConnectStatus ) *InstrumentConnectStatus = supported; if ( handle ) CmtReleaseTSVPtr ( handle ); RETURN_STDERR_POINTER; }
/** * Opens a UART session on an VISA implemented port. * * @param[in] port UART port information. * @param[in] baud Baud rate (bps). * @param[in] dataBits Number of bits per frame. * @param[in] stopBits Stop bit configuration. * @param[in] parity Parity configuration. * @return int32_t Error/success status */ int32_t Uart_Open(MyRio_Uart* port, const uint32_t baud, const uint8_t dataBits, const Uart_StopBits stopBits, const Uart_Parity parity) { int32_t status = VI_SUCCESS; /* * Open VISA resource manager. */ if (!port->defaultRM) { status = viOpenDefaultRM(&port->defaultRM); if (status < VI_SUCCESS || !port->defaultRM) { return status; } } /* * Open serial resource. */ if (!port->session) { status = viOpen(port->defaultRM, (ViRsrc)port->name, VI_NULL, VI_NULL, &port->session); if (status < VI_SUCCESS || !port->session) { return status; } } /* * Set timeout. */ status = viSetAttribute(port->session, VI_ATTR_TMO_VALUE, VisaDefaultTimeout); if (status < VI_SUCCESS) { return status; } /* * Set baud rate. */ status = viSetAttribute(port->session, VI_ATTR_ASRL_BAUD, baud); if (status < VI_SUCCESS) { return status; } /* * Set data bits. */ status = viSetAttribute(port->session, VI_ATTR_ASRL_DATA_BITS, dataBits); if (status < VI_SUCCESS) { return status; } /* * Set stop bits. */ status = viSetAttribute(port->session, VI_ATTR_ASRL_STOP_BITS, stopBits); if (status < VI_SUCCESS) { return status; } /* * Set parity. */ status = viSetAttribute(port->session, VI_ATTR_ASRL_PARITY, parity); if (status < VI_SUCCESS) { return status; } /* * Set termination character. */ status = viSetAttribute(port->session, VI_ATTR_TERMCHAR_EN, VI_FALSE); if (status < VI_SUCCESS) { return status; } return status; }
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); }
/* Use this function from user land to open a device and create a link. Can be * used multiple times for the same device (the library will keep track).*/ int vxi11_open_device(VXI11_CLINK **clink, const char *address, char *device) { #ifdef WIN32 ViStatus status; char buf[256]; #else int ret; struct _vxi11_client_t *tail, *client = NULL; #endif char default_device[6] = "inst0"; char *use_device; if(device){ use_device = device; }else{ use_device = default_device; } *clink = (VXI11_CLINK *) calloc(1, sizeof(VXI11_CLINK)); if (!(*clink)) { return 1; } #ifdef WIN32 status = viOpenDefaultRM(&clink->rm); if (status != VI_SUCCESS) { viStatusDesc(NULL, status, buf); printf("%s\n", buf); free(*clink); *clink = NULL; return 1; } viOpen(clink->rm, (char *)address, VI_NULL, VI_NULL, &clink->session); if (status != VI_SUCCESS) { viStatusDesc(clink->rm, status, buf); printf("%s\n", buf); free(*clink); *clink = NULL; return 1; } #else /* Have a look to see if we've already initialised an instrument with * this address */ tail = VXI11_CLIENTS; while (tail) { if (strcmp(address, tail->address) == 0) { client = tail; break; } tail = tail->next; } /* Couldn't find a match, must be a new address */ if (!client) { /* Create a new client, keep a note of where the client pointer * is, for this address. Because it's a new client, this * must be link number 1. Keep track of how many devices we've * opened so we don't run out of storage space. */ client = (struct _vxi11_client_t *)calloc(1, sizeof(struct _vxi11_client_t)); if (!client) { free(*clink); *clink = NULL; return 1; } (*clink)->client = clnt_create(address, DEVICE_CORE, DEVICE_CORE_VERSION, "tcp"); if ((*clink)->client == NULL) { clnt_pcreateerror(address); free(client); free(*clink); *clink = NULL; return 1; } ret = _vxi11_open_link(*clink, address, use_device); if (ret != 0) { clnt_destroy((*clink)->client); free(client); free(*clink); *clink = NULL; return 1; } strncpy(client->address, address, 20); client->client_address = (*clink)->client; client->link_count = 1; client->next = VXI11_CLIENTS; VXI11_CLIENTS = client; } else { /* Copy the client pointer address. Just establish a new link * not a new client). Add one to the link count */ (*clink)->client = client->client_address; ret = _vxi11_open_link((*clink), address, use_device); client->link_count++; } #endif return 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; }
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; }
// ================================================================================================ // 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; }
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; }
// ================================================================================================ // 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."); }
int main (void) { /* * First we open a session to the VISA resource manager. We are * returned a handle to the resource manager session that we must * use to open sessions to specific instruments. */ status = viOpenDefaultRM (&defaultRM); if (status < VI_SUCCESS) { printf("Could not open a session to the VISA Resource Manager!\n"); exit (EXIT_FAILURE); } /* * Next we use the resource manager handle to open a session to a * GPIB instrument at device 2. A handle to this session is * returned in the handle inst. Please consult the NI-VISA User Manual * for the syntax for using other instruments. */ status = viOpen (defaultRM, "GPIB::2::INSTR", VI_NULL, VI_NULL, &inst); /* * Now we install the handler for asynchronous i/o completion events. * To install the handler, we must pass our instrument session, the type of * event to handle, the handler function name and a user handle * which acts as a handle to the handler function. */ status = viInstallHandler (inst, VI_EVENT_IO_COMPLETION, AsyncHandler, uhandle); /* Now we must actually enable the I/O completion event so that our * handler will see the events. Note, one of the parameters is * VI_HNDLR indicating that we want the events to be handled by * an asynchronous event handler. The alternate mechanism for handling * events is to queue them and read events off of the queue when * you want to check them in your program. */ status = viEnableEvent (inst, VI_EVENT_IO_COMPLETION, VI_HNDLR, VI_NULL); /* * Now the VISA write command is used to send a request to the * instrument to generate a sine wave. This demonstrates the * synchronous read operation that blocks the application until viRead() * returns. Note that the command syntax is instrument specific. */ /* * Here you specify which string you wish to send to your instrument. * The command listed below is device specific. You may have to change * command to accommodate your instrument. */ strcpy(stringinput,"SOUR:FUNC SIN; SENS: DATA?\n"); BytesToWrite = strlen(stringinput); status = viWrite (inst, (ViBuf)stringinput,BytesToWrite, &rcount); /* * Next the asynchronous read command is called to read back the * date from the instrument. Immediately after this is called * the program goes into a loop which will terminate * on an i/o completion event triggering the asynchronous callback. * Note that the asynchronous read command returns a job id that is * a handle to the asynchronous command. We can use this handle * to terminate the read if too much time has passed. */ status = viReadAsync (inst, data, 1024, &job); printf("\n\nHit enter to continue."); letter = getchar(); /* * If the asynchronous callback was called and the flag was set * we print out the returned data otherwise we terminate the * asynchronous job. */ if (stopflag == VI_TRUE) { /* RtCount was set in the callback */ printf ("Here is the data: %*s", RtCount, data); } else { status = viTerminate (inst, VI_NULL, job); printf("The asynchronous read did not complete.\n"); } printf ("\nHit enter to continue."); fflush(stdin); getchar(); /* * Now we close the instrument session and the resource manager * session to free up resources. */ status = viClose(inst); status = viClose(defaultRM); return 0; }
int main(void) { /* * First we must call viOpenDefaultRM to get the manager * handle. We will store this handle in defaultRM. */ status=viOpenDefaultRM (&defaultRM); if (status < VI_SUCCESS) { printf ("Could not open a session to the VISA Resource Manager!\n"); exit (EXIT_FAILURE); } /* * Now we will open a VISA session to the serial port (COM1). * We must use the handle from viOpenDefaultRM and we must * also use a string that indicates which instrument to open. This * is called the instrument descriptor. The format for this string * can be found in the function panel by right clicking on the * descriptor parameter. After opening a session to the * device, we will get a handle to the instrument which we * will use in later VISA functions. The AccessMode and Timeout * parameters in this function are reserved for future * functionality. These two parameters are given the value VI_NULL. */ status = viOpen (defaultRM, "ASRL1::INSTR", VI_NULL, VI_NULL, &instr); if (status < VI_SUCCESS) { printf ("Cannot open a session to the device.\n"); goto Close; } /* * At this point we now have a session open to the serial instrument. * Now we need to configure the serial port: */ /* Set the timeout to 5 seconds (5000 milliseconds). */ status = viSetAttribute (instr, VI_ATTR_TMO_VALUE, 5000); /* Set the baud rate to 4800 (default is 9600). */ status = viSetAttribute (instr, VI_ATTR_ASRL_BAUD, 4800); /* Set the number of data bits contained in each frame (from 5 to 8). * The data bits for each frame are located in the low-order bits of * every byte stored in memory. */ status = viSetAttribute (instr, VI_ATTR_ASRL_DATA_BITS, 8); /* Specify parity. Options: * VI_ASRL_PAR_NONE - No parity bit exists, * VI_ASRL_PAR_ODD - Odd parity should be used, * VI_ASRL_PAR_EVEN - Even parity should be used, * VI_ASRL_PAR_MARK - Parity bit exists and is always 1, * VI_ASRL_PAR_SPACE - Parity bit exists and is always 0. */ status = viSetAttribute (instr, VI_ATTR_ASRL_PARITY, VI_ASRL_PAR_NONE); /* Specify stop bit. Options: * VI_ASRL_STOP_ONE - 1 stop bit is used per frame, * VI_ASRL_STOP_ONE_5 - 1.5 stop bits are used per frame, * VI_ASRL_STOP_TWO - 2 stop bits are used per frame. */ status = viSetAttribute (instr, VI_ATTR_ASRL_STOP_BITS, VI_ASRL_STOP_ONE); /* Specify that the read operation should terminate when a termination * character is received. */ status = viSetAttribute (instr, VI_ATTR_TERMCHAR_EN, VI_TRUE); /* Set the termination character to 0xA */ status = viSetAttribute (instr, VI_ATTR_TERMCHAR, 0xA); /* We will use the viWrite function to send the device the string "*IDN?\n", * asking for the device's identification. */ strcpy (stringinput,"*IDN?\n"); status = viWrite (instr, (ViBuf)stringinput, strlen(stringinput), &writeCount); if (status < VI_SUCCESS) { printf ("Error writing to the device.\n"); goto Close; } /* * Now we will attempt to read back a response from the device to * the identification query that was sent. We will use the viRead * function to acquire the data. We will try to read back 100 bytes. * This function will stop reading if it finds the termination character * before it reads 100 bytes. * After the data has been read the response is displayed. */ status = viRead (instr, buffer, 100, &retCount); if (status < VI_SUCCESS) { printf ("Error reading a response from the device.\n"); } else { printf ("\nData read: %*s\n", retCount, buffer); } /* * Now we will close the session to the instrument using * viClose. This operation frees all system resources. */ Close: status = viClose (instr); status = viClose (defaultRM); printf ("Hit enter to continue."); fflush (stdin); getchar(); return 0; }