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; }
float KeithGetVoltage ( void ){ strcpy(nextstringinput,":SOUR:VOLT:AMPL?\n"); status = viWrite (inst, (ViBuf)nextstringinput, (ViUInt32)strlen(nextstringinput), &rcount); if (status < VI_SUCCESS) { printf("There was an error writing the command to get the data\n"); return 0; } status = viRead (inst, data, 3000, &rcount); if (status < VI_SUCCESS) { printf("There was an error reading the data\n"); return 0; } status = viClose (ehandle); if (status < VI_SUCCESS) { printf("There was an error closing the event handle\n"); return 0; } std::ostringstream formatter; formatter << data; std::string myString = formatter.str(); float volt = (float)atof(myString.c_str()); return volt; }
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); }
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; }
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; }
/** * Reads binary data from a UART port. If the number of bytes in the UART * receive FIFO is less than number bytes to read, this function blocks until either * all the bytes are available to be removed from the FIFO, or until a timeout * occurs. * * @param[in] port Port to access * @param[out] data Buffer to receive read data * @param[in] nData Number of bytes to read * @return int32_t Error/success status */ int32_t Uart_Read(MyRio_Uart* port, uint8_t* const data, const size_t nData) { int32_t status = VI_SUCCESS; ViUInt32 numberRead = 0; status = viRead(port->session, (ViBuf)data, (ViUInt32)nData, &numberRead); return status; }
// ================================================================================================ // 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; }
// ================================================================================================ // 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; }
/** * Clears UART receive buffer. * * @param[in] port UART port to access * @return int32_t Error/success status */ int32_t Uart_Clear(MyRio_Uart* port) { int32_t status = VI_SUCCESS; int32_t oldTimeout = 0; uint8_t read[0xFF] = {0}; ViUInt32 nRead = 0; /* * Get timeout. */ status = viGetAttribute(port->session, VI_ATTR_TMO_VALUE, &oldTimeout); if (status < VI_SUCCESS) { return status; } /* * Set timeout to 1 ms. */ status = viSetAttribute(port->session, VI_ATTR_TMO_VALUE, 1); if (status < VI_SUCCESS) { return status; } /* * Read input buffer, up to 255 bytes at a time, until timeout occurs. */ while((status = viRead(port->session, (ViBuf)read, (ViUInt32)0xFF, &nRead)) >= VI_SUCCESS); if (status == VI_ERROR_TMO) { /* * Timeout expected. */ status = VI_SUCCESS; } /* * Reset timeout to previous value. */ status = viSetAttribute(port->session, VI_ATTR_TMO_VALUE, oldTimeout); if (status < VI_SUCCESS) { return status; } return status; }
uint32_t serialRead(uint8_t port, char* buffer, int32_t count, int32_t *status) { uint32_t retCount = 0; *status = viRead(m_portHandle[port], (ViPBuf)buffer, count, (ViPUInt32)&retCount); if(*status == VI_ERROR_IO || *status == VI_ERROR_ASRL_OVERRUN || *status == VI_ERROR_ASRL_FRAMING || *status == VI_ERROR_ASRL_PARITY) { int32_t localStatus = 0; serialClear(port, &localStatus); } if(*status == VI_ERROR_TMO || *status > 0) *status = 0; return retCount; }
int32_t HAL_ReadSerial(int32_t port, char* buffer, int32_t count, int32_t* status) { uint32_t retCount = 0; *status = viRead(m_portHandle[port], (ViPBuf)buffer, count, (ViPUInt32)&retCount); if (*status == VI_ERROR_IO || *status == VI_ERROR_ASRL_OVERRUN || *status == VI_ERROR_ASRL_FRAMING || *status == VI_ERROR_ASRL_PARITY) { int32_t localStatus = 0; HAL_ClearSerial(port, &localStatus); } if (*status == VI_ERROR_TMO || *status > 0) *status = 0; return static_cast<int32_t>(retCount); }
ViStatus CViRemote::RCT_viRead(ViSession vi, ViPBuf buf, ViUInt32 count, ViPUInt32 retCount) { ViStatus m_ViStat; if(retCount) { *retCount = 0; } m_ViStat = viRead(vi, buf, count, retCount); /* teminates the received C-string buffer with NULL terminator */ if(m_ViStat == VI_SUCCESS) { buf[*retCount] = 0; } GpibLogFunction("%X: %s", m_ViStat, buf); return m_ViStat; }
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); }
/** * @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); }
void VisaEmitter::EIO_Read(GenericBaton* data) { if (!this->isConnected || session < 1) { ErrorCodeToString("not connected", 11, data->errorString); return; } int64_t numberOfBytes = atoi(data->command); if (numberOfBytes < 1) { ErrorCodeToString("trying to read 0 bytes...", 11, data->errorString); return; } if (numberOfBytes > (uint32_t)-1) { ErrorCodeToString("trying to read more than uint32 bytes...", 11, data->errorString); return; } data->buffer = (char*) malloc(numberOfBytes + 1); char *temp = (char*) malloc(numberOfBytes + 1); char *p = temp; ViUInt32 returnCount; //while(p != temp+numberOfBytes) { // we need more checks before that cast below... //ViStatus status = viRead(session, reinterpret_cast<ViBuf>(p), (ViUInt32) (temp + numberOfBytes - p), &returnCount); ViStatus status = viRead(session, reinterpret_cast<ViBuf>(temp), (ViUInt32) numberOfBytes, &returnCount); if ((status < VI_SUCCESS)) { _snprintf(temp, sizeof(temp), "%d viRead, returnCount: %d", session, returnCount); ErrorCodeToString(temp, status, data->errorString); return; } //p += returnCount; //} temp[numberOfBytes] = 0; data->bufferLength = returnCount; memcpy(data->buffer, temp, returnCount); delete temp; }
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; }
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; }
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; }
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; }
double scan_meas_cnt_aver(ViSession *pvi, FILE *fp) { int cnt = 0; int actualCnt; int i; char *pbuf = buf+1; double res = 0, tmp; 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] = ' '; } for(i = 0; i < MEAS_CNT; ++i){ sscanf(pbuf, "%lf", &tmp); printf("%lf\n", tmp); res+=tmp; for(;*pbuf;++pbuf){ if(*pbuf == ' '){ pbuf++;pbuf++; break; } } if(!*pbuf){ i++; break; } } fprintf(fp, "%s", buf);////////////////////////////////////////////////////////////////////////// viPrintf(*pvi, "*rst\n"); fprintf(fpAll, "%s -- %s\n", strToSend2, buf); fflush(fpAll); return res / i; }
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; }
// ================================================================================================ // 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."); }
// ================================================================================================ // 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; }
ssize_t vxi11_receive_timeout(VXI11_CLINK * clink, char *buffer, size_t len, unsigned long timeout) { size_t curr_pos = 0; #ifdef WIN32 viRead(clink->session, (unsigned char *)buffer, len, &curr_pos); #else Device_ReadParms read_parms; Device_ReadResp read_resp; read_parms.lid = clink->link->lid; read_parms.requestSize = len; read_parms.io_timeout = timeout; /* in ms */ read_parms.lock_timeout = timeout; /* in ms */ read_parms.flags = 0; read_parms.termChar = 0; do { memset(&read_resp, 0, sizeof(read_resp)); read_resp.data.data_val = buffer + curr_pos; read_parms.requestSize = len - curr_pos; // Never request more total data than originally specified in len if (device_read_1(&read_parms, &read_resp, clink->client) != RPC_SUCCESS) { return -VXI11_NULL_READ_RESP; /* there is nothing to read. Usually occurs after sending a query which times out on the instrument. If we don't check this first, then the following line causes a seg fault */ } if (read_resp.error != 0) { /* Read failed for reason specified in error code. * (From published VXI-11 protocol, section B.5.2) * 0 no error * 1 syntax error * 3 device not accessible * 4 invalid link identifier * 5 parameter error * 6 channel not established * 8 operation not supported * 9 out of resources * 11 device locked by another link * 12 no lock held by this link * 15 I/O timeout * 17 I/O error * 21 invalid address * 23 abort * 29 channel already established */ printf("vxi11_user: read error: %d\n", (int)read_resp.error); return -(read_resp.error); } if ((curr_pos + read_resp.data.data_len) <= len) { curr_pos += read_resp.data.data_len; } if ((read_resp.reason & RCV_END_BIT) || (read_resp.reason & RCV_CHR_BIT)) { break; } else if (curr_pos == len) { printf("xvi11_user: read error: buffer too small. Read %d bytes without hitting terminator.\n", (int)curr_pos); return -100; } } while (1); #endif return (curr_pos); /*actual number of bytes received */ }
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; }